Files
loki/scripts/test/model-picker-browser.ts
CatoandClaude 882016e080 fix(terminal): a command is typed then entered, one Loki sheet on the phone, Keys keeps the terminal (#1316)
From a phone the owner switched the model and the session answered
"Model 'opusWhy is the name of the repo…' not found": the command and
its Enter went in one write, Claude Code read it as a paste, the Enter
became a newline, and the next message was typed after it. Then
"What's going on?" opened a sheet with a second composer and a second
model picker, which led to Loki chat and its own "Choose a model".

- Every command button types its words, then Enter as its own
  keystroke after a beat (lib/session-keystrokes typeCommand), and
  commands queue behind each other so two quick taps never interleave.
  Covers the model sheet, the commands sheet, the screen's action chips,
  the rail's "Type it" steps and a "/model opus" typed in the box.
- On a phone, "What's going on?" opens the answer: TerminalLokiRail in
  sheet form has no composer, no model picker, no run-status filler, a
  visible question button and one link to continue in Loki chat.
- Keys open hides the next-step row, so the terminal keeps its lines.
- Loki's model picker is named as Loki's ("Loki answers with"), and on
  a phone its button shows the model's name beside the count instead of
  "your key" alone.


Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 11:19:23 +02:00

150 lines
6.0 KiB
TypeScript

import assert from "node:assert/strict";
import { build } from "esbuild";
import { chromium } from "playwright";
import { partitionModelOptions } from "@/lib/loki/models";
async function main() {
const options = [
{ id: "gpt-oss-120b", provider: "groq", label: "GPT", usable: true },
{ id: "grok-4.7", provider: "xAI", label: "Grok", usable: true, own: true },
{ id: "gemini-flash", provider: "google", label: "Gemini", usable: false, reason: "Add a key" },
];
const exhausted = [
{ id: "groq/gpt-oss-120b", state: "exhausted" as const, note: "Out of free budget" },
];
const ownDuplicate = { ...options[0], own: true, provider: "Groq" };
assert.equal(
partitionModelOptions([...options, ownDuplicate], exhausted).available.find(
(o) => o.id === ownDuplicate.id,
)?.own,
true,
);
assert.equal(partitionModelOptions([...options, ownDuplicate], exhausted).unavailable.length, 1);
assert.deepEqual(
partitionModelOptions(options, [], "spent").available.map((o) => o.id),
["grok-4.7"],
"a spent user share cannot expose free choices as ready, while own keys remain available",
);
assert.ok(
partitionModelOptions(options, [
{ ...exhausted[0], state: "skipped", note: "Last prompt was too large" },
]).available.some((o) => o.id === "gpt-oss-120b"),
"a previous prompt-size skip is not measured exhaustion for the next request",
);
const js = (
await build({
stdin: {
resolveDir: process.cwd(),
loader: "tsx",
contents: `
import React from 'react'; import {createRoot} from 'react-dom/client';
import {ModelPicker} from './src/components/loki/ModelPicker';
function Harness(){const [value,setValue]=React.useState();return <ModelPicker value={value} onChange={(m)=>{window.picked=m??'auto';setValue(m)}}/>}
createRoot(document.getElementById('app')).render(<Harness/>);
`,
},
bundle: true,
write: false,
jsx: "automatic",
format: "iife",
define: { "process.env.NODE_ENV": "'production'" },
})
).outputFiles[0].text;
let browser;
try {
browser = await chromium.launch();
} catch (error) {
if (process.env.CI) throw error;
console.log("↷ model picker skipped: Chromium unavailable; CI runs it");
return;
}
try {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
let budgetCalls = 0,
modelCalls = 0;
let failModels = false;
await page.route("http://loki.fixture/**", async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === "/api/loki/models") {
modelCalls++;
return route.fulfill({
status: failModels ? 503 : 200,
contentType: "application/json",
body: JSON.stringify(
failModels
? { error: "offline" }
: {
options,
autoSummary: null,
autoStartsAt: "groq/gpt-oss-120b",
addKeyHref: "/models",
},
),
});
}
if (path === "/api/ai/budget") {
const call = ++budgetCalls;
// Deliberately finishes after models: the old effect cleaned up on
// setData and dropped this response, leaving stale choices enabled.
await new Promise((resolve) => setTimeout(resolve, 300));
return route.fulfill({
contentType: "application/json",
body: JSON.stringify({
headline: `Budget reading ${call}`,
freePool: { state: "ok", line: `Free budget ${call}`, short: `${call} left` },
ownKeys: [],
// Read once on load and again on every open: the first two readings say spent.
models: call <= 2 ? exhausted : [{ ...exhausted[0], state: "known", note: null }],
}),
});
}
return route.fulfill({ contentType: "text/html", body: '<main id="app"></main>' });
});
await page.goto("http://loki.fixture/");
await page.addScriptTag({ content: js });
const trigger = page.locator(".ui-loki-model-trigger");
// What is left is on the button itself, before anything is opened.
await trigger.getByText("1 left").waitFor();
assert.equal(budgetCalls, 1);
await trigger.click();
const dialog = page.getByRole("dialog", { name: "Loki answers with" });
await dialog.getByText("Budget reading 2", { exact: true }).waitFor();
assert.equal(await dialog.getByRole("button", { name: /Grok 4.7/ }).isEnabled(), true);
assert.equal(await dialog.getByRole("button", { name: /GPT-OSS 120B/ }).isVisible(), false);
await dialog.getByText("Unavailable right now (2)", { exact: true }).click();
assert.equal(await dialog.getByRole("button", { name: /GPT-OSS 120B/ }).isDisabled(), true);
await dialog.getByRole("button", { name: "Close", exact: true }).click();
await trigger.click();
await dialog.getByText("Budget reading 3", { exact: true }).waitFor();
assert.equal(modelCalls, 2);
// Closing reads nothing; each open reads once.
assert.equal(budgetCalls, 3);
await dialog.getByRole("button", { name: /GPT-OSS 120B/ }).click();
assert.equal(await page.evaluate("window.picked"), "gpt-oss-120b");
assert.equal(await dialog.count(), 0);
failModels = true;
await page.locator(".ui-loki-model-trigger").click();
await page.getByRole("alert").waitFor();
failModels = false;
await page.getByRole("button", { name: "Retry", exact: true }).click();
await dialog.getByRole("button", { name: /Grok 4.7/ }).waitFor();
await dialog.getByText("Free budget 5", { exact: true }).waitFor();
await page.keyboard.press("Escape");
assert.equal(await dialog.count(), 0);
assert.equal(
await page.evaluate(() => document.body.classList.contains("fc-overlay-open")),
false,
);
console.log(
"✓ count on the button, delayed budget, quota grouping, reopen freshness, selection, retry and sheet dismissal",
);
} finally {
await browser.close();
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});