Fix wave chunk A: no Default option, composer = strong slot, catalog revalidation

Item 1 — no Default in the slot selectors (owner, fix wave): a
"default" model is not a thing in this app. Picking Default used to
delete the slot and re-arm the first-run gate — incoherent. Now the
model menus carry NO clear row at all (a slot holds a pick or reads
"—"), the thinking menus carry a "—" row (menu-none) that clears only
the thinking pin, and the hint line is the roster only — the resolved
factory pin is never named. Master's amendment confirmed: the
factory-pin hint is SUPERSEDED entirely (Platform removes the pins).

Item 2 — the composer control IS the strong slot (owner: "one and the
same"): ModelControl (model-picker.tsx) reads the raw models section
(GET /api/settings) and the federated catalog, and writes
PUT /api/settings/models via composeSlotModel — the same seam the
settings Agent section and SetupDialog use. Props retired: chatId,
settings, onSaved, fallbackModelId, noDefaultModel — the control is
self-sufficient and identical on every surface (composer, home dock,
/chat/new). The per-chat model PUT is gone from the UI; legacy
per-chat overrides keep resolving server-side. StatsBar/DockOverlay
plumbing slimmed accordingly; chat.tsx drops its per-chat settings
state and initialSettings prop.

Item 3 — the composer catalog cache no longer freezes per page load:
fetchCatalog(force) invalidates, and every model-menu open revalidates
in the background (stale-while-revalidate — cached list shows
instantly, the fresh federation swaps in). Owner's repro verified live:
a key saved mid-session widens the menu without a reload.

Item 4 — stale doc comments fixed: model-catalog.ts's "OpenRouter
catalog"/"multi-provider future" (Platform's file — mechanical,
flagged for review) and model-picker's retired "config-pinned"/
per-chat-PUT narrative.

Live-verified on 3001: unpicked slots read "—" everywhere; model
menus have no clear row; the "—" thinking row clears the pin but
keeps the model; composer pick writes strong and preserves cheap/
vision siblings; thinking pill writes strong.thinkingLevel; groq key
added mid-session appears in the open menu without reload. Caught in
live verification: the record fetch was mapping the WHOLE settings
record into the models section (picks never wrote) — fixed to read
body.settings.models.

Gates: typecheck, lint, 807/807, build.
This commit is contained in:
amosblomqvist
2026-09-22 16:40:31 +03:00
parent d85d8a58a0
commit f6626f1703
10 changed files with 157 additions and 180 deletions
-1
View File
@@ -25,7 +25,6 @@ export default async function ChatPage({
// A teacher turn that outlived its client: the remounted view must
// attach (busy shimmer + poll), never resurrect the stale record.
initiallyInFlight={isTurnRunning(chat.id)}
initialSettings={chat.settings}
/>
);
}
-13
View File
@@ -118,7 +118,6 @@ export function Chat({
initialMessages,
initialPrompt,
initiallyInFlight,
initialSettings,
}: {
chatId: string;
title: string;
@@ -127,8 +126,6 @@ export function Chat({
/** A teacher turn is running server-side but attached to no client
* (navigated away mid-turn, returned while in flight). */
initiallyInFlight?: boolean;
/** The record's per-chat model/thinking settings (the picker's seed). */
initialSettings?: ChatSettings;
}) {
const { messages, sendMessage, addToolOutput, setMessages, status, error, stop } =
useChat<TeacherUIMessage>({
@@ -445,7 +442,6 @@ export function Chat({
const [turns, setTurns] = useState<TurnUsage[]>([]);
// The per-chat model control state (model-picker writes via PUT; the
// record is the source of truth, lifted here so the stats bar re-renders).
const [settings, setSettings] = useState<ChatSettings | undefined>(initialSettings);
// The dock's reserved tail height (DockOverlay reports it; the spacer at
// the end of the transcript renders it). Lives here because the spacer is
// inside the scroller while the dock overlays OUTSIDE it — two parents.
@@ -963,8 +959,6 @@ export function Chat({
<DockOverlay
pending={pending}
chatId={chatId}
settings={settings}
onSettingsSaved={setSettings}
plan={<PlanMarginalia messages={messages} />}
onOpenPlan={() => setPlanOpen(true)}
requiresReveal={requiresReveal}
@@ -1054,8 +1048,6 @@ function DockOverlay({
composer,
onSubmitAnswer,
chatId,
settings,
onSettingsSaved,
onReserve,
plan,
onOpenPlan,
@@ -1073,8 +1065,6 @@ function DockOverlay({
onSubmitAnswer: (output: QuestionAnswerData) => void;
/** The model control's pass-through (the stats bar hosts it). */
chatId: string;
settings?: ChatSettings;
onSettingsSaved: (settings: ChatSettings) => void;
/** Reports the dock's settled height (block + gradient) — ChatView's
* dockReserve state feeds the transcript's spacer from it. */
onReserve: (h: number) => void;
@@ -1351,9 +1341,6 @@ function DockOverlay({
morphing shell so it never joins a height animation. */}
<StatsBar
turns={turns}
chatId={chatId}
settings={settings}
onSettingsSaved={onSettingsSaved}
dictationSlot={dictationSlot}
/>
</div>
+2 -6
View File
@@ -167,15 +167,11 @@ export function Home({ initialSettings, initialConfigured }: { initialSettings:
</form>
{/* Same as the chat view's under-composer stats bar (owner) — no
session yet, so the free LEFT side carries the knowledge-context
budget (session-data slot), while the RIGHT keeps the model +
thinking control (deferred save). */}
budget (session-data slot), while the RIGHT keeps the strong-
slot control (fix wave: the pills write /api/settings/models). */}
<StatsBar
dictationSlot={<DictationBar dictation={dictation} />}
turns={[] as TurnUsage[]}
chatId=""
noDefaultModel
settings={settings}
onSettingsSaved={saveDraft}
leftSlot={
<GraphContextControl
value={effectiveContextTokens(settings)}
+107 -93
View File
@@ -1,32 +1,25 @@
"use client";
/**
* The model + thinking control (model-control wave, 2026-09-12) — the stats
* bar's right side. ONE controller for the conversation agents (prober +
* teacher are functionally one agent); background sub-agents stay
* config-pinned. Writes go to PUT /api/chats/[id]/settings (validated
* server-side against pi-ai's catalog) and take effect on the next turn by
* construction — the agents are stateless per turn.
*
* The data is pi-ai's catalog (GET /api/models): the model menu is a fuzzy
* search over "provider id name" (core/fuzzy.ts — pi's /model pattern), and
* the thinking menu lists EXACTLY the chosen model's supported levels
* (getSupportedThinkingLevels — GLM-5.3-flash shows low|high|max, never a
* level it would silently clamp). Menus open ABOVE the buttons (the
* composer owns everything below).
*/
import { useCallback, useEffect, useRef, useState } from "react";
import type { ChatSettings, ModelCatalogEntry, ModelCatalogResponse } from "@/src/core";
import type { ModelCatalogEntry, ModelCatalogResponse, ModelsSettings } 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";
/** GET /api/models is fetched once per page load and shared by every
* picker instance (the catalog is static within a pi-ai version). */
/** 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(): Promise<ModelCatalogResponse> {
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}`);
@@ -37,13 +30,13 @@ function fetchCatalog(): Promise<ModelCatalogResponse> {
return c;
})
.catch((err) => {
catalogInflight = undefined; // retry on next mount
catalogInflight = undefined; // retry on next mount/open
throw err;
});
return catalogInflight;
}
function useModelCatalog(): ModelCatalogResponse | undefined {
function useModelCatalog(): { catalog: ModelCatalogResponse | undefined; refresh: () => void } {
const [catalog, setCatalog] = useState(catalogCache);
useEffect(() => {
if (catalogCache) return;
@@ -51,14 +44,21 @@ function useModelCatalog(): ModelCatalogResponse | undefined {
fetchCatalog()
.then((c) => alive && setCatalog(c))
.catch(() => {
/* the picker stays closed on failure; the buttons still display
the effective model from props */
/* the picker stays closed on failure; the buttons still
display the strong slot from the record fetch */
});
return () => {
alive = false;
};
}, []);
return catalog;
const refresh = useCallback(() => {
fetchCatalog(true)
.then(setCatalog)
.catch(() => {
/* refresh is best-effort: the cached list stays on failure */
});
}, []);
return { catalog, refresh };
}
const LEVEL_LABEL: Record<string, string> = {
@@ -71,43 +71,51 @@ const LEVEL_LABEL: Record<string, string> = {
max: "Max",
};
export function ModelControl({
chatId,
settings,
onSaved,
fallbackModelId,
noDefaultModel,
}: {
chatId: string;
/** The record's current settings (undefined = config pin). */
settings?: ChatSettings;
/** Lifts the persisted settings into the chat view's state. */
onSaved: (settings: ChatSettings) => void;
/** The last turn's actual model (from the turns log) — the label until
* the catalog (with config's defaults) finishes loading. */
fallbackModelId?: string;
/** Default-surfaces only (owner, 2026-09-18): NO baked-in default —
* unset settings render "no model"/"—" (BYOK first boot), never the
* config pin. Chat surfaces keep the catalog-default fallback (the
* engine runs the pin, so the control shows what will run). */
noDefaultModel?: boolean;
}) {
const catalog = useModelCatalog();
/**
* 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);
const defaults = catalog?.defaults;
const effectiveId = noDefaultModel
? settings?.model?.id
: (settings?.model?.id ?? defaults?.model.id ?? fallbackModelId);
const effectiveLevel = noDefaultModel
? settings?.thinkingLevel
: (settings?.thinkingLevel ?? defaults?.thinkingLevel);
const entry = catalog?.models.find((m) => m.id === effectiveId);
const levels = entry?.supportedLevels ?? [];
useEffect(() => {
let alive = true;
fetch("/api/settings")
.then((r) => r.json() as Promise<{ settings: { models?: ModelsSettings } | null }>)
.then((body) => alive && setModels(body.settings?.models ?? undefined))
.catch(() => {
/* the record fetch failing leaves the control read-only
("—" triggers, closed menus) — same posture as a
catalog failure */
});
return () => {
alive = false;
};
}, []);
const override = models?.strong;
const effectiveId = override?.model?.id;
const effectiveProvider = override?.model?.provider;
const effectiveLevel = override?.thinkingLevel;
const entry = catalog?.models.find(
(m) => m.id === effectiveId && m.provider === effectiveProvider,
);
const levels = entry?.supportedLevels ?? [];
// The intuitive dropdown contract (owner, stats-control round 1): any
// click outside the open menu — or an Esc keypress — closes it. Only the
@@ -136,18 +144,14 @@ export function ModelControl({
};
}, [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: ChatSettings) => {
async (next: ModelsSettings) => {
setError(null);
// Home view (pre-chat): defer — the selection rides along on the
// chat POST and is PUT after creation (onSaved is still lifted).
if (!chatId) {
onSaved(next);
setOpen(null);
return;
}
try {
const res = await fetch(`/api/chats/${chatId}/settings`, {
const res = await fetch("/api/settings/models", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(next),
@@ -157,14 +161,13 @@ export function ModelControl({
setError(body.error ?? `settings rejected (${res.status})`);
return;
}
const { settings: saved } = (await res.json()) as { settings: ChatSettings };
onSaved(saved);
setModels(next);
setOpen(null);
} catch {
setError("Could not reach the server — try again.");
}
},
[chatId, onSaved],
[],
);
// Shortcut seams (keyboard wave A): ⌘K opens the model menu (the
@@ -175,63 +178,66 @@ export function ModelControl({
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);
void save({ ...(settings ?? {}), thinkingLevel: levels[(idx + 1) % levels.length] });
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, save, settings]);
}, [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 (config fallback clamps honestly; a carry-over would 400).
// Replace-whole discipline: spread the current settings — a model pick
// must not silently clear a sibling override (graphContextTokens).
// drop it (a carry-over would 400 at the server's catalog gate).
const pickModel = (m: ModelCatalogEntry) => {
const nextLevel =
effectiveLevel !== undefined && m.supportedLevels.includes(effectiveLevel)
? effectiveLevel
: undefined;
void save({ ...(settings ?? {}), model: { provider: m.provider, id: m.id }, thinkingLevel: nextLevel });
effectiveLevel !== undefined && m.supportedLevels.includes(effectiveLevel) ? effectiveLevel : undefined;
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">
<button
type="button"
data-testid="stats-model"
onClick={() => {
setOpen((o) => (o === "model" ? null : "model"));
setError(null);
}}
onClick={() => openMenu("model")}
aria-expanded={open === "model"}
title="Conversation model — applies next turn"
title="Strong tier model (prober + teacher) — set app-wide"
className="flex items-center gap-1.5 rounded-full border border-border/60 bg-card/70 px-2.5 py-1 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>
<span aria-hidden className="text-xs text-muted-foreground">▾</span>
</button>
<button
type="button"
data-testid="stats-thinking"
onClick={() => {
// No model yet (noDefaultModel first boot) → nothing to set a
// level FOR: the click is a no-op, never an empty menu.
// No model picked → nothing to set a level FOR: the click
// is a no-op, never an empty menu.
if (entry === undefined) return;
setOpen((o) => (o === "thinking" ? null : "thinking"));
setError(null);
openMenu("thinking");
}}
aria-expanded={open === "thinking"}
title="Thinking level — applies next turn"
title="Strong tier thinking level — set app-wide"
className="flex items-center gap-1.5 rounded-full border border-border/60 bg-card/70 px-2.5 py-1 transition-colors hover:border-border hover:bg-muted"
>
{/* Just the level — the button reads like the model button reads
@@ -243,7 +249,8 @@ export function ModelControl({
</button>
{/* The shared dropdown body (extracted 2026-09-20): the agent
settings' role selects use the exact same one. */}
settings' slot selects and the setup dialog use the exact same
one. */}
{open === "model" && (
<div
data-testid="model-menu"
@@ -253,8 +260,13 @@ export function ModelControl({
<ModelMenuList
models={catalog?.models}
effectiveId={effectiveId}
effectiveProvider={effectiveProvider}
onPick={pickModel}
footer="Applies to the next turn · background agents stay config-pinned"
footer={
catalog && catalog.models.length === 0
? "No models — add a provider key in Keys"
: "Strong tier — runs prober + teacher, app-wide"
}
/>
</div>
)}
@@ -267,7 +279,9 @@ export function ModelControl({
<ThinkingMenuList
levels={catalog ? levels : []}
effectiveLevel={effectiveLevel}
onPick={(level) => void save({ ...(settings ?? {}), thinkingLevel: level as ChatSettings["thinkingLevel"] })}
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"
/>
+4 -9
View File
@@ -125,10 +125,6 @@ export function DraftShell({
<StatsBar
dictationSlot={<DictationBar dictation={dictation} />}
turns={[]}
chatId=""
noDefaultModel
settings={settings}
onSettingsSaved={onSettingsSaved}
// The session-data slot (owner, 2026-09-15): pre-chat the left
// side is free — the knowledge-context budget lives exactly
// where session data will sit once a session exists.
@@ -161,11 +157,10 @@ export function NewSession({
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
// THE default settings (owner, 2026-09-18): this surface and the home
// topic dock ARE the settings page for the default model — no baked-in
// default exists; the user's last choice (server-rendered in via
// initialSettings, shared with home through data/default-settings.json)
// IS the default. ModelControl with an empty chatId never PUTs — it
// hands the choice up; it still rides the session POST then PUT-on-create.
// topic dock carries only the knowledge-context budget now (fix
// wave): the model pills ARE the strong slot (PUT /api/settings/models,
// app-wide) — the per-chat model pick is retired. saveDraft still
// lifts the context budget so it rides the session POST.
const { settings, save: saveDraft } = useDefaultSettings(initialSettings);
// First-run gate (model-slots wave, owner 2026-09-20): the send
+19 -20
View File
@@ -388,12 +388,16 @@ export function AgentSection({
.then((body: { prober: SegmentInfo[]; teacher: SegmentInfo[] }) => setPrompts(body));
}
/** The pinned Default row — clears this control's override (absent key
* = the factory pin). Same row language as the shared menu's list rows. */
const defaultRow = (active: boolean, onPick: () => void) => (
/** The "—" row — THINKING menus only: clears the thinking pin (the
* slot keeps its model; the tier's resolved budget takes over). Model
* menus carry no such row — unpicking a model would re-arm the
* first-run gate, and a "default" model is not a thing in this app
* (owner, fix wave: no factory fallback is ever presented as a
* choice; an unpicked slot just reads "—"). */
const noneRow = (active: boolean, onPick: () => void) => (
<button
type="button"
data-testid="menu-default"
data-testid="menu-none"
onClick={onPick}
className={`flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-muted ${
active ? "bg-muted/60 text-card-foreground" : "text-card-foreground"
@@ -514,10 +518,12 @@ export function AgentSection({
const modelId = override?.model?.id ?? "";
const provider = override?.model?.provider ?? "";
const thinking = override?.thinkingLevel ?? "";
// The tier's resolved pin (override → factory): the Default
// hint names it; the thinking list resolves from its levels.
// The tier's resolved pin is machinery only now (owner, fix
// wave): the UI never names the factory fallback — the hint
// carries the roster, the triggers read "—" when unpicked — but
// the pin still governs the thinking level LIST when no override
// names a model to read levels from.
const pin = slots?.[slot];
const defaultName = pin ? prettyModel(pin.model.id) : "config pin";
// The model whose levels govern the thinking list: the
// override, else the resolved pin (when it's in the federated
// catalog); the standard ladder as the last fallback.
@@ -532,7 +538,7 @@ export function AgentSection({
<SettingsRow
key={slot}
label={SLOT_META[slot].label}
hint={`${SLOT_META[slot].roster} · default: ${defaultName}`}
hint={SLOT_META[slot].roster}
testid={`slot-row-${slot}`}
>
{/* The anchor for the outside-click contract is the
@@ -543,7 +549,7 @@ export function AgentSection({
>
<MenuTrigger
value={modelId ? prettyModel(modelId) : ""}
emptyLabel="Default"
emptyLabel="—"
ariaLabel={`${SLOT_META[slot].label} model`}
testid={`slot-model-${slot}`}
open={thisMenuOpen === "model"}
@@ -552,7 +558,7 @@ export function AgentSection({
/>
<MenuTrigger
value={thinking}
emptyLabel="Default"
emptyLabel="—"
ariaLabel={`${SLOT_META[slot].label} thinking`}
testid={`slot-thinking-${slot}`}
open={thisMenuOpen === "thinking"}
@@ -565,17 +571,10 @@ export function AgentSection({
testid={`slot-model-menu-${slot}`}
menuClass="flex w-[22rem] flex-col rounded-xl border border-border bg-card p-2 text-xs shadow-xl"
>
{defaultRow(
modelId === "",
() => {
onModelsChange(composeSlotModel(models, slot, "", "", thinking));
setOpenMenu(null);
},
)}
<ModelMenuList
models={slotCatalog ?? undefined}
effectiveId={modelId || pin?.model.id}
effectiveProvider={provider || pin?.model.provider}
effectiveId={modelId}
effectiveProvider={provider}
onPick={(entry) => {
onModelsChange(composeSlotModel(models, slot, entry.provider, entry.id, thinking));
setOpenMenu(null);
@@ -594,7 +593,7 @@ export function AgentSection({
testid={`slot-thinking-menu-${slot}`}
menuClass="flex w-44 flex-col gap-0.5 rounded-xl border border-border bg-card p-2 text-xs shadow-xl"
>
{defaultRow(
{noneRow(
thinking === "",
() => {
onModelsChange(composeSlotModel(models, slot, provider, modelId, ""));
+1 -21
View File
@@ -29,24 +29,10 @@ import { ModelControl } from "@/components/model-picker";
*/
export function StatsBar({
turns,
chatId,
settings,
onSettingsSaved,
leftSlot,
dictationSlot,
noDefaultModel,
}: {
turns: TurnUsage[];
chatId: string;
settings?: ChatSettings;
onSettingsSaved: (settings: ChatSettings) => void;
/** Default-surfaces only (owner, 2026-09-18): there is NO baked-in
* default model — BYOK first boot shows "no model" until the user
* picks one, and that pick IS the default from then on. Chat surfaces
* keep the catalog-default fallback (the engine runs the config pin
* when a session record has no override — the control shows what will
* actually run). */
noDefaultModel?: boolean;
/** Pre-chat only: replaces the (empty) session-data summary — home and
* the /chat/new draft mount the knowledge-context slider here. */
leftSlot?: ReactNode;
@@ -178,13 +164,7 @@ export function StatsBar({
{/* The model + thinking control — one controller for the conversation
agents (prober/teacher); the record's `turns` above still folds
the ACTUAL models billed, regardless of what the picker says. */}
<ModelControl
chatId={chatId}
settings={settings}
onSaved={onSettingsSaved}
fallbackModelId={lastModel}
noDefaultModel={noDefaultModel}
/>
<ModelControl />
</div>
);
}
+10 -7
View File
@@ -1,17 +1,20 @@
/**
* The model catalog's server surface (model-control wave, 2026-09-12):
* pi-ai's shipped OpenRouter catalog projected to client-safe DTOs for the
* picker (GET /api/models), plus the validation gate for per-chat settings
* (PUT /api/chats/[id]/settings).
* The model catalog's server surface (model-control wave, 2026-09-12;
* federated since the model-slots wave, 2026-09-20): pi-ai's catalog for
* every KEYED provider, projected to client-safe DTOs for the picker (GET
* /api/models), plus the validation gate for settings writes (PUT
* /api/settings/* — the per-chat settings PUT is retired from the UI;
* legacy records' per-chat overrides still resolve server-side).
*
* pi-ai owns ALL the data: the catalog (id/name/cost/context/modality/
* thinkingLevelMap) and the per-model thinking truth
* (getSupportedThinkingLevels / clampThinkingLevel). This module only
* projects and validates — no second registry to drift out of sync.
*
* Multi-provider future: `getModels()` is called per configured provider,
* so a second provider (pi-ai ships ~30) appears in the picker by adding
* it to piModels() in src/agent/models.ts — nothing here changes.
* Federation: `getModels()` is called per keyed provider (federated, the
* model-slots wave), so a provider appears in the picker exactly when its
* key is present — piModels() in src/agent/models.ts owns the provider
* set; nothing here changes.
*/
import { getSupportedThinkingLevels, type Api, type Model } from "@earendil-works/pi-ai";
+7 -2
View File
@@ -59,7 +59,7 @@ describe("SettingsDialog (the designed surface, SSR)", () => {
});
describe("AgentSection (thin SSR)", () => {
it("renders the three model SLOT rows (slots-only, owner ruling 2026-09-20), Default-triggered dropdowns", () => {
it("renders the three model SLOT rows (slots-only, fix wave: unpicked reads —, no Default option)", () => {
const html = renderToStaticMarkup(<AgentSection agent={undefined} models={undefined} onSectionChange={() => {}} onModelsChange={() => {}} />);
for (const slot of ["strong", "cheap", "vision"]) {
assert.ok(html.includes(`data-testid="slot-row-${slot}"`), slot);
@@ -70,7 +70,12 @@ describe("AgentSection (thin SSR)", () => {
// the roster hint rides every row
assert.ok(html.includes("Prober + Teacher") || slot !== "strong", "strong roster");
}
assert.equal((html.match(/>Default<\/span>/g) ?? []).length, 6, "three slots × two Default triggers");
// Fix wave: no Default anywhere — an unpicked slot reads "—"
// (the owner's no-factory-fallback language), and no menu
// carries a Default row (menu-default testid is retired).
assert.equal((html.match(/>Default<\/span>/g) ?? []).length, 0, "no Default trigger");
assert.ok(!html.includes('data-testid="menu-default"'), "no Default row");
assert.equal((html.match(/>—<\/span>/g) ?? []).length, 6, "three slots × two — triggers");
// the per-role rows are GONE (slots-only)
for (const role of ["researcher", "demoBuilder", "visualMaker"]) {
assert.ok(!html.includes(`data-testid="role-row-${role}"`), `${role} retired`);
+7 -8
View File
@@ -24,12 +24,10 @@ function turn(over: Partial<TurnUsage> = {}): TurnUsage {
};
}
const SETTINGS_STUB = (_s: ChatSettings) => {};
describe("stats bar", () => {
it("renders — everywhere when the record has no turns yet (doctrine)", () => {
const html = renderToStaticMarkup(
<StatsBar turns={[]} chatId="chat_x" onSettingsSaved={SETTINGS_STUB} />,
<StatsBar turns={[]} />,
);
assert.match(html, /data-testid="stats-bar"/);
assert.match(html, /data-testid="stats-context">—</);
@@ -47,7 +45,7 @@ describe("stats bar", () => {
it("folds context + cost from the turns log (core/prices, no local math)", () => {
const html = renderToStaticMarkup(
<StatsBar turns={[turn(), turn()]} chatId="chat_x" onSettingsSaved={SETTINGS_STUB} />,
<StatsBar turns={[turn(), turn()]} />,
);
// last turn's last call: 10k in + 1k out = 11k; pi catalog limit
// 1_048_576 → "1M" (tables regenerated from pi-ai's catalog)
@@ -55,14 +53,15 @@ describe("stats bar", () => {
// pi catalog price 0.075/0.25 per 1M: each turn 10k×0.075 + 1k×0.25
// = $0.001 → two = $0.0020
assert.match(html, /data-testid="stats-cost">\$0\.0020</);
// model button label falls back to the last turn's actual model
// (the catalog + settings are what drive it once loaded)
assert.match(html, /data-testid="stats-model"[^>]*>\s*<span[^>]*>Glm 5\.3 Flash<\/span>/);
// model button label: SSR (record fetch not run yet) reads "—" —
// the strong slot arrives client-side via GET /api/settings; the
// turn log below still folds the ACTUAL models billed
assert.match(html, /data-testid="stats-model"[^>]*>\s*<span[^>]*>—<\/span>/);
});
it("shows — for cost when every turn is unpriceable, never a fake $0", () => {
const html = renderToStaticMarkup(
<StatsBar turns={[turn({ model: "nope/unknown" })]} chatId="chat_x" onSettingsSaved={SETTINGS_STUB} />,
<StatsBar turns={[turn({ model: "nope/unknown" })]} />,
);
assert.match(html, /data-testid="stats-cost">—</);
// unknown model also kills the context limit