Files
learnharness/components/model-picker.tsx
T
amosblomqvist b3c07f89f4 Fix ⌘B: dispatch/listen event-name mismatch; thinking pill → "Thinking (⇧⇥)"
Root cause (interlude, owner 2026-09-25): keyboard-shortcuts dispatches
registry actions on the lh:kbd-<action> convention, but the sidebar's
listener sat on the pre-convention name "lh:toggle-sidebar" — a name
nothing ever dispatches, so ⌘B silently did nothing while its tooltip
and cheat-sheet row kept claiming the binding. A sweep of every lh:
listener confirmed the sidebar was the lone stray (chat-renamed and
graph-revision are deliberate non-kbd events).

Fix, structural: kbdEventForAction(action) exported from
src/core/keyboard.ts — the ONE spelling — and both sides compose
through it (dispatcher's default branch, sidebar's toggle listener);
keyboard-shortcuts re-exports the helper so the contract pin can assert
no second spelling exists. The mismatch is now impossible by
construction.

Thinking pill: label trimmed to "Thinking" with its real shortcut via
the registry-composition path — "Thinking (⇧⇥)" (cycle-thinking,
rebind-live like every Hint suffix).

Pins (tests/keyboard-toggle-sidebar.test.ts): the full chain — mod+b →
actionForBinding → toggle-sidebar → kbdEventForAction →
lh:kbd-toggle-sidebar; formatBinding("shift+tab") → ⇧⇥; the
dispatcher-imports-the-same-helper contract.

Live-verified on :3001: ⌘B visually toggles on home, /chat/[id], and
/chat/new (sidebar 0↔288px, hamburger slot 0↔36); with the rebind
lh:keymap {"toggle-sidebar":"mod+j"}: ⌘J toggles and ⌘B is inert
(rebind-live); thinking pill renders "Thinking (⇧⇥)"; keymap restored,
sidebar left open.
2026-09-25 02:39:11 +03:00

358 lines
14 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { ModelCatalogEntry, ModelCatalogResponse, ModelsSettings, UserSettings } from "@/src/core";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import { prettyModel } from "@/components/usage-format";
import { ModelMenuList, ThinkingMenuList } from "@/components/settings/model-menu";
import { composeSlotModel } from "@/components/settings/agent-section";
import { MenuShell } from "@/components/menu-shell";
import { Hint } from "@/components/ui/hint";
import { notifySettingsSaved, useSettingsSaved } from "@/components/settings-signal";
import { defaultOrderLevel, populateLevel, THINKING_LABEL } from "@/components/thinking-default";
/** GET /api/models is cached per page load for instant menu opens, but
* the federation is LIVE per call — keys saved mid-session widen the
* catalog immediately server-side. ModelControl therefore re-fetches on
* every model-menu open (stale-while-revalidate: the cached list shows
* instantly, the fresh one swaps in while the menu is open). */
let catalogCache: ModelCatalogResponse | undefined;
let catalogInflight: Promise<ModelCatalogResponse> | undefined;
function fetchCatalog(force = false): Promise<ModelCatalogResponse> {
if (force) {
catalogCache = undefined;
catalogInflight = undefined;
}
catalogInflight ??= fetch("/api/models")
.then((r) => {
if (!r.ok) throw new Error(`catalog request failed: ${r.status}`);
return r.json() as Promise<ModelCatalogResponse>;
})
.then((c) => {
catalogCache = c;
return c;
})
.catch((err) => {
catalogInflight = undefined; // retry on next mount/open
throw err;
});
return catalogInflight;
}
export function useModelCatalog(): { catalog: ModelCatalogResponse | undefined; refresh: () => void } {
const [catalog, setCatalog] = useState(catalogCache);
useEffect(() => {
if (catalogCache) return;
let alive = true;
fetchCatalog()
.then((c) => alive && setCatalog(c))
.catch(() => {
/* the picker stays closed on failure; the buttons still
display the strong slot from the record fetch */
});
return () => {
alive = false;
};
}, []);
const refresh = useCallback(() => {
fetchCatalog(true)
.then(setCatalog)
.catch(() => {
/* refresh is best-effort: the cached list stays on failure */
});
}, []);
return { catalog, refresh };
}
/** provider:id → contextWindow over the cached catalog — the client-side
* twin of the server's catalogContextLimits join (context-meter
* amendment, owner 2026-09-23: pi's live catalog is the ONLY limit
* source — no hardcoded fallback exists anywhere, so a model missing
* from the index reads limit-null and the meter renders usage-only,
* the honest-render precedent). Consumed by the stats bar: the same
* cached /api/models fetch the picker rides feeds the denominator. */
export function catalogLimits(catalog: Pick<ModelCatalogResponse, "models">): Map<string, number> {
return new Map(catalog.models.map((m) => [`${m.provider}:${m.id}`, m.contextWindow]));
}
/**
* THE STRONG-SLOT CONTROL (fix wave, owner ruling: "one and the same").
* The composer's model + thinking pills ARE the strong slot — the tier
* that runs prober + teacher. Reads: the raw models section (GET
* /api/settings) for the user's pick, plus the federated catalog for the
* menus. Writes: PUT /api/settings/models via composeSlotModel — the same
* seam the settings Agent section and the SetupDialog write, so there is
* exactly one strong slot in the world and every surface edits it.
*
* Unpicked reads "—" (the no-factory-fallback language: the UI never
* presents a default model; the engine-side pin still resolves, the UI
* never claims it). Legacy per-chat model overrides on old records keep
* resolving server-side — the UI simply no longer writes that field
* anywhere.
*/
export function ModelControl() {
const { catalog, refresh } = useModelCatalog();
const [models, setModels] = useState<ModelsSettings | undefined>();
const [open, setOpen] = useState<"model" | "thinking" | null>(null);
const [error, setError] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
// The record read — BOTH mount and the cross-surface signal land
// here (fix wave: another surface's models write re-reads into the
// pill live; own writes also notify, and the refetch is idempotent).
const readRecord = useCallback(() => {
fetch("/api/settings")
.then((r) => r.json() as Promise<{ settings: { models?: ModelsSettings } | null }>)
.then((body) => setModels(body.settings?.models ?? undefined))
.catch(() => {
/* the record fetch failing leaves the control read-only
("—" triggers, closed menus) — same posture as a
catalog failure */
});
}, []);
useEffect(() => {
readRecord();
}, [readRecord]);
useSettingsSaved((section) => {
if (section === "models") readRecord();
});
const override = models?.strong;
const effectiveId = override?.model?.id;
const effectiveProvider = override?.model?.provider;
const storedLevel = override?.thinkingLevel;
const entry = catalog?.models.find(
(m) => m.id === effectiveId && m.provider === effectiveProvider,
);
const levels = entry?.supportedLevels ?? [];
// Legacy display (chunk 2 item 4, owner): a record with a model but no
// stored level shows the RESOLVED level — the ordering's first supported
// — because that is exactly what the engine build would run. Display-
// only: the record stays unset until a fresh pick populates it.
const effectiveLevel = storedLevel ?? (entry ? defaultOrderLevel(levels) : undefined);
// The intuitive dropdown contract (owner, stats-control round 1): any
// click outside the open menu — or an Esc keypress — closes it. The
// menu's own surface keeps it open: the toggle buttons live inside the
// container, and the menu BODY lives in a portal on document.body
// (MenuShell) — never a container descendant, so its rows are carved
// out via [data-lh-menu] (the settings sections' discipline; without
// it a row's pointerdown counts as outside and eats the pick —
// live-caught in the fix wave, broken since the MenuShell migration).
useEffect(() => {
if (open === null) return;
const onPointerDown = (e: PointerEvent) => {
const t = e.target as Element;
if (t instanceof Element && t.closest("[data-lh-menu]")) return;
if (containerRef.current && !containerRef.current.contains(t)) {
setOpen(null);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
// Claim the Esc (keyboard wave A): the window-level chain must
// not ALSO stop dictation / abort the turn under this menu.
e.stopPropagation();
setOpen(null);
}
};
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
};
}, [open]);
// One write seam: composeSlotModel preserves the cheap/vision siblings
// (replace-whole-section discipline) and the per-field independence of
// model + thinkingLevel within the strong slot.
const save = useCallback(
async (next: ModelsSettings) => {
setError(null);
try {
const res = await fetch("/api/settings/models", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(next),
});
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
setError(body.error ?? `settings rejected (${res.status})`);
return;
}
// Server truth, never the request body (fix wave): a pick
// that rides an unsupported level lands CLAMPED in the record
// — the pill must show the stored value in this interaction.
const stored = (
(await res.json().catch(() => null)) as { settings?: UserSettings } | null
)?.settings?.models;
setModels(stored ?? next);
setOpen(null);
notifySettingsSaved("models");
} catch {
setError("Could not reach the server — try again.");
}
},
[],
);
// Shortcut seams (keyboard wave A): ⌘K opens the model menu (the
// universal command convention); Shift+Tab cycles the thinking level
// up the ladder (wrapping) — the owner's replacement for browser
// tab-focus. Both work from any focus, including mid-typing.
useEffect(() => {
const onOpenPicker = () => {
setOpen("model");
setError(null);
refresh(); // mid-session key changes widen the menu (cache fix)
};
window.addEventListener("lh:kbd-open-model-picker", onOpenPicker);
return () => window.removeEventListener("lh:kbd-open-model-picker", onOpenPicker);
}, [refresh]);
useEffect(() => {
const onCycleThinking = () => {
if (levels.length === 0) return;
const idx = effectiveLevel === undefined ? -1 : levels.indexOf(effectiveLevel);
const next = levels[(idx + 1) % levels.length];
if (next === undefined) return;
void save(composeSlotModel(models, "strong", effectiveProvider ?? "", effectiveId ?? "", next));
};
window.addEventListener("lh:kbd-cycle-thinking", onCycleThinking);
return () => window.removeEventListener("lh:kbd-cycle-thinking", onCycleThinking);
}, [levels, effectiveLevel, effectiveProvider, effectiveId, models, save]);
// Selecting a model (click and Enter share one path): keep the
// thinking level only when the new model supports it — otherwise
// drop it (a carry-over would 400 at the server's catalog gate).
const pickModel = (m: ModelCatalogEntry) => {
// Auto-populate (chunk 2, owner: "populate everywhere"): a fresh pick
// ALWAYS writes a level — the STORED one rides as-is (the write clamps
// server-side when the new model doesn't support it; the signal
// re-reads and the clamped truth displays), and a record with no
// stored level populates the ordering's level. The unset state can
// never re-enter through this door. (The DERIVED display level never
// rides — it belongs to the OLD model; the fresh pick's level comes
// from the fresh model's own ladder.)
const nextLevel = populateLevel(storedLevel, m.supportedLevels);
void save(composeSlotModel(models, "strong", m.provider, m.id, nextLevel));
};
// Stale-while-revalidate on manual open too (⌘K covers the keyboard
// path above): the cached list shows instantly, the fresh federation
// swaps in when it lands.
const openMenu = (kind: "model" | "thinking") => {
setOpen((o) => (o === kind ? null : kind));
setError(null);
if (kind === "model") refresh();
};
return (
<div ref={containerRef} className="relative flex items-center gap-1.5" data-testid="model-control">
<Hint
// Trimmed (owner, subtlety round 2026-09-25): "Model selector"
// — the long sentence was way too much. ⌘K opens this same
// menu (registry, override-aware).
label="Model selector"
action="open-model-picker"
side="bottom"
>
<button
type="button"
data-testid="stats-model"
onClick={() => openMenu("model")}
aria-expanded={open === "model"}
// Chrome look (owner, fix wave round 3): matches the graph
// view's floating top-right buttons (import notes, gear,
// coverage) — blurred, fuller opacity, shadowed — so the
// graph no longer bleeds through these pills.
className="flex items-center gap-1.5 rounded-full border bg-card/85 px-2.5 py-1 shadow-lg backdrop-blur transition-colors hover:border-border hover:bg-muted"
>
<span className="text-card-foreground">{effectiveId ? prettyModel(effectiveId) : "—"}</span>
<span aria-hidden className="text-xs text-muted-foreground">▾</span>
</button>
</Hint>
<Hint
// "Thinking" + its real shortcut via the registry (owner interlude
// 2026-09-25): ⇧⇥ cycles the level, so "Thinking (⇧⇥)" —
// rebind-live like every Hint suffix.
label="Thinking"
action="cycle-thinking"
side="bottom"
>
<button
type="button"
data-testid="stats-thinking"
onClick={() => {
// No model picked → nothing to set a level FOR: the click
// is a no-op, never an empty menu.
if (entry === undefined) return;
openMenu("thinking");
}}
aria-expanded={open === "thinking"}
// Chrome look (owner, fix wave round 3): matches the graph
// view's floating top-right buttons (import notes, gear,
// coverage) — blurred, fuller opacity, shadowed — so the
// graph no longer bleeds through these pills.
className="flex items-center gap-1.5 rounded-full border bg-card/85 px-2.5 py-1 shadow-lg backdrop-blur transition-colors hover:border-border hover:bg-muted"
>
{/* Just the level — the button reads like the model button reads
the model name (owner, stats-control round 1). */}
<span className="text-card-foreground">
{effectiveLevel === undefined ? "—" : (THINKING_LABEL[effectiveLevel] ?? effectiveLevel)}
</span>
<span aria-hidden className="text-xs text-muted-foreground">▾</span>
</button>
</Hint>
{/* The shared dropdown body (extracted 2026-09-20): the agent
settings' slot selects and the setup dialog use the exact same
one. */}
{open === "model" && (
<MenuShell
anchorRef={containerRef}
testid="model-menu"
preferredSide="up"
menuClass="flex w-[22rem] flex-col rounded-xl border bg-card p-2 text-xs shadow-xl"
>
{error && <div className="mb-1.5 text-destructive">{error}</div>}
<ModelMenuList
models={catalog?.models}
effectiveId={effectiveId}
effectiveProvider={effectiveProvider}
onPick={pickModel}
footer={
catalog && catalog.models.length === 0
? "No models — add a provider key in Keys"
: "Strong tier — runs prober + teacher, app-wide"
}
/>
</MenuShell>
)}
{open === "thinking" && (
<MenuShell
anchorRef={containerRef}
testid="thinking-menu"
preferredSide="up"
menuClass="flex w-44 flex-col gap-0.5 rounded-xl border bg-card p-2 text-xs shadow-xl"
>
<ThinkingMenuList
levels={catalog ? levels : []}
effectiveLevel={effectiveLevel}
onPick={(level) =>
void save(composeSlotModel(models, "strong", effectiveProvider ?? "", effectiveId ?? "", level as ThinkingLevel))
}
empty={catalog ? (effectiveId ? `${prettyModel(effectiveId)} has no thinking levels.` : "Pick a model first.") : "Loading…"}
footer="Levels this model actually supports"
/>
{error && <div className="mt-1 text-destructive">{error}</div>}
</MenuShell>
)}
</div>
);
}