feat(agents): two-page model picker with pinned models, segmented effort, Reset and ACP cost badges (#3583)

The composer model picker becomes a two-page popover for every agent: page 1 lists models with search, a Pinned section, usage multiplier and description, and a summary bar for the active model; page 2 configures a model with Back, Reset to defaults, Pin, a segmented effort control and the cost category / multiplier from ACP _meta (copilotPriceCategory, copilotUsage) where present. Option defaults are kept across same-model updates for Reset. A contextTier / context_tier option is handled as per-model like effort. Agents with no effort, model options or cost metadata keep the plain select.

Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com>
This commit is contained in:
Deng Liu
2026-11-16 02:07:32 +08:00
committed by GitHub
co-authored by dengliu
parent 8535fb7645
commit 7b6962001b
18 changed files with 928 additions and 228 deletions
+6 -7
View File
@@ -106,18 +106,17 @@ impl ide_jsonrpc::Handler for DiscoveryUpdates {
}
}
fn is_thought_level(o: &AgentConfigOption) -> bool {
o.category.as_deref() == Some("thought_level")
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
}
fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Option<Vec<AgentConfigOption>> {
let levels: Vec<_> = options
.iter()
.filter(|o| is_thought_level(o))
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if o.category.as_deref() != Some("thought_level") {
if config::is_context_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.as_deref() != Some("thought_level") {
o.category = Some("thought_level".into());
}
o
+100 -11
View File
@@ -20,17 +20,22 @@ pub(crate) fn add_client_options(provider: &str, config: &mut Vec<AgentConfigOpt
description: Some("Tool approvals for this Cursor conversation".into()),
category: Some("approval".into()),
current: Some("ask".into()),
default_value: Some("ask".into()),
via: AgentConfigVia::Option,
values: vec![
AgentConfigValue {
value: "ask".into(),
name: "Ask for approval".into(),
description: Some("Show permission requests from Cursor".into()),
cost_category: None,
usage_multiplier: None,
},
AgentConfigValue {
value: "bypass".into(),
name: "Bypass approvals".into(),
description: Some("Automatically approve tool requests in this conversation".into()),
cost_category: None,
usage_multiplier: None,
},
],
});
@@ -118,6 +123,18 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
out
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context_tier" | "contextTier")
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_context_option(&o.id)
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
let Some(list) = options.as_array() else { return Vec::new() };
@@ -133,6 +150,8 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
None => values.extend(value_of(v)),
}
}
let current = str_of(o, "currentValue");
let default_value = str_of(o, "defaultValue").or_else(|| current.clone());
Some(AgentConfigOption {
name: str_of(o, "name").unwrap_or_else(|| id.clone()),
description: str_of(o, "description"),
@@ -143,9 +162,10 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into())
})
.or_else(|| matches!(id.as_str(), "fast").then(|| "model_config".into()))
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
}),
current: str_of(o, "currentValue"),
current,
default_value,
values,
via: AgentConfigVia::Option,
id,
@@ -155,9 +175,24 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
}
/// A `config_option_update`: its options replace the config-option ones; `modes` / `models`
/// stand-ins stay.
/// stand-ins stay, and initial `default_value`s survive same-model option edits for Reset.
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let fresh = parse_options(options);
let mut fresh = parse_options(options);
let old_model = config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.as_deref());
let new_model = fresh.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.as_deref());
let same_model = old_model == new_model;
for f in &mut fresh {
if f.default_value == f.current
&& (same_model || !is_per_model_option(f))
&& let Some(prev_default) = config
.iter()
.find(|p| p.id == f.id)
.and_then(|p| p.default_value.as_ref())
.filter(|def| f.values.iter().any(|v| v.value == **def))
{
f.default_value = Some(prev_default.clone());
}
}
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o)));
let legacy = std::mem::take(config);
@@ -251,16 +286,20 @@ fn legacy(
Some(AgentConfigValue {
name: str_of(m, "name").unwrap_or_else(|| value.clone()),
description: str_of(m, "description"),
cost_category: None,
usage_multiplier: None,
value,
})
})
.collect();
let current = str_of(v, current);
AgentConfigOption {
id: id.to_owned(),
name: name.to_owned(),
description: None,
category: Some(id.to_owned()),
current: str_of(v, current),
default_value: current.clone(),
current,
values,
via,
}
@@ -268,9 +307,23 @@ fn legacy(
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
let cost_category = meta
.and_then(|m| m.get("copilotPriceCategory").or_else(|| m.get("priceCategory")))
.and_then(Value::as_str)
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty());
let usage_multiplier = meta
.and_then(|m| m.get("copilotUsage").or_else(|| m.get("usageMultiplier")))
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
value,
})
}
@@ -402,17 +455,53 @@ mod tests {
#[test]
fn effort_and_fast_categories_are_inferred_from_ids() {
let c = options_of(&json!({
let mut c = options_of(&json!({
"configOptions": [
{"id": "effort", "type": "select", "currentValue": "high",
"options": [{"value": "low"}, {"value": "high"}]},
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
"options": [{"value": "gemini-4-carbon", "name": "Gemini 4 Carbon",
"description": "Powerful · Medium cost",
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
]
}));
assert_eq!(c.len(), 2);
assert_eq!(c[0].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].category.as_deref(), Some("model_config"));
assert_eq!(c.len(), 4);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
assert_eq!(c[2].category.as_deref(), Some("model_config"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
&mut c,
&json!([
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
"options": [{"value": "gemini-4-carbon"}]},
{"id": "effort", "type": "select", "currentValue": "high",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("high"), Some("medium")));
// Switching models refreshes per-model `default_value` to the new model's default.
merge_update(
&mut c,
&json!([
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
{"id": "effort", "type": "select", "currentValue": "low",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
}
#[test]
+12 -14
View File
@@ -188,7 +188,7 @@ impl Shared {
fn config_for_new_task(&self, mut config: Vec<AgentConfigOption>, provider: &str) -> Vec<AgentConfigOption> {
// Model-specific options are offered separately, never as provider-wide defaults.
config.retain(|o| o.category.as_deref() != Some("thought_level"));
config.retain(|o| !config::is_per_model_option(o));
config::add_client_options(provider, &mut config);
let hook = self.new_task_approvals.read().clone();
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
@@ -234,8 +234,7 @@ impl Shared {
&& let Some(config) = config.filter(|c| !c.is_empty())
{
if let Some(model) = model {
let levels: Vec<_> =
config.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
if known.thought_levels.get(model) != Some(&levels) {
known.thought_levels.insert(model.to_owned(), levels);
changed = true;
@@ -246,10 +245,9 @@ impl Shared {
changed = true;
}
}
// Discovery reads one model's efforts; a session on another model reports that model's.
// Discovery reads one model's options; a session on another model reports that model's.
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
let levels: Vec<_> =
config.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
(model, levels)
});
if let Some(commands) = commands.filter(|c| !c.is_empty())
@@ -1043,7 +1041,7 @@ impl AgentManager {
{
let mut s = task.state.lock();
if !model_options {
s.task.config.retain(|o| o.category.as_deref() != Some("thought_level"));
s.task.config.retain(|o| !config::is_per_model_option(o));
}
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == option) {
o.current = Some(value);
@@ -2121,10 +2119,10 @@ impl Task {
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
};
config::add_client_options(&provider_id, &mut options);
// Changing model can replace the effort choices; validate those only afterwards.
wanted.sort_by_key(|c| match options.iter().find(|o| o.id == c.id).and_then(|o| o.category.as_deref()) {
Some("model") => 0,
Some("thought_level") => 2,
// 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,
});
let mut model_options = known;
@@ -2137,7 +2135,7 @@ impl Task {
}
continue;
}
if o.category.as_deref() == Some("thought_level") && !model_options {
if config::is_per_model_option(&o) && !model_options {
continue;
}
let already = known && o.current.as_deref() == Some(choice.value.as_str());
@@ -2154,7 +2152,7 @@ impl Task {
model_options = true;
} else if o.category.as_deref() == Some("model") {
if o.current.as_deref() != Some(choice.value.as_str()) {
options.retain(|o| o.category.as_deref() != Some("thought_level"));
options.retain(|o| !config::is_per_model_option(o));
}
model_options = false;
}
@@ -2218,7 +2216,7 @@ impl Task {
if let Some(fresh) = reply.get("configOptions") {
config::merge_update(&mut s.task.config, fresh);
} else if option.category.as_deref() == Some("model") {
s.task.config.retain(|o| o.category.as_deref() != Some("thought_level"));
s.task.config.retain(|o| !config::is_per_model_option(o));
}
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == option.id) {
o.current = Some(value);
+12
View File
@@ -130,6 +130,14 @@ pub struct AgentConfigValue {
pub value: String,
pub name: String,
pub description: Option<String>,
/// Relative cost category from ACP `_meta` (`copilotPriceCategory`, e.g. `low`, `medium`, `high`, `very_high`).
#[serde(default)]
#[specta(optional)]
pub cost_category: Option<String>,
/// Usage multiplier from ACP `_meta` (`copilotUsage`, e.g. `1x`, `0x`, `3x`).
#[serde(default)]
#[specta(optional)]
pub usage_multiplier: Option<String>,
}
/// How a setting is changed.
@@ -155,6 +163,10 @@ pub struct AgentConfigOption {
/// ACP category: `model`, `mode`, `thought_level`, or agent-specific.
pub category: Option<String>,
pub current: Option<String>,
/// Initial default value reported by the agent, preserved across session updates for Reset.
#[serde(default)]
#[specta(optional)]
pub default_value: Option<String>,
pub values: Vec<AgentConfigValue>,
pub via: AgentConfigVia,
}
+4 -2
View File
@@ -363,9 +363,11 @@ test("Settings and model popup exclude the agent shortcut", async ({ workbench:
await modelButton(page).click();
const popup = page.getByRole("dialog", { name: "Model & effort settings", exact: true });
await expect(popup).toBeVisible();
await popup.getByRole("slider", { name: "Reasoning" }).focus();
await popup.getByRole("button", { name: "Configure model", exact: true }).click();
const gentle = popup.getByRole("radio", { name: "Gentle", exact: true });
await gentle.focus();
await page.keyboard.press("Alt+t");
await expect(popup.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "Gentle");
await expect(gentle).toHaveAttribute("aria-checked", "true");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
await page.keyboard.press("Escape");
await expectEffort(page, "Gentle");
+6
View File
@@ -1986,6 +1986,8 @@ export type AgentConfigOption = {
/** ACP category: `model`, `mode`, `thought_level`, or agent-specific. */
category: string | null,
current: string | null,
/** Initial default value reported by the agent, preserved across session updates for Reset. */
defaultValue?: string | null,
values: AgentConfigValue[],
via: AgentConfigVia,
};
@@ -1995,6 +1997,10 @@ export type AgentConfigValue = {
value: string,
name: string,
description: string | null,
/** Relative cost category from ACP `_meta` (`copilotPriceCategory`, e.g. `low`, `medium`, `high`, `very_high`). */
costCategory?: string | null,
/** Usage multiplier from ACP `_meta` (`copilotUsage`, e.g. `1x`, `0x`, `3x`). */
usageMultiplier?: string | null,
};
/** How a setting is changed. */
+2 -1
View File
@@ -21,6 +21,7 @@ import clsx from "clsx";
import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField, Select, Spinner, T } from "@/ui";
import { useSettingsForm } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { isPerModelOption } from "./composerModel";
import { providerIcon } from "./model";
import {
DISTRIBUTION_LABEL,
@@ -965,7 +966,7 @@ function ExternalLink({ url, label }: { url: string; label: string }) {
/** The options a new task of `agent` starts with: each the agent's own default unless chosen. */
export function defaultOptions(agent: AgentProvider, chosen: Record<string, string>): AgentConfigOption[] {
const base = agent.config.filter((o) => o.category !== "thought_level" && o.values.length > 1);
const base = agent.config.filter((o) => !isPerModelOption(o) && o.values.length > 1);
const modelOption = base.find((o) => o.category === "model");
const model = (modelOption && chosen[modelOption.id]) || modelOption?.current;
const levels = (model && agent.thoughtLevels?.[model]) || [];
+191 -58
View File
@@ -181,15 +181,12 @@
color: var(--fg-muted);
}
.modelEffortPopup {
width: min(340px, calc(100vw - 24px));
padding: 12px 0 6px;
}
.effortBlock {
padding: 0 12px 8px;
width: min(356px, calc(100vw - 24px));
padding: 6px 0;
}
/* The list takes the height of its models; with many it scrolls inside the popup. */
.modelEffortPopup .modelList {
max-height: 216px;
max-height: 240px;
}
.catalogFooter {
margin-top: 6px;
@@ -225,64 +222,200 @@
color: var(--fg-muted);
cursor: default;
}
.effortHeader {
.activeModelBar {
display: flex;
align-items: center;
gap: var(--space-2);
width: calc(100% - 12px);
margin: 2px 6px 6px;
padding: 6px 8px;
border: 0;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-strong);
text-align: left;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.activeModelBar:hover,
.activeModelBar:focus-visible {
outline: none;
background: var(--bg-hover);
}
.activeModelName {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
}
.activeModelMeta {
flex: none;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.activeModelGear {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
flex: none;
color: var(--fg-muted);
}
.modelRowConfigure {
display: grid;
place-items: center;
width: 20px;
height: 20px;
padding: 0;
border: 0;
border-radius: var(--radius-small);
background: transparent;
color: var(--fg-muted);
cursor: pointer;
}
.modelRowConfigure:hover,
.modelRowConfigure:focus-visible {
outline: none;
background: var(--bg-hover);
color: var(--fg-strong);
}
.costBadge {
flex: none;
padding: 1px 7px;
border-radius: var(--radius-popup);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
white-space: nowrap;
}
.costBadgeLow {
background: color-mix(in srgb, var(--success) 18%, var(--bg-elev));
color: var(--success);
}
.costBadgeHigh {
background: color-mix(in srgb, var(--warning) 20%, var(--bg-elev));
color: var(--warning);
}
/* Page 2: per-model configuration view. */
.modelDetail {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 6px 12px 8px;
}
.modelDetailHeader {
display: flex;
align-items: center;
gap: var(--space-1-5);
}
.modelDetailTitle {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-strong);
font-weight: 600;
}
.modelDetailActions {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
flex: none;
}
.pinnedButton {
color: var(--accent);
}
.detailSection {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.detailSectionLabel {
color: var(--fg-strong);
font-weight: 600;
font-size: var(--fs-small);
}
.detailRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}
.segmented {
display: flex;
align-items: stretch;
gap: var(--space-0-5);
padding: 2px;
border-radius: var(--radius-popup);
background: var(--bg-input);
box-shadow: inset 0 0 0 1px var(--border-strong);
}
.segment {
flex: 1 1 0;
min-width: 0;
height: 26px;
padding: 0 6px;
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--fg-secondary);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.segment:hover {
color: var(--fg-strong);
}
.segment:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.segmentActive {
background: var(--bg-floating-toolbar);
color: var(--fg-strong);
font-weight: 600;
}
.costCard {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: 8px 10px;
border-radius: var(--radius-popup);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.costCardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
}
.costCardTitle {
color: var(--fg-strong);
font-weight: 600;
font-size: var(--fs-small);
}
.costCardRow {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-3);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.effortValue {
.costCardValue {
color: var(--fg-strong);
}
.effortSlider {
--thumb: 14px;
margin-top: 8px;
}
.effortSlider input {
display: block;
width: 100%;
height: var(--thumb);
margin: 0;
appearance: none;
background: transparent;
}
.effortSlider input::-webkit-slider-runnable-track {
height: 4px;
border-radius: 2px;
background: linear-gradient(to right, var(--accent) var(--fill), var(--control-off) var(--fill));
}
.effortSlider input::-webkit-slider-thumb {
width: var(--thumb);
height: var(--thumb);
margin-top: calc((4px - var(--thumb)) / 2);
border-radius: 50%;
appearance: none;
background: var(--fg-on-accent);
box-shadow:
0 0 0 1px var(--border-button),
var(--shadow-tooltip);
}
.effortSlider input:focus-visible {
outline: none;
}
.effortSlider input:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 2px var(--focus-ring);
}
/* One dot per level, centred under the thumb's positions. */
.effortTicks {
display: flex;
justify-content: space-between;
padding: 0 calc(var(--thumb) / 2 - 2px);
margin-top: 4px;
}
.effortTicks > span {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--control-off);
}
.effortTicks > .effortTickActive {
background: var(--accent);
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.modePopup {
min-width: 200px;
+85 -13
View File
@@ -1,7 +1,12 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentConfigOption } from "@/bindings";
import { ConfigPickers, configPickerOptions } from "./ConfigPickers";
import { useAgents } from "./store";
beforeEach(() => {
useAgents.setState({ pinnedModels: [] });
});
const config = (values: AgentConfigOption["values"], category = "model"): AgentConfigOption => ({
id: "model",
@@ -46,6 +51,26 @@ describe("configPickerOptions", () => {
{ value: "a/One", label: "Custom", detail: "Description" },
]);
});
it("places pinned models in a top Pinned section and prepends usageMultiplier to detail", () => {
const options = configPickerOptions(
config([
{ value: "gpt-6-sol", name: "GPT-6 Sol", description: "Medium cost", usageMultiplier: "1x" },
{
value: "gemini-4-carbon",
name: "Gemini 4 Carbon",
description: "Powerful · Medium cost",
usageMultiplier: "1x",
},
]),
["gemini-4-carbon"],
);
expect(options).toEqual([
{ value: "__pinned__", label: "Pinned", section: true },
{ value: "gemini-4-carbon", label: "Gemini 4 Carbon", detail: "1x · Powerful · Medium cost", keywords: "" },
{ value: "__models__", label: "Models", section: true },
{ value: "gpt-6-sol", label: "GPT-6 Sol", detail: "1x · Medium cost", keywords: "" },
]);
});
});
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
@@ -276,22 +301,69 @@ describe("model and effort button", () => {
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
});
it("steps through the advertised effort levels and picks a model from the popup", () => {
it("navigates to the detail page for segmented effort, Reset, Pin, and cost badge", () => {
const onChange = vi.fn();
render(<ConfigPickers config={copilotConfig()} values={{ reasoning_effort: "high" }} onChange={onChange} />);
const cfg = copilotConfig().map((o) =>
o.id === "model"
? {
...o,
values: o.values.map((v) =>
v.value === "claude-sonnet-5.5" ? { ...v, costCategory: "medium", usageMultiplier: "1x" } : v,
),
}
: o.id === "reasoning_effort"
? { ...o, defaultValue: "medium" }
: o,
);
cfg.push({
id: "contextTier",
name: "Context Size",
category: "model_config",
description: null,
current: "long_context",
defaultValue: "default",
via: "option",
values: [value("default", "200K"), value("long_context", "1M")],
});
render(<ConfigPickers config={cfg} values={{ reasoning_effort: "high" }} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5high · 1M");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
const slider = within(dialog).getByRole("slider", { name: "Reasoning Effort" });
expect(slider).toHaveAttribute("max", "3");
expect(slider).toHaveValue("2");
expect(slider).toHaveAttribute("aria-valuetext", "high");
fireEvent.change(slider, { target: { value: "3" } });
expect(onChange).toHaveBeenLastCalledWith("reasoning_effort", "xhigh");
// The model list is in the popup itself, not behind a second dropdown.
expect(within(dialog).queryByRole("button", { name: "Model" })).not.toBeInTheDocument();
expect(within(dialog).getByText("Medium cost")).toBeVisible();
// Pick another model directly from Page 1.
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
expect(onChange).toHaveBeenLastCalledWith("model", "gpt-6-sol");
expect(screen.getByRole("dialog", { name: "Model & effort settings" })).toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
// Open Page 2 (detail configuration view) for the active model.
fireEvent.click(within(dialog).getByRole("button", { name: "Configure model" }));
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Reasoning Effort" });
expect(within(effortGroup).getByRole("radio", { name: "high" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(effortGroup).getByRole("radio", { name: "XHigh" }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "xhigh");
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
// Cost badge & multiplier render in the detail card.
expect(within(dialog).getByText("Medium cost")).toBeVisible();
expect(within(dialog).getByText("1x")).toBeVisible();
// Reset restores both effort and contextTier to their agent defaults.
onChange.mockClear();
fireEvent.click(within(dialog).getByRole("button", { name: "Reset to defaults" }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "medium");
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
// Pin model, navigate back to Page 1, and verify Pinned + Models sections appear.
fireEvent.click(within(dialog).getByRole("button", { name: "Pin model" }));
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
expect(within(listbox).getByText("Models")).toBeVisible();
});
it("filters the model list and picks the highlighted model with the keyboard", () => {
+398 -94
View File
@@ -1,44 +1,61 @@
/**
* Model, mode, approvals and thinking-effort controls for a composer's bottom row.
* With both a model and an effort option, one button shows both and opens the model
* list and an effort slider; with a mode and an on/off permissions option (Allow All),
* the mode menu carries the switch. Names and descriptions are the agent's own.
* With a model plus effort, model-config or cost metadata, one button shows the active
* summary and opens a two-page popup: a searchable model list (with pinned models and
* per-row configure buttons) and a per-model configuration view with segmented Effort
* Level, optional segmented Context Size, Reset / Pin actions, and a cost badge.
*/
import { useEffect, useRef, useState, type CSSProperties } from "react";
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { tx as rawTx, useTx } from "@/platform/i18n";
import { Icon, IconButton, Popup, Select, T, Toggle } from "@/ui";
import { SelectListbox, type SelectOption } from "@/ui/Select";
import { mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
import { isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
import { togglePinnedModel, useAgents } from "./store";
import styles from "./Composer.module.css";
export function configPickerOptions(option: AgentConfigOption): SelectOption[] {
export function configPickerOptions(option: AgentConfigOption, pinned: readonly string[] = []): SelectOption[] {
if (option.category !== "model") {
return option.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }));
}
const groups = new Map<string, SelectOption[]>();
for (const v of option.values) {
const pinnedSet = new Set(pinned);
const buildItem = (v: AgentConfigOption["values"][number]): { provider: string; opt: SelectOption } => {
const slash = v.value.indexOf("/");
const provider = slash >= 0 ? v.value.slice(0, slash) : "";
const path = slash >= 0 ? v.value.slice(slash + 1) : "";
const label = path ? path.slice(path.lastIndexOf("/") + 1) : v.name || v.value;
const detail = path ? [path, v.description].filter(Boolean).join(" · ") : (v.description ?? undefined);
const mult = v.usageMultiplier && !v.description?.startsWith(v.usageMultiplier) ? v.usageMultiplier : undefined;
const parts = [path || undefined, mult, v.description ?? undefined].filter((p): p is string => !!p);
const detail = parts.length > 0 ? parts.join(" · ") : undefined;
return { provider, opt: { value: v.value, label, detail, keywords: provider } };
};
const pinnedItems: SelectOption[] = [];
const groups = new Map<string, SelectOption[]>();
for (const v of option.values) {
const { provider, opt } = buildItem(v);
if (pinnedSet.has(v.value)) {
pinnedItems.push(opt);
continue;
}
const bucket = groups.get(provider) ?? [];
bucket.push({ value: v.value, label, detail, keywords: provider });
bucket.push(opt);
groups.set(provider, bucket);
}
const plain = groups.get("") ?? [];
groups.delete("");
return [
...(pinnedItems.length > 0 ? [{ value: "__pinned__", label: "Pinned", section: true }, ...pinnedItems] : []),
...(pinnedItems.length > 0 && plain.length > 0 ? [{ value: "__models__", label: "Models", section: true }] : []),
...plain,
...[...groups].flatMap(([provider, items]) => [{ value: provider, label: provider, section: true }, ...items]),
];
}
/** The on and off values of a two-state permissions option, or null when it has other values. */
/** The on and off values of a two-state permissions or fast option, or null when it has other values. */
function switchValues(option: AgentConfigOption): { on: string; off: string } | null {
const isFast = option.id === "fast" || option.category === "model_config";
const isFast = option.id === "fast" || (option.category === "model_config" && !isContextOption(option.id));
if (option.category !== "permissions" && !isFast) return null;
const on = option.values.find((v) => /^(on|true)$/i.test(v.value))?.value;
const off = option.values.find((v) => /^(off|false)$/i.test(v.value))?.value;
@@ -86,7 +103,8 @@ export function ConfigPickers({
const model = options.find((o) => o.category === "model");
const effort = config.find((o) => o.category === "thought_level" && o.values.length > 0);
const modelConfigs = modelConfigOptions(config);
const combinedModel = model && (modelRefresh || effort || modelConfigs.length > 0);
const hasCostMeta = model?.values.some((v) => !!v.costCategory || !!v.usageMultiplier) ?? false;
const combinedModel = model && (modelRefresh || effort || modelConfigs.length > 0 || hasCostMeta);
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
@@ -218,7 +236,7 @@ function ConfigPicker({
);
}
/** One button for the model and its effort; the popup has the model list and an effort slider. */
/** Two-page model & per-model configuration picker (searchable list + detail page). */
function ModelEffortPicker({
model,
modelValue,
@@ -240,22 +258,64 @@ function ModelEffortPicker({
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const [page, setPage] = useState<"list" | "detail">("list");
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLButtonElement>(null);
const unavailable = modelRefresh && modelValue !== null && !selected(model, modelValue);
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selected(model, modelValue)?.name ?? tx("Default"));
const selectedModel = selected(model, modelValue);
const unavailable = modelRefresh && modelValue !== null && !selectedModel;
const modelName = unavailable ? tx`${modelValue} (unavailable)` : (selectedModel?.name ?? tx("Default"));
const effortName = effort ? (selected(effort, effortValue)?.name ?? tx("Default")) : null;
const modelConfigSummary = modelConfigs
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
const contextValue = contextOption ? valueOf(contextOption) : null;
const contextLabel = contextOption ? (selected(contextOption, contextValue)?.name ?? null) : null;
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
const chipBadges = [effortName, contextLabel].filter((x): x is string => !!x);
const chipBadgeText = chipBadges.join(" · ");
const otherSummary = otherModelConfigs
.map((o) => {
const current = selected(o, valueOf(o));
return current ? `${tx(o.name)}: ${current.name}` : null;
})
.filter(Boolean)
.join(" · ");
const summary = [effortName ? `${tx(effort!.name)}: ${effortName}` : null, modelConfigSummary]
const summary = [
effortName ? `${tx(effort!.name)}: ${effortName}` : null,
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
otherSummary,
]
.filter(Boolean)
.join(" · ");
const canConfigureActive = !!(
effort ||
contextOption ||
otherModelConfigs.length > 0 ||
selectedModel?.costCategory ||
selectedModel?.usageMultiplier
);
const closePopup = () => {
setOpen(false);
setPage("list");
};
const openDetailFor = (targetModelValue: string) => {
if (targetModelValue !== modelValue) {
onChange(model.id, targetModelValue);
}
setPage("detail");
};
const sizerCandidates =
effort && !contextLabel
? [...new Set([chipBadgeText, ...effort.values.map((v) => v.name)])]
: chipBadgeText
? [chipBadgeText]
: [];
return (
<>
<button
@@ -266,19 +326,23 @@ function ModelEffortPicker({
aria-haspopup="dialog"
aria-expanded={open}
title={`${tx(model.name)}: ${modelName}${summary ? ` · ${summary}` : ""}`}
onClick={() => setOpen((v) => !v)}
onClick={() => {
setOpen((prev) => {
if (prev) setPage("list");
return !prev;
});
}}
>
<span className={styles.chipValue}>{modelName}</span>
{/* Every level's name in one cell, so the button keeps the widest one's width. */}
{effort && (
{chipBadgeText && (
<span className={styles.chipDetail}>
{[...new Set([effortName, ...effort.values.map((v) => v.name)])].map((name) => (
{sizerCandidates.map((text) => (
<span
key={name}
className={name === effortName ? undefined : styles.chipSizer}
aria-hidden={name !== effortName}
key={text}
className={text === chipBadgeText ? undefined : styles.chipSizer}
aria-hidden={text !== chipBadgeText}
>
{name}
{text}
</span>
))}
</span>
@@ -288,45 +352,89 @@ function ModelEffortPicker({
<Popup
open={open}
anchor={anchor}
onClose={() => setOpen(false)}
onClose={closePopup}
aria-label={tx("Model & effort settings")}
className={styles.modelEffortPopup}
>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{effort && (
<div className={styles.effortBlock}>
<div className={styles.effortHeader}>
<span className={styles.settingsLabel}>{tx(effort.name)}</span>
<span className={styles.effortValue}>{effortName}</span>
</div>
<EffortSlider option={effort} value={effortValue} onChange={(v) => onChange(effort.id, v)} />
</div>
)}
{modelConfigs.map((o) => (
<div key={o.id} className={styles.modeFooter}>
<span title={o.description ?? undefined}>{tx(o.name)}</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model)}
searchable
listClassName={styles.modelList}
onChoose={(v) => onChange(model.id, v)}
{page === "detail" && selectedModel ? (
<ModelDetailView
modelEntry={selectedModel}
effort={effort}
effortValue={effortValue}
contextOption={contextOption}
contextValue={contextValue}
otherModelConfigs={otherModelConfigs}
valueOf={valueOf}
pinned={pinnedModels.includes(selectedModel.value)}
onBack={() => setPage("list")}
onTogglePin={() => togglePinnedModel(selectedModel.value)}
onChange={onChange}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
<>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{canConfigureActive && selectedModel && (
<button
type="button"
className={styles.activeModelBar}
aria-label={tx("Configure model")}
onClick={() => setPage("detail")}
>
<span className={styles.activeModelName}>{modelName}</span>
<CostBadge category={selectedModel.costCategory} />
{chipBadgeText && <span className={styles.activeModelMeta}>{chipBadgeText}</span>}
<span className={styles.activeModelGear}>
<Icon name="sliders" size={13} />
<Icon name="chevron-right" size={12} />
</span>
</button>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.modeFooter}>
<span title={o.description ?? undefined}>{tx(o.name)}</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels)}
searchable
listClassName={styles.modelList}
onChoose={(v) => onChange(model.id, v)}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const showRowBadge = !!raw.costCategory && !raw.description;
return (
<>
{showRowBadge && <CostBadge category={raw.costCategory} />}
<button
type="button"
className={styles.modelRowConfigure}
aria-label={rawTx`Configure ${opt.label}`}
title={rawTx`Configure ${opt.label}`}
onClick={() => openDetailFor(opt.value)}
>
<Icon name="sliders" size={12} />
</button>
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</Popup>
</>
);
@@ -356,46 +464,242 @@ function ModelRefreshFooter({ refreshing, retryAtMs, error, onRefresh }: ModelRe
);
}
/** A stepped slider over the agent's effort levels, in the order the agent lists them. */
function EffortSlider({
option,
function CostBadge({ category }: { category: string | null | undefined }) {
if (!category) return null;
const label =
category === "free" ? (
<T>Free</T>
) : category === "low" ? (
<T>Low cost</T>
) : category === "medium" ? (
<T>Medium cost</T>
) : category === "high" ? (
<T>High cost</T>
) : category === "very_high" ? (
<T>Very high cost</T>
) : null;
if (!label) return null;
return (
<span
className={clsx(
styles.costBadge,
(category === "free" || category === "low") && styles.costBadgeLow,
(category === "high" || category === "very_high") && styles.costBadgeHigh,
)}
>
{label}
</span>
);
}
/** Page 2: per-model configuration view (segmented Effort, optional Context Size, Reset, Pin, and cost info). */
function ModelDetailView({
modelEntry,
effort,
effortValue,
contextOption,
contextValue,
otherModelConfigs,
valueOf,
pinned,
onBack,
onTogglePin,
onChange,
}: {
modelEntry: AgentConfigOption["values"][number];
effort?: AgentConfigOption;
effortValue: string | null;
contextOption?: AgentConfigOption;
contextValue: string | null;
otherModelConfigs: AgentConfigOption[];
valueOf: (o: AgentConfigOption) => string | null;
pinned: boolean;
onBack: () => void;
onTogglePin: () => void;
onChange: (option: string, value: string) => void;
}) {
const tx = useTx();
const defaultEffort = effort ? (effort.defaultValue ?? effort.current) : null;
const defaultContext = contextOption ? (contextOption.defaultValue ?? contextOption.current) : null;
const effortAtDefault = !effort || !defaultEffort || effortValue === defaultEffort;
const contextAtDefault = !contextOption || !defaultContext || contextValue === defaultContext;
const othersAtDefault = otherModelConfigs.every((o) => {
const def = o.defaultValue ?? o.current;
return !def || valueOf(o) === def;
});
const atDefaults = effortAtDefault && contextAtDefault && othersAtDefault;
const handleReset = () => {
if (effort && defaultEffort && effortValue !== defaultEffort) {
onChange(effort.id, defaultEffort);
}
if (contextOption && defaultContext && contextValue !== defaultContext) {
onChange(contextOption.id, defaultContext);
}
for (const o of otherModelConfigs) {
const def = o.defaultValue ?? o.current;
if (def && valueOf(o) !== def) {
onChange(o.id, def);
}
}
};
const compactEffort = (effort?.values.length ?? 0) >= 5;
const hasCostCard = !!(modelEntry.costCategory || modelEntry.usageMultiplier);
return (
<div className={styles.modelDetail}>
<div className={styles.modelDetailHeader}>
<IconButton
icon="arrow-left"
size="small"
aria-label={tx("Back to models")}
title={tx("Back to models")}
onClick={onBack}
/>
<span className={styles.modelDetailTitle} title={modelEntry.name}>
{modelEntry.name}
</span>
<div className={styles.modelDetailActions}>
<IconButton
icon="undo"
size="small"
disabled={atDefaults}
aria-label={tx("Reset to defaults")}
title={tx("Reset to defaults")}
onClick={handleReset}
/>
<IconButton
icon="pin"
size="small"
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
title={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
className={clsx(pinned && styles.pinnedButton)}
onClick={onTogglePin}
/>
</div>
</div>
{effort && effort.values.length > 0 && (
<div className={styles.detailSection}>
<div className={styles.detailSectionLabel}>
<T>Effort Level</T>
</div>
<SegmentedControl
ariaLabel={tx(effort.name)}
options={effort.values.map((v) => ({
value: v.value,
label: compactEffort && v.value === "xhigh" ? tx("XHigh") : v.name,
description: v.description ?? undefined,
}))}
value={effortValue ?? effort.values[0]!.value}
onChange={(v) => onChange(effort.id, v)}
/>
</div>
)}
{contextOption && contextOption.values.length > 0 && (
<div className={styles.detailSection}>
<div className={styles.detailSectionLabel}>
<T>Context Size</T>
</div>
<SegmentedControl
ariaLabel={tx("Context Size")}
options={contextOption.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={contextValue ?? contextOption.values[0]!.value}
onChange={(v) => onChange(contextOption.id, v)}
/>
</div>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.detailRow}>
<span className={styles.detailSectionLabel} title={o.description ?? undefined}>
{tx(o.name)}
</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
{hasCostCard && (
<div className={styles.costCard}>
<div className={styles.costCardHeader}>
<span className={styles.costCardTitle}>
<T>Pricing details</T>
</span>
<CostBadge category={modelEntry.costCategory} />
</div>
{modelEntry.usageMultiplier && (
<div className={styles.costCardRow}>
<span>
<T>Multiplier</T>
</span>
<span className={styles.costCardValue}>{modelEntry.usageMultiplier}</span>
</div>
)}
</div>
)}
</div>
);
}
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
function SegmentedControl({
ariaLabel,
options,
value,
onChange,
}: {
option: AgentConfigOption;
value: string | null;
ariaLabel: string;
options: readonly { value: string; label: string; description?: string }[];
value: string;
onChange: (value: string) => void;
}) {
const tx = useTx();
const steps = option.values;
const index = Math.max(
const groupRef = useRef<HTMLDivElement>(null);
const currentIndex = Math.max(
0,
steps.findIndex((v) => v.value === value),
options.findIndex((o) => o.value === value),
);
const last = steps.length - 1;
const fill = last > 0 ? (index / last) * 100 : 100;
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
const delta = e.key === "ArrowRight" ? 1 : -1;
const nextIndex = (currentIndex + delta + options.length) % options.length;
const next = options[nextIndex];
if (!next) return;
onChange(next.value);
const buttons = groupRef.current?.querySelectorAll<HTMLButtonElement>('button[role="radio"]');
buttons?.[nextIndex]?.focus();
};
return (
<div className={styles.effortSlider}>
<input
type="range"
min={0}
max={last}
step={1}
value={index}
aria-label={tx(option.name)}
aria-valuetext={steps[index]?.name}
title={steps[index]?.description ?? undefined}
style={{ "--fill": `${fill}%` } as CSSProperties}
onChange={(e) => {
const next = steps[Number(e.target.value)];
if (next && next.value !== value) onChange(next.value);
}}
/>
<div className={styles.effortTicks} aria-hidden>
{steps.map((v) => (
<span key={v.value} className={clsx(v.value === steps[index]?.value && styles.effortTickActive)} />
))}
</div>
<div ref={groupRef} role="radiogroup" aria-label={ariaLabel} className={styles.segmented} onKeyDown={onKeyDown}>
{options.map((opt, idx) => {
const active = idx === currentIndex;
return (
<button
key={opt.value}
type="button"
role="radio"
aria-checked={active}
tabIndex={active ? 0 : -1}
title={opt.description}
className={clsx(styles.segment, active && styles.segmentActive)}
onClick={() => {
if (opt.value !== value) onChange(opt.value);
}}
>
{opt.label}
</button>
);
})}
</div>
);
}
+5 -4
View File
@@ -88,10 +88,11 @@ it("switches model-specific levels and restores each draft effort before startin
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
await chooseModel("small");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const slider = screen.getByRole("slider", { name: "Reasoning" });
expect(slider).toHaveAttribute("max", "2");
expect(slider).toHaveAttribute("aria-valuetext", "minimal");
fireEvent.change(slider, { target: { value: "1" } });
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
const group = screen.getByRole("radiogroup", { name: "Reasoning" });
expect(group).toBeVisible();
expect(screen.getByRole("radio", { name: "minimal" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("radio", { name: "medium" }));
fireEvent.keyDown(document, { key: "Escape" });
await chooseModel("big");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
+14 -4
View File
@@ -349,12 +349,22 @@ export function atEdgeLine(text: string, caret: number, dir: -1 | 1): boolean {
return dir < 0 ? !text.slice(0, caret).includes("\n") : !text.slice(caret).includes("\n");
}
const matchesCategory = (o: AgentConfigOption, category: string) =>
o.category === category || (category === "model_config" && (o.category === "model_config" || o.id === "fast"));
export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.test(id);
/** Cursor / ACP model parameters (`fast`, `context`…), separate from the model id itself. */
/** Whether an option's available values and default belong to the selected model rather than the provider. */
export const isPerModelOption = (o: AgentConfigOption) =>
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
const matchesCategory = (o: AgentConfigOption, category: string) =>
o.category === category ||
(category === "model_config" &&
(o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id)));
/** Cursor / ACP model parameters (`fast`, `contextTier`…), separate from the model id itself. */
export function modelConfigOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
return config.filter((o) => o.category === "model_config" || o.id === "fast");
return config.filter(
(o) => o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id),
);
}
/** The settings shown in the composer: model, mode, collaboration mode, permissions, approvals, effort, fast. */
+3 -2
View File
@@ -215,7 +215,7 @@ it("retains cached model and effort choices after a command failure and retries
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
expect(screen.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "low");
expect(screen.getByRole("button", { name: "Configure model" })).toHaveTextContent("biglow");
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
@@ -241,7 +241,8 @@ it("preserves a valid remembered model and effort when discovery changes the def
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("biglow");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
expect(screen.getByRole("slider", { name: "Reasoning" })).toHaveAttribute("aria-valuetext", "low");
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
expect(screen.getByRole("radio", { name: "low" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
+17 -5
View File
@@ -32,6 +32,7 @@ import {
cursorModelDefaults,
emptyDraft,
isMentioned,
isPerModelOption,
toPrompt,
type ComposerDraft,
type FileRef,
@@ -125,12 +126,14 @@ interface AgentsState {
homeOpen: boolean;
/** Side conversations by task id: kept out of the task list, discarded when their view closes. */
ephemeral: ReadonlySet<string>;
pinnedModels: string[];
}
const DRAFT_KEY = "openidea.agents.draft.v2";
const HISTORY_KEY = "openidea.agents.history.v1";
const HISTORY_SIZE = 50;
const SESSION_LOCATION_KEY = "openidea.agents.sessionLocation.v1";
const PINNED_MODELS_KEY = "openidea.agents.pinnedModels.v1";
function load<T>(key: string, fallback: T): T {
try {
@@ -194,9 +197,17 @@ export const useAgents = create<AgentsState>(() => ({
lastTask: null,
homeOpen: false,
ephemeral: new Set<string>(),
pinnedModels: load<string[]>(PINNED_MODELS_KEY, []),
scrollPositions: new Map(),
}));
export function togglePinnedModel(modelValue: string) {
const current = useAgents.getState().pinnedModels;
const next = current.includes(modelValue) ? current.filter((m) => m !== modelValue) : [...current, modelValue];
useAgents.setState({ pinnedModels: next });
save(PINNED_MODELS_KEY, next);
}
export function updateDraft(patch: Partial<Draft>) {
const current = useAgents.getState().draft;
if (patch.provider && patch.provider !== current.provider) draftGeneration++;
@@ -230,12 +241,13 @@ export function draftConfig(
? [...offered, { ...priorModel, values: [] }]
: offered;
const config = source
.filter((o) => o.category !== "thought_level")
.filter((o) => !isPerModelOption(o))
.map((o) => {
const explicit = draft.config[o.id];
const choice = explicit ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current:
o.category === "model" && explicit !== undefined
? explicit
@@ -251,6 +263,7 @@ export function draftConfig(
const choice = draft.thoughtLevels?.[model]?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
};
}),
@@ -266,7 +279,8 @@ export function setDraftOption(id: string, value: string) {
draft,
);
const model = config.find((o) => o.category === "model")?.current;
if (model && config.find((o) => o.id === id)?.category === "thought_level") {
const target = config.find((o) => o.id === id);
if (model && target && isPerModelOption(target)) {
updateDraft({
thoughtLevels: {
...draft.thoughtLevels,
@@ -945,9 +959,7 @@ export async function startTask(
};
const config = options.flatMap((o) => {
const value =
o.category === "model" || o.category === "thought_level"
? o.current
: (draft.config[o.id] ?? defaults[o.id] ?? null);
o.category === "model" || isPerModelOption(o) ? o.current : (draft.config[o.id] ?? defaults[o.id] ?? null);
return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : [];
});
try {
+18
View File
@@ -47,6 +47,24 @@
"Unpin Agent Tasks": "Unpin Agent Tasks",
"New Agent Task Group": "New Agent Task Group",
"Refresh models": "Refresh models",
"Configure model": "Configure model",
"Configure {name}": "Configure {name}",
"Back to models": "Back to models",
"Reset to defaults": "Reset to defaults",
"Pin model": "Pin model",
"Unpin model": "Unpin model",
"Pinned": "Pinned",
"Models": "Models",
"Effort Level": "Effort Level",
"Context Size": "Context Size",
"Pricing details": "Pricing details",
"Free": "Free",
"Low cost": "Low cost",
"Medium cost": "Medium cost",
"High cost": "High cost",
"Very high cost": "Very high cost",
"Multiplier": "Multiplier",
"XHigh": "XHigh",
"model": "model",
"Refreshing…": "Refreshing…",
"Refresh in {seconds}s": "Refresh in {seconds}s",
+17
View File
@@ -41,6 +41,23 @@
"Unpin Agent Tasks": "取消固定 Agent 任务",
"New Agent Task Group": "新建 Agent 任务组",
"Refresh models": "刷新模型",
"Configure model": "配置模型",
"Configure {name}": "配置 {name}",
"Back to models": "返回模型列表",
"Reset to defaults": "重置为默认值",
"Pin model": "置顶模型",
"Unpin model": "取消置顶模型",
"Models": "模型",
"Effort Level": "思考强度",
"Context Size": "上下文大小",
"Pricing details": "价格详情",
"Free": "免费",
"Low cost": "低开销",
"Medium cost": "中等开销",
"High cost": "高开销",
"Very high cost": "极高开销",
"Multiplier": "倍率",
"XHigh": "超高",
"model": "模型",
"Refreshing…": "正在刷新…",
"Refresh in {seconds}s": "{seconds} 秒后可刷新",
+7
View File
@@ -158,3 +158,10 @@
.option {
display: contents;
}
.rowAction {
display: inline-flex;
align-items: center;
flex: none;
margin-left: 2px;
}
+31 -13
View File
@@ -60,6 +60,8 @@ export interface SelectListboxProps<V extends string = string> {
onChoose: (value: V) => void;
searchable?: boolean;
onPreview?: (value: V | null) => void;
/** Optional trailing action control rendered at the end of a non-section row. */
renderAction?: (option: SelectOption<V>) => ReactNode;
/** Extra class for the scrolling list, e.g. to set its height. */
listClassName?: string;
"aria-label"?: string;
@@ -72,6 +74,7 @@ export function SelectListbox<V extends string = string>({
onChoose,
searchable = false,
onPreview,
renderAction,
listClassName,
...aria
}: SelectListboxProps<V>) {
@@ -242,20 +245,35 @@ export function SelectListbox<V extends string = string>({
rowHeight={24}
aria-label={given(aria["aria-label"])}
className={clsx(styles.list, listClassName)}
renderItem={(o) => (
<span className={clsx(styles.option, o.disabled && styles.disabled)} aria-disabled={o.disabled || undefined}>
<span className={styles.check}>{o.value === value && <Icon name="check" size={12} />}</span>
{o.icon && <Icon name={o.icon} size={14} />}
<span className={clsx(styles.optionLabel, o.detail && styles.withDetail)} title={labelOf(o)}>
{labelOf(o)}
</span>
{o.detail && (
<span className={styles.detail} title={o.detail}>
{given(o.detail)}
renderItem={(o) => {
const action = !o.section && !o.disabled ? renderAction?.(o) : null;
return (
<span
className={clsx(styles.option, o.disabled && styles.disabled)}
aria-disabled={o.disabled || undefined}
>
<span className={styles.check}>{o.value === value && <Icon name="check" size={12} />}</span>
{o.icon && <Icon name={o.icon} size={14} />}
<span className={clsx(styles.optionLabel, o.detail && styles.withDetail)} title={labelOf(o)}>
{labelOf(o)}
</span>
)}
</span>
)}
{o.detail && (
<span className={styles.detail} title={o.detail}>
{given(o.detail)}
</span>
)}
{action && (
<span
className={styles.rowAction}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
{action}
</span>
)}
</span>
);
}}
/>
</div>
);