A local-first multi-agent app development platform, built on PenguinHarness
feat(web): the model picker is a dialog that opens on the current model (#847)
Yaowei Zheng735a20ee1c05
diff --git a/changelog/unreleased/2026-09-24-model-picker-modal.md b/changelog/unreleased/2026-09-24-model-picker-modal.mdnew file mode 100644index 00000000..c4a4cb5b--- /dev/null+++ b/changelog/unreleased/2026-09-24-model-picker-modal.md@@ -0,0 +1,30 @@+# Model picker opens as a dialog++- **Date:** 2026-09-24+- **Type:** feature+- **Scope:** `web`++[中文版](2026-09-24-model-picker-modal.zh.md)++The model picker is now a dialog. It opens on the current model and makes a model in any group a few keystrokes away.++## Layout++- A search field sits on top. Below it, a rail on the left lists the provider groups (logo, name, model count) in the order saved on the models page, and the right side lists the models of the active group.+- Typing in the search field replaces the right side with matches from every group, grouped by provider with the best matches first. Clearing the search returns to the group view.+- Each row is one line: the provider's logo, the display name, and right after the name the badges the model library's cards wear — Default, Vision, Fast, Free and a running discount — then the no-key mark and the current-model check. The upstream id is no longer printed; hovering a row shows it.+- At phone width the dialog fills the screen, and the rail becomes a strip of group chips that scrolls sideways above the list.++## Focus and keyboard++- The dialog opens with the current model's group active and the current model highlighted and scrolled into view. With nothing chosen yet, it opens on the first group that has a configured key.+- ↑/↓ move through the list or the rail, ←/→ or Tab switch between them, ⌥1–9 (Alt+1–9 outside macOS) jump to a group — not ⌘/Ctrl, which the browser keeps for switching tabs — Enter chooses and Esc closes. Typing always goes to the search field.++## Models without a key++- As before, models without a configured key are hidden unless they are selected or the Project default. A footer toggle, "Show models without a key (N)", lists them along with their groups and can turn them off again. When no model has a key, every model is listed.++## Where it opens++- The composer's model button, the model fields in Project settings, the schedule form, the company dialogs and the benchmark dialog open the dialog. Their triggers look the same, and each host receives the same selection as before.+- The in-session `/model` command opens the same dialog. A pick is still staged as a chip and applied when the message is sent.diff --git a/changelog/unreleased/2026-09-24-model-picker-modal.zh.md b/changelog/unreleased/2026-09-24-model-picker-modal.zh.mdnew file mode 100644index 00000000..e26f856f--- /dev/null+++ b/changelog/unreleased/2026-09-24-model-picker-modal.zh.md@@ -0,0 +1,30 @@+# 模型选择器改为弹窗++- **Date:** 2026-09-24+- **Type:** feature+- **Scope:** `web`++[English](2026-09-24-model-picker-modal.md)++模型选择器改为弹窗:打开时定位到当前模型,任意分组里的模型都能用几次按键找到并切换。++## 布局++- 顶部是搜索框;下方左侧的分组栏按模型页保存的分组顺序列出各厂商分组(logo、名称、模型数),右侧列出当前分组的模型。+- 在搜索框输入后,右侧改为跨全部分组的搜索结果,按厂商分组、最佳匹配在前;清空搜索即回到分组视图。+- 每个模型只占一行:厂商 logo、展示名,名称右侧紧跟模型库卡片的同款徽标(默认、视觉、快速、免费与当前折扣),行尾为未配置 key 标记与当前模型的勾选;不再显示上游 id,悬停该行即可看到。+- 手机宽度下弹窗全屏,分组栏变为列表上方可横向滚动的一排分组标签。++## 焦点与键盘++- 打开时当前模型所在分组处于选中状态,当前模型高亮并滚动到可见处;尚未选择模型时,定位到第一个已配置 key 的分组。+- ↑/↓ 在列表或分组栏内移动,←/→ 或 Tab 在两者之间切换,⌥1–9(macOS 以外为 Alt+1–9)跳到对应分组(不用 ⌘/Ctrl,浏览器用它们切换标签页),Enter 确认,Esc 关闭;任何时候打字都输入到搜索框。++## 未配置 key 的模型++- 与此前一致:未配置 key 的模型默认隐藏,当前选中的模型与 Project 默认模型除外。底栏的「显示未配置 key 的模型(N 个)」开关会连同其分组一并列出,并可再次关闭;没有任何模型配置 key 时列出全部模型。++## 入口++- 对话输入区的模型按钮,以及 Project 设置、定时任务表单、公司弹窗与评估弹窗中的模型字段都改为打开该弹窗;各处触发按钮外观不变,选中后得到的结果也与此前相同。+- 会话中的 `/model` 命令打开同一个弹窗;选中后仍先暂存为 chip,发送消息时才切换。diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 4ca10e0a..0ad8ece0 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -599,11 +599,24 @@ test("layout: mobile chat dropdowns stay inside the viewport", async ({ page })await close();await open("Thinking level", `thinking @${vp.width}`);await close();- await open("Choose model", `model @${vp.width}`);- // Reveal the key-less remainder — the widest state of the w-max panel — and re-check.+ // The model picker is a dialog, not a hanging menu: at phone width it fills the screen,+ // with the group rail folded into a chip strip that scrolls inside itself. Checked with+ // the key-less models revealed, the state with the most groups on that strip.+ await page.locator('button[aria-label="Choose model"]').click();+ const picker = page.getByRole("dialog", { name: "Choose model" });+ await expect(picker, `model @${vp.width}: dialog open`).toBeVisible();await page.getByRole("button", { name: /without a key/ }).click();- await checkPanel(`model show-all @${vp.width}`);- await close();+ await page.waitForTimeout(200); // let the pop-in animation settle before measuring+ const box = await picker.boundingBox();+ expect(box.x, `model @${vp.width}: dialog left edge`).toBeLessThanOrEqual(0.5);+ expect(box.width, `model @${vp.width}: dialog full width`).toBeGreaterThanOrEqual(vp.width - 1);+ expect(box.y, `model @${vp.width}: dialog top edge`).toBeLessThanOrEqual(0.5);+ const pd = await docWidths(page);+ expect(pd.scrollWidth, `model @${vp.width}: no horizontal overflow`).toBeLessThanOrEqual(+ pd.clientWidth,+ );+ await page.keyboard.press("Escape");+ await expect(picker).toHaveCount(0);await open("Choose agent", `agent @${vp.width}`);await close();await open("Workspace", `workspace @${vp.width}`);diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex 3d445800..079e19c0 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -539,9 +539,9 @@ function MembersSection({ projectId, isOwner }: { projectId: string; isOwner: bo* delete zone): the `[default_chat]` block (Agent / Workspace / approval mode / thinking* level) plus the Project's default model, laid out as a compact responsive two-column* grid. Workspace and model reuse the chat draft's own pickers — WorkspaceSelect (the- * dir browser) and ModelSelect (the composer's model dropdown) — with their `form`- * trigger variant, so the controls line up with the dialog's Input/Select while the- * POPOVER menus stay exactly the composer's.+ * dir browser) and ModelSelect (the composer's model picker) — with their `form`+ * trigger variant, so the controls line up with the dialog's Input/Select while what they+ * open stays exactly the composer's (the directory menu, the model-picker dialog).* The model default is SINGLE-SOURCED with the models page — the picker renders and writes* the same top-level `default_model` (via the narrow PUT /models/default route), never a* second key; changing it also releases the draft-cached model pin exactly as the models@@ -739,8 +739,8 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne</span>{models.models.length > 0 ? (<>- {/* The composer's model dropdown (provider logo + name + searchable grouped- panel); the default row carries the S.models.default marker. */}+ {/* The composer's model picker (provider logo + name, opening the model-picker+ dialog); the default row carries the S.models.default marker. */}<ModelSelectmodels={models.models}value={modelRef}diff --git a/packages/web/src/components/ui/badge.tsx b/packages/web/src/components/ui/badge.tsxindex 562a8d58..9059bea4 100644--- a/packages/web/src/components/ui/badge.tsx+++ b/packages/web/src/components/ui/badge.tsx@@ -10,7 +10,7 @@ import { toneSurface } from "../../lib/tone";* wrong at half the call sites. The class strings themselves still come from the shared status* tones, so a badge that *does* report a status matches every other mark for that state.*/-export type BadgeTone = "gray" | "brand" | "green" | "yellow" | "amber" | "red";+export type BadgeTone = "gray" | "brand" | "green" | "amber" | "red";const toneClass: Record<BadgeTone, string> = {gray: toneSurface.muted,@@ -18,10 +18,6 @@ const toneClass: Record<BadgeTone, string> = {// as prominent without claiming any severity ("default", "origin", "queued").brand: "bg-gray-200/80 text-gray-700 dark:bg-gray-700/60 dark:text-gray-200",green: toneSurface.success,- // Light-yellow, also outside the status vocabulary: a neutral informational tag (the "Free"- // model badge). It stays on the yellow palette so it reads as distinct from amber, which- // carries warning semantics (aborted stop_reason, the proxy-vision badge on the same card).- yellow: "bg-yellow-50 text-yellow-700 dark:bg-yellow-950 dark:text-yellow-300",amber: toneSurface.attention,red: toneSurface.danger,};diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsxindex 5aea5930..d3c6e19c 100644--- a/packages/web/src/components/ui/dropdown.tsx+++ b/packages/web/src/components/ui/dropdown.tsx@@ -155,7 +155,7 @@ export function Dropdown({/*** Up/Down walk the panel's items, wrapping at both ends (the standard menu idiom) —- * but only for plain menus. Two panels own their own keyboard model (model-select and+ * but only for plain menus. Some panels own their own keyboard model (PickerList and* the slash/skill pickers drive a highlighted-index list from an autofocused search* box), so this yields whenever an inner handler already consumed the key, and* whenever focus sits in a text field where the arrows belong to the caret.diff --git a/packages/web/src/components/ui/form-picker.tsx b/packages/web/src/components/ui/form-picker.tsxindex ec3209f6..60cd678a 100644--- a/packages/web/src/components/ui/form-picker.tsx+++ b/packages/web/src/components/ui/form-picker.tsx@@ -3,7 +3,8 @@* (controlBase + the shared size tier, sm by default — leading icon, truncating label, trailing* chevron) with a portaled dropdown hanging under its left edge. It is the single source of the* "form-variant" look shared by the model picker, the workspace picker and the schedule's- * session picker, so the three read identically and none re-hand-rolls the trigger.+ * session picker, so the three read identically and none re-hand-rolls the trigger. The model+ * picker opens a dialog instead of a menu, so it takes the trigger alone (FormPickerTrigger).** It owns only the trigger + Dropdown wiring; the menu body is the caller's `children`* (a searchable list, a directory browser, …), and open/close state stays with the caller@@ -16,23 +17,8 @@ import { controlBase } from "./field";import { sizeClass } from "./input";import type { ControlSize } from "./input";-export function FormPicker({- open,- setOpen,- leading,- label,- labelClassName = "",- muted = false,- title,- ariaLabel,- ariaHaspopup = "listbox",- disabled = false,- size = "sm",- menuClass,- children,-}: {- open: boolean;- setOpen: (open: boolean) => void;+/** The trigger's own props: everything FormPicker draws, minus the menu it hangs. */+export interface FormPickerTriggerProps {/** Leading visual (provider logo / folder icon), sized by the caller; omitted when there's none. */leading?: ReactNode;/** The selected value's display, or a placeholder (pair with `muted`). */@@ -44,9 +30,61 @@ export function FormPicker({title: string;ariaLabel: string;ariaHaspopup?: "listbox" | "dialog";+ /** Whether the thing it opens is open (announced as `aria-expanded`). */+ expanded: boolean;disabled?: boolean;/** Same size tier as Input/Select; sm is the form rung every picker sits at today. */size?: ControlSize;+ onClick: () => void;+}++/**+ * The form-variant trigger on its own, for a picker that opens a dialog rather than a hanging+ * menu (the model picker): the same button FormPicker draws, so both kinds of picker read+ * identically in a form.+ */+export function FormPickerTrigger({+ leading,+ label,+ labelClassName = "",+ muted = false,+ title,+ ariaLabel,+ ariaHaspopup = "listbox",+ expanded,+ disabled = false,+ size = "sm",+ onClick,+}: FormPickerTriggerProps) {+ return (+ <button+ type="button"+ title={title}+ aria-label={ariaLabel}+ aria-haspopup={ariaHaspopup}+ aria-expanded={expanded}+ disabled={disabled}+ onClick={onClick}+ className={`flex w-full items-center gap-2 text-left ${controlBase} ${sizeClass[size]} disabled:cursor-not-allowed disabled:opacity-60`}+ >+ {leading}+ <span className={`min-w-0 flex-1 truncate ${muted ? "text-gray-400" : ""} ${labelClassName}`}>+ {label}+ </span>+ <ChevronDown className="text-gray-400" />+ </button>+ );+}++export function FormPicker({+ open,+ setOpen,+ menuClass,+ children,+ ...trigger+}: Omit<FormPickerTriggerProps, "expanded" | "onClick"> & {+ open: boolean;+ setOpen: (open: boolean) => void;/** Width / origin classes for the dropdown panel (placement itself is measured from the trigger). */menuClass: string;/** The dropdown menu body. */@@ -58,26 +96,7 @@ export function FormPicker({setOpen={setOpen}menuClass={menuClass}portal={{ direction: "down", align: "left" }}- button={- <button- type="button"- title={title}- aria-label={ariaLabel}- aria-haspopup={ariaHaspopup}- aria-expanded={open}- disabled={disabled}- onClick={() => setOpen(!open)}- className={`flex w-full items-center gap-2 text-left ${controlBase} ${sizeClass[size]} disabled:cursor-not-allowed disabled:opacity-60`}- >- {leading}- <span- className={`min-w-0 flex-1 truncate ${muted ? "text-gray-400" : ""} ${labelClassName}`}- >- {label}- </span>- <ChevronDown className="text-gray-400" />- </button>- }+ button={<FormPickerTrigger {...trigger} expanded={open} onClick={() => setOpen(!open)} />}>{children}</Dropdown>diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 0bbba416..44712af8 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -6,9 +6,8 @@* immediately on change) + help text (to the right of approval mode) | context usage (ring* indicator) + Model + send (up arrow);* In draft state (Session not yet created), when models/onChangeModel are supplied, the model- * selector sits to the left of the send button (provider logo + name, popup opens **downward**,- * with a top quick-search box, an internal scroll cap to avoid overflowing the screen, and a- * configured-key-first list with a bottom "show all" row — see ModelSelect) — once+ * selector sits to the left of the send button (provider logo + name; it opens the model-picker+ * dialog — search, provider-group rail, configured-key-first listing — see ModelSelect) — once* the Session is created the model is locked, and the same spot switches to a read-only* logo + name display;* Draft state also renders a thinking-level picker left of the model selector (backed by the@@ -109,7 +108,8 @@ import { ZoomableImage } from "../../components/ui/image-zoom";import { ProviderLogo } from "../../components/ui/provider-logo";import { sameModelRef } from "../models/model-grouping";import { filterAgents, stagedSendRoute } from "./agent-handoff";-import { ModelMenuList, ModelSelect, PickerList, modelLabel } from "./model-select";+import { ModelSelect, PickerList, modelLabel } from "./model-select";+import { ModelPickerModal } from "./model-picker-modal";import { matchSlash, removeSlashToken } from "./slash-token";import { SELECTABLE_THINKING_LEVELS, thinkingLevelLabel } from "./thinking-level";import { BOOK_ICON, buildSkillsMessage, localizedShortText, skillSlashItems } from "./skill-use";@@ -135,13 +135,12 @@ import type { ComposerReference } from "../../lib/workspace-tree";import { ReferenceChip } from "./reference-chip";/**- * Agent candidate panel for the `/agent` switch picker — the agent-side counterpart of- * ModelMenuList, and now literally the same panel (PickerList: search, scroll cap, keyboard- * navigation, current-entry marker). Only the row differs: the Agent avatar (the same identity- * tile the draft Agent picker uses), the agentId in monospace — the id is what identifies an- * Agent everywhere else in the app — and the display name after it when it differs. The- * conversation's own Agent is marked like the model list marks the session's model; picking it- * is still a real action (a fresh conversation with the same Agent), not a no-op.+ * Agent candidate panel for the `/agent` switch picker, on the shared PickerList (search, scroll+ * cap, keyboard navigation, current-entry marker). The row is the Agent avatar (the same identity+ * tile the draft Agent picker uses), the agentId in monospace — the id is what identifies an Agent+ * everywhere else in the app — and the display name after it when it differs. The conversation's+ * own Agent is marked like the model list marks the session's model; picking it is still a real+ * action (a fresh conversation with the same Agent), not a no-op.*/function AgentMenuList({agents,@@ -186,10 +185,11 @@ function AgentMenuList({}/**- * Popup frame shared by the two `/` switch pickers (`/model`, `/agent`): the upward-opening- * panel and its title bar. It opens upward from the composer and is height-capped to the room- * actually measured above it (see upwardMaxH), so it can never render off-screen; the panel has- * no trigger button of its own, so dismissal (click-outside / Escape) is handled by the host.+ * Popup frame of the `/agent` switch picker: the upward-opening panel and its title bar (`/model`+ * opens the model-picker dialog instead). It opens upward from the composer and is height-capped to+ * the room actually measured above it (see upwardMaxH), so it can never render off-screen; the+ * panel has no trigger button of its own, so dismissal (click-outside / Escape) is handled by the+ * host.*/function SwitchPickerPanel({panelRef,@@ -988,13 +988,12 @@ export function ChatInput({const [slashIndex, setSlashIndex] = useState(0);// Slash token start where Escape closed the menu: it stays shut for that one token.const [slashDismissed, setSlashDismissed] = useState<number | null>(null);- // Switch pickers (opened by /model — session state — and /agent). Each command consumes its- // slash token immediately (same as /compact), so closing a picker — Escape, click outside, or- // the picked-current-model no-op — can never re-open the slash menu, and there is no stale- // token range to recompute at pick time; whatever text remains is the draft (and becomes the- // new session's first message once the staged switch is sent).+ // Switch pickers (opened by /model — session state, the model-picker dialog — and /agent, an+ // upward panel). Each command consumes its slash token immediately (same as /compact), so closing+ // a picker — Escape, click outside, or the picked-current-model no-op — can never re-open the+ // slash menu, and there is no stale token range to recompute at pick time; whatever text remains+ // is the draft (and becomes the new session's first message once the staged switch is sent).const [modelSwitchOpen, setModelSwitchOpen] = useState(false);- const modelSwitchRef = useRef<HTMLDivElement>(null);const [agentSwitchOpen, setAgentSwitchOpen] = useState(false);const agentSwitchRef = useRef<HTMLDivElement>(null);// Anchor for the popups that open upward, and the room actually available above them.@@ -1493,27 +1492,26 @@ export function ChatInput({const slashOpen = slashMatches.length > 0;const activeSlash = slashMatches[Math.min(slashIndex, slashMatches.length - 1)];- // Close a switch picker on click-outside / Escape (same convention as Dropdown; these panels- // have no trigger button of their own, so the handling lives here). Only one can be open at a- // time — the slash menu that opens them is suppressed while either is up.+ // Close the `/agent` picker on click-outside / Escape (same convention as Dropdown; the panel+ // has no trigger button of its own, so the handling lives here). The `/model` picker is a+ // Modal and closes itself — its overlay click and esc layer — so it is not handled here.useEffect(() => {- if (!modelSwitchOpen && !agentSwitchOpen) return;+ if (!agentSwitchOpen) return;// Dismissing the panel puts the caret back where the user was typing: the picker's search// box stole the focus when it opened, and without this it would be left on <body>.const closeAll = () => {- setModelSwitchOpen(false);setAgentSwitchOpen(false);textareaRef.current?.focus();};// globalThis.* event types: the React ones imported above would shadow the DOM ones here.const onClick = (e: globalThis.MouseEvent) => {- const panel = modelSwitchOpen ? modelSwitchRef.current : agentSwitchRef.current;+ const panel = agentSwitchRef.current;if (panel && !panel.contains(e.target as Node)) closeAll();};const onKey = (e: globalThis.KeyboardEvent) => {// `isComposing`: Escape while an IME candidate list is up means "drop the candidates",// not "close the picker". Closing there would be unrecoverable — the command already- // consumed its `/agent` / `/model` token, so the user's remaining draft is all they have+ // consumed its `/agent` token, so the user's remaining draft is all they have// and the picker is the only way back to the pick they were making.if (e.key === "Escape" && !e.isComposing) closeAll();};@@ -1523,7 +1521,7 @@ export function ChatInput({window.removeEventListener("mousedown", onClick);window.removeEventListener("keydown", onKey);};- }, [modelSwitchOpen, agentSwitchOpen]);+ }, [agentSwitchOpen]);/** Stage a model as the /model chip (null = drop it), keeping the draft cache in step. */const stageModel = (m: ModelInfo | null) => {@@ -1583,7 +1581,7 @@ export function ChatInput({// top edge sits well below the viewport's. A static `40vh` cap can't know that distance and// clipped the first rows on shorter windows, so measure the real gap when a menu opens.useEffect(() => {- if (!slashOpen && !modelSwitchOpen && !agentSwitchOpen) return;+ if (!slashOpen && !agentSwitchOpen) return;const measure = () => {const el = anchorRef.current;if (!el) return;@@ -1601,7 +1599,7 @@ export function ChatInput({measure();window.addEventListener("resize", measure);return () => window.removeEventListener("resize", measure);- }, [slashOpen, modelSwitchOpen, agentSwitchOpen]);+ }, [slashOpen, agentSwitchOpen]);/** Auto-grow the textarea (caps at roughly 6 lines, scrolls internally beyond that). */const autoGrow = () => {@@ -2082,29 +2080,27 @@ export function ChatInput({</div>)}- {/* /model switch picker (session state): reuses the draft model dropdown's list —- search + configured-key-first grouping + "show all"; the current model is marked and- picking it is a no-op. The /model token was already consumed when the command ran,- so cancelling (Escape / click outside) keeps the remaining draft and cannot re-open- the slash menu. A pick only stages the chip below — the switch happens on send. */}- {modelSwitchOpen && models && (- <SwitchPickerPanel- panelRef={modelSwitchRef}- maxHeight={upwardMaxH}+ {/* /model switch picker (session state): the same model-picker dialog the draft's model+ selector opens, on the session's model; picking it is a no-op. The /model token was+ already consumed when the command ran, so cancelling (Escape / overlay click) keeps+ the remaining draft and cannot re-open the slash menu, and the dialog hands focus back+ to the textarea it was opened from. A pick only stages the chip below — the switch+ happens on send. */}+ {models && (+ <ModelPickerModal+ open={modelSwitchOpen}+ onClose={() => setModelSwitchOpen(false)}title={S.chat.switchModelTitle}- >- <ModelMenuList- models={models}- value={modelRef}- {...(defaultModel !== undefined ? { defaultModel } : {})}- onPick={pickSwitchModel}- />- </SwitchPickerPanel>+ models={models}+ value={modelRef}+ {...(defaultModel !== undefined ? { defaultModel } : {})}+ onPick={pickSwitchModel}+ />)}- {/* /agent handoff picker: the same panel as the /model one above (title bar + search box- + capped list + keyboard navigation), and the same staged semantics — the pick becomes- the target chip, and sending is what hands the conversation over. */}+ {/* /agent handoff picker (title bar + search box + capped list + keyboard navigation),+ with the same staged semantics as /model — the pick becomes the target chip, and+ sending is what hands the conversation over. */}{agentSwitchOpen && (<SwitchPickerPanelpanelRef={agentSwitchRef}diff --git a/packages/web/src/features/chat/model-picker-logic.ts b/packages/web/src/features/chat/model-picker-logic.tsnew file mode 100644index 00000000..93dca967--- /dev/null+++ b/packages/web/src/features/chat/model-picker-logic.ts@@ -0,0 +1,285 @@+/**+ * Pure logic behind the model-picker modal (model-picker-modal.tsx), kept out of the component+ * so the node-only test suite can pin it without a DOM:+ *+ * - which models each provider group holds, under the same visibility rule the composer's+ * picker has always applied (visibleChatModels: configured-key models plus the selected and+ * the default one, everything once "show all" is on or when nothing has a key);+ * - which group is active when the modal opens;+ * - which marks a row wears;+ * - how search results rank and group across providers;+ * - how the arrow keys move between the group rail and the model list.+ *+ * `modelLabel` lives here too (model-select.tsx re-exports it for its existing importers), so+ * the modal and the triggers share it without importing each other.+ */+import type { ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";+import type { ModelInfo } from "@prismshadow/penguin-server/api";+import {+ discountedPrice,+ groupModelRows,+ hasConfiguredKey,+ isFreeModel,+ sameModelRef,+ visibleChatModels,+} from "../models/model-grouping";+import type { ModelCredentialRowLike, ModelRefValue, ModelRowLike } from "../models/model-grouping";+import { modelTags } from "../models/model-tags";+import type { ModelTag } from "../models/model-tags";++/**+ * Display label for a model: the display name, or falls back to the upstream id (model_id is+ * the raw field, no prefix parsing). Blank counts as absent — a name the user cleared is sent+ * as the empty string, which must read as the id rather than as an empty label.+ */+export function modelLabel(m: Pick<ModelRowLike, "displayName" | "modelId">): string {+ return m.displayName?.trim() || m.modelId;+}++/** One provider group as the picker shows it: the rail entry and the rows behind it. */+export interface PickerGroup<T> {+ /** The group key (the rows' `provider` field). */+ id: string;+ provider: ModelProviderInfo;+ rows: T[];+}++export interface PickerVisibility {+ /** The "show models without a key" toggle. */+ showAll: boolean;+ selected?: ModelRefValue | null;+ defaultModel?: ModelRefValue | null;+ /** The models page's stored group order (loadModelGroupOrder); empty = catalog order. */+ groupOrder?: readonly string[];+}++/** Visible rows regrouped by provider; groups with nothing visible are left off the rail. */+function regroup<T extends ModelCredentialRowLike>(+ visible: T[],+ groupOrder: readonly string[] | undefined,+): PickerGroup<T>[] {+ return groupModelRows(visible, "", groupOrder ?? [])+ .filter((g) => g.rows.length > 0)+ .map((g) => ({ id: g.provider.id, provider: g.provider, rows: g.rows }));+}++/** The rail: every group holding a visible model, in the user's group order. */+export function pickerGroups<T extends ModelCredentialRowLike>(+ models: T[],+ { showAll, selected, defaultModel, groupOrder }: PickerVisibility,+): PickerGroup<T>[] {+ return regroup(+ visibleChatModels(models, {+ showAll,+ query: "",+ selected: selected ?? null,+ defaultModel: defaultModel ?? null,+ ...(groupOrder !== undefined ? { groupOrder } : {}),+ }),+ groupOrder,+ );+}++/**+ * How many models the key filter hides under `query` — the number on the "show models without+ * a key" toggle. Zero once the toggle is on, and zero when nothing has a key (everything is+ * already listed then).+ */+export function hiddenModelCount<T extends ModelCredentialRowLike>(+ models: T[],+ { showAll, selected, defaultModel, groupOrder, query }: PickerVisibility & { query: string },+): number {+ if (showAll) return 0;+ const opts = {+ query,+ selected: selected ?? null,+ defaultModel: defaultModel ?? null,+ ...(groupOrder !== undefined ? { groupOrder } : {}),+ };+ return (+ visibleChatModels(models, { ...opts, showAll: true }).length -+ visibleChatModels(models, { ...opts, showAll: false }).length+ );+}++/**+ * The group active when the picker opens: the current model's group, so the modal opens on+ * what is already chosen; with nothing chosen (or a choice no longer in the list), the first+ * group that has a configured key — the one the user can actually run — and failing that the+ * first group. Null only when the rail is empty.+ */+export function initialGroupId<T extends ModelCredentialRowLike>(+ groups: readonly PickerGroup<T>[],+ value: ModelRefValue | null | undefined,+): string | null {+ const holding = groups.find((g) => g.rows.some((m) => sameModelRef(m, value)));+ if (holding) return holding.id;+ const keyed = groups.find((g) => g.rows.some(hasConfiguredKey));+ return (keyed ?? groups[0])?.id ?? null;+}++/**+ * The marks a picker row wears after its name — the models page's card marks (model-tags.ts),+ * read off the models endpoint's DTO: the Project default, vision (an unannotated entry counts+ * as supporting it, as everywhere else), fast mode, zero cost, and the saving in effect at+ * `now`. The vision proxy is left to the models page: it says nothing about which model to+ * chat with.+ */+export function pickerRowTags(+ m: Pick<ModelInfo, "provider" | "modelId" | "vision" | "fastMode" | "pricing" | "discount">,+ defaultModel: ModelRefValue | null | undefined,+ now: Date = new Date(),+): ModelTag[] {+ return modelTags({+ isDefault: sameModelRef(m, defaultModel),+ vision: m.vision !== false,+ fastMode: m.fastMode === true,+ free: isFreeModel(m.pricing),+ discount: discountedPrice(+ {+ provider: m.provider,+ modelId: m.modelId,+ ...(m.discount !== undefined ? { discount: m.discount } : {}),+ ...m.pricing,+ },+ now,+ ),+ });+}++/** Where a row's highlight lands when its group becomes active: the current model, else the top. */+export function entryRow<T extends ModelRowLike>(+ rows: readonly T[],+ value: ModelRefValue | null | undefined,+): number {+ const at = rows.findIndex((m) => sameModelRef(m, value));+ return at >= 0 ? at : 0;+}++/**+ * How well a row matches a query, lower is better: an exact name or id (0), a prefix (1), a+ * match at a word boundary (2), a match anywhere in the name or id (3), and a row that matches+ * only through its provider's name (4). It orders results and never filters them — the result+ * set stays exactly what matchesQuery lets through, so search finds what it always found.+ */+export function matchRank(row: ModelRowLike, query: string): number {+ const q = query.trim().toLowerCase();+ if (!q) return 0;+ let best = 4;+ for (const field of [row.displayName?.trim() ?? "", row.modelId]) {+ const f = field.toLowerCase();+ if (!f) continue;+ if (f === q) return 0;+ if (f.startsWith(q)) best = Math.min(best, 1);+ else if (atWordBoundary(f, q)) best = Math.min(best, 2);+ else if (f.includes(q)) best = Math.min(best, 3);+ }+ return best;+}++/** Whether `q` occurs in `f` right after a separator ("mini" in `gpt-5-mini`). */+function atWordBoundary(f: string, q: string): boolean {+ for (let i = f.indexOf(q, 1); i > 0; i = f.indexOf(q, i + 1)) {+ if (/[\s\-_/.:]/.test(f[i - 1]!)) return true;+ }+ return false;+}++/**+ * Search results across every group: the visible rows matching `query`, grouped by provider,+ * best matches first — rows within a group by rank, and groups by their best row. Ties keep the+ * library order (the user's group order, then in-group order), so equally good matches read in+ * the sequence the rail shows.+ */+export function searchPickerGroups<T extends ModelCredentialRowLike>(+ models: T[],+ { showAll, selected, defaultModel, groupOrder, query }: PickerVisibility & { query: string },+): PickerGroup<T>[] {+ const visible = visibleChatModels(models, {+ showAll,+ query,+ selected: selected ?? null,+ defaultModel: defaultModel ?? null,+ ...(groupOrder !== undefined ? { groupOrder } : {}),+ });+ const ranked = regroup(visible, groupOrder).map((g, order) => {+ const rows = g.rows+ .map((row, i) => ({ row, i, rank: matchRank(row, query) }))+ .sort((a, b) => a.rank - b.rank || a.i - b.i);+ return { group: { ...g, rows: rows.map((r) => r.row) }, order, best: rows[0]?.rank ?? 4 };+ });+ return ranked.sort((a, b) => a.best - b.best || a.order - b.order).map((r) => r.group);+}++/** Which half of the group view the arrow keys drive. */+export type PickerRegion = "rail" | "list";++/** Keyboard position in the group view: the region, the active group, the highlighted row. */+export interface PickerNav {+ region: PickerRegion;+ group: number;+ row: number;+}++export type PickerNavKey = "up" | "down" | "left" | "right" | "tab";++/**+ * One step through `count` entries with wrap-around; from nothing (-1), down lands on the first+ * entry and up on the last.+ */+export function stepIndex(index: number, count: number, delta: 1 | -1): number {+ if (count <= 0) return -1;+ if (index < 0 || index >= count) return delta === 1 ? 0 : count - 1;+ return (index + delta + count) % count;+}++/**+ * The group view's arrow keys. In the rail, up/down walk the groups (the list follows, its+ * highlight landing on `entry(group)`) and right/Tab step into the list; in the list, up/down+ * walk the rows and left/Tab step back to the rail. Both ends wrap.+ */+export function movePickerNav(+ nav: PickerNav,+ key: PickerNavKey,+ shape: {+ groupCount: number;+ rowCount: (group: number) => number;+ entry: (group: number) => number;+ },+): PickerNav {+ if (shape.groupCount === 0) return nav;+ if (nav.region === "rail") {+ if (key === "up" || key === "down") {+ const group = stepIndex(nav.group, shape.groupCount, key === "down" ? 1 : -1);+ return { region: "rail", group, row: shape.entry(group) };+ }+ if (key === "right" || key === "tab") return { ...nav, region: "list" };+ return nav;+ }+ if (key === "up" || key === "down") {+ return { ...nav, row: stepIndex(nav.row, shape.rowCount(nav.group), key === "down" ? 1 : -1) };+ }+ if (key === "left" || key === "tab") return { ...nav, region: "rail" };+ return nav;+}++/**+ * The group an ⌥1–9 (Alt+1–9 off macOS) chord jumps to, as a 0-based index, or null when the+ * event is not such a chord.+ *+ * Not ⌘/Ctrl+1–9: browsers reserve those for switching tabs and handle them before the page,+ * so the chord would leave the app instead of moving the picker. Alt reaches the page. The+ * digit is read from `code`, not `key`, because on macOS Option+1 types "¡" — the physical key+ * is the only stable thing about the chord.+ */+export function groupShortcutIndex(e: {+ code: string;+ metaKey: boolean;+ ctrlKey: boolean;+ altKey: boolean;+ shiftKey: boolean;+}): number | null {+ if (!e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return null;+ const m = /^Digit([1-9])$/.exec(e.code);+ return m === null ? null : Number(m[1]) - 1;+}diff --git a/packages/web/src/features/chat/model-picker-modal.tsx b/packages/web/src/features/chat/model-picker-modal.tsxnew file mode 100644index 00000000..5c1dabe9--- /dev/null+++ b/packages/web/src/features/chat/model-picker-modal.tsx@@ -0,0 +1,444 @@+/**+ * The model picker as a dialog: a search field on top, the provider groups down a rail on the+ * left and the active group's models on the right. Every model picker in the app opens it —+ * the composer's pill, the dialog forms' field (both in model-select.tsx) and the in-session+ * `/model` switch.+ *+ * - **Rows** read as the provider's logo, the model's name and its marks (pickerRowTags: the+ * models page's default / vision / fast / free / discount pills), then the no-key glyph and+ * the ✓. The upstream id is not printed; it is the row's tooltip, which also tells apart two+ * groups' models of the same name.+ * - **Opens on the current model**: its group is active and its row highlighted and scrolled+ * into view. With nothing chosen, the first group with a configured key is active.+ * - **Search** replaces the right side with matches from every group, grouped by provider,+ * best matches first (model-picker-logic.ts); clearing it returns to the group view. The+ * rail stays, and picking a group from it leaves the search.+ * - **Models without a key** follow the rule the dropdown always had (visibleChatModels):+ * hidden unless selected or the Project default, with a footer toggle that lists them —+ * their groups join the rail, each row marked by the struck-through key. When nothing has a+ * key, everything is listed and the toggle is not shown.+ * - **Keyboard**: the search field keeps focus the whole time and drives a highlight (the+ * combobox pattern, via `aria-activedescendant`), so typing always lands in it. ↑/↓ walk the+ * list or the rail, ←/→ or Tab switch between them, ⌥1–9 (Alt off macOS) jump to a group,+ * Enter chooses, Escape closes (the Modal's esc layer, so a picker opened from a dialog closes+ * alone). Rows and rail entries are not in the Tab order, and no click takes focus away+ * from the search field.+ * - **Phone width**: the dialog fills the screen and the rail becomes a strip of group chips+ * scrolling sideways above the list.+ *+ * The state (query, toggle, highlight) lives in the body, which Modal mounts only while open,+ * so each opening starts fresh on the current model.+ */+import { useEffect, useId, useMemo, useRef, useState } from "react";+import type { KeyboardEvent as ReactKeyboardEvent } from "react";+import type { ModelInfo, ModelRefDto } from "@prismshadow/penguin-server/api";+import { S } from "../../lib/strings";+import { ICON_SIZE } from "../../lib/icon-scale";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { CloseButton } from "../../components/ui/icons";+import { Modal } from "../../components/ui/modal";+import { noAutofill, panelSearchClass } from "../../components/ui/input";+import { ProviderLogo } from "../../components/ui/provider-logo";+import { hasConfiguredKey, sameModelRef } from "../models/model-grouping";+import { loadModelGroupOrder } from "../models/model-group-order";+import { TAG_SHAPE } from "../models/model-tags";+import { useProject } from "../../state/project";+import {+ entryRow,+ groupShortcutIndex,+ hiddenModelCount,+ initialGroupId,+ modelLabel,+ movePickerNav,+ pickerGroups,+ pickerRowTags,+ searchPickerGroups,+ stepIndex,+} from "./model-picker-logic";+import type { PickerGroup, PickerNavKey, PickerRegion } from "./model-picker-logic";++/**+ * "No key" marker for key-less rows: a key struck through by a prohibition slash (24x24 line+ * art, grayscale via currentColor, matching the approval-mode icon style).+ */+const NO_KEY_ICON =+ "M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4M2 2l20 20";++const NAV_KEYS: Record<string, PickerNavKey> = {+ ArrowUp: "up",+ ArrowDown: "down",+ ArrowLeft: "left",+ ArrowRight: "right",+ Tab: "tab",+};++function isMacPlatform(): boolean {+ return typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);+}++export interface ModelPickerModalProps {+ open: boolean;+ onClose: () => void;+ /** Names the dialog for assistive tech ("Choose model", "Switch model"). */+ title: string;+ models: ModelInfo[];+ /** Currently selected (provider, modelId) pair; null = not yet chosen. */+ value: ModelRefDto | null;+ defaultModel?: ModelRefDto;+ /** A row was chosen. The host closes the dialog (it owns `open`). */+ onPick: (m: ModelInfo) => void;+}++export function ModelPickerModal({ open, onClose, title, ...body }: ModelPickerModalProps) {+ return (+ <Modal+ open={open}+ onClose={onClose}+ title={title}+ headerless+ bare+ // Sized to its rows — a logo, a name and a few pills on one line — so the list does not+ // open an empty band between a name and its ✓. Full screen on a phone: the rail needs a+ // strip of its own above the list, and a bottom sheet leaves too little height for both.+ widthClass="sm:max-w-xl max-sm:rounded-none max-sm:border-0"+ >+ <ModelPickerBody {...body} onClose={onClose} />+ </Modal>+ );+}++function ModelPickerBody({+ models,+ value,+ defaultModel,+ onPick,+ onClose,+}: Omit<ModelPickerModalProps, "open" | "title">) {+ // The models page's dragged group order, read once per open (the body remounts on each), so+ // an order changed there is picked up on the next open without a reload.+ const { currentProject } = useProject();+ const projectId = currentProject?.projectId ?? null;+ const groupOrder = useMemo(() => loadModelGroupOrder(projectId), [projectId]);++ const [query, setQuery] = useState("");+ const [showAll, setShowAll] = useState(false);+ const searching = query.trim() !== "";+ const visibility = {+ showAll,+ selected: value,+ defaultModel: defaultModel ?? null,+ groupOrder,+ };+ const groups = pickerGroups(models, visibility);+ const results = searching ? searchPickerGroups(models, { ...visibility, query }) : [];+ const hidden = hiddenModelCount(models, { ...visibility, query });++ // Group-view position, by group id so it survives the rail changing under it (the toggle+ // adding or removing groups); a vanished group falls back to the opening rule.+ const [groupId, setGroupId] = useState(() => initialGroupId(groups, value));+ const [region, setRegion] = useState<PickerRegion>("list");+ const [row, setRow] = useState(() =>+ entryRow(groups.find((g) => g.id === groupId)?.rows ?? [], value),+ );+ // Search-view highlight over the flattened results; the top match until the arrows move it,+ // so "type a few letters, press Enter" takes the best match.+ const [searchRow, setSearchRow] = useState(0);++ let groupIndex = groups.findIndex((g) => g.id === groupId);+ if (groupIndex < 0) {+ const fallback = initialGroupId(groups, value);+ groupIndex = Math.max(+ 0,+ groups.findIndex((g) => g.id === fallback),+ );+ }+ const activeGroup: PickerGroup<ModelInfo> | undefined = groups[groupIndex];+ const groupRows = activeGroup?.rows ?? [];+ const rowIndex = Math.min(row, groupRows.length - 1);+ const flatResults = results.flatMap((g) => g.rows);+ const searchIndex = Math.min(searchRow, flatResults.length - 1);+ const highlighted: ModelInfo | undefined = searching+ ? flatResults[searchIndex]+ : region === "list"+ ? groupRows[rowIndex]+ : undefined;++ const idBase = useId();+ const listId = `${idBase}-list`;+ const optionId = (m: ModelInfo) =>+ `${idBase}-opt-${encodeURIComponent(`${m.provider}:${m.modelId}`)}`;+ const inputRef = useRef<HTMLInputElement>(null);++ // The opening scroll centres the current model; keyboard moves after that only nudge.+ const centeredRef = useRef(false);+ const scrollHighlight = (el: HTMLElement | null) => {+ if (!el) return;+ el.scrollIntoView({ block: centeredRef.current ? "nearest" : "center" });+ centeredRef.current = true;+ };+ // The active rail entry follows the keyboard too — sideways on the phone strip.+ const activeRailRef = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ activeRailRef.current?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [groupIndex]);++ const activateGroup = (index: number, nextRegion: PickerRegion) => {+ const g = groups[index];+ if (!g) return;+ setGroupId(g.id);+ setRow(entryRow(g.rows, value));+ setRegion(nextRegion);+ setQuery("");+ setSearchRow(0);+ };++ const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {+ const jump = groupShortcutIndex(e);+ if (jump !== null) {+ // Claimed even past the last group, so Option+digit never types its symbol (¡, ™, …)+ // into the search field while the picker is up.+ e.preventDefault();+ if (jump < groups.length) activateGroup(jump, "list");+ return;+ }+ if (e.target !== inputRef.current) {+ // Focus sits on the close button or the toggle (reached with Tab): typing goes to the+ // search field anyway — a printable key moved there lands in it.+ if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) inputRef.current?.focus();+ return;+ }+ if (e.nativeEvent.isComposing) {+ // Escape while an IME candidate list is up drops the candidates, not the dialog.+ if (e.key === "Escape") e.stopPropagation();+ return;+ }+ if (searching) {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ setSearchRow(stepIndex(searchIndex, flatResults.length, e.key === "ArrowDown" ? 1 : -1));+ } else if (e.key === "Enter") {+ e.preventDefault();+ if (highlighted) onPick(highlighted);+ }+ // ←/→ belong to the caret while there is text; Tab walks the dialog's controls.+ return;+ }+ const key = NAV_KEYS[e.key];+ if (key !== undefined) {+ e.preventDefault();+ const next = movePickerNav({ region, group: groupIndex, row: rowIndex }, key, {+ groupCount: groups.length,+ rowCount: (i) => groups[i]?.rows.length ?? 0,+ entry: (i) => entryRow(groups[i]?.rows ?? [], value),+ });+ setRegion(next.region);+ setRow(next.row);+ if (next.group !== groupIndex) setGroupId(groups[next.group]?.id ?? null);+ return;+ }+ if (e.key === "Enter") {+ e.preventDefault();+ if (region === "rail") setRegion("list");+ else if (highlighted) onPick(highlighted);+ }+ };++ // Discounts follow the clock (off-peak tiers); the body remounts per opening, so one reading+ // per render is as fresh as the rows need.+ const now = new Date();+ const renderRow = (m: ModelInfo, isHighlighted: boolean, onHover: () => void) => {+ const current = sameModelRef(m, value);+ const label = modelLabel(m);+ return (+ <li+ key={`${m.provider}:${m.modelId}`}+ id={optionId(m)}+ role="option"+ aria-selected={isHighlighted}+ ref={isHighlighted ? scrollHighlight : undefined}+ >+ <button+ type="button"+ tabIndex={-1}+ title={label === m.modelId ? label : `${label} · ${m.modelId}`}+ // Mouse movement, not mouseenter: rows scrolling under a resting pointer while the+ // keyboard drives the list must not steal the highlight.+ onMouseMove={isHighlighted ? undefined : onHover}+ onClick={() => onPick(m)}+ className={`flex w-full items-center gap-2 px-4 py-2 text-left transition-colors duration-150 ${+ current ? "text-gray-900 dark:text-gray-100" : "text-gray-700 dark:text-gray-300"+ }${isHighlighted ? " bg-gray-100 dark:bg-gray-800" : ""}`}+ >+ <ProviderLogo provider={m.provider} className="h-4 w-4 shrink-0" />+ {/* The marks follow the name rather than the row's far edge, so each reads as part of+ the model it describes; a long name truncates before they give way. */}+ <span className="flex min-w-0 flex-1 items-center gap-1.5">+ <span className={`min-w-0 truncate text-sm${current ? " font-medium" : ""}`}>+ {label}+ </span>+ {pickerRowTags(m, defaultModel, now).map((tag) => (+ <span+ key={tag.key}+ title={tag.title}+ className={`${TAG_SHAPE} shrink-0 ${tag.className}`}+ >+ {tag.label}+ </span>+ ))}+ </span>+ {!hasConfiguredKey(m) && (+ <span+ role="img"+ title={S.models.noKey}+ aria-label={S.models.noKey}+ className="shrink-0 text-gray-400 dark:text-gray-500"+ >+ <GlyphIcon d={NO_KEY_ICON} size={ICON_SIZE.inlineGlyph} />+ </span>+ )}+ <span className="w-3 shrink-0 text-center text-xs">{current ? "✓" : ""}</span>+ </button>+ </li>+ );+ };++ const mod = isMacPlatform() ? "⌥" : "Alt+";+ const showToggle = hidden > 0 || showAll;+ return (+ <div+ onKeyDown={onKeyDown}+ // The search field keeps focus through every click inside the dialog — a row, a rail+ // entry, the toggle, or the blank space around them, which would otherwise focus the+ // panel itself and leave the next keystroke with nowhere to go. Clicks still fire.+ onMouseDown={(e) => {+ if (e.target !== inputRef.current) e.preventDefault();+ }}+ // The Modal panel adds the bottom safe-area inset below this, so the phone height leaves+ // room for it rather than pushing the search field under the status bar.+ className="flex h-[calc(100dvh_-_env(safe-area-inset-bottom))] flex-col pt-[env(safe-area-inset-top)] sm:h-[min(32rem,80vh)] sm:pt-0"+ >+ <div className="flex shrink-0 items-center gap-2 border-b border-gray-200 px-3 py-2.5 dark:border-gray-800">+ <input+ ref={inputRef}+ autoFocus+ value={query}+ onChange={(e) => {+ setQuery(e.target.value);+ setSearchRow(0);+ }}+ placeholder={S.models.searchPlaceholder}+ aria-label={S.models.searchPlaceholder}+ role="combobox"+ aria-expanded="true"+ aria-controls={listId}+ aria-autocomplete="list"+ {...(highlighted ? { "aria-activedescendant": optionId(highlighted) } : {})}+ {...noAutofill}+ className={`${panelSearchClass} min-w-0 flex-1 px-2.5 py-1.5`}+ />+ <CloseButton onClose={onClose} />+ </div>++ <div className="flex min-h-0 flex-1 flex-col sm:flex-row">+ {/* Rail: a column beside the list, a sideways-scrolling strip of chips on a phone. */}+ <nav+ aria-label={S.modelPicker.groups}+ className="flex shrink-0 gap-1.5 overflow-x-auto border-b border-gray-100 px-3 py-2 sm:w-52 sm:flex-col sm:gap-0.5 sm:overflow-x-visible sm:overflow-y-auto sm:border-b-0 sm:border-r sm:p-2 dark:border-gray-800"+ >+ {groups.map((g, i) => {+ // No group is active in the results view: they span every group.+ const active = !searching && i === groupIndex;+ const keyboardHere = active && region === "rail";+ return (+ <button+ key={g.id}+ ref={active ? activeRailRef : undefined}+ type="button"+ tabIndex={-1}+ aria-current={active ? "true" : undefined}+ title={i < 9 ? `${g.provider.label} · ${mod}${i + 1}` : g.provider.label}+ onClick={() => activateGroup(i, "rail")}+ className={`flex shrink-0 items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-sm transition-colors duration-150 sm:w-full sm:rounded-md sm:border-transparent sm:py-1.5 sm:dark:border-transparent ${+ active+ ? "border-gray-300 bg-gray-200/70 font-medium text-gray-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"+ : "border-gray-200 text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"+ }${keyboardHere ? " ring-1 ring-inset ring-gray-400 dark:ring-gray-500" : ""}`}+ >+ <ProviderLogo provider={g.id} className="h-4 w-4 shrink-0" />+ <span className="min-w-0 truncate sm:flex-1 sm:text-left">{g.provider.label}</span>+ <span className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500">+ {g.rows.length}+ </span>+ </button>+ );+ })}+ </nav>++ <div+ id={listId}+ role="listbox"+ aria-label={+ searching+ ? S.models.searchPlaceholder+ : (activeGroup?.provider.label ?? S.chat.chooseModel)+ }+ className="min-h-0 flex-1 overflow-y-auto py-1"+ >+ {searching ? (+ flatResults.length === 0 ? (+ <p className="px-4 py-3 text-sm text-gray-400">{S.models.noSearchResults}</p>+ ) : (+ results.map((g) => (+ <ul key={g.id} role="group" aria-label={g.provider.label}>+ <li+ role="presentation"+ className="flex items-center gap-2 px-4 pb-1 pt-2.5 text-xs font-medium text-gray-500 dark:text-gray-400"+ >+ <ProviderLogo provider={g.id} className="h-4 w-4 shrink-0" />+ <span className="min-w-0 truncate">{g.provider.label}</span>+ <span className="tabular-nums text-gray-400 dark:text-gray-500">+ {g.rows.length}+ </span>+ </li>+ {g.rows.map((m) => {+ const at = flatResults.indexOf(m);+ return renderRow(m, at === searchIndex, () => setSearchRow(at));+ })}+ </ul>+ ))+ )+ ) : groups.length === 0 ? (+ <p className="px-4 py-3 text-sm text-gray-400">{S.models.empty}</p>+ ) : (+ <ul role="group" aria-label={activeGroup?.provider.label}>+ {groupRows.map((m, i) =>+ renderRow(m, region === "list" && i === rowIndex, () => {+ setRegion("list");+ setRow(i);+ }),+ )}+ </ul>+ )}+ </div>+ </div>++ {/* On a phone the bar exists only for the toggle: the keyboard legend is desktop-only. */}+ <div+ className={`${showToggle ? "flex" : "hidden sm:flex"} shrink-0 items-center gap-3 border-t border-gray-200 px-4 py-2 text-xs text-gray-400 dark:border-gray-800 dark:text-gray-500`}+ >+ {/* Models without a key: listed on request, as the dropdown's bottom row did. It turns+ back off too, since the rail grows by every key-less group while it is on. */}+ {showToggle && (+ <button+ type="button"+ onClick={() => setShowAll(!showAll)}+ className="shrink-0 rounded transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300"+ >+ {showAll ? S.modelPicker.hideModelsWithoutKey : S.models.showModelsWithoutKey(hidden)}+ </button>+ )}+ <span className="ml-auto hidden truncate sm:block">{S.modelPicker.hint(mod)}</span>+ </div>+ </div>+ );+}diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsxindex d17a36a1..c0b523b3 100644--- a/packages/web/src/features/chat/model-select.tsx+++ b/packages/web/src/features/chat/model-select.tsx@@ -1,64 +1,41 @@/**- * Model picker pieces, extracted from chat-input.tsx so the Project settings dialog's- * "new chat defaults" section can offer the same menu the chat composer uses (the panels- * are mechanical moves; the composer's trigger is unchanged, and a "form" trigger variant- * is added for dialog hosts — see ModelSelect):+ * Model picker pieces, extracted from chat-input.tsx so every host offers the same picker:* - PickerList: the generic candidate panel (search box, scroll cap, keyboard navigation,- * current-entry marker) shared with chat-input's `/agent` handoff picker;- * - ModelMenuList: the model candidate panel (grouped, key-configured-first, "show all"- * expander) shared by the draft dropdown and the in-session `/model` switch picker;- * - ModelSelect: the dropdown trigger (provider logo + name + chevron), pill or form style.+ * current-entry marker) used by chat-input's `/agent` handoff picker;+ * - ModelSelect: the model picker's trigger (provider logo + name + chevron), pill or form+ * style. Either opens the model-picker dialog (model-picker-modal.tsx), which the in-session+ * `/model` switch opens too.*/-import { useMemo, useState } from "react";+import { useState } from "react";import type { KeyboardEvent, ReactNode } from "react";import type { ModelInfo, ModelRefDto } from "@prismshadow/penguin-server/api";import { S } from "../../lib/strings";-import { Badge } from "../../components/ui/badge";-import { Dropdown } from "../../components/ui/dropdown";-import { FormPicker } from "../../components/ui/form-picker";-import { GlyphIcon } from "../../components/ui/glyph-icon";+import { FormPickerTrigger } from "../../components/ui/form-picker";import { ChevronDown } from "../../components/ui/icons";import { ICON_SIZE } from "../../lib/icon-scale";import { menuSearchClass, noAutofill } from "../../components/ui/input";import { ProviderLogo } from "../../components/ui/provider-logo";-import {- hasConfiguredKey,- isFreeModel,- sameModelRef,- visibleChatModels,-} from "../models/model-grouping";-import { loadModelGroupOrder } from "../models/model-group-order";-import { useProject } from "../../state/project";+import { sameModelRef } from "../models/model-grouping";+import { modelLabel } from "./model-picker-logic";+import { ModelPickerModal } from "./model-picker-modal";-/**- * Display label for a model: the display name, or falls back to the upstream id (model_id is- * the raw field, no prefix parsing). Blank counts as absent — a name the user cleared is sent- * as the empty string, which must read as the id rather than as an empty label.- */-export function modelLabel(m: ModelInfo): string {- return m.displayName?.trim() || m.modelId;-}+// Re-exported for the pages that label models (the models page, the Project and company+// dialogs); it lives beside the picker's pure logic so the dialog can share it without an+// import cycle back to this module.+export { modelLabel };/**- * "No key" marker for the model dropdown's key-less rows: a key struck through by a prohibition- * slash (24x24 line art, grayscale via currentColor, matching the approval-mode icon style).- */-const NO_KEY_ICON =- "M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4M2 2l20 20";--/**- * Candidate panel shared by every picker of this family (the model dropdown / `/model` switch- * picker and the `/agent` handoff picker): the search box, the internal scroll cap, the row- * chrome, the keyboard navigation and the "current entry" marker slot all live here, so the- * two pickers can differ only in what a row *contains* (provider logo vs Agent avatar) and in- * what they hang below the list (`footer`, e.g. the model list's "show all" expander).+ * Searchable candidate panel for the composer's switch pickers (today the `/agent` handoff+ * picker; the model picker grew into its own dialog): the search box, the internal scroll cap,+ * the row chrome, the keyboard navigation and the "current entry" marker slot all live here,+ * so a picker supplies only what a row *contains* and what hangs below the list (`footer`).** Keyboard navigation deliberately starts with **no** row highlighted: the search box is* autofocused, and pre-highlighting a row would repaint a panel that has looked the same since* before this control existed. ArrowDown/ArrowUp begin the navigation, and Enter/Tab commits —* the highlighted row if there is one, otherwise the top match, which is what makes "type a few* letters, press Enter" work. Escape is NOT handled here: each host closes its own panel at the- * window level (an IME-safe handler for the switch pickers, Dropdown's for the model dropdown).+ * window level (an IME-safe handler for the switch pickers).*/export function PickerList<T>({items,@@ -155,138 +132,18 @@ export function PickerList<T>({}/**- * Model candidate panel (search box + grouped list + "show all" expander) shared by the- * draft-state ModelSelect dropdown and the in-session `/model` switch picker. Search and- * expanded state are internal and reset by remount (both hosts only render the panel while- * open); the list is capped by an internal scroll (max-h-56) so it never overflows the- * viewport no matter how many models there are.- * Dropdown order mirrors the model library page (visibleChatModels): a top quick-search box- * (the model page's rule — filters by id / display name / provider name); by default only- * models with an API key are listed (hasConfiguredKey — a stored masked key or a masked env- * fallback, the same standard as the model page's key status; `envKey` is merely the NAME of a- * fallback env var and doesn't count on its own), with the selected and the default model- * always visible even without a key; a muted bottom row reveals the remaining key-less models- * (marked by a struck-through key icon, with the "no key" text in its title) without closing- * the menu or changing the selection — when no model has a key at all, everything is listed- * directly. Rows carry the provider logo, the light-yellow "Free" badge for zero-cost models- * (same as the model library card), the project-default marker, and the selected checkmark.- */-export function ModelMenuList({- models,- value,- defaultModel,- onPick,-}: {- models: ModelInfo[];- /** Currently selected (provider, modelId) pair; null = not yet chosen. */- value: ModelRefDto | null;- defaultModel?: ModelRefDto;- onPick: (m: ModelInfo) => void;-}) {- const [query, setQuery] = useState("");- // Expanded "show all" state: collapses back to key-configured models on each open (remount).- const [showAll, setShowAll] = useState(false);- // The model page's dragged group order, so "mirrors the model library page" keeps holding- // once a user has arranged their groups. Read here rather than threaded through every call- // site, once per open (both hosts render the panel only while open, so opening it remounts- // this) — an order changed on that page, in this tab or another, is picked up on the next- // open without a reload. Not on every render: the search box below re-renders this panel- // on each keystroke, and the Project context does so for reasons of its own.- const { currentProject } = useProject();- const projectId = currentProject?.projectId ?? null;- const groupOrder = useMemo(() => loadModelGroupOrder(projectId), [projectId]);- const visible = visibleChatModels(models, {- showAll,- query,- selected: value,- defaultModel,- groupOrder,- });- // How many models the key filter hides under the current query (0 when expanded): drives the bottom "show all" row.- const hiddenCount = showAll- ? 0- : visibleChatModels(models, {- showAll: true,- query,- selected: value,- defaultModel,- groupOrder,- }).length - visible.length;- return (- <PickerList- items={visible}- itemKey={(m) => `${m.provider}:${m.modelId}`}- isCurrent={(m) => sameModelRef(m, value)}- query={query}- onQueryChange={setQuery}- // Quick search: supports model id / display name / provider name- searchPlaceholder={S.models.searchPlaceholder}- emptyText={S.models.noSearchResults}- onPick={onPick}- renderRow={(m) => (- <>- <ProviderLogo provider={m.provider} className="h-4 w-4 shrink-0" />- <span className="min-w-0 flex-1 truncate">{modelLabel(m)}</span>- {/* Zero-cost rows (all three price buckets 0): same light-yellow "Free" badge as- the model library card, so free models stand out while picking. */}- {isFreeModel(m.pricing) && (- <span className="shrink-0">- <Badge tone="yellow">{S.models.freeBadge}</Badge>- </span>- )}- {/* Key-less rows (visible via show-all / selected / default / no-key-at-all) carry a- struck-through key icon (the "no key" text lives in the title/aria-label). */}- {!hasConfiguredKey(m) && (- <span- role="img"- title={S.models.noKey}- aria-label={S.models.noKey}- className="shrink-0 text-gray-400 dark:text-gray-500"- >- <GlyphIcon d={NO_KEY_ICON} size={13} />- </span>- )}- {sameModelRef(m, defaultModel) && (- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">- {S.models.default}- </span>- )}- </>- )}- // Bottom expander row (pinned below the scroll area, mirroring the search box on top):- // reveals the models hidden by the configured-key filter in place — the menu stays open- // and the selection is untouched.- {...(hiddenCount > 0- ? {- footer: (- <div className="border-t border-gray-100 dark:border-gray-800">- <button- type="button"- onClick={() => setShowAll(true)}- className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300"- >- {S.models.showModelsWithoutKey(hiddenCount)}- </button>- </div>- ),- }- : {})}- />- );-}--/**- * Model selector (the chat composer's bottom-toolbar dropdown, also hosted by the Project- * settings' new-chat-defaults section): the button shows the provider logo + name, and the- * menu opens **downward** — the draft card is vertically centered with room below. The- * candidate list itself is the shared ModelMenuList panel (search, key-configured-first- * grouping, Free badge, "show all" expander — documented there).+ * Model selector (the chat composer's bottom-toolbar trigger, also hosted by the Project+ * settings' new-chat-defaults section, the schedule form, the company dialogs and the benchmark+ * dialog): the button shows the provider logo + name and opens the model-picker dialog (search,+ * provider-group rail, key-configured-first listing, Free badge — documented there). A pick+ * closes the dialog and reports `{ provider, modelId }` through `onChange`.*- * Two trigger variants, one menu:+ * Two trigger variants, one dialog:* - "pill" (default): the composer's compact toolbar button — collapses to the logo alone- * under the card's own `@container` query, menu right-aligned;- * - "form": the shared FormPicker (full-width Input/Select-styled trigger, menu left-aligned- * under the control), used by every dialog host.+ * under the card's own `@container` query;+ * - "form": the shared form trigger (full-width, Input/Select-styled), used by every dialog+ * host. The picker opened from inside a dialog stacks above it as a second Modal, and Escape+ * closes only the picker.** `emptyLabel` is for the one kind of host where an unpicked model is a decision and not a* gap — the organization dialogs' "Project default"; see the prop.@@ -311,7 +168,7 @@ export function ModelSelect({/*** What the trigger reads while nothing is picked, for a host where "nothing" is itself a* choice rather than an unfinished one — the organization dialogs, where an empty model- * means "follow the Project's default". The menu still offers models only, so such a host+ * means "follow the Project's default". The picker still offers models only, so such a host* carries its own way back to the empty value; here the label is grayed as a placeholder* and the provider logo is dropped, since no provider is being named.*/@@ -328,8 +185,12 @@ export function ModelSelect({className="h-4 w-4 shrink-0"/>);- const menu = (- <ModelMenuList+ const isDisabled = disabled || models.length === 0;+ const picker = (+ <ModelPickerModal+ open={open}+ onClose={() => setOpen(false)}+ title={S.chat.chooseModel}models={models}value={value}{...(defaultModel !== undefined ? { defaultModel } : {})}@@ -342,48 +203,42 @@ export function ModelSelect({// Form: the shared full-width trigger (same look as Input/Select), used by every dialog picker.if (variant === "form") {return (- <FormPicker- size="sm"- open={open}- setOpen={setOpen}- leading={logo}- label={label}- muted={unset}- title={`${S.chat.chooseModel}:${label}`}- ariaLabel={S.chat.chooseModel}- ariaHaspopup="listbox"- disabled={disabled || models.length === 0}- menuClass="w-max min-w-56 origin-top-left"- >- {menu}- </FormPicker>+ <>+ <FormPickerTrigger+ size="sm"+ expanded={open}+ onClick={() => setOpen(true)}+ leading={logo}+ label={label}+ muted={unset}+ title={`${S.chat.chooseModel}:${label}`}+ ariaLabel={S.chat.chooseModel}+ ariaHaspopup="dialog"+ disabled={isDisabled}+ />+ {picker}+ </>);}- // Pill: the composer's compact toolbar button — the panel's right edge docks to it; portal- // placement then clamps both edges inside the viewport.+ // Pill: the composer's compact toolbar button.return (- <Dropdown- open={open}- setOpen={setOpen}- menuClass="w-max min-w-56 origin-top-right"- portal={{ direction: "down", align: "right" }}- button={- <button- type="button"- title={`${S.chat.chooseModel}:${label}`}- aria-label={S.chat.chooseModel}- disabled={disabled || models.length === 0}- onClick={() => setOpen(!open)}- className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- {logo}- {/* When the card is narrower than @md, only the provider logo remains (title shows the full name). */}- <span className="hidden min-w-0 truncate @md:block">{label}</span>- <ChevronDown size={ICON_SIZE.caretDense} />- </button>- }- >- {menu}- </Dropdown>+ <>+ <button+ type="button"+ title={`${S.chat.chooseModel}:${label}`}+ aria-label={S.chat.chooseModel}+ aria-haspopup="dialog"+ aria-expanded={open}+ disabled={isDisabled}+ onClick={() => setOpen(true)}+ className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ >+ {logo}+ {/* When the card is narrower than @md, only the provider logo remains (title shows the full name). */}+ <span className="hidden min-w-0 truncate @md:block">{label}</span>+ <ChevronDown size={ICON_SIZE.caretDense} />+ </button>+ {picker}+ </>);}diff --git a/packages/web/src/features/models/model-grouping.ts b/packages/web/src/features/models/model-grouping.tsindex 3182b910..f326140a 100644--- a/packages/web/src/features/models/model-grouping.ts+++ b/packages/web/src/features/models/model-grouping.ts@@ -127,7 +127,7 @@ export function groupModelRows<T extends ModelRowLike>(}/**- * Flattens the library grouping into one ordered list (the chat model dropdown uses this):+ * Flattens the library grouping into one ordered list (the chat model picker uses this):* rows ordered exactly as the model page shows them — built-in provider groups in* MODEL_PROVIDERS order (custom last), then user-defined groups, with `groupOrder` applied* on top; in-group row order preserved. Passing the page's stored order here is what keeps@@ -354,10 +354,10 @@ export interface VisibleChatModelsOptions {}/**- * Candidate list for the chat model dropdown: library order → keep only models with a key+ * Candidate list for the chat model picker: library order → keep only models with a key* (hasConfiguredKey: stored or env-backed; plus the selected and the default model, unless* showAll) → the query then filters whatever is visible. When NO model has a key, the filter- * degrades to showAll (everything listed), so the dropdown is never uselessly empty.+ * degrades to showAll (everything listed), so the picker is never uselessly empty.*/export function visibleChatModels<T extends ModelCredentialRowLike>(models: T[],diff --git a/packages/web/src/features/models/model-tags.ts b/packages/web/src/features/models/model-tags.tsnew file mode 100644index 00000000..10e941bf--- /dev/null+++ b/packages/web/src/features/models/model-tags.ts@@ -0,0 +1,93 @@+/**+ * The standing marks a model carries wherever it is listed — the models page's cards and the+ * model picker's rows — so the two agree on which marks exist, what they say, their order and+ * their ink.+ *+ * Every mark wears one small neutral pill — the same faint border whatever it says — and the+ * hue survives only in the text. Six marks filling six coloured chips turned a row of tags into+ * confetti; on a list whose job is scanning names, the marks are meant to be noticed second.+ *+ * Three inks, so the row groups instead of enumerating: what the model IS (its default status),+ * what it CAN do, and what it COSTS. Identity is carried by the words in every case — the ink+ * only sorts them at a glance, and never alone says which mark this is.+ *+ * These are identities, not judgements, which is why they are spelled here instead of in+ * `lib/tone.ts`, whose five tones each rate a thing's state — the same reason+ * `category-colors.ts` and `update-dot.tsx` keep their own colours. Contrast against the+ * surfaces a mark sits on (white and gray-50 in light; this app's overridden gray-950 `#000000`+ * and gray-900 `#0d0d0d` in dark) clears 4.5:1 for every ink; the shared border is decorative,+ * so it is not held to 3:1.+ */+import { S } from "../../lib/strings";+import type { DiscountedPrice } from "./model-grouping";++/** The pill itself: no fill at all, so a row of marks sits on its row rather than on top of it. */+export const TAG_SHAPE =+ "whitespace-nowrap rounded-full border border-gray-200 px-1.5 text-[10px] font-medium leading-[15px] dark:border-gray-700";++export const TAG_INK = {+ /** This model's standing in the Project. */+ status: "text-brand-700 dark:text-brand-300",+ /** What it can do. */+ capability: "text-emerald-700 dark:text-emerald-400",+ /** What it costs. */+ price: "text-amber-700 dark:text-amber-400",+} as const;++export interface ModelTag {+ key: "default" | "vision" | "visionModel" | "fastMode" | "free" | "discount";+ label: string;+ /** Hover text, for a mark whose word needs a sentence behind it (a discount's terms). */+ title?: string;+ /** One of TAG_INK. */+ className: string;+}++/** What a list knows about one model, from which its marks follow. */+export interface ModelTagFacts {+ /** The Project's default model. */+ isDefault: boolean;+ /** Accepts image input (the effective annotation: unset counts as supported). */+ vision: boolean;+ /** The Project's vision proxy for read_file. Only the models page shows it. */+ isVisionModel?: boolean;+ /** Fast mode (premium serving tier) is on for this entry. */+ fastMode?: boolean;+ /** Zero-cost (isFreeModel). */+ free: boolean;+ /** The saving that applies right now (discountedPrice); absent when none does. */+ discount?: DiscountedPrice | undefined;+}++/**+ * Every mark `facts` earns, in a fixed order rather than by which happen to be true, so the eye+ * can learn where to look: what this Project chose (default, vision proxy) before what the+ * model is (vision, fast, free) before what it costs today (the discount).+ */+export function modelTags(facts: ModelTagFacts): ModelTag[] {+ const { discount } = facts;+ const tags: Array<ModelTag | false | undefined> = [+ facts.isDefault && { key: "default", label: S.models.default, className: TAG_INK.status },+ facts.vision && { key: "vision", label: S.models.visionBadge, className: TAG_INK.capability },+ facts.isVisionModel && {+ key: "visionModel",+ label: S.models.visionModelBadge,+ className: TAG_INK.capability,+ },+ facts.fastMode && {+ key: "fastMode",+ label: S.models.fastModeBadge,+ className: TAG_INK.capability,+ },+ facts.free && { key: "free", label: S.models.freeBadge, className: TAG_INK.price },+ discount && {+ key: "discount",+ label: S.models.discountBadge(discount.percent),+ title: discount.peak+ ? S.models.offPeakTitle(discount.percent, discount.peak)+ : S.models.discountTitle(discount.percent),+ className: TAG_INK.price,+ },+ ];+ return tags.filter((tag): tag is ModelTag => !!tag);+}diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 01fa3fa9..8c4c4160 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -109,6 +109,7 @@ import {loadModelGroupOrder,saveModelGroupOrder,} from "./model-group-order";+import { TAG_INK, TAG_SHAPE, modelTags } from "./model-tags";import { protocolPathForModel } from "./protocol-path";import { ProtocolSuffixMenu } from "./protocol-suffix";import {@@ -2059,35 +2060,6 @@ function AddGroupDialog({// Model card// ----------------------------------------------------------------------------/**- * Card tag palette. Every mark wears one small neutral pill — the same faint surface and border- * whatever it says — and the hue survives only in the text. Six marks filling six coloured- * chips turned a row of tags into confetti; on a page whose job is scanning names, the marks- * are meant to be noticed second.- *- * Three inks, so the row groups instead of enumerating: what the model IS (its default status),- * what it CAN do, and what it COSTS. Identity is carried by the words in every case — the ink- * only sorts them at a glance, and never alone says which mark this is.- *- * These are identities, not judgements, which is why they are spelled here instead of in- * `lib/tone.ts`, whose five tones each rate a thing's state — the same reason- * `category-colors.ts` and `update-dot.tsx` keep their own colours. Contrast against the- * surfaces a card sits on (white and gray-50 in light; this app's overridden gray-950 `#000000`- * and gray-900 `#0d0d0d` in dark) clears 4.5:1 for every ink; the shared border is decorative,- * so it is not held to 3:1.- */-/** The pill itself: no fill at all, so a row of marks sits on the card rather than on top of it. */-const TAG_SHAPE =- "whitespace-nowrap rounded-full border border-gray-200 px-1.5 text-[10px] font-medium leading-[15px] dark:border-gray-700";-const TAG_INK = {- /** This model's standing in the Project. */- status: "text-brand-700 dark:text-brand-300",- /** What it can do. */- capability: "text-emerald-700 dark:text-emerald-400",- /** What it costs. */- price: "text-amber-700 dark:text-amber-400",-} as const;-/*** Card: display name + lifetime Token spend + status badges; context / pricing / key status folded* into one line of small text; group speed-test results (TTFT / TPS, tone-colored) ride the@@ -2137,75 +2109,21 @@ function ModelCard({}: { cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output };/**- * Every standing mark this row carries, in one horizontal row of its own.+ * Every standing mark this row carries (model-tags.ts, shared with the model picker's rows),+ * in one horizontal row of its own.** They had been sharing the title's line, where each was width the model's NAME had to give* up — a long name truncated to make room for a mark that could have been read anywhere. A* row of their own costs one line and gives the name the whole of the first.- *- * Order is fixed rather than by which happen to be true, so the eye can learn where to look:- * what this Project chose (default, vision proxy) before what the model is (vision, fast,- * free) before what it costs today (the discount).*/- const tags: Array<{ key: string; label: string; title?: string; className: string }> = [- ...(isDefault- ? [- {- key: "default",- label: S.models.default,- className: TAG_INK.status,- },- ]- : []),- ...(row.vision- ? [- {- key: "vision",- label: S.models.visionBadge,- className: TAG_INK.capability,- },- ]- : []),- ...(isVisionModel- ? [- {- key: "visionModel",- label: S.models.visionModelBadge,- className: TAG_INK.capability,- },- ]- : []),- ...(row.fastMode- ? [- {- key: "fastMode",- label: S.models.fastModeBadge,- className: TAG_INK.capability,- },- ]- : []),- ...(isFreeModel(row)- ? [- {- key: "free",- label: S.models.freeBadge,- className: TAG_INK.price,- },- ]- : []),- ...(discount- ? [- {- key: "discount",- label: S.models.discountBadge(discount.percent),- title: discount.peak- ? S.models.offPeakTitle(discount.percent, discount.peak)- : S.models.discountTitle(discount.percent),- className: TAG_INK.price,- },- ]- : []),- ];+ const tags = modelTags({+ isDefault,+ vision: row.vision,+ isVisionModel,+ fastMode: row.fastMode,+ free: isFreeModel(row),+ discount,+ });const priceLine = (a: string, b: string, c: string): string =>`${displayPrice(a, currency)} / ${displayPrice(b, currency)} / ${displayPrice(c, currency)}`;diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex f2db8a9f..33a4b499 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -439,6 +439,11 @@ export const en: Strings = {hint: "Ctrl+P / Ctrl+Shift+P (⌘P) to toggle · ↑↓ to select · Enter to run",harnessHistory: "Harness history",},+ modelPicker: {+ groups: "Model groups",+ hideModelsWithoutKey: "Hide models without a key",+ hint: (mod: string): string => `←→ groups / models · ${mod}1–9 jump to a group`,+ },workflows: {tabsLabel: "Chat and workflows",chatTab: "Chat",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 263ab0a9..90bb469b 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -495,6 +495,18 @@ export const zh = {hint: "Ctrl+P / Ctrl+Shift+P(⌘P)切换 · ↑↓ 选择 · Enter 执行",harnessHistory: "Harness 历史",},+ modelPicker: {+ /** Accessible name of the dialog's provider-group rail. */+ groups: "模型分组",+ /** Footer toggle while models without a key are listed: turns the listing back off. */+ hideModelsWithoutKey: "隐藏未配置 key 的模型",+ /**+ * Footer keyboard legend; `mod` is "⌥" on macOS and "Alt+" elsewhere. Only the two moves a+ * list does not suggest by itself — ↑↓, Enter and Esc go without saying, and the footer+ * shares its line with the key-less toggle.+ */+ hint: (mod: string): string => `←→ 切换分组与列表 · ${mod}1–9 跳到分组`,+ },workflows: {tabsLabel: "聊天与工作流",chatTab: "聊天",@@ -1574,7 +1586,7 @@ export const zh = {* which is what identifies the key to the reader.*/readFromEnv: "读取自环境变量",- /** Chat model dropdown's bottom expander row: reveals the models hidden by the configured-key filter. */+ /** Model picker's footer toggle: lists the models hidden by the configured-key filter. */showModelsWithoutKey: (n: number): string => `显示未配置 key 的模型(${n} 个)`,modelIdExists: "该模型 id 已存在",pricingAllOrNone: "三项价格需一并填写",diff --git a/packages/web/test/model-picker.test.ts b/packages/web/test/model-picker.test.tsnew file mode 100644index 00000000..9dd8df65--- /dev/null+++ b/packages/web/test/model-picker.test.ts@@ -0,0 +1,272 @@+/**+ * The model-picker dialog's pure logic (model-picker-logic.ts): which groups the rail shows+ * and how the key-less models stay reachable, which group is active on open, which marks a+ * row wears, how search ranks and groups results across providers, and how the keyboard moves+ * between the rail and the list. A short source contract pins what the node suite cannot+ * render: every host opens the dialog, the dialog is the shared Modal rather than an overlay+ * of its own, and a row reads as logo, name and marks rather than as an upstream id.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import type { ModelCredentialRowLike } from "../src/features/models/model-grouping";+import {+ entryRow,+ groupShortcutIndex,+ hiddenModelCount,+ initialGroupId,+ matchRank,+ movePickerNav,+ pickerGroups,+ pickerRowTags,+ searchPickerGroups,+ stepIndex,+} from "../src/features/chat/model-picker-logic";+import { S } from "../src/lib/strings";++const configured = (+ provider: string,+ modelId: string,+ displayName?: string,+): ModelCredentialRowLike => ({+ provider,+ modelId,+ ...(displayName !== undefined ? { displayName } : {}),+ credential: { apiKeyMasked: "sk-***" },+});+const keyless = (provider: string, modelId: string): ModelCredentialRowLike => ({+ provider,+ modelId,+});++// Library order puts deepseek before anthropic before moonshot, custom last.+const pool: ModelCredentialRowLike[] = [+ keyless("deepseek", "deepseek-v4"),+ configured("anthropic", "claude-sonnet-4-6", "Claude Sonnet 4.6"),+ keyless("anthropic", "claude-opus-4-8"),+ configured("moonshot", "kimi-k2.6", "Kimi K2.6"),+ keyless("custom", "my-proxy"),+];++const ids = (groups: { id: string }[]) => groups.map((g) => g.id);++describe("pickerGroups: the rail", () => {+ it("shows only groups holding a key-configured model, in library order", () => {+ const groups = pickerGroups(pool, { showAll: false });+ expect(ids(groups)).toEqual(["anthropic", "moonshot"]);+ expect(groups[0]!.rows.map((m) => m.modelId)).toEqual(["claude-sonnet-4-6"]);+ });++ it("follows the user's saved group order", () => {+ expect(ids(pickerGroups(pool, { showAll: false, groupOrder: ["moonshot"] }))).toEqual([+ "moonshot",+ "anthropic",+ ]);+ });++ it("keeps the selected and the default model visible without a key", () => {+ const groups = pickerGroups(pool, {+ showAll: false,+ selected: { provider: "deepseek", modelId: "deepseek-v4" },+ defaultModel: { provider: "custom", modelId: "my-proxy" },+ });+ expect(ids(groups)).toEqual(["deepseek", "anthropic", "moonshot", "custom"]);+ });++ it("the toggle reaches every key-less model: counted, then listed with their groups", () => {+ expect(hiddenModelCount(pool, { showAll: false, query: "" })).toBe(3);+ // The count follows the search, so the toggle names what it would add to these results.+ expect(hiddenModelCount(pool, { showAll: false, query: "claude" })).toBe(1);+ const all = pickerGroups(pool, { showAll: true });+ expect(ids(all)).toEqual(["deepseek", "anthropic", "moonshot", "custom"]);+ expect(all.flatMap((g) => g.rows)).toHaveLength(pool.length);+ expect(hiddenModelCount(pool, { showAll: true, query: "" })).toBe(0);+ });++ it("lists everything, with nothing to toggle, when no model has a key", () => {+ const bare = pool.map((m) => keyless(m.provider, m.modelId));+ expect(pickerGroups(bare, { showAll: false }).flatMap((g) => g.rows)).toHaveLength(5);+ expect(hiddenModelCount(bare, { showAll: false, query: "" })).toBe(0);+ });+});++describe("initialGroupId / entryRow: the opening focus", () => {+ it("opens on the current model's group and row", () => {+ const value = { provider: "moonshot", modelId: "kimi-k2.6" };+ const groups = pickerGroups(pool, { showAll: false, selected: value });+ expect(initialGroupId(groups, value)).toBe("moonshot");+ expect(entryRow(groups[1]!.rows, value)).toBe(0);+ });++ it("with nothing chosen, opens on the first group that has a key", () => {+ // The key-less default puts deepseek first on the rail, but it cannot run.+ const groups = pickerGroups(pool, {+ showAll: false,+ defaultModel: { provider: "deepseek", modelId: "deepseek-v4" },+ });+ expect(ids(groups)[0]).toBe("deepseek");+ expect(initialGroupId(groups, null)).toBe("anthropic");+ });++ it("falls back to the first group when nothing has a key, and to null on an empty rail", () => {+ const bare = pool.map((m) => keyless(m.provider, m.modelId));+ expect(initialGroupId(pickerGroups(bare, { showAll: false }), null)).toBe("deepseek");+ expect(initialGroupId([], null)).toBeNull();+ });+});++describe("pickerRowTags: a row's marks", () => {+ const keys = (tags: { key: string }[]) => tags.map((t) => t.key);+ const priced = { cacheRead: 0.3, cacheWrite: 3.75, output: 15 };++ it("follows the model card's order: default, vision, fast, then the discount", () => {+ const m = {+ provider: "custom",+ modelId: "my-proxy",+ fastMode: true,+ pricing: priced,+ discount: 0.2,+ };+ const tags = pickerRowTags(m, { provider: "custom", modelId: "my-proxy" });+ expect(keys(tags)).toEqual(["default", "vision", "fastMode", "discount"]);+ expect(tags[3]!.label).toBe(S.models.discountBadge(20));+ expect(tags[3]!.title).toBe(S.models.discountTitle(20));+ });++ it("counts an unannotated entry as vision-capable, as everywhere else", () => {+ expect(keys(pickerRowTags({ provider: "custom", modelId: "a" }, null))).toEqual(["vision"]);+ expect(pickerRowTags({ provider: "custom", modelId: "a", vision: false }, null)).toEqual([]);+ });++ it("marks zero-cost rows free, and leaves unpriced ones unmarked", () => {+ const free = { cacheRead: 0, cacheWrite: 0, output: 0 };+ const row = { provider: "custom", modelId: "a", vision: false };+ expect(keys(pickerRowTags({ ...row, pricing: free }, null))).toEqual(["free"]);+ expect(keys(pickerRowTags({ ...row, pricing: priced }, null))).toEqual([]);+ expect(keys(pickerRowTags(row, null))).toEqual([]);+ });++ it("marks only the default model of this Project as default", () => {+ const row = { provider: "anthropic", modelId: "claude-sonnet-4-6", vision: false };+ expect(keys(pickerRowTags(row, { provider: "openrouter", modelId: row.modelId }))).toEqual([]);+ expect(keys(pickerRowTags(row, undefined))).toEqual([]);+ });+});++describe("search across groups", () => {+ it("ranks exact, prefix, word-boundary, substring, then provider-only matches", () => {+ const row = { provider: "openai", modelId: "gpt-5-mini", displayName: "GPT-5 Mini" };+ expect(matchRank(row, "gpt-5 mini")).toBe(0);+ expect(matchRank(row, "gpt")).toBe(1);+ expect(matchRank(row, "mini")).toBe(2);+ expect(matchRank(row, "ini")).toBe(3);+ expect(matchRank(row, "openai")).toBe(4);+ });++ it("groups results by provider, the group with the best match first, best rows first", () => {+ const models = [+ configured("anthropic", "claude-sonnet-4-6"),+ configured("anthropic", "sonnet-lite"),+ configured("moonshot", "sonnet"),+ ];+ const results = searchPickerGroups(models, { showAll: false, query: "sonnet" });+ // moonshot holds the exact match, so it leads although anthropic comes first on the rail.+ expect(ids(results)).toEqual(["moonshot", "anthropic"]);+ expect(results[1]!.rows.map((m) => m.modelId)).toEqual(["sonnet-lite", "claude-sonnet-4-6"]);+ });++ it("finds exactly what the dropdown's search found: the same visibility, only reordered", () => {+ const found = (showAll: boolean) =>+ searchPickerGroups(pool, { showAll, query: "claude" }).flatMap((g) => g.rows);+ expect(found(false)).toHaveLength(1);+ expect(found(true)).toHaveLength(2);+ });+});++describe("keyboard", () => {+ const shape = {+ groupCount: 3,+ rowCount: (g: number) => [2, 4, 1][g] ?? 0,+ // The current model sits at row 2 of the second group.+ entry: (g: number) => (g === 1 ? 2 : 0),+ };++ it("stepIndex wraps, and enters from nothing at the near end", () => {+ expect(stepIndex(2, 3, 1)).toBe(0);+ expect(stepIndex(0, 3, -1)).toBe(2);+ expect(stepIndex(-1, 3, 1)).toBe(0);+ expect(stepIndex(-1, 3, -1)).toBe(2);+ expect(stepIndex(0, 0, 1)).toBe(-1);+ });++ it("up/down walk the list's rows, wrapping", () => {+ const nav = { region: "list" as const, group: 1, row: 3 };+ expect(movePickerNav(nav, "down", shape)).toEqual({ region: "list", group: 1, row: 0 });+ expect(movePickerNav(nav, "up", shape)).toEqual({ region: "list", group: 1, row: 2 });+ });++ it("up/down in the rail walk the groups, and the list lands on the group's entry row", () => {+ const nav = { region: "rail" as const, group: 0, row: 1 };+ expect(movePickerNav(nav, "down", shape)).toEqual({ region: "rail", group: 1, row: 2 });+ expect(movePickerNav(nav, "up", shape)).toEqual({ region: "rail", group: 2, row: 0 });+ });++ it("left/right and Tab move between the rail and the list", () => {+ const list = { region: "list" as const, group: 1, row: 2 };+ const rail = { region: "rail" as const, group: 1, row: 2 };+ expect(movePickerNav(list, "left", shape)).toEqual(rail);+ expect(movePickerNav(list, "tab", shape)).toEqual(rail);+ expect(movePickerNav(list, "right", shape)).toEqual(list);+ expect(movePickerNav(rail, "right", shape)).toEqual(list);+ expect(movePickerNav(rail, "tab", shape)).toEqual(list);+ expect(movePickerNav(rail, "left", shape)).toEqual(rail);+ });++ it("⌥1–9 / Alt+1–9 name a group; the browser keeps ⌘/Ctrl+digit", () => {+ type Mods = Partial<Record<"metaKey" | "ctrlKey" | "altKey" | "shiftKey", boolean>>;+ const k = (digit: string, mods: Mods) => ({+ code: `Digit${digit}`,+ metaKey: false,+ ctrlKey: false,+ altKey: false,+ shiftKey: false,+ ...mods,+ });+ expect(groupShortcutIndex(k("1", { altKey: true }))).toBe(0);+ expect(groupShortcutIndex(k("9", { altKey: true }))).toBe(8);+ expect(groupShortcutIndex(k("0", { altKey: true }))).toBeNull();+ expect(groupShortcutIndex(k("3", {}))).toBeNull();+ // The browser owns ⌘/Ctrl+digit (tab switching); the picker must not claim it.+ expect(groupShortcutIndex(k("3", { metaKey: true }))).toBeNull();+ expect(groupShortcutIndex(k("3", { ctrlKey: true }))).toBeNull();+ expect(groupShortcutIndex(k("3", { altKey: true, shiftKey: true }))).toBeNull();+ });+});++describe("wiring (source contract)", () => {+ const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");+ const select = read("../src/features/chat/model-select.tsx");+ const modal = read("../src/features/chat/model-picker-modal.tsx");+ const chatInput = read("../src/features/chat/chat-input.tsx");++ it("both trigger variants open the dialog, not a dropdown", () => {+ expect(select).toContain("<ModelPickerModal");+ expect(select).not.toMatch(/<Dropdown\b|<FormPicker\b/);+ });++ it("the dialog is the shared Modal, so stacked dialogs and Escape behave as elsewhere", () => {+ expect(modal).toContain("<Modal");+ expect(modal).not.toContain("createPortal");+ });++ it("/model opens the same dialog", () => {+ expect(chatInput).toMatch(/<ModelPickerModal[\s\S]*?open=\{modelSwitchOpen\}/);+ expect(chatInput).not.toContain("ModelMenuList");+ });++ it("a row reads as its provider's logo, its name and its marks; the id is only its tooltip", () => {+ expect(modal).toContain("<ProviderLogo provider={m.provider}");+ expect(modal).toContain("pickerRowTags(m, defaultModel");+ expect(modal).not.toMatch(/>\s*\{m\.modelId\}\s*</);+ });+});