feat(overlay): pick the backend and its model from the chat header

The agent button opened a flat list of three backends. It now opens a group per
backend, and choosing a row picks the backend and its model in one go, because
they are one choice — a model id means nothing without the harness that runs it.
The pick is stored per backend, so switching away and back returns to what was
chosen there rather than carrying an id across to something that cannot run it.

The catalogue is asked for when the menu is first opened rather than pushed at
the handshake. Probing opencode starts an `opencode serve` process, and booting
one for a session that never opens the picker is a cost with no return. A group
that comes back carrying a `note` is re-probed on the next open, since the fix
for "not signed in" happens in a terminal somewhere else; a clean one is not.

`AirshipSocket.send` drops a message when the socket is not open, which is a
1.5s window on every reconnect, so the request is gated on `isOpen()`. Marking
it asked anyway pinned the picker to the seed list for the life of the page —
the only re-probe condition is a group with a `note`, and the seed sets none.

The change rail gets the keyboard half of what it already did with a pointer.
The strip is one tab stop with arrow keys inside it rather than one stop per
chip, twelve pending edits having meant twelve stops between the composer and
anything after it. "Discard all" joins that roving instead of sitting outside it
as a second tab stop, and each chip says what it is and that Backspace drops it.

Removing a pasted attachment is reachable from a keyboard now. That control was
a span with a click handler and no role, no label and no tab stop, so it existed
for the mouse alone.
This commit is contained in:
Nayan
2026-08-15 10:24:28 +05:30
parent 149373c1c1
commit f6477a74ce
14 changed files with 1600 additions and 81 deletions
@@ -368,6 +368,28 @@ describe("buildEditRequest", () => {
});
});
describe("the backend and its model", () => {
it("carries both when the picker has chosen one", () => {
const request = buildEditRequest(
parts({ agent: "codex", model: "gpt-5.3-codex", prompt: "hi" })
);
expect(request?.agent).toBe("codex");
expect(request?.model).toBe("gpt-5.3-codex");
});
it("omits the model when the picker is on Default", () => {
// Absent, not empty: the daemon reads a missing model as "use the default
// resolved for this backend", and `""` would be an id of "".
const request = buildEditRequest(parts({ model: "", prompt: "hi" }));
expect(request && "model" in request && request.model).toBeFalsy();
expect(request?.model).toBeUndefined();
});
it("omits the model when the picker never set one", () => {
expect(buildEditRequest(parts({ prompt: "hi" }))?.model).toBeUndefined();
});
});
describe("hasVisualDeltas", () => {
it("is false for a plain typed turn", () => {
const request = buildEditRequest(parts({ prompt: "hello" }));
@@ -24,6 +24,8 @@ export interface EditRequestParts {
changeSet: ChangeSet;
commentSet: CommentSet;
images: ImageInput[];
/** Which model that backend runs on. Absent leaves it to the daemon. */
model?: string;
moveSet: MoveSet;
/** The turn this one continues, when refining rather than starting fresh. */
parentJobId: string | null;
@@ -108,6 +110,10 @@ export function buildEditRequest(p: EditRequestParts): CreateJobRequest | null {
comments,
element,
images: p.images?.length ? p.images : undefined,
// Absent rather than empty, like the arrays above but for a different
// reason: the daemon reads a missing model as "use the default resolved for
// this backend", and an empty string would be a model id of "".
model: p.model || undefined,
moveChanges,
// Feedback on an edit is a follow-up on *that* edit's session. Without
// this, commenting on an older turn after starting a new chat would
@@ -3,7 +3,14 @@ import { cls, el } from "../dom";
import { icon } from "../icons";
import { type Caption, dock, plainStage } from "../stories/chrome";
import { BRAND, noop } from "../stories/fixtures";
import { type ChangeChip, renderChangeChips, shortValue } from "./change-chips";
import { onStoryTeardown } from "../stories/lifecycle";
import {
attachRailKeys,
attachRailWheel,
type ChangeChip,
renderChangeChips,
shortValue,
} from "./change-chips";
/*
* The composer's pending-change strip.
@@ -26,6 +33,11 @@ import { type ChangeChip, renderChangeChips, shortValue } from "./change-chips";
*
* **"Discard all" appears at two chips, not one.** With a single chip it would
* be a second control doing exactly what the first one does.
*
* **A chip is three fields, not a sentence.** Subject, detail and value, told
* apart by tone alone, because the strip has no colour left to spend. They were
* one space-joined string until a user pointed at "RootDocument flex 0 0" and
* asked what it meant.
*/
const meta: Meta = {
@@ -36,38 +48,54 @@ export default meta;
/** The accent selection chip the composer places before any change chips. */
function selectionChip(label: string): HTMLElement {
return el("span", { class: cls("sel-chip"), "data-tip": label }, [
icon("tool-move", "sm"),
el("span", { text: label }),
el("span", { class: cls("chip-x"), onClick: noop }, [icon("close", "sm")]),
]);
return el(
"span",
{
class: cls("sel-chip"),
"data-chip": "",
"data-tip": label,
tabindex: "-1",
},
[
icon("tool-move", "sm"),
el("span", { class: cls("chip-subject"), text: label }),
el(
"span",
{ class: cls("chip-x"), onClick: noop, role: "button", tabindex: "-1" },
[icon("close", "sm")]
),
]
);
}
/**
* One style chip, as `AirshipApp.styleChips` builds it.
*
* The glyph is `settings` for *every* style chip — not a per-property icon —
* and the label carries the element, the property and a shortened value. That is
* a real decision rather than an oversight: at chip size a distinct glyph per
* CSS property would be forty unlearnable marks, and what distinguishes two
* chips is the text. Structure chips use `drag`, which is the one distinction
* that survives at this size.
* No glyph. A style chip used to carry `settings` — the same mark on every one
* of them, which is the one fact a strip of style chips never needs told twelve
* times, and it cost 26px of rail each time. A per-property icon was never the
* alternative: at chip size that would be forty unlearnable marks. What tells
* two chips apart is the text, so the text is all there is. The kinds that stay
* distinguishable at this size keep theirs — `drag` for a move, `minus` and
* `plus` for a delete and a duplicate.
*/
const chip = (
element: string,
property: string,
value: string
): ChangeChip => ({
icon: "settings",
label: `${element} ${property} ${shortValue(value)}`,
detail: property,
onRemove: noop,
subject: element,
tip: `${element} — ${property}: ${value}`,
value: shortValue(value),
});
const moveChip = (element: string): ChangeChip => ({
detail: "moved",
icon: "drag",
label: `${element} moved`,
onRemove: noop,
subject: element,
tip: `${element} moved`,
});
@@ -88,10 +116,15 @@ const CHIPS: ChangeChip[] = [
* asking about them.
*/
function composer(chips: ChangeChip[], caption: Caption): HTMLElement {
const strip = el("div", { class: cls("sel-chips") }, [
const strip = el("div", { class: `${cls("sel-chips")} ${cls("scroll-x")}` }, [
selectionChip("<button>"),
]);
renderChangeChips(strip, chips, noop);
// The rail's behaviour is the point of the Overflow story, and it lives in
// listeners rather than in CSS — so the stories install it the way the
// composer does rather than rendering a strip that only looks right.
onStoryTeardown(attachRailWheel(strip));
onStoryTeardown(attachRailKeys(strip));
const field = el("div", { class: cls("field") }, [
strip,
@@ -151,11 +184,21 @@ export const Several: StoryObj = {
/**
* More chips than the strip is wide.
*
* It scrolls horizontally with no visible scrollbar (`::-webkit-scrollbar {
* display: none }`), which is a deliberate trade: a scrollbar inside a composer
* field is three pixels of chrome on a control that is already dense. The chips
* are `flex: 0 0 auto`, so they keep their size rather than compressing into
* illegibility.
* The chips are `flex: 0 0 auto`, so they keep their size rather than
* compressing into illegibility — which means the strip has to scroll, and for
* a long time it did so in complete silence. The scrollbar was hidden
* (`scrollbar-width: none` plus `::-webkit-scrollbar { display: none }`), there
* was no wheel handler, and nothing marked the ends.
*
* That reads as a clean composer on a trackpad, where a two-finger swipe sends
* `deltaX` and scrolls the rail natively. On a mouse it is a bug: every wheel a
* mouse sends is `deltaY`, a box that only overflows on X ignores it, and the
* ninth chip cannot be reached at all. The people who built it were on
* trackpads. This is the story that would have caught it.
*
* Four affordances now, and it takes all four: a thin scrollbar that tints on
* hover, a fade on whichever end has more, a wheel handler that turns vertical
* delta into horizontal scroll, and ←/→ to walk the chips.
*/
export const Overflow: StoryObj = {
render: () =>
@@ -169,8 +212,8 @@ export const Overflow: StoryObj = {
chip("Title", "opacity", "0.92"),
],
{
try: "drag the strip sideways — it scrolls, and the scrollbar is hidden on purpose",
what: "Nine chips in a strip built for four. They scroll rather than compress.",
try: "scroll with a wheel over the strip, then tab to it and walk it with ← and →",
what: "Nine chips in a strip built for four. They scroll rather than compress, and now they say so.",
}
),
};
@@ -178,9 +221,15 @@ export const Overflow: StoryObj = {
/**
* Values long enough to need `shortValue`.
*
* A chip has to stay a chip. The label is truncated to fourteen characters and
* the full value moves to the tooltip — which is why `ChangeChip` carries `tip`
* separately rather than letting the label be the whole truth.
* A chip has to stay a chip. `shortValue` truncates the *value* to fourteen
* characters and the full text moves to the tooltip — which is why `ChangeChip`
* carries `tip` separately rather than letting the visible fields be the whole
* truth.
*
* The subject is not truncated in TS at all: it ellipsises in CSS, so it is the
* field that gives way first when the rail is narrow. That is deliberate — a
* component display name has a long tail, and losing the end of "PricingCardHeader"
* costs less than losing the property you changed.
*/
export const LongValues: StoryObj = {
render: () =>
@@ -0,0 +1,385 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cls, el } from "../dom";
import { keys } from "../keys/registry";
import {
attachRailKeys,
attachRailWheel,
type ChangeChip,
renderChangeChips,
shortValue,
} from "./change-chips";
/*
* The pending-change rail.
*
* Two of the three things under test here are invisible to the person who wrote
* them, because they only fail on hardware that person was not using:
*
* - A rail that overflows on X ignores a mouse's `deltaY` entirely. On a
* trackpad the same gesture arrives as `deltaX` and the browser scrolls the
* rail for free, so the strip is perfect on a laptop and broken on a desk.
* - Most mouse wheels report *lines*, not pixels — a notch is `deltaY: 3`. Read
* unconverted that scrolls a rail three pixels, which reads as a dead strip
* rather than a slow one.
*
* happy-dom does no layout, so `scrollWidth` and `clientWidth` are patched per
* node by `rail()`. That is the same stubbing `inspector/test-support.ts` does
* for `getBoundingClientRect`, and for the same reason.
*/
const DISPOSERS: (() => void)[] = [];
/** A rail with a measurable overflow, since happy-dom measures nothing. */
function rail(opts: { clientWidth?: number; scrollWidth?: number } = {}) {
const node = el("div", { class: `${cls("sel-chips")} ${cls("scroll-x")}` });
Object.defineProperty(node, "scrollWidth", {
configurable: true,
value: opts.scrollWidth ?? 600,
});
Object.defineProperty(node, "clientWidth", {
configurable: true,
value: opts.clientWidth ?? 200,
});
document.body.append(node);
return node;
}
function wheel(node: HTMLElement, init: WheelEventInit): boolean {
return node.dispatchEvent(
new WheelEvent("wheel", { bubbles: true, cancelable: true, ...init })
);
}
/** Scroll a rail to its far end and let it notice. */
function atEnd(node: HTMLElement): void {
node.scrollLeft = node.scrollWidth - node.clientWidth;
node.dispatchEvent(new Event("scroll"));
}
function press(node: HTMLElement, key: string): void {
node.dispatchEvent(
new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
code: key,
key,
})
);
}
const chip = (subject: string, over: Partial<ChangeChip> = {}): ChangeChip => ({
detail: "flex",
onRemove: () => {
// Overridden where a case cares.
},
subject,
tip: `${subject} · flex: 0 0`,
value: "0 0",
...over,
});
function keep(off: () => void): void {
DISPOSERS.push(off);
}
beforeEach(() => {
document.body.replaceChildren();
});
afterEach(() => {
for (const off of DISPOSERS.splice(0)) {
off();
}
keys.destroy();
});
describe("the rail's wheel", () => {
it("turns a mouse's vertical wheel into horizontal scroll", () => {
const node = rail();
keep(attachRailWheel(node));
const survived = wheel(node, { deltaMode: 0, deltaX: 0, deltaY: 120 });
expect(node.scrollLeft).toBe(120);
expect(survived).toBe(false);
});
it("converts a line-mode notch rather than reading it as pixels", () => {
const node = rail();
keep(attachRailWheel(node));
// What a real mouse sends: three lines, not 120 pixels.
wheel(node, { deltaMode: 1, deltaX: 0, deltaY: 3 });
// 3 lines × LINE_HEIGHT. Unconverted this would have been 3px.
expect(node.scrollLeft).toBe(120);
});
it("leaves a horizontal wheel to the browser", () => {
const node = rail();
keep(attachRailWheel(node));
const survived = wheel(node, { deltaMode: 0, deltaX: 40, deltaY: 10 });
expect(node.scrollLeft).toBe(0);
expect(survived).toBe(true);
});
it("declines at the end so the wheel chains to the transcript", () => {
const node = rail();
keep(attachRailWheel(node));
node.scrollLeft = 400; // scrollWidth 600 - clientWidth 200
const survived = wheel(node, { deltaMode: 0, deltaX: 0, deltaY: 120 });
expect(node.scrollLeft).toBe(400);
expect(survived).toBe(true);
});
it("ignores a rail with nothing to scroll", () => {
const node = rail({ clientWidth: 600, scrollWidth: 600 });
keep(attachRailWheel(node));
const survived = wheel(node, { deltaMode: 0, deltaX: 0, deltaY: 120 });
expect(node.scrollLeft).toBe(0);
expect(survived).toBe(true);
});
});
describe("the rail's overflow flag", () => {
it("says nothing when everything fits", () => {
const node = rail({ clientWidth: 600, scrollWidth: 600 });
keep(attachRailWheel(node));
expect(node.dataset.overflow).toBeUndefined();
});
it("tracks which ends have more", () => {
const node = rail();
keep(attachRailWheel(node));
// A fresh rail sits at its start, so the only fade is on the right.
expect(node.dataset.overflow).toBe("right");
node.scrollLeft = 200;
node.dispatchEvent(new Event("scroll"));
expect(node.dataset.overflow).toBe("both");
node.scrollLeft = 400;
node.dispatchEvent(new Event("scroll"));
expect(node.dataset.overflow).toBe("left");
});
it("keeps the selection chip in view when a change arrives", () => {
// The rail starts unpinned, unlike the transcript. Its leftmost item is the
// selection chip — the one accent-coloured thing in the composer, and the
// only thing saying what these edits are *about*. Following the end from
// the start scrolled it off on the very first tweak.
const node = rail();
keep(attachRailWheel(node));
renderChangeChips(node, [chip("Button")]);
expect(node.scrollLeft).toBe(0);
});
it("follows the end for a reader who is already there", () => {
const node = rail();
keep(attachRailWheel(node));
atEnd(node);
renderChangeChips(node, [chip("Button")]);
expect(node.scrollLeft).toBe(400);
});
it("leaves a rail alone once it has been scrolled back", () => {
const node = rail();
keep(attachRailWheel(node));
atEnd(node);
node.scrollLeft = 120;
node.dispatchEvent(new Event("scroll"));
renderChangeChips(node, [chip("Button")]);
// Unpinned again, so chip twelve arriving does not interrupt reading three.
expect(node.scrollLeft).toBe(120);
});
});
describe("a chip's fields", () => {
it("renders subject, detail and value as separate spans, in order", () => {
const node = rail();
renderChangeChips(node, [chip("RootDocument")]);
const spans = [...node.querySelectorAll("span[class]")]
.map((s) => s.className)
.filter((c) => c.includes("chip-"));
expect(spans[0]).toContain(cls("chip-subject"));
expect(spans[1]).toContain(cls("chip-detail"));
expect(spans[2]).toContain(cls("chip-value"));
expect(node.querySelector(`.${cls("chip-subject")}`)?.textContent).toBe(
"RootDocument"
);
});
it("gives a style chip no glyph", () => {
const node = rail();
renderChangeChips(node, [chip("Button")]);
// The ✕ carries the only icon on a style chip.
const chipEl = node.querySelector("[data-chip]");
expect(chipEl?.querySelector(`.${cls("ic")}`)?.closest("[data-chip]")).toBe(
chipEl
);
expect(chipEl?.children[0].className).toContain(cls("chip-subject"));
});
it("keeps a glyph where the kind is not spoken by the text", () => {
const node = rail();
renderChangeChips(node, [
chip("Badge", { detail: "moved", icon: "drag", value: undefined }),
]);
const chipEl = node.querySelector("[data-chip]");
expect(chipEl?.children[0].className).toContain(cls("ic"));
expect(chipEl?.querySelector(`.${cls("chip-value")}`)).toBeNull();
});
it("truncates only the value", () => {
expect(shortValue("cubic-bezier(0.16, 1, 0.3, 1)")).toBe("cubic-bezier(…");
expect(shortValue("0 0")).toBe("0 0");
});
it("makes the rail one tab stop, not one per chip", () => {
const node = rail();
renderChangeChips(node, [chip("A"), chip("B"), chip("C")]);
keep(attachRailKeys(node));
const tabbable = [...node.querySelectorAll<HTMLElement>("[tabindex='0']")];
expect(tabbable).toHaveLength(1);
expect(
node.querySelectorAll(`.${cls("chip-x")}[tabindex='0']`)
).toHaveLength(0);
});
it("counts the natively-tabbable Discard all as part of the roving", () => {
/*
* `[tabindex='0']` alone cannot see this, which is how it got through.
*
* "Discard all" is a real `<button>`, so it is a tab stop with no
* `tabindex` at all — and it carried no `data-chip`, so `attachRailKeys`
* never adopted it. The rail was two tab stops while the case above went on
* reporting one. This asks the question the other way: every element in the
* rail that the browser would stop on must be one the roving owns.
*/
const node = rail();
renderChangeChips(node, [chip("A"), chip("B")], () => undefined);
keep(attachRailKeys(node));
const stops = [...node.querySelectorAll<HTMLElement>("*")].filter(
(n) => n.tabIndex === 0
);
expect(stops).toHaveLength(1);
// And the button really is present, or the case proves nothing.
expect(node.querySelector(`.${cls("chip-all")}`)).not.toBeNull();
expect(
node.querySelector(`.${cls("chip-all")}`)?.getAttribute("data-chip")
).toBe("");
});
});
describe("arrowing through the chips", () => {
it("walks forward and back, and stops at the ends", () => {
const node = rail();
renderChangeChips(node, [chip("A"), chip("B"), chip("C")]);
keep(attachRailKeys(node));
const chips = [...node.querySelectorAll<HTMLElement>("[data-chip]")];
chips[0].focus();
press(chips[0], "ArrowRight");
expect(document.activeElement).toBe(chips[1]);
press(chips[1], "ArrowRight");
press(chips[2], "ArrowRight");
expect(document.activeElement).toBe(chips[2]);
press(chips[2], "ArrowLeft");
expect(document.activeElement).toBe(chips[1]);
});
it("jumps to the ends with Home and End", () => {
const node = rail();
renderChangeChips(node, [chip("A"), chip("B"), chip("C")]);
keep(attachRailKeys(node));
const chips = [...node.querySelectorAll<HTMLElement>("[data-chip]")];
chips[1].focus();
press(chips[1], "End");
expect(document.activeElement).toBe(chips[2]);
press(chips[2], "Home");
expect(document.activeElement).toBe(chips[0]);
});
it("scrolls the chip it lands on into view", () => {
const node = rail();
renderChangeChips(node, [chip("A"), chip("B")]);
keep(attachRailKeys(node));
const chips = [...node.querySelectorAll<HTMLElement>("[data-chip]")];
const seen = vi.fn();
chips[1].scrollIntoView = seen;
chips[0].focus();
press(chips[0], "ArrowRight");
expect(seen).toHaveBeenCalledWith({ block: "nearest", inline: "nearest" });
});
it("drops the focused chip on Backspace and keeps focus in the rail", () => {
const node = rail();
const dropped: string[] = [];
const three = ["A", "B", "C"].map((s) =>
chip(s, { onRemove: () => dropped.push(s) })
);
renderChangeChips(node, three);
keep(attachRailKeys(node));
const chips = [...node.querySelectorAll<HTMLElement>("[data-chip]")];
chips[1].focus();
press(chips[1], "Backspace");
expect(dropped).toEqual(["B"]);
// Nothing re-rendered the rail in this test, so the chip is still present;
// what matters is that focus stayed on a chip rather than escaping.
expect(
(document.activeElement as HTMLElement | null)?.hasAttribute("data-chip")
).toBe(true);
});
it("never fires outside its own rail", () => {
const node = rail();
renderChangeChips(node, [chip("A"), chip("B")]);
keep(attachRailKeys(node));
const chips = [...node.querySelectorAll<HTMLElement>("[data-chip]")];
chips[0].focus();
// The same chord, from a node the rail does not contain. Without `within`
// this is the nudge binding's keystroke and the rail would steal it.
const outside = el("div", { tabindex: "0" });
document.body.append(outside);
press(outside, "ArrowRight");
expect(document.activeElement).toBe(chips[0]);
});
it("describes itself as a toolbar", () => {
const node = rail();
keep(attachRailKeys(node));
expect(node.getAttribute("role")).toBe("toolbar");
expect(node.getAttribute("aria-orientation")).toBe("horizontal");
expect(node.getAttribute("aria-label")).toBe("Pending changes");
});
});
+304 -25
View File
@@ -11,17 +11,40 @@
* blue things side by side both claiming to be the important one is worse than
* either. The selection chip keeps the accent, which makes it the one coloured
* thing in the row — the hierarchy the strip actually wants.
*
* The strip is a horizontal rail, and reaching the far end of it used to depend
* on the pointing device. See `attachRailWheel`.
*/
import { pixelDelta } from "../canvas/wheel";
import { cls, el } from "../dom";
import { type IconName, icon } from "../icons";
import { keys } from "../keys/registry";
/** One pending edit, as the composer shows it. */
/** Fractional scroll positions never land exactly on the ends. */
const SCROLL_EPSILON = 1;
/**
* One pending edit, as the composer shows it.
*
* Three fields rather than one string. They were joined with spaces at the call
* site and rendered as a single run of 10px mono, so a style chip read
* "RootDocument flex 0 0" — three different kinds of thing with nothing to say
* where one ended and the next began. Splitting them lets the strip spend its
* one available axis, tone, on the boundary: what it is about, what changed,
* what it changed to.
*/
export interface ChangeChip {
icon: IconName;
label: string;
onRemove: () => void;
/** Full text for the tooltip — `label` is truncated to fit the strip. */
tip: string;
/** What changed: "flex", "moved", "duplicated". */
readonly detail?: string;
/** Leading glyph, where the kind is not already spoken by `detail`. */
readonly icon?: IconName;
readonly onRemove: () => void;
/** What the edit is about: "RootDocument", "Button:hover". Ellipsises first. */
readonly subject: string;
/** Full text for the tooltip — the fields above are truncated to fit. */
readonly tip: string;
/** The new value, where there is one. */
readonly value?: string;
}
/**
@@ -41,27 +64,57 @@ export function renderChangeChips(
onDiscardAll?: (anchor: HTMLElement) => void
): void {
for (const chip of chips) {
const parts: HTMLElement[] = [];
if (chip.icon) {
// `xs`, not `sm`: a 20px glyph beside 11px text made a chip 28px tall and
// mostly whitespace, on a rail whose scarce axis is width.
parts.push(icon(chip.icon, "xs"));
}
parts.push(el("span", { class: cls("chip-subject"), text: chip.subject }));
if (chip.detail) {
parts.push(el("span", { class: cls("chip-detail"), text: chip.detail }));
}
if (chip.value) {
parts.push(el("span", { class: cls("chip-value"), text: chip.value }));
}
parts.push(
el(
"span",
{
"aria-label": `Drop ${chip.tip}`,
class: cls("chip-x"),
"data-tip": "Drop this change",
onClick: chip.onRemove,
role: "button",
// Not a tab stop of its own. Twelve pending edits used to mean twelve
// stops between the composer and anything after it; the rail is one
// stop now and ⌫ on the focused chip is the keyboard route to this.
tabindex: "-1",
},
[icon("close", "sm")]
)
);
host.append(
el("span", { class: `${cls("sel-chip")} ${cls("tweak-chip")}` }, [
icon(chip.icon, "sm"),
el("span", { class: cls("chip-label"), text: chip.label }),
el(
"span",
{
"aria-label": `Drop ${chip.tip}`,
class: cls("chip-x"),
"data-tip": "Drop this change",
onClick: chip.onRemove,
role: "button",
tabindex: "0",
},
[icon("close", "sm")]
),
])
el(
"span",
{
// A labelled group, not a bare span. The rail is a `role="toolbar"`
// and this is one of its items, so without these a screen reader
// reaches a focusable element that announces nothing and gives no clue
// that ⌫ is what removes it.
"aria-keyshortcuts": "Delete",
"aria-label": chip.tip,
class: `${cls("sel-chip")} ${cls("tweak-chip")}`,
// The tip goes on the chip itself so hovering anywhere on it explains
// the change; the ✕ overrides it with what clicking will do.
"data-chip": "",
"data-tip": chip.tip,
role: "group",
tabindex: "-1",
},
parts
)
);
// The tip goes on the chip itself so hovering anywhere on it explains the
// change; the ✕ overrides it with what clicking will do.
(host.lastElementChild as HTMLElement).dataset.tip = chip.tip;
}
if (onDiscardAll && chips.length > 1) {
@@ -69,7 +122,15 @@ export function renderChangeChips(
"button",
{
class: `${cls("sel-chip")} ${cls("chip-all")}`,
// In the roving order like every other item, and not a tab stop of its
// own. As a native button with neither, it escaped `attachRailKeys`
// (which selects on `[data-chip]`) while still being tabbable — so the
// rail was two tab stops, which is exactly what the roving exists to
// prevent. ⌫ on it finds no ✕ and is a safe no-op; Enter and Space
// activate it natively.
"data-chip": "",
"data-tip": "Discard every pending change",
tabindex: "-1",
type: "button",
},
[icon("close", "sm"), el("span", { text: "Discard all" })]
@@ -84,3 +145,221 @@ export function shortValue(value: string, max = 14): string {
const v = value.trim();
return v.length > max ? `${v.slice(0, max - 1)}…` : v;
}
/**
* Make a horizontal chip rail reachable with a mouse, and say when it has more.
*
* The rail has always scrolled. What it had no way of telling you is that it
* scrolls: the scrollbar was hidden outright, there was no wheel handler, and
* nothing marked the edges. A trackpad papers over all three — a two-finger
* swipe produces `deltaX` and scrolls the rail natively — so on a trackpad the
* strip is fine and on a mouse the twelfth chip does not exist. Every wheel a
* mouse sends is `deltaY`, and a box that only overflows on X ignores it.
*
* So: translate a vertical wheel into horizontal scroll, and publish how much
* is off each end as `data-overflow` for the mask in `base.css`.
*
* `pixelDelta` rather than raw `deltaY`, for the reason written where it lives:
* most mouse wheels report *lines* (a notch is `deltaY: 3`, not `120`), so the
* unconverted value scrolls a rail by three pixels per notch and reads as
* broken rather than as slow. That normalisation is the whole difference
* between this working on a mouse and only appearing to.
*
* The gesture is declined at either end rather than clamped silently: an
* uncancelled wheel there chains to the transcript above, which is what a
* vertical wheel over a full rail should do.
*
* Self-syncing, because the caller cannot be trusted to remember both triggers:
* chips arrive and leave without the rail's own box changing (MutationObserver),
* and the dock resizes without the chips changing (ResizeObserver).
*
* A rail already scrolled to its end stays there when a chip is appended — the
* same pin the transcript keeps (`AirshipApp.scrollTranscript`), and for the
* same reason: the newest thing is what you just did and what you want to see
* confirmed. A rail scrolled back is left alone, so reading chip three is not
* interrupted by chip twelve arriving.
*
* It starts *un*pinned, which is the opposite of the transcript and is the
* whole difference between the two: the transcript's newest entry is at the
* bottom and nothing above it needs to stay in view, while this rail's leftmost
* item is the *selection* chip — the one accent-coloured thing in the composer,
* and the only thing saying what these edits are about. Pinning from the start
* scrolled it off the moment the first change landed.
*/
export function attachRailWheel(rail: HTMLElement): () => void {
let pinned = false;
const sync = (): void => {
const max = rail.scrollWidth - rail.clientWidth;
if (max <= SCROLL_EPSILON) {
rail.removeAttribute("data-overflow");
return;
}
if (pinned) {
rail.scrollLeft = max;
}
const left = rail.scrollLeft > SCROLL_EPSILON;
const right = rail.scrollLeft < max - SCROLL_EPSILON;
if (left && right) {
rail.dataset.overflow = "both";
} else if (left) {
rail.dataset.overflow = "left";
} else {
rail.dataset.overflow = "right";
}
};
const onScroll = (): void => {
const max = rail.scrollWidth - rail.clientWidth;
pinned = max <= SCROLL_EPSILON || rail.scrollLeft >= max - SCROLL_EPSILON;
sync();
};
const onWheel = (e: WheelEvent): void => {
// A horizontal wheel is already this rail's own scrolling — leave it alone
// rather than adding our delta to the browser's.
if (e.deltaX !== 0 || e.deltaY === 0) {
return;
}
const max = rail.scrollWidth - rail.clientWidth;
if (max <= SCROLL_EPSILON) {
return;
}
const next = Math.max(0, Math.min(max, rail.scrollLeft + pixelDelta(e).y));
if (next === rail.scrollLeft) {
return;
}
rail.scrollLeft = next;
e.preventDefault();
};
rail.addEventListener("wheel", onWheel, { passive: false });
rail.addEventListener("scroll", onScroll, { passive: true });
const resize = new ResizeObserver(sync);
resize.observe(rail);
const mutate = new MutationObserver(sync);
mutate.observe(rail, { childList: true, subtree: true });
sync();
return () => {
rail.removeEventListener("wheel", onWheel);
rail.removeEventListener("scroll", onScroll);
resize.disconnect();
mutate.disconnect();
};
}
/**
* Arrow through the chips on a rail, and drop the one you land on.
*
* A roving tabindex: the rail is one tab stop, ← and → move between chips,
* Home and End jump to the ends, and ⌫ discards the focused chip. Before this
* the only focusable thing in a chip was its ✕, so a dozen pending edits put a
* dozen tab stops between the composer and everything after it — and there was
* still no way to *see* a chip that had scrolled off, because focus never
* moved to one.
*
* Bound with `within` so these never fire outside the rail: ← and → are the
* nudge bindings everywhere else, and a chip is only ever focused while the
* user is looking at the strip. `within` is checked before the chord, so the
* nudge never gets the keystroke.
*
* The rail is a toolbar rather than a list: its children are controls, one tab
* stop with arrow navigation between them is the pattern that describes, and a
* list would promise a reading structure that a horizontally-scrolled strip of
* eleven-pixel chips does not have.
*/
export function attachRailKeys(rail: HTMLElement): () => void {
rail.setAttribute("role", "toolbar");
rail.setAttribute("aria-label", "Pending changes");
rail.setAttribute("aria-orientation", "horizontal");
const chipsOf = (): HTMLElement[] => [
...rail.querySelectorAll<HTMLElement>("[data-chip]"),
];
/** Exactly one chip must stay tabbable, or the rail drops out of tab order. */
const seed = (): void => {
const all = chipsOf();
if (!all.length || all.some((c) => c.tabIndex === 0)) {
return;
}
all[0].tabIndex = 0;
};
const focusAt = (i: number): void => {
const all = chipsOf();
if (!all.length) {
return;
}
const next = all[Math.max(0, Math.min(all.length - 1, i))];
for (const c of all) {
c.tabIndex = c === next ? 0 : -1;
}
next.focus();
// `nearest`, so a chip already on screen does not recentre the rail under
// the pointer. This is the half that makes arrowing feel like scrolling.
next.scrollIntoView({ block: "nearest", inline: "nearest" });
};
const focused = (): { all: HTMLElement[]; chip: HTMLElement | null } => {
const all = chipsOf();
const active = rail.ownerDocument.activeElement as HTMLElement | null;
return { all, chip: active?.closest<HTMLElement>("[data-chip]") ?? null };
};
const step = (delta: number) => () => {
const { all, chip } = focused();
focusAt(chip ? all.indexOf(chip) + delta : 0);
};
const off = keys.bindAll([
{
id: "chips.next",
run: step(1),
within: rail,
},
{
id: "chips.prev",
run: step(-1),
within: rail,
},
{
id: "chips.first",
run: () => focusAt(0),
within: rail,
},
{
id: "chips.last",
run: () => focusAt(chipsOf().length - 1),
within: rail,
},
{
id: "chips.drop",
run: () => {
const { all, chip } = focused();
if (!chip) {
return;
}
const i = all.indexOf(chip);
// Click the ✕ rather than calling `onRemove` directly: the chip is
// rebuilt from scratch by `renderComposerChips`, so the handler that
// knows how to discard this one lives on the node, not here.
chip.querySelector<HTMLElement>(`.${cls("chip-x")}`)?.click();
// The rail has been rebuilt by now. Land on whatever took its place,
// so a run of ⌫ clears the strip without the focus falling out of it.
focusAt(Math.min(i, chipsOf().length - 1));
},
within: rail,
},
]);
const mutate = new MutationObserver(seed);
mutate.observe(rail, { childList: true });
seed();
return () => {
off();
mutate.disconnect();
};
}
+25 -8
View File
@@ -8,6 +8,7 @@
*/
import { cls, el } from "../dom";
import { icon } from "../icons";
import { keys } from "../keys/registry";
import { closeOpenPopover, openPopover } from "../popover-host";
export interface CommentContext {
@@ -47,17 +48,15 @@ export function openCommentPopover(
// The popover host owns Escape for the shell, but a focused field swallows
// the keydown before it ever reaches the document — so the field has to
// close the popover itself. ⌘↵ submits, matching the composer.
// close the popover itself. Escape stays field-local for that reason; ⌘↵
// does not, because `allowWhileTyping` is exactly the exemption that lets a
// field's own submit through the registry, and going through it is what puts
// the right chord on the hint below on every platform.
field.addEventListener("keydown", (e) => {
const ev = e as KeyboardEvent;
if (ev.key === "Escape") {
ev.preventDefault();
closeOpenPopover("escape");
return;
}
if (ev.key === "Enter" && (ev.metaKey || ev.ctrlKey)) {
ev.preventDefault();
submit();
}
});
@@ -68,7 +67,10 @@ export function openCommentPopover(
]),
field,
el("div", { class: cls("comment-actions") }, [
el("span", { class: cls("comment-hint"), text: "⌘↵ to add" }),
el("span", {
class: cls("comment-hint"),
text: `${keys.hint("comment.add") ?? ""} to add`,
}),
el(
"button",
{
@@ -81,6 +83,21 @@ export function openCommentPopover(
]),
]);
openPopover({ anchor, className: "pop-comment", content, prefer: "below" });
// Scoped to the popover's own content, so ⌘↵ here never reaches the
// composer's Send — the two commands share a chord and are told apart by
// scope, which is what `catalog.test.ts` licenses them on.
const offSubmit = keys.bind({
id: "comment.add",
run: submit,
within: content,
});
openPopover({
anchor,
className: "pop-comment",
content,
onClose: offSubmit,
prefer: "below",
});
field.focus();
}
@@ -0,0 +1,223 @@
/**
* The picker's content: three harness groups, and the typed-id escape hatch.
*
* `modelGroups` returns data rather than DOM, which is what makes most of this
* testable without a menu to put it in — the same reason `deviceGroups` is
* split out of the two menus that render it. `customModelRow` does build an
* element, so its tests drive the real one.
*/
import type { ModelCatalogue } from "@airship/protocol";
import { describe, expect, it, vi } from "vitest";
import type { MenuItem } from "../popover-host";
import { customModelRow, modelGroups, modelLabel } from "./model-menu";
const CATALOGUE: ModelCatalogue = [
{
agent: "claude",
default: "opus",
models: [
{ hint: "1M", id: "claude-opus-5", label: "Opus 5" },
{ id: "sonnet", label: "Sonnet" },
],
},
{ agent: "codex", models: [{ id: "gpt-5.6", label: "GPT-5.6" }] },
{ agent: "opencode", models: [], note: "Not signed in" },
];
function groupsFor(
agent: "claude" | "codex" | "opencode",
models: Record<string, string> = {},
pick = vi.fn()
) {
return {
groups: modelGroups({ agent, catalogue: CATALOGUE, models, pick }),
pick,
};
}
/** A group's rows, which are all `MenuItem`s by construction. */
function labels(items: MenuItem[]): string[] {
return items.map((i) => i.label);
}
describe("modelGroups", () => {
it("offers every harness, in picker order", () => {
const { groups } = groupsFor("claude");
expect(groups.map((g) => g.group)).toEqual(["claude", "codex", "opencode"]);
});
it("opens the group for the backend the composer is on", () => {
// Seeded from the current agent rather than left to fall back to the first,
// so opening the menu on Codex shows you Codex.
expect(groupsFor("codex").groups.find((g) => g.open)?.group).toBe("codex");
expect(groupsFor("opencode").groups.find((g) => g.open)?.group).toBe(
"opencode"
);
});
it("opens exactly one group", () => {
const open = groupsFor("codex").groups.filter((g) => g.open);
expect(open).toHaveLength(1);
});
it("leads every group with Default", () => {
for (const group of groupsFor("claude").groups) {
expect(group.items[0].label).toBe("Default");
}
});
it("shows the daemon's resolved default as the Default row's hint", () => {
const [claude] = groupsFor("claude").groups;
expect(claude.items[0].hint).toBe("opus");
});
it("falls back to a phrase when no default was resolved", () => {
const [, codex] = groupsFor("codex").groups;
expect(codex.items[0].hint).toBe("the backend decides");
});
it("marks Default as on when no model is picked for that backend", () => {
const [claude] = groupsFor("claude").groups;
expect(claude.items[0].on).toBe(true);
});
it("marks the picked model instead, once there is one", () => {
const [claude] = groupsFor("claude", { claude: "sonnet" }).groups;
expect(claude.items[0].on).toBe(false);
expect(claude.items.find((i) => i.label === "Sonnet")?.on).toBe(true);
});
it("marks each backend's own model, not the active one's", () => {
// The reason the state is per harness at all: Claude's pick must not light
// up a row in Codex's group.
const [claude, codex] = groupsFor("claude", {
claude: "sonnet",
codex: "gpt-5.6",
}).groups;
expect(claude.items.find((i) => i.label === "Sonnet")?.on).toBe(true);
expect(codex.items.find((i) => i.label === "GPT-5.6")?.on).toBe(true);
});
it("shows a backend's note as a disabled row when it has no models", () => {
// An empty group reads as a broken picker; a group that says "Not signed
// in" reads as something the user can go and fix.
const [, , opencode] = groupsFor("claude").groups;
expect(labels(opencode.items)).toEqual(["Default", "Not signed in"]);
expect(opencode.items[1].disabled).toBe(true);
});
it("keeps a failing backend in the list", () => {
// Switching *to* a backend you have not signed into yet is a thing the
// picker has to allow, so a group never disappears on a failed probe.
expect(groupsFor("claude").groups).toHaveLength(3);
});
it("picks the backend and the model together", () => {
const { groups, pick } = groupsFor("claude");
const [, codex] = groups;
codex.items.find((i) => i.label === "GPT-5.6")?.run();
expect(pick).toHaveBeenCalledWith({ agent: "codex", model: "gpt-5.6" });
});
it("sends an empty model for the Default row", () => {
const { groups, pick } = groupsFor("claude");
groups[0].items[0].run();
expect(pick).toHaveBeenCalledWith({ agent: "claude", model: "" });
});
it("carries each backend's mark on its header", () => {
expect(groupsFor("claude").groups.map((g) => g.icon)).toEqual([
"claude",
"codex",
"opencode",
]);
});
});
describe("modelLabel", () => {
it("reads default when nothing is picked", () => {
expect(modelLabel(CATALOGUE, "claude", undefined)).toBe("default");
});
it("resolves a picked id to its label", () => {
expect(modelLabel(CATALOGUE, "claude", "claude-opus-5")).toBe("Opus 5");
});
it("falls back to the raw id for a model it has never heard of", () => {
// A typed id, or one the seed predates. Showing it verbatim is better than
// showing nothing, and it is what the user entered.
expect(modelLabel(CATALOGUE, "claude", "claude-opus-9")).toBe(
"claude-opus-9"
);
});
});
describe("customModelRow", () => {
function row(agent: "claude" | "opencode" = "claude") {
const apply = vi.fn();
const close = vi.fn();
const node = customModelRow(agent, apply, close);
const input = node.querySelector("input") as HTMLInputElement;
const button = node.querySelector("button") as HTMLButtonElement;
return { apply, button, close, input, node };
}
function press(input: HTMLInputElement, key: string): void {
input.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key }));
}
it("commits on Enter and closes the menu", () => {
const { apply, close, input } = row();
input.value = "claude-opus-9";
press(input, "Enter");
expect(apply).toHaveBeenCalledWith("claude-opus-9");
expect(close).toHaveBeenCalled();
});
it("commits on the button too", () => {
const { apply, button, input } = row();
input.value = "sonnet";
button.click();
expect(apply).toHaveBeenCalledWith("sonnet");
});
it("trims what was typed", () => {
const { apply, input } = row();
input.value = " sonnet ";
press(input, "Enter");
expect(apply).toHaveBeenCalledWith("sonnet");
});
it("does nothing on Enter in an empty field", () => {
const { apply, close, input } = row();
press(input, "Enter");
expect(apply).not.toHaveBeenCalled();
expect(close).not.toHaveBeenCalled();
});
it("closes on Escape without applying", () => {
// Handled on the field rather than left to the menu: `keys/registry.ts` suppresses
// bindings without `allowWhileTyping` while a field has focus, so the
// menu's own Escape never fires here.
const { apply, close, input } = row();
input.value = "sonnet";
press(input, "Escape");
expect(apply).not.toHaveBeenCalled();
expect(close).toHaveBeenCalled();
});
it("stops a press in the field from picking the row it sits in", () => {
const { input } = row();
for (const type of ["click", "pointerdown"]) {
const event = new Event(type, { bubbles: true, cancelable: true });
input.dispatchEvent(event);
expect(event.cancelBubble).toBe(true);
}
});
it("shows opencode the form it needs", () => {
expect(row("opencode").input.placeholder).toBe("provider/model");
expect(row("claude").input.placeholder).not.toContain("/");
});
});
+207
View File
@@ -0,0 +1,207 @@
/**
* "Which backend, on which model?", as menu content.
*
* The header used to ask only the first half, because the second was settled at
* launch by `--model` and could not be changed without restarting the daemon.
* Splitting them into two controls was the obvious shape and the wrong one: a
* model id only means anything against a backend — `claude-opus-5` is not a
* thing Codex can run — so two independent pickers would spend most of their
* time in states that cannot be sent.
*
* So it stays one menu, and the grouping carries the pairing: one collapsible
* group per harness, and choosing any row inside it chooses both. This is the
* same construction `canvas/device-menu.ts` uses for the device presets, for
* the same reason — a flat column of every model across three backends is a
* scroll, and four lines you open one of is a menu.
*/
import type { AgentKind, ModelCatalogue, ModelOption } from "@airship/protocol";
import { cls, el } from "../dom";
import type { IconName } from "../icons";
import type { MenuGroup, MenuItem } from "../popover-host";
/** The id that means "send no model and let the daemon's default stand". */
export const MODEL_DEFAULT = "";
export interface ModelPick {
agent: AgentKind;
/** `MODEL_DEFAULT` for the group's leading row. */
model: string;
}
export interface ModelMenuDeps {
/** The harness the composer is on. Its group opens. */
agent: AgentKind;
/** Live catalogue if one has arrived, else the seed. */
catalogue: ModelCatalogue;
/** The current model per harness, so each group marks its own. */
models: Partial<Record<AgentKind, string>>;
pick: (choice: ModelPick) => void;
}
/** Product marks, in the order the picker offers the backends. */
const AGENT_META: { icon: IconName; kind: AgentKind; label: string }[] = [
{ icon: "claude", kind: "claude", label: "Claude" },
{ icon: "codex", kind: "codex", label: "Codex" },
{ icon: "opencode", kind: "opencode", label: "OpenCode" },
];
/** The label a picked model gets in the button's tooltip. */
export function modelLabel(
catalogue: ModelCatalogue,
agent: AgentKind,
model: string | undefined
): string {
if (!model) {
return "default";
}
const group = catalogue.find((g) => g.agent === agent);
return group?.models.find((m) => m.id === model)?.label ?? model;
}
/**
* The rows for one harness.
*
* Every group leads with Default, and it is a real choice rather than a
* placeholder: picking it clears the model from the request so the daemon's
* own resolved setting applies — which is what `--claude-model` and
* `airship.config.json` are for, and the only way back to them once a model has
* been picked by hand.
*/
function rowsFor(
agent: AgentKind,
models: ModelOption[],
current: string | undefined,
fallback: string | undefined,
note: string | undefined,
pick: (choice: ModelPick) => void
): MenuItem[] {
const rows: MenuItem[] = [
{
hint: fallback ?? "the backend decides",
label: "Default",
on: !current,
run: () => pick({ agent, model: MODEL_DEFAULT }),
},
];
// A backend that could not be reached says so in place of its models. A group
// that is simply empty reads as a broken picker rather than a missing login,
// and the two want very different things from the user.
if (note && !models.length) {
rows.push({ disabled: true, label: note, run: () => undefined });
}
for (const model of models) {
rows.push({
hint: model.hint,
label: model.label,
on: model.id === current,
run: () => pick({ agent, model: model.id }),
});
}
return rows;
}
/**
* The catalogue as collapsible `createMenu` groups.
*
* `open` is seeded from the composer's current backend rather than left to fall
* back to the first, so opening the menu on Codex shows you Codex's models. The
* three groups are always present even when a probe returned nothing — the
* picker's job includes letting you *switch to* a backend you have not signed
* into yet, and a group that vanishes when it fails cannot do that.
*/
export function modelGroups(deps: ModelMenuDeps): MenuGroup[] {
return AGENT_META.map((meta) => {
const group = deps.catalogue.find((g) => g.agent === meta.kind);
return {
group: meta.kind,
icon: meta.icon,
items: rowsFor(
meta.kind,
group?.models ?? [],
deps.models[meta.kind],
group?.default,
group?.note,
deps.pick
),
label: meta.label,
open: meta.kind === deps.agent,
};
});
}
/**
* The typed-id escape hatch from the list.
*
* `close` is a parameter rather than a call to the menu's own closer for the
* same reason `customSizeRow` takes one: the row has no business knowing which
* menu it was put in.
*
* Enter and Escape are handled on the field, not left to the menu. `Keys` skips
* every binding without `allowWhileTyping` while a field has focus, so with
* this one focused the menu's own Escape never runs and the only way out would
* be the mouse — `keys/registry.ts` prescribes exactly this, and `customSizeRow` and
* `renameFrame` already do it.
*/
export function customModelRow(
agent: AgentKind,
apply: (model: string) => void,
close: () => void
): HTMLElement {
const input = el("input", {
// A placeholder is not a label: it is announced inconsistently and vanishes
// the moment anyone types. This field is the only unlabelled control in the
// picker, and it is the one that takes free text.
"aria-label": `Model id for ${agent}`,
class: cls("pop-custom-input"),
// The form each backend takes, shown rather than explained: opencode drops
// an id it cannot attribute to a provider, and the placeholder is the
// cheapest place to say so.
placeholder: agent === "opencode" ? "provider/model" : "model id or alias",
spellcheck: "false",
type: "text",
}) as HTMLInputElement;
const commit = (): void => {
const model = input.value.trim();
if (!model) {
return;
}
// Deliberately not rejected here when opencode gets a bare id. The daemon
// is the one that knows — the CLI already refuses `--opencode-model sonnet`
// outright — and a field that argues with what you typed, in a menu, with
// nowhere to put the message, is worse than a turn that reports back.
apply(model);
close();
};
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
commit();
return;
}
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
close();
}
});
// A press in the field is not a choice, and the row it sits in is inside a
// menu that closes on one.
input.addEventListener("click", (e) => e.stopPropagation());
input.addEventListener("pointerdown", (e) => e.stopPropagation());
return el("div", { class: cls("pop-custom") }, [
input,
el("button", {
class: cls("pop-custom-go"),
onClick: (e: Event) => {
e.stopPropagation();
commit();
},
text: "Use",
type: "button",
}),
]);
}
@@ -0,0 +1,131 @@
/**
* The picker's stored choice.
*
* Every test here stubs `localStorage` explicitly, and that is not boilerplate.
* happy-dom hands the suite a bare object with no `getItem`/`setItem`, so the
* calls below would throw into the `catch` and every assertion would pass
* against a store that had silently done nothing — a green suite proving the
* opposite of what it claims. The rest of the overlay's persisted state gets
* away without one only because it saves through a callback the tests never
* fire (see the note in `canvas/frames.test.ts`); this one saves eagerly.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { restoreModelPick, saveModelPick } from "./model-store";
const NAMESPACED = /^__airship/;
let store: Record<string, string>;
beforeEach(() => {
store = {};
vi.stubGlobal("localStorage", {
getItem: (k: string) => store[k] ?? null,
removeItem: (k: string) => {
delete store[k];
},
setItem: (k: string, v: string) => {
store[k] = v;
},
});
});
afterEach(() => {
vi.unstubAllGlobals();
});
/** Whatever the store wrote, under whichever key it chose. */
function written(): string | undefined {
return Object.values(store)[0];
}
describe("saveModelPick / restoreModelPick", () => {
it("round-trips a backend and its models", () => {
const state = {
agent: "codex" as const,
models: { claude: "opus", codex: "gpt-5.6" },
};
saveModelPick(state);
expect(restoreModelPick()).toEqual(state);
});
it("actually writes something", () => {
// The assertion the stub exists for: without it this file would pass with
// an empty store and prove nothing at all.
saveModelPick({ agent: "claude", models: {} });
expect(written()).toContain("claude");
});
it("namespaces its key", () => {
saveModelPick({ agent: "claude", models: {} });
expect(Object.keys(store)[0]).toMatch(NAMESPACED);
});
it("returns nothing when there is nothing stored", () => {
expect(restoreModelPick()).toEqual({ models: {} });
});
});
describe("restoreModelPick — untrusted input", () => {
function stored(value: string): void {
store["__airship-model"] = value;
}
it("survives unparseable JSON", () => {
stored("{ nope");
expect(restoreModelPick()).toEqual({ models: {} });
});
it("survives a value that is not an object", () => {
stored('"claude"');
expect(restoreModelPick()).toEqual({ models: {} });
});
it("drops an agent it does not recognise", () => {
// A backend that was removed, or a hand-edited value. Leaving it would put
// the composer on an agent the daemon has never heard of.
stored(JSON.stringify({ agent: "gemini", models: {} }));
expect(restoreModelPick().agent).toBeUndefined();
});
it("drops a model keyed to an agent it does not recognise", () => {
stored(JSON.stringify({ agent: "claude", models: { gemini: "x" } }));
expect(restoreModelPick().models).toEqual({});
});
it("drops a model that is not a non-empty string", () => {
stored(
JSON.stringify({ models: { claude: 5, codex: "", opencode: "a/b" } })
);
expect(restoreModelPick().models).toEqual({ opencode: "a/b" });
});
it("keeps the models when only the agent is unusable", () => {
// The two halves are independent: a bad agent must not cost the user every
// model they had picked.
stored(JSON.stringify({ agent: 7, models: { claude: "opus" } }));
expect(restoreModelPick()).toEqual({ models: { claude: "opus" } });
});
});
describe("when storage itself fails", () => {
it("does not throw on save", () => {
vi.stubGlobal("localStorage", {
getItem: () => null,
setItem: () => {
throw new Error("QuotaExceededError");
},
});
expect(() => saveModelPick({ agent: "claude", models: {} })).not.toThrow();
});
it("falls back to the defaults on read", () => {
vi.stubGlobal("localStorage", {
getItem: () => {
throw new Error("SecurityError");
},
setItem: () => undefined,
});
expect(restoreModelPick()).toEqual({ models: {} });
});
});
+85
View File
@@ -0,0 +1,85 @@
/**
* The picker's choice, remembered between sessions.
*
* Its own module rather than a pair of methods on `AirshipApp` — which is what
* the dock's widths and layout are — for one reason: this is the only stored
* state in the overlay that is written *eagerly*. The canvas's viewport and
* frame layouts save through a callback that tests simply never trigger, so
* they have never needed `localStorage` to exist. This saves on every pick, so
* it does, and a module is something a test can drive without standing up the
* whole app.
*
* Reading is deliberately forgiving. The value is a convenience, and anything
* unparseable, half-written or left over from an older shape has to degrade to
* "nothing stored" rather than take the editor down on boot.
*/
import type { AgentKind } from "@airship/protocol";
import { PREFIX } from "../dom";
const KEY = `${PREFIX}-model`;
/** The agents a stored value may name, in the picker's order. */
const KINDS: readonly AgentKind[] = ["claude", "codex", "opencode"];
export interface ModelPickState {
/** The backend the composer is on. */
agent?: AgentKind;
/** The model chosen for each backend. Absent means that backend's default. */
models: Partial<Record<AgentKind, string>>;
}
function isAgent(value: unknown): value is AgentKind {
return typeof value === "string" && KINDS.includes(value as AgentKind);
}
/**
* Keep only the entries that could have come from this picker.
*
* A stored blob is untrusted input: it survives upgrades, it is editable by
* hand, and a stale key from a renamed backend would otherwise be sent to the
* daemon as a model for an agent that no longer exists.
*/
function cleanModels(raw: unknown): Partial<Record<AgentKind, string>> {
const models: Partial<Record<AgentKind, string>> = {};
if (!raw || typeof raw !== "object") {
return models;
}
for (const [agent, model] of Object.entries(raw)) {
if (isAgent(agent) && typeof model === "string" && model) {
models[agent] = model;
}
}
return models;
}
export function saveModelPick(state: ModelPickState): void {
try {
localStorage.setItem(KEY, JSON.stringify(state));
} catch {
// Quota or private mode — a forgotten model choice is not worth a crash.
}
}
/**
* What was stored, or nothing.
*
* `agent` being present is what the caller uses to decide that the daemon's
* `hello` must not re-seed the picker, so it is only set when a real backend
* name was found — an empty object here means "the daemon decides", which is
* the right answer for a first run.
*/
export function restoreModelPick(): ModelPickState {
try {
const raw = localStorage.getItem(KEY);
const parsed = raw ? JSON.parse(raw) : null;
if (!parsed || typeof parsed !== "object") {
return { models: {} };
}
const models = cleanModels(parsed.models);
return isAgent(parsed.agent) ? { agent: parsed.agent, models } : { models };
} catch {
// Unparseable, or no storage at all. Fall through to the defaults.
return { models: {} };
}
}
+6 -1
View File
@@ -182,7 +182,12 @@ function renderToolBody(body: HTMLElement, item: TimelineToolItem): void {
const detail = item.result?.detail;
if (detail) {
body.append(el("pre", { class: cls("tl-out"), text: detail }));
body.append(
el("pre", {
class: `${cls("tl-out")} ${cls("scroll-y")}`,
text: detail,
})
);
}
if (item.result?.truncated) {
const n = item.result.droppedLines;
+9 -2
View File
@@ -350,9 +350,16 @@ export function turnMenu(
const change: MenuEntry[] = [];
if (actions.onUndo) {
change.push({
hint: "⌘Z",
// No `hint`, and the label says "Revert" rather than "Undo".
//
// This row carried a `⌘Z` chip, which was not a stale glyph but a false
// statement: `onUndo` here is `AirshipApp.undo(jobId)`, the *server-side*
// revert of a finished job, while ⌘Z is `history.undo`, the local
// direct-manipulation stack. `app.ts` says in as many words that the two
// must never be wired together — and this menu was telling the user they
// were. There is no chord for this, so it advertises none.
icon: "rotate-ccw",
label: "Undo this change",
label: "Revert this change",
run: actions.onUndo,
});
}
+86 -18
View File
@@ -3,8 +3,10 @@ import { ROOT } from "./const";
/** Left dock: transcript, bubbles, composer, chips, actions, todos, diffs. */
export const css = `
/* The overflow and the scrollbar come from \`.scroll-y\` in base.css, the same
way the chip rails take theirs from \`.scroll-x\`. */
.${PREFIX}-transcript {
flex: 1 1 auto; overflow-y: auto; display: flex; flex-direction: column;
flex: 1 1 auto; display: flex; flex-direction: column;
gap: var(--ap-space-md); padding: var(--ap-space-md) var(--ap-space-lg);
}
/* The transcript's empty state is a \`.empty-md\` block (empty.css). This class
@@ -54,24 +56,37 @@ export const css = `
bordered box that starts one line tall — the previous arrangement spent
~145px at rest on padding, a 64px textarea floor and a Send pill on its own
row, which is a lot of permanent furniture for a panel whose real content is
the transcript above it. The right padding clears the absolutely-positioned
Send glyph so text never runs under it. */
the transcript above it.
The gutter that clears Send and the preview toggle belongs to \`.input\`, not
here. It lived on this rule as \`padding-right: 65px\`, and because \`.field\` is
a flex *column* that reserved 65px on every row — including the chip rails
above, where the two buttons are not: they are \`position: absolute\` and
*bottom*-anchored, so they only ever overlap the textarea. At the default
340px dock that left the rails ~223px of a possible ~322px and a permanent
dead gutter, which read as a mystery gap next to a lone chip.
Moving it costs nothing: an absolutely-positioned child resolves \`right\` and
\`bottom\` against this element's *padding box*, whose edges do not move when
padding changes. Both buttons keep their exact coordinates. */
.${PREFIX}-composer { flex: 0 0 auto; border-top: 1px solid var(--ap-border-default); padding: var(--ap-space-sm) var(--ap-space-md); }
.${PREFIX}-field {
position: relative; display: flex; flex-direction: column; gap: 4px;
padding: 6px 65px 6px 8px;
padding: 6px 8px;
background: var(--ap-input-bg); border: 1px solid var(--ap-input-border);
border-radius: var(--ap-radius-sm);
}
.${PREFIX}-field:focus-within { border-color: var(--ap-input-focus-border); }
/* Chip rows scroll sideways rather than wrapping: each pending change is now
its own chip, and wrapping a dozen of them would push the field to half the
dock. Hidden when empty so they cost nothing at rest. */
dock. Hidden when empty so they cost nothing at rest.
The overflow, the scrollbar and the edge fade come from \`.scroll-x\` in
base.css — see the note there about why hiding the scrollbar broke the mouse
and left it working on a trackpad. */
.${PREFIX}-sel-chips {
display: flex; flex-wrap: nowrap; gap: var(--ap-space-xs);
overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: none;
}
.${PREFIX}-sel-chips::-webkit-scrollbar { display: none; }
.${PREFIX}-sel-chips:empty { display: none; }
/* In a nowrap row a chip would otherwise shrink to fit rather than scroll. */
.${PREFIX}-sel-chips > * { flex: 0 0 auto; }
@@ -91,10 +106,45 @@ export const css = `
.${PREFIX}-tweak-chip {
color: var(--ap-text-secondary); background: var(--ap-surface-hover);
border-color: var(--ap-border-subtle);
font-size: var(--ap-font-size-caption); max-width: 240px;
font-family: var(--ap-font-sans);
/* Was \`caption\` (10px). At that size, with the three fields run together into
one string, the strip read as fine print you were meant to skip rather than
as the list of what Send is about to do. \`label\` is the editor's own
control size and it fits now that the rail has its full width back. */
font-size: var(--ap-font-size-label); max-width: 240px;
}
.${PREFIX}-tweak-chip:hover { color: var(--ap-text-primary); border-color: var(--ap-border-default); }
.${PREFIX}-chip-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Inset, like \`.tl-head\`'s. The rail is \`overflow-y: hidden\` — a one-row strip
has nothing to scroll vertically and should never grow a second scrollbar —
so a ring drawn *outside* the chip is clipped top and bottom, and the focus
state of a keyboard-only affordance reads as a rendering fault. */
.${PREFIX}-tweak-chip:focus-visible,
.${PREFIX}-sel-chip:focus-visible {
outline: 2px solid var(--ap-border-focus); outline-offset: -2px;
}
/* The three fields of a chip.
They were one space-joined string in 10px mono, so "RootDocument flex 0 0"
gave the reader no way to tell the element from the property from the value.
The strip has no colour left to spend — the selection chip is the one
emphasised thing in the row — so the boundary is carried by the tone ramp
instead, and a single \`·\` separates the two fields that can both be present.
Only the subject shrinks: it is the field with a long tail (component display
names run long), and \`min-width: 0\` is what lets it ellipsise inside a flex
row rather than pushing the value off the end. */
.${PREFIX}-chip-subject {
min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
color: var(--ap-text-primary);
}
.${PREFIX}-chip-detail { white-space: nowrap; color: var(--ap-text-secondary); }
.${PREFIX}-chip-value {
white-space: nowrap; color: var(--ap-text-tertiary); font-family: var(--ap-font-mono);
}
.${PREFIX}-chip-detail + .${PREFIX}-chip-value::before {
content: "·"; margin-right: 4px; opacity: .55;
}
/* The bulk escape hatch, at the end of the strip. Ghost — it is the most
destructive thing in the row and should not look like the cheapest. */
.${PREFIX}-chip-all {
@@ -109,8 +159,9 @@ export const css = `
so its empty state has a dock's worth of space to centre in, and \`margin:
auto\` needs a flex container to have anything to distribute. The head stays
pinned at the top either way — it is content-sized. */
/* Overflow from \`.scroll-y\`, as above. */
.${PREFIX}-drawer {
position: absolute; inset: 0; z-index: 2; overflow-y: auto;
position: absolute; inset: 0; z-index: 2;
padding: var(--ap-space-md) var(--ap-space-lg); background: var(--ap-surface-panel);
display: flex; flex-direction: column;
}
@@ -127,8 +178,9 @@ export const css = `
field you type into. So it takes the transcript's slot (hidden while this is
up) and leaves the head and composer where they are. Borrows the drawer's
head, eyebrow and close button so it still reads as the same kind of surface. */
/* Overflow from \`.scroll-y\`, as above. */
.${PREFIX}-pane {
flex: 1 1 auto; min-height: 0; overflow-y: auto;
flex: 1 1 auto; min-height: 0;
padding: var(--ap-space-md) var(--ap-space-lg); background: var(--ap-surface-panel);
display: flex; flex-direction: column;
}
@@ -173,11 +225,16 @@ export const css = `
/* Chat input. The box, border and background now belong to \`.field\`; this is
just the text surface inside it. \`resize: none\` because the height is
driven by content (see \`autoGrow\`) — a manual resize handle would fight it
on the next keystroke. No min-height: one row is the resting state. */
on the next keystroke. No min-height: one row is the resting state.
The 65px right padding is the gutter for Send and the preview toggle, and it
is on this rule rather than on \`.field\` because this is the only row those
two buttons overlap. \`box-sizing: border-box\` (base.css) means it comes out
of the 100%, not on top of it. */
.${PREFIX}-input {
width: 100%; resize: none; display: block; font-family: var(--ap-font-sans);
font-size: var(--ap-font-size-title); line-height: 1.45; color: var(--ap-text-primary);
background: transparent; border: 0; padding: 2px 0;
background: transparent; border: 0; padding: 2px 65px 2px 0;
}
.${PREFIX}-input::placeholder { color: var(--ap-text-placeholder); }
.${PREFIX}-input:focus { outline: none; }
@@ -213,12 +270,10 @@ export const css = `
/* A toggle that stays down while its surface is open. */
.${PREFIX}-iconbtn-on { background: var(--ap-surface-selected); color: var(--ap-text-primary); }
/* Chips. */
/* Chips. Same rail treatment as \`.sel-chips\` — \`.scroll-x\` owns the overflow. */
.${PREFIX}-chips {
display: flex; flex-wrap: nowrap; gap: var(--ap-space-xs);
overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: none;
}
.${PREFIX}-chips::-webkit-scrollbar { display: none; }
.${PREFIX}-chips:empty { display: none; }
.${PREFIX}-chips > * { flex: 0 0 auto; }
.${PREFIX}-chip {
@@ -226,8 +281,19 @@ export const css = `
background: var(--ap-surface-active); border: 1px solid var(--ap-border-default);
border-radius: var(--ap-radius-sm); padding: 4px 6px 4px 8px;
}
.${PREFIX}-chip-x { cursor: pointer; display: inline-flex; opacity: .6; }
/* Two elements wear this: the attachment rail's ✕ is a real \`<button>\`, so that
removing a pasted image is reachable from the keyboard, while the change
rail's is a span the roving strip drives with ⌫. The reset is what lets one
rule serve both — without it the button arrives with the UA's grey chrome,
its own border and its own font. Inert on the span. */
.${PREFIX}-chip-x {
cursor: pointer; display: inline-flex; opacity: .6;
padding: 0; border: 0; background: none; color: inherit; font: inherit;
}
.${PREFIX}-chip-x:hover { opacity: 1; }
.${PREFIX}-chip-x:focus-visible {
outline: 1px solid var(--ap-border-focus); outline-offset: 1px; opacity: 1;
}
/* Action buttons — compact, at editor density. Self-sized and right-aligned in the
composer (not a full-width marketing pill): the editor's controls are 28px
@@ -374,8 +440,10 @@ ${ROOT} .${PREFIX}-tl-res .${PREFIX}-ic { flex: 0 0 auto; --${PREFIX}-ic-tone: v
.${PREFIX}-tl-args-list dt { margin: 0; color: var(--ap-text-tertiary); }
.${PREFIX}-tl-args-list dd { margin: 0; color: var(--ap-text-secondary); word-break: break-word; }
/* Vertical overflow from \`.scroll-y\`; \`overflow-x\` stays here because a tool's
output is preformatted and its long lines scroll sideways. */
.${PREFIX}-tl-out {
margin: 0; padding: 6px 8px; max-height: 260px; overflow: auto;
margin: 0; padding: 6px 8px; max-height: 260px; overflow-x: auto;
font-family: var(--ap-font-mono); font-size: var(--ap-font-size-body); line-height: 1.5;
color: var(--ap-text-secondary); white-space: pre-wrap; word-break: break-word;
background: var(--ap-surface-panel);
+36 -1
View File
@@ -6,6 +6,10 @@ type Listener = (event: ServerEvent) => void;
export class AirshipSocket {
private ws: WebSocket | null = null;
private readonly listeners = new Set<Listener>();
/** The pending reconnect, so teardown can cancel one mid-flight. */
private retry = 0;
/** Torn down. Stops the reconnect loop, which is otherwise unstoppable. */
private dead = false;
private readonly path: string;
@@ -14,6 +18,9 @@ export class AirshipSocket {
}
connect(): void {
if (this.dead) {
return;
}
const proto = location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${proto}//${location.host}${this.path}`);
this.ws = ws;
@@ -29,11 +36,39 @@ export class AirshipSocket {
};
ws.onclose = () => {
this.ws = null;
setTimeout(() => this.connect(), 1500);
if (this.dead) {
return;
}
this.retry = window.setTimeout(() => this.connect(), 1500);
};
ws.onerror = () => ws.close();
}
/**
* Stop reconnecting and let go of every listener.
*
* Without this the reconnect loop is unstoppable by construction: `onclose`
* schedules the next attempt, so closing the socket is what *causes* it to
* come back. An overlay torn down and rebuilt in the same page — which
* `?__airship=inline` does on every HMR cycle — therefore left a live socket
* per cycle, each one holding a listener closed over a dead app and each one
* reconnecting to the daemon forever. `AirshipApp.destroy` releases the key
* bindings and the DOM; this is the third thing it has to release.
*
* The flag is checked in `connect` as well as in `onclose`, because a retry
* already in flight when this runs would otherwise open one last socket.
*/
destroy(): void {
this.dead = true;
clearTimeout(this.retry);
this.retry = 0;
this.listeners.clear();
// `onclose` is still wired and will fire; the flag above is what makes it
// a no-op rather than the start of the next attempt.
this.ws?.close();
this.ws = null;
}
/**
* Whether a `send` would actually reach the daemon.
*