Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md

- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
This commit is contained in:
Evan Whittaker
2026-10-20 02:40:13 -05:00
parent 99e30d6d0f
commit d2129a886f
423 changed files with 31666 additions and 1669 deletions

View File

@@ -0,0 +1,113 @@
// The slash commands the phone carries out, and the frames they send.
import assert from "node:assert/strict";
import { test } from "node:test";
import { commandAction, matchCommands, runCommand } from "../app/commands.js";
const names = (commands) => commands.map((command) => command.name);
// The break this catches: the picker missing at the bare slash, which is where you'd browse
test("a bare slash offers every command", () => {
assert.deepEqual(names(matchCommands("/")), ["compact", "cost", "dock", "mode", "model", "thinking"]);
});
// The break this catches: names matched anywhere but their start, or with case counted
test("what's typed narrows by the start of the name", () => {
assert.deepEqual(names(matchCommands("/mo")), ["mode", "model"]);
assert.deepEqual(names(matchCommands("/MOD")), ["mode", "model"]);
assert.deepEqual(names(matchCommands("/st")), []);
});
// The break this catches: the picker staying up over the words a command takes, or over a
// message that happens to hold a slash
test("nothing is offered once there's a space, or no slash first", () => {
assert.deepEqual(matchCommands("/compact the API"), []);
assert.deepEqual(matchCommands("see a/b"), []);
});
// The break this catches: the focus dropped, so the summary keeps what it likes
test("compact sends its focus", () => {
assert.deepEqual(commandAction("/compact the API decisions", "build"), {
frame: { kind: "compact_now", content: { focus: "the API decisions" } },
});
});
// The break this catches: an empty focus sent, which the summary would be told to keep
test("compact alone sends no focus", () => {
assert.deepEqual(commandAction("/compact", "build"), { frame: { kind: "compact_now" } });
});
// The break this catches: a bare `/mode` sent as a mode named nothing, rather than the next one
test("mode alone moves to the next mode", () => {
assert.deepEqual(commandAction("/mode", "build"), { frame: { kind: "set_mode", content: "plan" } });
});
// The break this catches: a named mode ignored for the next one, or any word sent as a mode
test("mode takes plan or build, and anything else goes to the agent", () => {
assert.deepEqual(commandAction("/mode build", "build"), { frame: { kind: "set_mode", content: "build" } });
assert.equal(commandAction("/mode fast", "build"), null);
});
// The break this catches: the pickers' commands sent to the agent as a message
test("model, thinking and cost open the details", () => {
for (const name of ["model", "thinking", "cost"]) assert.deepEqual(commandAction(`/${name}`, "build"), { details: true });
});
// The break this catches: a bare `/dock` doing nothing, where the TUI's toggles
test("dock alone toggles", () => {
assert.deepEqual(commandAction("/dock", "build"), { dock: "toggle" });
});
// The break this catches: one of the TUI's `/dock` verbs dropped, or any word taken for one
test("dock takes the TUI's verbs, and anything else goes to the agent", () => {
for (const verb of ["show", "hide", "auto", "left", "right"]) assert.deepEqual(commandAction(`/dock ${verb}`, "build"), { dock: verb });
assert.deepEqual(commandAction("/dock Left", "build"), { dock: "left" });
assert.equal(commandAction("/dock is in the way", "build"), null);
});
/** Hooks that record what a command did. */
function recorded() {
/** @type {unknown[]} */
const did = [];
const hooks = {
send: (/** @type {unknown} */ frame) => (did.push(frame), true),
details: () => void did.push("details"),
dock: (/** @type {string} */ verb) => void did.push(`dock ${verb}`),
};
return { did, hooks };
}
// The break this catches: a command routed to the wrong place, the sheet's commands sent to the
// session or the dock's left undone, or a message run as a command
test("each command goes where it's carried out", () => {
const { did, hooks } = recorded();
assert.equal(runCommand({ details: true }, hooks), true);
assert.equal(runCommand({ dock: "left" }, hooks), true);
assert.equal(runCommand({ frame: { kind: "compact_now" } }, hooks), true);
assert.equal(runCommand(null, hooks), null);
assert.deepEqual(did, ["details", "dock left", { kind: "compact_now" }]);
});
// The break this catches: a frame that couldn't go out reported as sent, so the box clears and
// the command is lost
test("a command frame that couldn't be sent says so", () => {
const hooks = { ...recorded().hooks, send: () => false };
assert.equal(runCommand({ frame: { kind: "compact_now" } }, hooks), false);
});
// The break this catches: a command the keyboard capitalized sent to the agent as a message
test("a command counts whatever its case", () => {
assert.deepEqual(commandAction("/Model", "build"), { details: true });
});
// The break this catches: a known command given words it doesn't take swallowed, so the message
// never reaches the agent
test("a command given words it doesn't take is a message", () => {
assert.equal(commandAction("/model is slow today", "build"), null);
});
// The break this catches: a slash that isn't one of the phone's commands kept from the agent
test("anything else that starts with a slash is a message", () => {
assert.equal(commandAction("/review the diff", "build"), null);
assert.equal(commandAction("not /compact", "build"), null);
});

View File

@@ -0,0 +1,161 @@
// @ts-check
// Comments from the phone: where one goes, the edits the buttons send, and the session they answer.
import assert from "node:assert/strict";
import { test } from "node:test";
import { actEdit, anchorFor, anchorWords, commentEdit, labelOf, unsent } from "../app/comments.js";
import { composedEdit, tapCard } from "../app/comments-view.js";
import { applyReview, chapterPiece, createReview } from "../app/review.js";
const line = (/** @type {number | null} */ n) => ({ new_line: n });
/** `src/a.rs` with two hunks (lines 1–3, then 10–11), and a chapter naming both. */
const REVIEW = {
id: "review:1",
chapters: [{ id: "chapter:1", items: [{ kind: "hunk", id: "hunk:1" }, { kind: "hunk", id: "hunk:2" }] }],
files: [{ id: "file:a", new_path: "src/a.rs", hunks: [
{ id: "hunk:1", lines: [line(1), line(2), line(null), line(3)] },
{ id: "hunk:2", lines: [line(10), line(11)] },
] }],
};
const pick = (/** @type {number} */ first, last = first, path = "src/a.rs") => ({ path, first, last });
// The break this catches: a one-line pick anchored anywhere but its line (the comment lands on the
// wrong code), or on the old side, which a pick can't name
test("one picked line is a line comment on the new side", () => {
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2)), { kind: "line", file_id: "file:a", hunk_id: "hunk:1", side: "new", line: 2 });
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(11)).hunk_id, "hunk:2");
});
// The break this catches: a run inside one hunk anchored to its first line only, or a run across
// hunks pinned to one of them
test("a run is its hunk's comment, and a wider one the chapter's", () => {
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(1, 3)), { kind: "hunk", file_id: "file:a", hunk_id: "hunk:1" });
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2, 10)), { kind: "chapter", chapter_id: "chapter:1" });
});
// The break this catches: a comment with no pick, or on a line the review doesn't hold, sent with
// an anchor the desk refuses
test("no pick, or a line the review doesn't hold, comments on the chapter", () => {
const chapter = { kind: "chapter", chapter_id: "chapter:1" };
assert.deepEqual(anchorFor(REVIEW, "chapter:1", null), chapter);
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2, 2, "src/b.rs")), chapter);
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(7)), chapter);
});
// The break this catches: the composer saying "line 12" over a comment going on the chapter
test("the composer says where the comment goes", () => {
assert.equal(anchorWords({ kind: "line", line: 12 }, pick(12)), "Comment on line 12");
assert.equal(anchorWords({ kind: "hunk" }, pick(1, 3)), "Comment on lines 1–3");
assert.equal(anchorWords({ kind: "chapter" }, null), "Comment on this chapter");
});
// The break this catches: a question sent as an issue (the agent fixes instead of answering), or
// Save sending what was meant to wait
test("a comment carries its kind and whether it goes now", () => {
const anchor = { kind: "chapter", chapter_id: "chapter:1" };
assert.deepEqual(commentEdit(anchor, "Why?", true, false), { edit: "comment", anchor, body: "Why?", severity: "question", send: false });
assert.equal(commentEdit(anchor, "Fix it", false, true).severity, "issue");
assert.equal(commentEdit(anchor, "Fix it", false, true).send, true);
});
// The break this catches: a card's button sending another edit than it says, or a reply left
// unsent (the TUI's go at once)
test("each card button sends its own edit", () => {
assert.deepEqual(actEdit("send", "f:1"), { edit: "send", finding_ids: ["f:1"] });
assert.deepEqual(actEdit("delete", "f:1"), { edit: "delete_comment", finding_id: "f:1" });
assert.deepEqual(actEdit("resolve", "f:1"), { edit: "resolve", finding_id: "f:1" });
assert.deepEqual(actEdit("reopen", "f:1"), { edit: "reopen", finding_id: "f:1" });
assert.deepEqual(actEdit("reply", "f:1", "Thanks"), { edit: "reply", finding_id: "f:1", body: "Thanks", send: true });
assert.equal(actEdit("explode", "f:1"), null);
});
// The break this catches: Send all re-sending sent comments, or posting one already on GitHub
test("only drafts not on GitHub are unsent", () => {
const session = { findings: [
{ id: "f:1", state: "draft", label: "R1" }, { id: "f:2", state: "open", label: "R2" },
{ id: "f:3", state: "draft", posted: { url: "x" }, label: "R3" },
] };
assert.deepEqual(unsent(session), ["f:1"]);
assert.deepEqual(unsent(null), []);
assert.equal(labelOf(session, "f:2"), "R2");
});
/** A tap on a card's `act` button, and what it did. */
function tapAct(/** @type {string | null} */ act) {
const edits = /** @type {any[]} */ ([]);
const composed = /** @type {any[]} */ ([]);
const card = { getAttribute: () => "f:1" };
const button = act && { getAttribute: () => act, closest: () => card };
const event = /** @type {any} */ ({ target: { closest: () => button } });
const review = { shown: { value: { session: { findings: [{ id: "f:1", label: "R1" }] } } }, edit: (/** @type {any} */ _send, /** @type {any} */ edit) => edits.push(edit) };
tapCard(event, /** @type {any} */ ({ review, send: () => true }), (composing) => composed.push(composing));
return { edits, composed };
}
// The break this catches: Reply sending an empty reply instead of opening the composer, or a tap
// between buttons sending something
test("Reply opens the composer and other buttons send", () => {
assert.deepEqual(tapAct("reply"), { edits: [], composed: [{ heading: "Reply to R1", reply: "f:1" }] });
assert.deepEqual(tapAct("resolve").edits, [{ edit: "resolve", finding_id: "f:1" }]);
assert.deepEqual(tapAct(null), { edits: [], composed: [] });
});
// The break this catches: the composer's words sent as a new comment when they reply to one
test("the composer replies or comments as it was opened", () => {
assert.equal(composedEdit({ heading: "", reply: "f:1" }, "Yes", false, false).edit, "reply");
assert.equal(composedEdit({ heading: "", anchor: { kind: "review" } }, "No", true, true).severity, "question");
});
/** A review tab showing REVIEW, and everything it sent. */
function shownTab() {
const sent = /** @type {any[]} */ ([]);
const state = createReview();
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
state.ask(send);
state.apply({ kind: "open_review_shown", content: { request_id: sent[0].content.request_id, review: REVIEW, session: { id: "review:1", findings: [] } } });
return { state, sent, send };
}
// The break this catches: comments made in the TUI, or the desk's answer to the phone's own edit,
// not reaching the phone, or another review's session taken for this one
test("a saved session for the open review is the one shown", () => {
const { state } = shownTab();
const session = { id: "review:1", findings: [{ id: "f:1" }], progress: { walked_chapter_ids: ["chapter:1"] } };
state.apply({ kind: "review_session_saved", content: { request_id: "elsewhere", session } });
assert.deepEqual([state.shown.value.session, state.shown.value.walked], [session, ["chapter:1"]]);
state.apply({ kind: "review_session_saved", content: { request_id: "x", session: { id: "review:9", findings: [] } } });
assert.equal(state.shown.value.session, session);
});
// The break this catches: an edit sent without the open review's id, a refusal of it unsaid, or
// another client's refusal shown as this one's
test("an edit names the open review and its refusal is said", () => {
const { state, sent, send } = shownTab();
state.edit(send, { edit: "resolve", finding_id: "f:1" });
const edit = sent[sent.length - 1];
assert.deepEqual([edit.kind, edit.content.review_id, edit.content.edit], ["edit_review", "review:1", "resolve"]);
state.apply({ kind: "review_session_save_failed", content: { request_id: "elsewhere", message: "no" } });
assert.equal(state.shown.value.problem, undefined);
state.apply({ kind: "review_session_save_failed", content: { request_id: edit.content.request_id, message: "That comment was sent already." } });
assert.equal(state.shown.value.problem, "That comment was sent already.");
});
// The break this catches: an edit that couldn't be sent read as sent, or an edit with no review
// open sent anyway
test("an edit that can't go says so, and none goes without a review", () => {
const { state } = shownTab();
state.edit(() => false, { edit: "resolve", finding_id: "f:1" });
assert.match(state.shown.value.problem ?? "", /Connection lost/);
const none = createReview();
const sent = /** @type {any[]} */ ([]);
none.edit((frame) => sent.push(frame) > 0, { edit: "resolve", finding_id: "f:1" });
assert.equal(sent.length, 0);
});
// The break this catches: a chapter drawn without the session's comments, so none ever show
test("a chapter's piece carries the session's comments", () => {
const findings = [{ id: "f:1" }];
const piece = chapterPiece(/** @type {any} */ ({ review: REVIEW, reading: [], walked: [], session: { findings } }), "chapter:1");
assert.equal(piece.findings, findings);
assert.deepEqual(chapterPiece(/** @type {any} */ ({ review: REVIEW, reading: [], walked: [] }), "chapter:1").findings, []);
assert.deepEqual(applyReview(/** @type {any} */ ({ review: null }), { kind: "review_session_saved", content: { session: { id: "review:1" } } }, { id: "", load: "" }).next, { review: null });
});

View File

@@ -0,0 +1,34 @@
// What the composer says while a turn runs, since its buttons are icons.
import assert from "node:assert/strict";
import { test } from "node:test";
import { sendLabel, steeringLine } from "../app/composer.js";
// The break this catches: a line shown between turns, which says sending steers when it starts one
test("idle, with nothing waiting, there's no line", () => {
assert.equal(steeringLine(false, 0, false), "");
});
// The break this catches: the running turn left unsaid, so the icon gives no hint a message steers
test("while a turn runs, the line says sending steers it", () => {
assert.equal(steeringLine(true, 0, false), "Send steers the turn");
});
// The break this catches: a message with a photo promised to steer, when it waits for the turn
test("with a photo attached, the line says it waits for the turn", () => {
assert.equal(steeringLine(true, 0, true), "Photos wait for the turn");
});
// The break this catches: waiting steering hidden behind the running-turn hint, or once the turn
// ends, though the engine holds it for the next one and it can still be withdrawn
test("steering that waits is counted, running or not", () => {
assert.equal(steeringLine(true, 1, false), "1 message waiting to steer");
assert.equal(steeringLine(false, 3, false), "3 messages waiting to steer");
});
// The break this catches: the send icon's spoken name left at Send while it steers or queues
test("the send button's name follows what it does", () => {
assert.equal(sendLabel(false, true), "Send");
assert.equal(sendLabel(true, false), "Steer");
assert.equal(sendLabel(true, true), "Queue");
});

View File

@@ -0,0 +1,59 @@
import { test } from "node:test";
import assert from "node:assert/strict";
/** A WebSocket that only records: the test plays the browser's part. */
class FakeSocket {
static OPEN = 1;
static made = [];
constructor(url) {
this.url = url;
this.closedWith = null;
FakeSocket.made.push(this);
}
close(code) {
this.closedWith = code;
}
}
const page = /** @type {EventTarget & { visibilityState: string }} */ (Object.assign(new EventTarget(), { visibilityState: "visible" }));
Object.assign(globalThis, { document: page, WebSocket: FakeSocket, location: { protocol: "http:", host: "bridge" } });
const { connect } = await import("../app/connection.js");
function show(state) {
page.visibilityState = state;
page.dispatchEvent(new Event("visibilitychange"));
}
function joined() {
FakeSocket.made = [];
const statuses = [];
const link = connect("s-1", { onFrame: () => {}, onStatus: (status) => statuses.push(status) });
return { link, statuses };
}
// The break this catches: a socket held open while the app is hidden, so the bridge thinks you're
// looking and never notifies you, or a hidden app's close taken for the session ending.
test("the socket closes while the app is hidden and opens again on return", () => {
const { link, statuses } = joined();
const first = FakeSocket.made[0];
first.onopen();
show("hidden");
assert.equal(first.closedWith, 1000);
first.onclose?.({ code: 1000 });
assert.ok(!statuses.includes("ended"), `${statuses}`);
show("visible");
assert.equal(FakeSocket.made.length, 2, "a new socket on return");
assert.deepEqual(statuses, ["connecting", "live", "connecting"]);
link.close();
});
// The break this catches: a session opened while the app is out of sight (a retry coming due, or
// a load in the background), holding a socket open with nobody looking.
test("nothing opens while the app is hidden", () => {
show("hidden");
const { link } = joined();
assert.equal(FakeSocket.made.length, 0);
show("visible");
assert.equal(FakeSocket.made.length, 1);
link.close();
});

View File

@@ -0,0 +1,29 @@
// The details sheet's readings, from the markup the bridge renders for the status line.
import assert from "node:assert/strict";
import { test } from "node:test";
import { hasReadings } from "../app/details.js";
const MODEL = '<span class="seg seg-model">Scripted</span>';
const THINKING = '<span class="seg seg-thinking"><span class="seg-glyph" aria-hidden="true">x</span> off</span>';
// The break this catches: a SESSION heading over nothing, when the line holds only the model and
// thinking the sheet already has pickers for
test("a line with only the model and thinking has no readings", () => {
assert.equal(hasReadings(THINKING + MODEL), false);
});
// The break this catches: the context reading missed, so a filling window goes unshown
test("the context is a reading", () => {
assert.equal(hasReadings(`<span class="seg seg-context tone-error">95%/200k</span>${MODEL}`), true);
});
// The break this catches: the cost missed, which the phone's line leaves to the sheet alone
test("the cost is a reading", () => {
assert.equal(hasReadings(`<span class="seg seg-cost">$1.20</span>${MODEL}`), true);
});
// The break this catches: nothing rendered yet read as something, or a crash before the first render
test("nothing rendered has no readings", () => {
assert.equal(hasReadings(null), false);
});

View File

@@ -0,0 +1,267 @@
// The app end to end in WebKit, Safari's engine: pair by pasting the invitation link, open the
// session from the list, send a message, grant the write it asks for, and watch the mock model's
// turn arrive as the TUI would show it: the rendered answer, the changed file in the dock, and its
// diff.
//
// Needs a built `luxe` (`LUXE_BIN`, or target/debug/luxe) and Playwright's WebKit
// (`npx playwright install webkit`). Run: npm run e2e
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import { basename } from "node:path";
import { after, before, test } from "node:test";
import { LOGIN, startHost } from "./host.mjs";
import { WRITTEN, startMockProvider } from "./mock-provider.mjs";
const playwright = createRequire(import.meta.url)("playwright");
let model, host, browser, page;
const troubles = [];
before(async () => {
model = await startMockProvider();
host = await startHost(model.port);
browser = await playwright.webkit.launch();
const context = await browser.newContext({
...playwright.devices["iPad Pro 11 landscape"],
extraHTTPHeaders: { "Tailscale-User-Login": LOGIN },
});
page = await context.newPage();
page.on("pageerror", (error) => troubles.push(`page error: ${error.message}`));
page.on("console", (message) => message.type() === "error" && troubles.push(`console: ${message.text()}`));
});
after(async () => {
await browser?.close();
await host?.stop();
await model?.close();
});
// The break this catches: any link in the chain from invitation to diff (the unpaired app's
// pairing field, pairing, the session list, the socket, the composer, the permission card,
// rendering, the dock, the diff request) broken in Safari's engine
test("a paired iPad drives a turn and reads its diff", async () => {
await pair();
await page.locator("a.session").click();
await page.locator(".composer textarea").fill("Write the file, please.");
await page.locator(".send").click();
await page.locator(".prompt .choice.once").click();
await page.locator(".item.reply strong", { hasText: WRITTEN.path }).waitFor();
await page.locator(`button.change[data-path="${WRITTEN.path}"]`).click();
const added = page.locator(".sheet .dl-addition code");
assert.equal((await added.textContent())?.trim(), WRITTEN.content.trim());
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});
// Pairs as an app on the home screen would: the unpaired app takes the pasted link to the
// invitation page. Serve puts HTTPS in front of the bridge, so the credential is a Secure cookie,
// and WebKit drops one that arrives over this test's plain HTTP; the test carries it over itself,
// then opens the app as the page's redirect would.
async function pair() {
await page.goto(host.url);
await page.locator(".pair-link input").fill(`https://desk.example.ts.net/pair#${host.invitation}`);
await page.locator(".pair-link button").click();
const answered = page.waitForResponse("**/api/pair");
await page.locator("#pair button").click();
const cookie = (await (await answered).headerValue("set-cookie"))?.split(";")[0] ?? "";
// let the page's own redirect land and finish asking, or the visit below races it
await page.waitForURL((url) => url.pathname === "/", { waitUntil: "networkidle" });
const at = cookie.indexOf("=");
await page.context().addCookies([{ name: cookie.slice(0, at), value: cookie.slice(at + 1), url: host.url }]);
// the page's own redirect may have asked for the list before the cookie was carried over
troubles.length = 0;
await page.goto(host.url);
}
// The break this catches: the turn reaching the model without the tool's result, so the answer
// on screen came from somewhere other than the loop the app drove
test("the model saw the message and the tool's result", () => {
const turns = model.requests.filter((request) => request.tools?.length);
assert.equal(turns.length, 2, "one request to act, one with the result");
const sent = JSON.stringify(turns[0].messages);
assert.ok(sent.includes("Write the file, please."), sent);
assert.equal(turns[1].messages.at(-1).role, "tool");
});
// The break this catches: the Files tab's chain (the header's button, `list_directory` and
// `read_project_file` through the bridge, the file piece's rendering, Mention into the composer)
// broken in Safari's engine
test("the project panel lists the project, shows a file and mentions it", async () => {
await page.keyboard.press("Escape");
// The break this catches: the session's header naming its folder bare, without the branch it's on
const header = page.locator("header.bar:has(.back) .title .project-name");
await header.locator(".project-branch").waitFor();
assert.match((await header.textContent()) ?? "", new RegExp(`${basename(host.project)}.*\\S+ \\*$`));
await page.locator(".panel-button").click();
const named = page.locator(".panel .bar .project-name");
await named.waitFor();
assert.ok((await named.textContent())?.includes(basename(host.project)), "the bar names the project");
assert.ok(await named.locator(".project-mark").first().textContent(), "behind the tree's folder mark");
// the project is a git repository the turn just wrote into, so its branch shows, starred
assert.match((await named.locator(".project-branch").textContent()) ?? "", /\S+ \*$/);
// the file the turn wrote wears its change, as it does in the TUI's tree
await page.locator(`button.tree-row[data-file="${WRITTEN.path}"] .tree-name[class*="change-"]`).waitFor();
await page.locator("button.tree-row", { hasText: "README.md" }).click();
assert.equal((await page.locator(".peek .file .fl code").first().textContent())?.trim(), "# e2e");
// Escape closes the file and leaves the tree, as the TUI's Escape leaves a peek
await page.keyboard.press("Escape");
await page.locator(".peek").waitFor({ state: "detached" });
await page.locator("button.tree-row", { hasText: "README.md" }).click();
await page.locator(".peek .mention").click();
await page.waitForFunction(() => document.querySelector("textarea")?.value === "`README.md` ");
assert.equal(await page.locator(".panel, .peek").count(), 0, "Mention leaves the composer in view");
await page.locator(".panel-button").click();
await page.locator("button.tree-row").first().waitFor();
assert.equal(await page.locator(".peek").count(), 0, "the mentioned file isn't waiting in the panel");
// straight away: Escape is armed as soon as the panel is on screen, not a frame later
await page.keyboard.press("Escape");
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});
// The break this catches: the Review tab's chain (`show_open_review` through the engine to the
// review desk, `load_guided_review` of the working changes, the guide and chapter pieces, and
// `record_review_progress` kept in the session the next ask reads) broken in Safari's engine
test("the review tab reviews the changes and keeps a chapter marked", async () => {
await page.locator(".panel-button").click();
await page.locator('button.tab:has-text("Review")').click();
await page.locator('.panel button.retry:has-text("Review changes")').click();
await page.locator(".rv-target", { hasText: "Working changes" }).waitFor();
await page.locator(".rv-chapter .rv-title").first().click();
await page.locator(".peek .rv-chapter-view .rv-file", { hasText: WRITTEN.path }).waitFor();
await page.locator('.peek button.mention:has-text("Reviewed")').click();
await page.locator('.peek button.mention[aria-pressed="true"]').waitFor();
// Escape closes the chapter, then the panel, as it closes a file and then the panel
await page.keyboard.press("Escape");
await page.locator(".peek").waitFor({ state: "detached" });
await page.keyboard.press("Escape");
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
await page.locator(".panel-button").click();
await page.locator('button.tab:has-text("Review")').click();
// asked afresh, the host's session says which chapter was walked
await page.locator(".rv-chapter .rv-walked").first().waitFor();
await page.keyboard.press("Escape");
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});
/** Opens README.md from the Files tab, its lines drawn. */
async function openReadme() {
await page.locator(".panel").waitFor({ state: "detached" });
await page.locator(".panel-button").click();
await page.locator('button.tab:has-text("Files")').click();
await page.locator("button.tree-row", { hasText: "README.md" }).click();
await page.locator('.peek .fl[data-line="4"]').waitFor();
}
/** Selects `words` inside line `line` of the open file, as a long press and drag would. */
async function selectWithin(/** @type {number} */ line, /** @type {string} */ words) {
await page.evaluate(([line, words]) => {
const code = document.querySelector(`.peek .fl[data-line="${line}"] code`);
const walker = document.createTreeWalker(/** @type {Node} */ (code), NodeFilter.SHOW_TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const at = node.textContent?.indexOf(String(words)) ?? -1;
if (at < 0) continue;
const range = document.createRange();
range.setStart(node, at);
range.setEnd(node, at + String(words).length);
document.getSelection()?.removeAllRanges();
document.getSelection()?.addRange(range);
return;
}
}, [line, words]);
}
// The break this catches: line picks lost between the host's markup and the composer (rows not
// naming their lines, a tap on a number not picking, a second tap not stretching, picked rows not
// marked), or a selection inside a line, the phone's own way, not offering Ask for that line, or
// Ask writing other words than the TUI sends for the same lines
test("lines picked by number, or selected in part, are asked about in the TUI's words", async () => {
await openReadme();
const number = (/** @type {number} */ line) => page.locator(`.peek .fl[data-line="${line}"] .ln`);
await number(3).click();
await page.locator(".line-ask button", { hasText: "Ask about line 3" }).waitFor();
await number(4).click();
await page.locator(".line-ask button", { hasText: "Ask about lines 3–4" }).waitFor();
assert.equal(await page.locator(".peek .fl.picked").count(), 2, "the picked rows are marked");
await page.locator(".line-ask button").click();
await page.waitForFunction(() => document.querySelector("textarea")?.value.includes("`README.md` lines 3–4"));
assert.equal(await page.locator(".panel, .peek").count(), 0, "Ask leaves the composer in view");
await openReadme();
await selectWithin(3, "4519");
await page.locator(".line-ask button", { hasText: "Ask about line 3" }).click();
await page.waitForFunction(() => document.querySelector("textarea")?.value.includes("`README.md` line 3"));
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});
/** Writes a comment in the open composer, as a question or not, and saves it unsent. */
async function saveComment(/** @type {string} */ words, question = false) {
if (question) await page.locator(".rv-kinds button", { hasText: "Question" }).click();
await page.locator(".rv-compose textarea").fill(words);
await page.locator(".rv-compose button", { hasText: "Save" }).click();
}
// The break this catches: comments lost between the phone and the review desk (a line pick not
// anchoring to its line, the chapter comment not offered with nothing picked, the desk's saved
// session not redrawn as cards, a card's Delete not reaching the desk, or the guide not counting
// what's unsent)
test("a review chapter takes comments on its lines and on itself, kept by the host", async () => {
await page.locator(".panel").waitFor({ state: "detached" });
await page.locator(".panel-button").click();
await page.locator('button.tab:has-text("Review")').click();
await page.locator(".rv-chapter .rv-title").first().click();
await page.locator('.peek .dl[data-line="1"] .ln').first().click();
await page.locator(".line-ask button", { hasText: /^Comment$/ }).click();
await page.locator(".rv-compose", { hasText: "Comment on line 1" }).waitFor();
await saveComment("Why this file?", true);
const asked = page.locator(".peek .rv-finding", { hasText: "Why this file?" });
await asked.locator(".rv-state", { hasText: "unsent" }).waitFor();
assert.match((await asked.locator(".rv-finding-head").textContent()) ?? "", /question.*line 1/);
await page.locator(".line-ask button", { hasText: "Comment on the chapter" }).click();
await saveComment("Split this up.");
await page.locator(".peek .rv-finding", { hasText: "Split this up." }).waitFor();
await asked.locator('button[data-act="delete"]').click();
await asked.waitFor({ state: "detached" });
await page.keyboard.press("Escape");
await page.locator(".peek").waitFor({ state: "detached" });
await page.locator(".rv-unsent", { hasText: "1 unsent comment" }).waitFor();
await page.keyboard.press("Escape");
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});
/** Sends `command` from the composer, as typed. */
async function runCommand(/** @type {string} */ command) {
await page.locator(".composer textarea").fill(command);
await page.locator(".send").click();
}
/** The label of the panel tab showing. */
const shownTab = () => page.locator('.panel button.tab[aria-selected="true"]').textContent();
// The break this catches: a phone keeping two header buttons, the panel's button not reaching the
// dock, its tabs wrapping to a second row on the narrowest iPhone, a diff opened from the dock
// drawn under the panel, Escape closing the panel with the diff, or `/dock` on a phone doing
// nothing now the dock lives in the panel
test("on a phone one header button opens the dock and the project", async () => {
await page.locator(".panel").waitFor({ state: "detached" });
await page.setViewportSize({ width: 375, height: 812 });
// no dock button beside the panel's, once the app sees the narrow screen
await page.locator(".dock-toggle").waitFor({ state: "detached", timeout: 2000 });
await page.locator(".panel-button").click();
assert.equal(await shownTab(), "Dock");
const rows = await page.$$eval(".panel button.tab", (tabs) => new Set(tabs.map((tab) => tab.getBoundingClientRect().top)).size);
assert.equal(rows, 1, "the tabs fit one row");
await page.locator(`.panel button.change[data-path="${WRITTEN.path}"]`).click();
await page.locator(".peek .dl-addition").waitFor();
const onTop = await page.evaluate(() => document.elementFromPoint(innerWidth / 2, innerHeight / 2)?.closest(".peek") !== null);
assert.ok(onTop, "the diff covers the panel");
await page.keyboard.press("Escape");
await page.locator(".peek").waitFor({ state: "detached" });
assert.equal(await page.locator(".panel").count(), 1, "the diff took the Escape, not the panel");
await page.keyboard.press("Escape");
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
await runCommand("/dock");
assert.equal(await shownTab(), "Dock");
await page.locator(".panel .close").click();
await page.setViewportSize(playwright.devices["iPad Pro 11 landscape"].viewport);
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
});

View File

@@ -0,0 +1,117 @@
// A Luxe of the test's own: a session in a fresh git project, driven by the mock model, and a
// bridge serving it, all under one temporary directory, so nothing touches the real config.
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");
/** The tailnet login the bridge lets in, sent as Tailscale Serve would send it. */
export const LOGIN = "e2e@luxe.test";
/** The `luxe` to test: `LUXE_BIN`, or the debug build. */
const LUXE = process.env.LUXE_BIN ?? join(REPO, "target/debug/luxe");
/** Starts a session and a bridge for the mock model on `modelPort`. */
export async function startHost(modelPort) {
const root = mkdtempSync(join(tmpdir(), "luxe-e2e-"));
const env = isolatedEnv(root);
const project = gitProject(root);
writeConfig(env.LUXE_CONFIG_DIR, modelPort);
const children = [];
const host = { root, project, children, stop: () => stop(host) };
host.sessionId = await startSession(env, project, children);
host.invitation = invite(env);
host.url = await startBridge(env, children);
return host;
}
function isolatedEnv(root) {
const dirs = { LUXE_CONFIG_DIR: "config", LUXE_STATE_DIR: "state", LUXE_RUNTIME_DIR: "run", XDG_CACHE_HOME: "cache" };
/** @type {NodeJS.ProcessEnv} */
const env = { ...process.env, LUXE_MODELS_DEV_REFRESH: "0", HOME: join(root, "home") };
for (const [name, dir] of Object.entries(dirs)) mkdirSync((env[name] = join(root, dir)), { recursive: true });
return env;
}
function gitProject(root) {
const project = join(root, "project");
mkdirSync(project);
const git = (...args) => execFileSync("git", ["-c", "user.name=e2e", "-c", "user.email=e2e@luxe.test", ...args], { cwd: project });
git("init", "-q");
// a few lines, so a phone can pick a range of them and select part of one
writeFileSync(join(project, "README.md"), "# e2e\n\nThe port is 4519.\nThe host is luxe.local.\n");
git("add", ".");
git("commit", "-qm", "start");
return project;
}
// The mock model, and a rule that stops its write for a permission the phone has to grant
function writeConfig(configDir, port) {
const models = {
providers: { mock: { base_url: `http://127.0.0.1:${port}/v1`, api_key: "unused", api: "openai-completions" } },
models: { "mock/scripted": { name: "Scripted", context_window: 32000, max_tokens: 4000 } },
};
writeFileSync(join(configDir, "models.json"), JSON.stringify(models));
writeFileSync(join(configDir, "permissions.json"), JSON.stringify({ permission: { edit: "ask" } }));
}
// `--rpc` keeps the session while its stdin is open, and its `ready` event names it. Its events
// keep being read after that, so a full pipe never stalls it.
function startSession(env, project, children) {
const luxe = spawn(LUXE, ["--rpc", "--model", "mock/scripted"], { cwd: project, env, stdio: ["pipe", "pipe", "inherit"] });
children.push(luxe);
return new Promise((ready, failed) => {
createInterface({ input: luxe.stdout }).on("line", (line) => {
const event = JSON.parse(line);
if (event.kind === "ready") ready(event.content.session_id);
});
luxe.once("exit", (code) => failed(new Error(`luxe --rpc exited (${code}) before it was ready`)));
});
}
// The token is the link's fragment, or printed on its own where Tailscale can't name the machine
function invite(env) {
const out = execFileSync(LUXE, ["remote", "pair"], { env, encoding: "utf8" });
const token = /#([\w-]+)/.exec(out)?.[1];
if (!token) throw new Error(`no invitation in: ${out}`);
return token;
}
async function startBridge(env, children) {
const port = await freePort();
const bridge = spawn(LUXE, ["remote", "--port", String(port), "--allow", LOGIN], { env, stdio: "inherit" });
children.push(bridge);
const url = `http://127.0.0.1:${port}`;
await until(() => fetch(url).then(() => true, () => false), "the bridge to listen");
return url;
}
function freePort() {
return new Promise((done) => {
const probe = createServer().listen(0, "127.0.0.1", () => {
const { port } = /** @type {import("node:net").AddressInfo} */ (probe.address());
probe.close(() => done(port));
});
});
}
/** Polls `check` until it's true, for at most ten seconds. */
export async function until(check, what) {
for (let tries = 0; tries < 100; tries += 1) {
if (await check()) return;
await new Promise((done) => setTimeout(done, 100));
}
throw new Error(`timed out waiting for ${what}`);
}
async function stop(host) {
for (const child of host.children) child.kill();
await Promise.all(host.children.map((child) => child.exitCode ?? new Promise((done) => child.once("exit", done))));
rmSync(host.root, { recursive: true, force: true });
}

View File

@@ -0,0 +1,62 @@
// A model that follows a script, served the way an OpenAI-compatible endpoint streams: asked to
// act, it calls `write`; given the tool's result, it says what it did. A request with no tools
// (a session title, say) gets a word back. Every request is kept for the test to look at.
import { createServer } from "node:http";
/** The file the scripted model writes, and what it writes in it. */
export const WRITTEN = { path: "hello.txt", content: "hello from the mock\n" };
/** Starts the server on a free port. */
export async function startMockProvider() {
const requests = [];
const server = createServer((request, response) => answer(request, response, requests));
await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined)));
const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
return { port, requests, close: () => new Promise((resolve) => server.close(resolve)) };
}
async function answer(request, response, requests) {
if (request.method !== "POST" || !request.url?.endsWith("/chat/completions")) {
response.writeHead(404).end();
return;
}
const body = JSON.parse(await readBody(request));
requests.push(body);
response.writeHead(200, { "content-type": "text/event-stream" });
for (const chunk of reply(body)) response.write(`data: ${JSON.stringify(chunk)}\n\n`);
response.end("data: [DONE]\n\n");
}
async function readBody(request) {
let text = "";
for await (const part of request) text += part;
return text;
}
function reply(body) {
if (!body.tools?.length) return words("Mock");
if (body.messages.at(-1)?.role === "tool") return words(`Wrote **${WRITTEN.path}**.`);
return writeCall();
}
const chunk = (delta, finish = null) => ({
id: "mock", object: "chat.completion.chunk", created: 0, model: "scripted",
choices: [{ index: 0, delta, finish_reason: finish }],
});
const usage = { id: "mock", object: "chat.completion.chunk", created: 0, model: "scripted", choices: [],
usage: { prompt_tokens: 1200, completion_tokens: 20, total_tokens: 1220 } };
function words(text) {
const half = Math.ceil(text.length / 2);
return [chunk({ role: "assistant", content: text.slice(0, half) }), chunk({ content: text.slice(half) }),
chunk({}, "stop"), usage];
}
function writeCall() {
const call = { index: 0, id: "call_write", type: "function", function: { name: "write", arguments: "" } };
const args = { index: 0, function: { arguments: JSON.stringify(WRITTEN) } };
return [chunk({ role: "assistant", content: null, tool_calls: [call] }), chunk({ tool_calls: [args] }),
chunk({}, "tool_calls"), usage];
}

View File

@@ -0,0 +1,181 @@
// The Files tab: the tree's rows and taps, reading a file, its answer, and mentioning it.
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyRead, childPath, createFiles, entriesNote, fileMention, toggled, treeRows, withMention } from "../app/files.js";
import { createGithub } from "../app/github.js";
import { createReview } from "../app/review.js";
import { tapRow } from "../app/files-view.js";
/** @import { OpenFile } from "../app/files.js" */
/** @type {OpenFile} */
const ASKING = { path: "src/a.rs", requestId: "file:1", state: "asking" };
/** A `project_file_read` frame's file, copied from `luxe --rpc`. */
const FILE = { path: "a.rs", text: "fn main() {}\n", bytes: 13, truncated: false, binary: false };
// The break this catches: the question in a shape `read_project_file` doesn't take, or its id
// counted rather than random, so two phones in one session open each other's files
test("reading a file asks read_project_file with an id of its own", () => {
/** @type {any[]} */
const frames = [];
const files = createFiles();
files.read("src/a.rs", (frame) => (frames.push(frame), true));
files.read("src/a.rs", (frame) => (frames.push(frame), true));
assert.deepEqual(frames[0], { kind: "read_project_file", content: { request_id: frames[0].content.request_id, path: "src/a.rs" } });
assert.match(frames[0].content.request_id, /^file:/);
assert.notEqual(frames[0].content.request_id, frames[1].content.request_id);
assert.equal(files.open.value?.state, "asking");
});
// The break this catches: a read that never left shown as loading forever
test("a read that couldn't be sent shows as lost", () => {
const files = createFiles();
files.read("a.rs", () => false);
assert.equal(files.open.value?.state, "lost");
});
// The break this catches: the answer's file read from the wrong field
test("the answer to the open file shows it", () => {
const read = applyRead(ASKING, { kind: "project_file_read", content: { request_id: "file:1", file: FILE } });
assert.deepEqual(read, { ...ASKING, state: "read", file: FILE });
});
// The break this catches: a failure left loading, or its reason dropped
test("a failed read says why", () => {
const failed = applyRead(ASKING, { kind: "project_file_read_failed", content: { request_id: "file:1", path: "src/a.rs", error: "not_found" } });
assert.deepEqual(failed, { ...ASKING, state: "failed", error: "not_found" });
});
// The break this catches: another phone's answer, or one for a file since closed, shown here
test("an answer to another question changes nothing", () => {
const frame = { kind: "project_file_read", content: { request_id: "file:2", file: FILE } };
assert.equal(applyRead(ASKING, frame), ASKING);
assert.equal(applyRead(null, frame), null);
});
// The break this catches: a read asked for before the connection dropped left loading forever
test("a new connection marks a read still on its way as lost", () => {
assert.equal(applyRead(ASKING, { kind: "ready", content: {} })?.state, "lost");
});
// The break this catches: a file already shown thrown back to lost by a reconnect
test("a new connection leaves a file already read alone", () => {
/** @type {OpenFile} */
const read = { ...ASKING, state: "read", file: FILE };
assert.equal(applyRead(read, { kind: "ready", content: {} }), read);
});
// The break this catches: a root entry asked for as `/name`, which isn't a project path
test("a path inside the root has no leading slash", () => {
assert.equal(childPath("", "src"), "src");
assert.equal(childPath("src/app", "a.rs"), "src/app/a.rs");
});
/** Listings as `directory_listed` leaves them: the root, `src` and `src/app`. */
const FOLDERS = /** @type {Record<string, import("../app/mentions.js").Listing>} */ ({
"": { state: "listed", entries: [{ name: "src", kind: "directory" }, { name: "README.md", kind: "file" }] },
src: { state: "listed", entries: [{ name: "app", kind: "directory" }, { name: "lib.rs", kind: "file" }] },
"src/app": { state: "listed", entries: [{ name: "a.rs", kind: "file" }] },
});
// The break this catches: an open folder's entries left out, placed after its siblings rather than
// under it, at the wrong depth, or by name alone rather than their whole path
test("an open folder's entries sit under it, a level in", () => {
assert.deepEqual(treeRows(FOLDERS, new Set(["src"])), [
{ kind: "folder", path: "src", name: "src", depth: 0, open: true },
{ kind: "folder", path: "src/app", name: "app", depth: 1, open: false },
{ kind: "file", path: "src/lib.rs", name: "lib.rs", depth: 1 },
{ kind: "file", path: "README.md", name: "README.md", depth: 0 },
]);
});
// The break this catches: a folder open inside a closed one shown anyway, which the TUI hides until
// the closed one opens again
test("a closed folder hides what's open inside it", () => {
const rows = treeRows(FOLDERS, new Set(["src/app"]));
assert.deepEqual(rows.map((row) => row.kind === "note" ? row.text : row.path), ["src", "README.md"]);
});
// The break this catches: an open folder not listed yet shown as empty, or its note at the
// folder's own depth rather than where its entries will be
test("an open folder still being listed says so where its entries will be", () => {
const rows = treeRows({ "": FOLDERS[""] }, new Set(["src"]));
assert.deepEqual(rows[1], { kind: "note", depth: 1, text: "Loading…" });
assert.deepEqual(treeRows({}, new Set()), [{ kind: "note", depth: 0, text: "Loading…" }]);
});
// The break this catches: a tap that only ever opens, so a folder can't be closed again, or one
// that closes every other folder too
test("toggling opens a closed folder and closes an open one", () => {
const opened = toggled(new Set(["docs"]), "src");
assert.deepEqual([...opened], ["docs", "src"]);
assert.deepEqual([...toggled(opened, "src")], ["docs"]);
});
/**
* A tap on a tree row with `dataset`, and what it asked for.
* @param {Record<string, string>} dataset @param {Iterable<string>} [unfolded]
*/
function tap(dataset, unfolded = []) {
/** @type {any[]} */
const asked = [];
const files = createFiles();
files.unfolded.value = new Set(unfolded);
const listings = /** @type {any} */ ({ ask: (/** @type {any[]} */ ...args) => asked.push(args) });
const event = /** @type {any} */ ({ target: { closest: () => ({ dataset }) } });
const send = () => true;
const github = createGithub();
github.open.value = /** @type {any} */ ({ subject: { number: 1 } });
const review = createReview();
review.open.value = "chapter:1";
tapRow(event, /** @type {any} */ ({ files, github, review, listings, send }));
return { files, github, review, asked, send };
}
// The break this catches: a folder opened without being listed afresh, so it shows what was there
// before the agent changed it, or listed again on closing, which asks for nothing anyone sees
test("opening a folder lists it afresh and closing it doesn't", () => {
const opened = tap({ folder: "src" });
assert.deepEqual([...opened.files.unfolded.value], ["src"]);
assert.deepEqual(opened.asked, [["src", opened.send, { fresh: true }]]);
const closed = tap({ folder: "src" }, ["src"]);
assert.deepEqual([...closed.files.unfolded.value], []);
assert.deepEqual(closed.asked, []);
});
// The break this catches: a file tap that unfolds nothing but doesn't open the file either, opens
// the wrong path, or leaves an open pull request in the pane over it
test("tapping a file opens it", () => {
const { files, github, review } = tap({ file: "src/lib.rs" });
assert.equal(files.open.value?.path, "src/lib.rs");
assert.deepEqual([...files.unfolded.value], []);
assert.equal(github.open.value, null);
assert.equal(review.open.value, null, "one pane at a time");
});
// The break this catches: a folder tap that closes the open pull request, which only a file
// taking the pane should
test("tapping a folder leaves the pane alone", () => {
const { github, review } = tap({ folder: "src" });
assert.notEqual(github.open.value, null);
assert.equal(review.open.value, "chapter:1");
});
// The break this catches: a mention run into the word before it, or a file not in the backticks
// the `@` picker writes, which is what the TUI sends the model for a file
test("a mention goes at the end of the draft, spaced from what's there", () => {
assert.deepEqual(withMention("look at", fileMention("a.rs")), { text: "look at `a.rs` ", caret: 15, placed: true });
assert.deepEqual(withMention("look at ", "#7").text, "look at #7 ");
assert.deepEqual(withMention("", "#7").text, "#7 ");
});
// The break this catches: an empty folder shown as loading, a failure as empty, or a folder being
// listed again hidden behind "Loading…" when its last entries are there to show
test("a folder with nothing to list says why", () => {
assert.equal(entriesNote(undefined), "Loading…");
assert.equal(entriesNote({ state: "asking", entries: [] }), "Loading…");
assert.equal(entriesNote({ state: "listed", entries: [] }), "Empty folder");
assert.equal(entriesNote({ state: "failed", entries: [] }), "Couldn't list this folder");
assert.equal(entriesNote({ state: "asking", entries: [{ name: "a", kind: "file" }] }), "");
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,77 @@
// Starting a session from the phone.
import assert from "node:assert/strict";
import { test } from "node:test";
import { matchFolders, startIn } from "../app/folders.js";
const folder = (path) => ({ path, name: path.split("/").pop(), sessions: 0 });
const WORKED_IN = [
folder("/home/me/code/notes-app"),
folder("/home/me/code/app"),
folder("/home/me/apparel/site"),
folder("/home/me/docs"),
];
const names = (matched) => matched.map((entry) => entry.name);
/** A fetch that records what it was asked and answers `status` with `body`. */
function answering(status, body) {
const asked = [];
const post = async (url, init) => {
asked.push({ url, init });
const text = typeof body === "string" ? body : JSON.stringify(body);
return new Response(status === 204 ? null : text, { status });
};
return { asked, post };
}
// The break this catches: the request the bridge's start route doesn't take (another path, a GET,
// or the folder under another name), so every tap on a folder is refused
test("a start posts the folder and opens the session the bridge started", async () => {
const started = { session: { session_id: "abc-123", cwd: "/home/me/app" }, place: "herdr" };
const { asked, post } = answering(201, started);
assert.equal(await startIn("~/app", post), "abc-123");
assert.equal(asked[0].url, "/api/sessions");
assert.equal(asked[0].init.method, "POST");
assert.deepEqual(JSON.parse(asked[0].init.body), { folder: "~/app" });
});
// The break this catches: a refused start taken for a session, or shown without the bridge's
// reason, so "isn't a folder on this machine" never reaches the reader
test("a refused start says why, in the bridge's words", async () => {
const { post } = answering(400, "/nope isn't a folder on this machine");
await assert.rejects(startIn("/nope", post), { message: "/nope isn't a folder on this machine" });
});
// The break this catches: an empty field showing nothing, so the folders you've worked in only
// appear once you start typing
test("an empty field offers every folder, in the bridge's order", () => {
assert.deepEqual(matchFolders(WORKED_IN, " "), WORKED_IN);
});
// The break this catches: the ranks collapsed or reordered, so the folder named for what you typed
// sits under ones that only hold it somewhere
test("a name starting with what's typed leads, then a name holding it, then a path", () => {
assert.deepEqual(names(matchFolders(WORKED_IN, "app")), ["app", "notes-app", "site"]);
});
// The break this catches: a folder that holds the text nowhere offered anyway
test("a folder that doesn't hold what's typed is left out", () => {
assert.deepEqual(names(matchFolders(WORKED_IN, "docs")), ["docs"]);
});
// The break this catches: case counted, so "App" finds nothing on a phone that capitalizes
test("case doesn't matter", () => {
assert.deepEqual(names(matchFolders(WORKED_IN, "DOCS")), ["docs"]);
});
// The break this catches: the `~/` kept, which no absolute path holds, so typing a path the way
// you'd type it in a terminal finds nothing
test("a path typed from home still finds the folder under it", () => {
assert.deepEqual(names(matchFolders(WORKED_IN, "~/code/app")), ["app"]);
});
// The break this catches: a refusal with no words read as an empty message, which shows nothing
test("a refusal with no reason still says the start failed", async () => {
const { post } = answering(504, "");
await assert.rejects(startIn("/slow", post), { message: "starting failed: 504" });
});

View File

@@ -0,0 +1,195 @@
// @ts-check
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyItem, applyListed, createGithub, githubMention, rowSubject, shownSection } from "../app/github.js";
import { linkedSubject, tapDetail, tapGithubRow } from "../app/github-view.js";
/** @import { OpenItem, GithubListing } from "../app/github.js" */
/** A `github_listed` frame's content, cut from a live session to one section and one row. */
const LISTED = {
repository: "nora-quinn/luxe-dev",
sections: [
{ name: "Review requested", items: [], error: null, total: 0 },
{ name: "Pull requests", items: [{ number: 211, title: "chore: refresh the embedded models.dev snapshot" }], error: null, total: 5 },
],
};
/** @type {GithubListing} */
const ASKING = { state: "asking", repository: null, sections: [], at: 0 };
/** @param {Partial<OpenItem>} [fields] @returns {OpenItem} */
function asking(fields = {}) {
const subject = { number: 235, pull_request: true, repository: null, url: "https://github.com/nora-quinn/luxe-dev/pull/235" };
return { subject, tab: "overview", overview: { state: "asking" }, conversation: { state: "asking" }, ...fields };
}
// The break this catches: the answer not kept, or kept while nothing was asked, or a reconnect
// that leaves the tab saying it's loading for good
test("the listing takes the answer to what it asked", () => {
const listed = applyListed(ASKING, { kind: "github_listed", content: LISTED });
assert.equal(listed.state, "listed");
assert.equal(listed.repository, "nora-quinn/luxe-dev");
assert.equal(listed.sections.length, 2);
assert.ok(listed.at > 1_700_000_000, "stamped with the clock its ages are drawn from");
const idle = { ...ASKING, state: /** @type {const} */ ("idle") };
assert.equal(applyListed(idle, { kind: "github_listed", content: LISTED }), idle);
assert.equal(applyListed(ASKING, { kind: "ready", content: {} }).state, "lost");
assert.equal(applyListed(ASKING, { kind: "workspace_updated", content: {} }), ASKING);
});
// The break this catches: an answer for another item, or the same number in another repository,
// taken as this one's
test("an item takes only its own answers", () => {
const item = asking();
const overview = { kind: "pull_request", overview: { number: 235 } };
assert.equal(applyItem(item, { kind: "github_overview_read", content: { number: 211, repository: null, overview } }), item);
assert.equal(applyItem(item, { kind: "github_overview_read", content: { number: 235, repository: "a/b", overview } }), item);
const read = applyItem(item, { kind: "github_overview_read", content: { number: 235, repository: null, overview, error: null } });
assert.equal(read?.overview.state, "read");
assert.deepEqual(read?.overview.value, overview);
assert.equal(read?.conversation.state, "asking", "the overview's answer isn't the conversation's");
});
// The break this catches: a failure shown as an empty read, the conversation's answer dropped,
// or a later answer overwriting the first
test("each half is read or failed on its own", () => {
const entries = [{ kind: "opening" }];
const content = { number: 235, repository: null, entries, error: null };
const read = applyItem(asking(), { kind: "github_conversation_read", content });
assert.deepEqual(read?.conversation.value, entries);
const failed = applyItem(asking(), { kind: "github_overview_read", content: { number: 235, repository: null, overview: null, error: "gh failed" } });
assert.deepEqual([failed?.overview.state, failed?.overview.error], ["failed", "gh failed"]);
const again = applyItem(read, { kind: "github_conversation_read", content: { ...content, entries: [] } });
assert.deepEqual(again?.conversation.value, entries);
const silent = applyItem(asking(), { kind: "github_conversation_read", content: { ...content, entries: null, error: "gone" } });
assert.deepEqual([silent?.conversation.state, silent?.conversation.error], ["failed", "gone"]);
const overviewRead = applyItem(asking(), { kind: "github_overview_read", content: { number: 235, repository: null, overview: 1 } });
const overviewAgain = applyItem(overviewRead, { kind: "github_overview_read", content: { number: 235, repository: null, overview: 2 } });
assert.equal(overviewAgain?.overview.value, 1);
});
// The break this catches: a reconnect that strands a half still asking, or throws away one
// already read
test("a reconnect loses only what was still being asked", () => {
const item = asking({ overview: { state: "read", value: {}, at: 1 } });
const after = applyItem(item, { kind: "ready", content: {} });
assert.equal(after?.overview.state, "read");
assert.equal(after?.conversation.state, "lost");
assert.equal(applyItem(null, { kind: "ready", content: {} }), null);
});
// The break this catches: opening an item that asks for only one half, asks without saying which,
// or claims to be loading when nothing went out
test("opening an item asks for both halves", () => {
const github = createGithub();
/** @type {any[]} */
const sent = [];
github.read(asking().subject, (frame) => sent.push(frame) > 0);
const content = { number: 235, pull_request: true, repository: null };
assert.deepEqual(sent, [{ kind: "read_github_overview", content }, { kind: "read_github_conversation", content }]);
assert.equal(github.open.value?.overview.state, "asking");
github.read(asking().subject, () => false);
assert.equal(github.open.value?.conversation.state, "lost");
});
// The break this catches: the tab never asking for its sections, or saying it's loading when
// nothing went out
test("listing asks for every section", () => {
const github = createGithub();
/** @type {any[]} */
const sent = [];
github.list((frame) => sent.push(frame) > 0);
assert.deepEqual(sent, [{ kind: "list_github", content: {} }]);
assert.equal(github.listing.value.state, "asking");
github.list(() => false);
assert.equal(github.listing.value.state, "lost");
});
// The break this catches: the tab opening on an empty section when another has rows, or losing
// the reader's pick on a refresh
test("the tab shows the pick, else the first section with rows", () => {
assert.equal(shownSection(LISTED.sections, "Review requested").name, "Review requested");
assert.equal(shownSection(LISTED.sections, null).name, "Pull requests");
assert.equal(shownSection(LISTED.sections, "Gone").name, "Pull requests");
assert.equal(shownSection([LISTED.sections[0]], null).name, "Review requested");
});
/** A row as the host draws it. @param {string} repository */
const row = (repository) => /** @type {any} */ ({ dataset: { number: "211", pull: "true", repository, url: "https://github.com/x/pull/211" } });
// The break this catches: the number read as text, the kind inverted, or the checkout's own
// repository named in the ask, which the host reads as somewhere else
test("a row says which item to open", () => {
const here = "nora-quinn/luxe-dev";
assert.deepEqual(rowSubject(row(here), here), { number: 211, pull_request: true, repository: null, url: "https://github.com/x/pull/211" });
assert.equal(rowSubject(row("someone/else"), here).repository, "someone/else");
const issue = row(here);
issue.dataset.pull = "false";
assert.equal(rowSubject(issue, here).pull_request, false);
});
// The break this catches: a mention that names the wrong kind, leaves out the repository the
// agent needs to read it, or drops the link
test("a mention says what it is and where", () => {
const subject = { number: 7, pull_request: true, repository: null, url: "https://github.com/o/r/pull/7" };
assert.equal(githubMention(subject, "o/r"), "pull request o/r#7 (https://github.com/o/r/pull/7)");
const issue = { number: 8, pull_request: false, repository: "x/y", url: "https://github.com/x/y/issues/8" };
assert.equal(githubMention(issue, "o/r"), "issue x/y#8 (https://github.com/x/y/issues/8)");
});
/** An event that landed in `element` when asked for `selector`. @param {string} selector @param {any} element */
const landing = (selector, element) => /** @type {any} */ ({ target: { closest: (/** @type {string} */ asked) => (asked === selector ? element : null) } });
/** Hooks with a GitHub state, a file open, and what was sent. */
function hooks() {
const github = createGithub();
github.listing.value = { state: "listed", repository: "o/r", sections: [], at: 1 };
let fileOpen = true;
/** @type {any[]} */
const sent = [];
const files = { close: () => (fileOpen = false) };
let chapterOpen = true;
const review = { close: () => (chapterOpen = false) };
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
return { github, files, review, send, sent, fileOpen: () => fileOpen, chapterOpen: () => chapterOpen };
}
// The break this catches: a row tap that leaves the open file in the pane, opens nothing, or
// reacts to a tap between rows
test("tapping a row opens it in place of the file", () => {
const at = hooks();
tapGithubRow(landing("button.gh-row", row("o/r")), /** @type {any} */ (at));
assert.equal(at.fileOpen(), false);
assert.equal(at.chapterOpen(), false, "one pane at a time");
assert.equal(at.github.open.value?.subject.number, 211);
const missed = hooks();
tapGithubRow(landing("nothing", null), /** @type {any} */ (missed));
assert.equal(missed.fileOpen(), true);
assert.equal(missed.chapterOpen(), true);
assert.equal(missed.sent.length, 0);
});
// The break this catches: "open #N" opening an issue or another repository's number, "more lines"
// not switching to Conversation, or "Show all" not unfolding its own card
test("taps inside the detail open, switch and unfold", () => {
const at = hooks();
at.github.read({ number: 235, pull_request: true, repository: "x/y", url: "" }, at.send);
tapDetail(landing("button.gh-open", { dataset: { number: "230" } }), /** @type {any} */ (at));
assert.deepEqual(at.github.open.value?.subject, { number: 230, pull_request: true, repository: "x/y", url: "https://github.com/x/y/pull/230" });
tapDetail(landing("button.gh-more", {}), /** @type {any} */ (at));
assert.equal(at.github.open.value?.tab, "conversation");
const removed = /** @type {string[]} */ ([]);
const card = { classList: { remove: (/** @type {string} */ name) => removed.push(name) } };
tapDetail(landing("button.gh-unfold", { closest: () => card }), /** @type {any} */ (at));
assert.deepEqual(removed, ["folded"]);
});
// The break this catches: a linked pull request's link pointing at nowhere when it's in the
// checkout's own repository
test("a linked pull request's link names the checkout when it's there", () => {
const subject = { number: 1, pull_request: false, repository: null, url: "" };
assert.equal(linkedSubject(subject, 5, "o/r").url, "https://github.com/o/r/pull/5");
assert.equal(linkedSubject(subject, 5, "o/r").repository, null);
});

View File

@@ -0,0 +1,105 @@
// Whether the dock shows and on which side: started from the page, changed by `/dock` and the
// header's button.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { WIDE, createDock, dockAfter, dockVisible, panelTabs, phoneDock, shownTab, startingMode } from "../app/layout.js";
const ids = (/** @type {boolean} */ wide) => panelTabs(wide).map(({ id }) => id);
// The break this catches: a phone left with no way to the plan and changes once its dock button is
// gone, or a wide screen showing them twice, in the rail and the panel
test("a phone's panel holds the dock first; a wide screen's leaves it to the rail", () => {
assert.deepEqual(ids(false), ["dock", "files", "github", "review"]);
assert.deepEqual(ids(true), ["files", "github", "review"]);
});
// The break this catches: a panel open on the dock going blank when an iPad turns wide, or a tab
// the screen has swapped for its first
test("the panel shows its tab where the screen has it, and the screen's first where it doesn't", () => {
assert.equal(shownTab("dock", true), "files");
assert.equal(shownTab("github", true), "github");
assert.equal(shownTab("review", false), "review");
assert.equal(shownTab(null, false), "dock");
});
// The break this catches: `/dock` on a phone doing nothing now the dock lives in the panel, a bare
// one that can't close what it opened, or one closing Files as though it were the dock
test("on a phone, /dock opens the panel on the dock and a bare one closes it from there", () => {
assert.equal(phoneDock("toggle", null), "open");
assert.equal(phoneDock("toggle", "files"), "open");
assert.equal(phoneDock("toggle", "dock"), "close");
assert.equal(phoneDock("show", "dock"), "open");
assert.equal(phoneDock("hide", "files"), "close");
assert.equal(phoneDock("left", null), null);
assert.equal(phoneDock("auto", "dock"), null);
});
// The break this catches: a stylesheet's breakpoint moved without the script's, so on a screen
// between the two the button says the dock is hidden while the rail shows, or a peek that's only a
// pane beside the rail is announced as covering the page
test("the script's wide screen is the stylesheets'", () => {
for (const sheet of ["dock.css", "peek.css"]) {
const css = readFileSync(new URL(`../app/${sheet}`, import.meta.url), "utf8");
assert.ok(css.includes(`@media ${WIDE} {`), `${sheet} has no @media ${WIDE}`);
}
});
// The break this catches: the config's mode ignored, or a value the app doesn't know taken as is,
// where the TUI falls back to auto
test("the mode starts from the page, and auto when it says nothing known", () => {
assert.equal(startingMode({ dockMode: "shown" }), "shown");
assert.equal(startingMode({ dockMode: "hidden" }), "hidden");
assert.equal(startingMode({ dockMode: "sideways" }), "auto");
assert.equal(startingMode({}), "auto");
});
// The break this catches: auto showing the dock over a phone's conversation, or hiding the rail
// on an iPad
test("auto shows the dock on a wide screen only", () => {
assert.equal(dockVisible("auto", true), true);
assert.equal(dockVisible("auto", false), false);
});
// The break this catches: shown or hidden bent by the screen's width, which only auto follows
test("shown and hidden hold at any width", () => {
assert.equal(dockVisible("shown", false), true);
assert.equal(dockVisible("hidden", true), false);
});
// The break this catches: the toggle flipping the mode rather than what's on screen, so the first
// tap on an iPad in auto shows a dock already showing
test("the toggle flips what's on screen", () => {
assert.equal(dockAfter("auto", "toggle", true), "hidden");
assert.equal(dockAfter("auto", "toggle", false), "shown");
assert.equal(dockAfter("hidden", "toggle", true), "shown");
});
// The break this catches: a `/dock` verb setting the wrong mode, or a side verb changing it
test("show, hide and auto set the mode, and the sides leave it", () => {
assert.equal(dockAfter("hidden", "show", false), "shown");
assert.equal(dockAfter("shown", "hide", false), "hidden");
assert.equal(dockAfter("shown", "auto", false), "auto");
assert.equal(dockAfter("shown", "left", false), null);
});
// The break this catches: the side kept anywhere the stylesheet doesn't read, or a side verb
// taken for a mode
test("a side moves the page's dock side and leaves the mode", () => {
const page = { dataset: { dockMode: "shown", dockSide: "left" } };
const dock = createDock(/** @type {any} */ (page), () => true);
dock.apply("right");
assert.equal(page.dataset.dockSide, "right");
assert.equal(dock.mode.value, "shown");
});
// The break this catches: the screen's width read once at start, so a rotated iPad's toggle
// flips the wrong way
test("the toggle reads the width when it's tapped", () => {
let wide = true;
const dock = createDock(/** @type {any} */ ({ dataset: {} }), () => wide);
wide = false;
dock.apply("toggle");
assert.equal(dock.mode.value, "shown");
});

View File

@@ -0,0 +1,95 @@
// @ts-check
// Line picks: what a tap on a line's number picks, what a selection covers, and what Ask writes.
import assert from "node:assert/strict";
import { test } from "node:test";
import { askLabel, lineWords, markPicked, selectedLines, tapLine, tapped } from "../app/lines.js";
const at = (/** @type {number} */ first, last = first, path = "src/a.rs") => ({ path, first, last });
// The break this catches: a second tap starting over instead of stretching, a stretch that runs
// backwards when the second line is above the first, or a lone pick that can't be let go
test("a tap picks, a second stretches, and the same line lets go", () => {
assert.deepEqual(tapLine(null, "src/a.rs", 12), at(12));
assert.deepEqual(tapLine(at(12), "src/a.rs", 18), at(12, 18));
assert.deepEqual(tapLine(at(12), "src/a.rs", 4), at(4, 12));
assert.equal(tapLine(at(12), "src/a.rs", 12), null);
});
// The break this catches: a third tap stretching a stretch, or a tap in another file stretching
// across files
test("after a stretch, or in another file, a tap starts over", () => {
assert.deepEqual(tapLine(at(12, 18), "src/a.rs", 30), at(30));
assert.deepEqual(tapLine(at(12), "src/b.rs", 18), at(18, 18, "src/b.rs"));
});
// The break this catches: Ask writing something other than what the TUI sends for the same lines
// (its mention expands to the path in backticks, then `line 12` or `lines 12–18` with an en dash)
test("ask writes the path and lines as the TUI does", () => {
assert.equal(lineWords(at(12)), "`src/a.rs` line 12");
assert.equal(lineWords(at(12, 18)), "`src/a.rs` lines 12–18");
assert.equal(askLabel(at(12)), "Ask about line 12");
assert.equal(askLabel(at(12, 18)), "Ask about lines 12–18");
});
/** A row of the host's HTML: line `line` in the block for `path`. */
function row(/** @type {number | null} */ line, path = "src/a.rs") {
const block = { getAttribute: () => path };
const classes = new Set();
const element = {
getAttribute: (/** @type {string} */ name) => (name === "data-line" ? String(line) : null),
closest: (/** @type {string} */ selector) => (selector === "[data-path]" ? block : line === null ? null : element),
classList: { toggle: (/** @type {string} */ name, /** @type {boolean} */ on) => (on ? classes.add(name) : classes.delete(name)), has: (/** @type {string} */ name) => classes.has(name) },
};
return element;
}
/** A tap that landed on `row`'s number, or on its code. */
const landing = (/** @type {any} */ target, onNumber = true) => ({ closest: (/** @type {string} */ selector) => (selector === ".ln" && onNumber ? target : null) });
// The break this catches: a tap on the code (where a selection starts) picking the line, or a tap
// on a number not reading its line and file from the host's HTML
test("only a tap on a line's number picks it", () => {
assert.deepEqual(tapped(null, /** @type {any} */ (landing(row(7)))), at(7));
assert.equal(tapped(at(7), /** @type {any} */ (landing(row(9), false))), null, "a tap elsewhere lets go");
assert.equal(tapped(at(7), null), null);
});
/** A selection whose range touches `touched` rows of a block holding `rows`. */
function selecting(/** @type {any[]} */ rows, /** @type {any[]} */ touched, inside = true, path = "src/a.rs") {
const block = { nodeType: 1, getAttribute: () => path, closest: () => block, querySelectorAll: () => rows };
const range = { commonAncestorContainer: block, intersectsNode: (/** @type {any} */ node) => touched.includes(node) };
const selection = { isCollapsed: false, rangeCount: 1, getRangeAt: () => range };
const root = { contains: () => inside };
return { selection: /** @type {any} */ (selection), root: /** @type {any} */ (root) };
}
// The break this catches: a selection that starts partway through a line not counting it, or the
// lines read from the first and last rows rather than every row touched
test("a selection offers every line it touches", () => {
const rows = [row(3), row(4), row(5), row(6)];
const { selection, root } = selecting(rows, [rows[1], rows[2]]);
assert.deepEqual(selectedLines(selection, root), at(4, 5));
});
// The break this catches: Ask offered for nothing (a collapsed caret, a selection in another pane,
// or one across deleted lines alone, which no line in the file stands for)
test("a selection offers nothing when it covers no line of this pane", () => {
const rows = [row(3), row(4)];
assert.equal(selectedLines({ ...selecting(rows, rows).selection, isCollapsed: true }, selecting(rows, rows).root), null);
const outside = selecting(rows, rows, false);
assert.equal(selectedLines(outside.selection, outside.root), null);
const none = selecting(rows, []);
assert.equal(selectedLines(none.selection, none.root), null);
assert.equal(selectedLines(null, none.root), null);
});
// The break this catches: rows outside the pick, or in another file with the same line numbers,
// marked as picked, or a let-go pick leaving its marks behind
test("only the picked rows of the picked file are marked", () => {
const rows = [row(3), row(4), row(5), row(6), row(4, "src/b.rs")];
const root = /** @type {any} */ ({ querySelectorAll: () => rows });
markPicked(root, at(4, 5));
assert.deepEqual(rows.map((it) => it.classList.has("picked")), [false, true, true, false, false]);
markPicked(root, null);
assert.deepEqual(rows.map((it) => it.classList.has("picked")), [false, false, false, false, false]);
});

View File

@@ -0,0 +1,18 @@
// @ts-check
// Which computer the app reaches, as the bridge names the page for it.
import assert from "node:assert/strict";
import { test } from "node:test";
import { machineName } from "../app/sessions.js";
/** A page whose `luxe-machine` meta says `name`, or that has none. */
const page = (/** @type {string | null} */ name) => ({
querySelector: (/** @type {string} */ selector) =>
selector === 'meta[name="luxe-machine"]' && name !== null ? { getAttribute: () => name } : null,
});
// The break this catches: the session list of two computers' apps looking the same because the
// meta goes unread, or a page without one (Tailscale couldn't say) showing a stray label
test("the app names the computer its page is named for, and nothing without a name", () => {
assert.equal(machineName(/** @type {any} */ (page("desk"))), "desk");
assert.equal(machineName(/** @type {any} */ (page(null))), "");
});

View File

@@ -0,0 +1,157 @@
// `@` mentions of project files: reading one back from the box, and the folders listed for it.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createListings, matchEntries, mentionAt, pickEntry } from "../app/mentions.js";
/** @import { Entry } from "../app/mentions.js" */
/** @param {string} name @returns {Entry} */
const dir = (name) => ({ name, kind: "directory" });
/** @param {string} name @returns {Entry} */
const file = (name) => ({ name, kind: "file" });
// The break this catches: the mention missed at the start of the box, where most begin
test("an @ at the start is a mention", () => {
assert.deepEqual(mentionAt("@ma", 3), { start: 0, folder: "", name: "ma" });
});
// The break this catches: the folder and name split anywhere but the last slash
test("what's typed splits into a folder and a name at the last slash", () => {
const text = "look at @src/cli/ma";
assert.deepEqual(mentionAt(text, text.length), { start: 8, folder: "src/cli", name: "ma" });
});
// The break this catches: an address read as a mention, which pops the picker mid-email
test("an @ inside a word isn't a mention", () => {
assert.equal(mentionAt("me@example.com", 14), null);
});
// The break this catches: the picker kept up after the mention's done and a space typed
test("a space ends the mention", () => {
assert.equal(mentionAt("@src ", 5), null);
});
// The break this catches: the caret ignored, so a mention typed mid-message reads the end instead
test("the mention is the one just before the caret", () => {
assert.deepEqual(mentionAt("@do and more", 3), { start: 0, folder: "", name: "do" });
});
// The break this catches: the ranks lost, so a name holding the text comes before one starting
// with it, or one holding it nowhere stays in
test("names starting with what's typed lead, then names holding it", () => {
const entries = [file("domain.rs"), file("main.rs"), file("Makefile"), file("lib.rs")];
assert.deepEqual(matchEntries(entries, "ma").map((entry) => entry.name), ["main.rs", "Makefile", "domain.rs"]);
});
// The break this catches: case counted, so a capital the keyboard put in hides every file
test("names match whatever the case typed", () => {
assert.deepEqual(matchEntries([file("main.rs")], "MA").map((entry) => entry.name), ["main.rs"]);
});
// The break this catches: a file put in bare or without the folder it's in, which isn't what the
// TUI sends the model, or the caret left before it
test("a picked file goes in as its path in backticks", () => {
const text = "fix @src/ma please";
const query = /** @type {any} */ (mentionAt(text, 11));
assert.deepEqual(pickEntry(text, 11, query, file("main.rs")), { text: "fix `src/main.rs` please", caret: 18 });
});
// The break this catches: a picked folder closing the mention, so its files can't be reached
test("a picked folder opens it for the next level", () => {
const query = /** @type {any} */ (mentionAt("@sr", 3));
assert.deepEqual(pickEntry("@sr", 3, query, dir("src")), { text: "@src/", caret: 5 });
});
/**
* Listings that have asked for `folders`, the frames they sent, and the id of the nth question.
* @param {string[]} folders
*/
function listingsAsked(...folders) {
const listings = createListings();
/** @type {import("../app/connection.js").Frame[]} */
const frames = [];
for (const folder of folders) listings.ask(folder, (frame) => (frames.push(frame), true));
return { listings, frames, idOf: (/** @type {number} */ nth) => frames[nth].content.request_id };
}
// The break this catches: the question in a shape `list_directory` doesn't take, or asked twice
test("a folder is asked for once, as list_directory", () => {
const { listings, frames, idOf } = listingsAsked("src", "src");
assert.deepEqual(frames, [{ kind: "list_directory", content: { request_id: idOf(0), path: "src" } }]);
assert.equal(listings.folders.value.src.state, "asking");
});
// The break this catches: ids counted from one on every phone, so two phones in one session file
// each other's answers, since every client hears every answer
test("no two phones ask with the same id", () => {
const first = listingsAsked("src");
const second = listingsAsked("src");
assert.notEqual(first.idOf(0), second.idOf(0));
});
// The break this catches: the answer filed under the wrong folder, or its entries read from the
// wrong field
test("the answer is filed under the folder that was asked for", () => {
const { listings, idOf } = listingsAsked("", "src");
const listing = { path: "src", entries: [file("main.rs")], omitted: 0 };
listings.apply({ kind: "directory_listed", content: { request_id: idOf(1), listing } });
assert.deepEqual(listings.folders.value.src, { state: "listed", entries: [file("main.rs")] });
assert.equal(listings.folders.value[""].state, "asking");
});
// The break this catches: a folder that can't be listed left asking forever
test("a folder that can't be listed says so", () => {
const { listings, idOf } = listingsAsked("gone");
listings.apply({ kind: "directory_list_failed", content: { request_id: idOf(0), path: "gone", error: "no such folder" } });
assert.equal(listings.folders.value.gone.state, "failed");
});
// The break this catches: another client's answer, or a stale one, filed as if it were ours
test("an answer to a question not asked here changes nothing", () => {
const { listings } = listingsAsked("src");
const listing = { path: "lib", entries: [], omitted: 0 };
listings.apply({ kind: "directory_listed", content: { request_id: "listing:elsewhere", listing } });
assert.deepEqual(Object.keys(listings.folders.value), ["src"]);
});
// The break this catches: a question that never left counted as asked, so it's never asked again
test("a question that couldn't be sent is asked again next time", () => {
const listings = createListings();
listings.ask("src", () => false);
assert.equal(listings.folders.value.src, undefined);
});
/** Listings with `src` listed as holding `main.rs`, and the frames sent so far. */
function srcListed() {
const asked = listingsAsked("src");
const listing = { path: "src", entries: [file("main.rs")], omitted: 0 };
asked.listings.apply({ kind: "directory_listed", content: { request_id: asked.idOf(0), listing } });
return asked;
}
// The break this catches: the Files tab shown a folder as it was when the picker first listed it,
// missing what the agent has written since
test("a fresh ask lists a known folder again, keeping its entries up meanwhile", () => {
const { listings, frames } = srcListed();
listings.ask("src", (frame) => (frames.push(frame), true), { fresh: true });
assert.equal(frames.length, 2);
assert.deepEqual(listings.folders.value.src, { state: "asking", entries: [file("main.rs")] });
});
// The break this catches: a fresh ask sent again while one is on its way, doubling every request
// each time the view draws
test("a fresh ask waits for the one on its way", () => {
const { listings, frames } = listingsAsked("src");
listings.ask("src", (frame) => (frames.push(frame), true), { fresh: true });
assert.equal(frames.length, 1);
});
// The break this catches: a folder asked for just before the connection dropped left loading
// forever, since the new connection never answers the old question
test("a new connection forgets the folders still on their way, and only those", () => {
const { listings, frames } = srcListed();
listings.ask("lib", (frame) => (frames.push(frame), true));
listings.apply({ kind: "ready", content: {} });
assert.deepEqual(Object.keys(listings.folders.value), ["src"]);
});

View File

@@ -0,0 +1,88 @@
// The model and thinking pickers: asking the session for its models, and the frames a pick sends.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createModels, isCurrent, selectModelFrame, thinkingFrame, thinkingLevels } from "../app/models.js";
const SONNET = { provider: "anthropic", model: "claude-sonnet-5", name: "Claude Sonnet 5", thinking_levels: ["off", "low", "high"] };
const MINI = { provider: "openai", model: "gpt-mini", name: "GPT Mini", thinking_levels: ["off"] };
/** A models state that has asked once, and the frames it sent. */
function asked(sent = true) {
const models = createModels();
const frames = [];
models.ask((frame) => (frames.push(frame), sent));
return { models, frames };
}
// The break this catches: the question sent in a shape `list_models` doesn't take, or the sheet
// not showing that it's waiting
test("asking sends list_models with an id, and waits", () => {
const { models, frames } = asked();
assert.deepEqual(frames, [{ kind: "list_models", content: { request_id: "models-1" } }]);
assert.equal(models.listing.value.state, "asking");
});
// The break this catches: a question that never left counted as asked, so the sheet waits forever
test("a question that couldn't be sent says so", () => {
assert.equal(asked(false).models.listing.value.state, "lost");
});
// The break this catches: the answer not taken, or taken from the wrong field
test("the answer to the question is listed", () => {
const { models } = asked();
models.apply({ kind: "models_listed", content: { request_id: "models-1", models: [SONNET, MINI] } });
assert.deepEqual(models.listing.value, { state: "listed", models: [SONNET, MINI] });
});
// The break this catches: an answer to an earlier question, arriving late, replacing the latest
test("an answer to an earlier question is ignored", () => {
const { models } = asked();
models.ask(() => true);
models.apply({ kind: "models_listed", content: { request_id: "models-1", models: [MINI] } });
assert.equal(models.listing.value.state, "asking");
});
// The break this catches: an older Luxe's refusal ignored, so the sheet says it's listing forever
test("a Luxe that doesn't know the question is told apart", () => {
const { models } = asked();
models.apply({ kind: "action_rejected", content: { kind: "list_models", reason: "unknown kind" } });
assert.equal(models.listing.value.state, "unsupported");
});
// The break this catches: any refusal, of something else entirely, taken for the question's
test("a refusal of something else leaves the question waiting", () => {
const { models } = asked();
models.apply({ kind: "action_rejected", content: { kind: "steer_turn", reason: "missing text" } });
assert.equal(models.listing.value.state, "asking");
});
// The break this catches: the running model matched by provider or by id alone, which marks a
// second provider's model of the same name as running
test("the running model is matched by provider and id together", () => {
assert.equal(isCurrent(SONNET, { provider: "anthropic", model: "claude-sonnet-5" }), true);
assert.equal(isCurrent(SONNET, { provider: "bedrock", model: "claude-sonnet-5" }), false);
assert.equal(isCurrent(SONNET, { provider: "anthropic", model: "claude-opus-5" }), false);
});
// The break this catches: the levels offered from another model's list, or every level offered
// before the running model's are known, which the session would clamp without a word
test("thinking offers the running model's levels, and none before it's listed", () => {
const current = { provider: "openai", model: "gpt-mini" };
assert.deepEqual(thinkingLevels([SONNET, MINI], current), ["off"]);
assert.deepEqual(thinkingLevels([], current), []);
});
// The break this catches: a pick sent with the display name or levels, which `select_model`
// doesn't take, or under another key
test("a picked model is sent as provider and id", () => {
assert.deepEqual(selectModelFrame(SONNET), {
kind: "select_model",
content: { provider: "anthropic", model: "claude-sonnet-5" },
});
});
// The break this catches: the level wrapped in an object, when `set_thinking_level` takes a string
test("a picked level is sent bare", () => {
assert.deepEqual(thinkingFrame("high"), { kind: "set_thinking_level", content: "high" });
});

View File

@@ -0,0 +1,23 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { keyBytes, support } from "../app/notifications.js";
// The break this catches: the switch offered where subscribing can only fail, or a Safari tab on
// iOS told notifications are impossible when the Home Screen is the way to them.
test("what the switch offers follows what the browser can do", () => {
assert.equal(support({ worker: true, push: true, standalone: false }), "ready");
assert.equal(support({ worker: true, push: true, standalone: true }), "ready");
assert.equal(support({ worker: true, push: false, standalone: false }), "home-screen");
assert.equal(support({ worker: false, push: true, standalone: false }), "home-screen");
assert.equal(support({ worker: true, push: false, standalone: true }), "unsupported");
});
// The break this catches: the key passed as base64url text or decoded as plain base64, which
// PushManager refuses, so turning notifications on fails on every device.
test("the bridge's key reaches the browser as bytes", () => {
assert.deepEqual([...keyBytes("AQID_-8")], [1, 2, 3, 255, 239]);
const key = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
const bytes = keyBytes(key);
assert.equal(bytes.length, 65);
assert.equal(bytes[0], 4, "an uncompressed point");
});

View File

@@ -0,0 +1,133 @@
{
"name": "luxe-remote-app-tests",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "luxe-remote-app-tests",
"devDependencies": {
"@preact/signals": "2.11.3",
"@preact/signals-core": "1.14.4",
"@types/node": "^24.0.0",
"htm": "3.1.1",
"playwright": "1.63.0",
"preact": "11.0.1",
"typescript": "5.9.3"
}
},
"node_modules/@preact/signals": {
"version": "2.11.3",
"resolved": "https://registry.npmjs.org/@preact/signals/-/signals-2.11.3.tgz",
"integrity": "sha512-mttwFM98G/JiriTgMwU+UWygL6sfVmYEiNcPSKkUnv4PxPpZhmP2ugGC4qi360+ZIHyQ8NY05bfJT3b4RUIGlw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@preact/signals-core": "^1.14.4"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
},
"peerDependencies": {
"preact": ">= 10.25.0 || >=11.0.0-0"
}
},
"node_modules/@preact/signals-core": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz",
"integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==",
"dev": true,
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
}
},
"node_modules/@types/node": {
"version": "24.19.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": ">=7.24.0 <7.24.7"
}
},
"node_modules/htm": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/htm/-/htm-3.1.1.tgz",
"integrity": "sha512-983Vyg8NwUE7JkZ6NmOqpCZ+sh1bKv2iYTlUkzlWmA5JD2acKoxd4KVxbMmxX/85mtfdnDmTFoNKcg5DGAvxNQ==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/preact": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/preact/-/preact-11.0.1.tgz",
"integrity": "sha512-TNNwEq++jYNHy747LziCjPRVgEwnLSOIOAw/oYcjI3Tdnubx2EXtt76I0an8PATvUWtx/DX1kFIg1eFN+O/fkw==",
"dev": true,
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
},
"peerDependencies": {
"preact-render-to-string": ">=6.7.0"
},
"peerDependenciesMeta": {
"preact-render-to-string": {
"optional": true
}
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
"dev": true,
"license": "MIT"
}
}
}

View File

@@ -0,0 +1,20 @@
{
"name": "luxe-remote-app-tests",
"private": true,
"description": "Type checks, unit tests and the WebKit end-to-end test for the luxe remote phone app",
"type": "module",
"scripts": {
"check": "tsc -p . && tsc -p tsconfig.worker.json && tsc -p tsconfig.tests.json",
"test": "node --import ./register.mjs --test",
"e2e": "node --test --test-timeout=60000 e2e/flow.mjs"
},
"devDependencies": {
"@preact/signals": "2.11.3",
"@preact/signals-core": "1.14.4",
"htm": "3.1.1",
"playwright": "1.63.0",
"preact": "11.0.1",
"typescript": "5.9.3",
"@types/node": "^24.0.0"
}
}

View File

@@ -0,0 +1,28 @@
// Reading an invitation out of what someone pasted.
import assert from "node:assert/strict";
import { test } from "node:test";
import { invitationFrom } from "../app/pairing.js";
/** A token as `luxe remote pair` makes one: 32 random bytes, URL-safe base64 without padding. */
const TOKEN = "q3J0-Zx_8fLmN2pQrStUvWxYz0123456789AbCdEfGh";
// The break this catches: the whole link sent as the invitation, which the bridge can't match
test("the token is read out of the printed link", () => {
assert.equal(invitationFrom(`https://desk.tail1234.ts.net/pair#${TOKEN}`), TOKEN);
});
// The break this catches: insisting on a whole link, when a notes app or a message may carry only
// the part after the #, or a copy picks up the line's spaces
test("the token alone is taken, spaces and all", () => {
assert.equal(invitationFrom(TOKEN), TOKEN);
assert.equal(invitationFrom(` ${TOKEN}\n`), TOKEN);
});
// The break this catches: a link without its invitation, or text that isn't one, enabling Pair
// for a request that can only fail
test("nothing that can't be an invitation is taken for one", () => {
for (const text of ["", "https://desk.tail1234.ts.net/pair", "https://desk.tail1234.ts.net/pair#", "two words"]) {
assert.equal(invitationFrom(text), null, JSON.stringify(text));
}
});

View File

@@ -0,0 +1,105 @@
// Prompts and steering, folded from frames, and the frames the phone sends back.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createPending, messageFrame, permissionReply, questionReply } from "../app/pending.js";
import { permissionChoices, toggled } from "../app/prompt.js";
const frame = (kind, content) => ({ kind, content });
const asked = (id) => frame("permission_requested", {
id, session_id: "s", tool: "bash", permission: "bash", summary: "Run: rm -rf build", always_patterns: ["rm *"],
});
const ids = (pending) => pending.prompts.value.map((prompt) => prompt.id);
function fold(frames) {
const pending = createPending();
frames.forEach(pending.apply);
return pending;
}
// The break this catches: `prompt_closed` taking down every prompt, or the wrong one, so a
// question answered at the desk clears the approval still waiting on the phone
test("a prompt closes by its own id, whoever answered it", () => {
const pending = fold([asked("perm:1"), asked("perm:2"), asked("perm:3"), frame("prompt_closed", { id: "perm:2" })]);
assert.deepEqual(ids(pending), ["perm:1", "perm:3"]);
});
// The break this catches: a question shown as a permission card, or its options lost
test("a question opens as a question, with its options", () => {
const options = [{ label: "postgres", description: "Relational", recommended: true }];
const pending = fold([frame("question_asked", { id: "ask:1", session_id: "s", prompt: "Which?", options, multi: false })]);
const [prompt] = pending.prompts.value;
assert.equal(prompt.kind, "question");
assert.deepEqual(prompt.options, options);
});
// The break this catches: the same prompt sent twice (a snapshot racing the live event) drawn as
// two, so answering one leaves a card behind that can't be answered
test("a prompt already open isn't opened twice", () => {
assert.deepEqual(ids(fold([asked("perm:1"), asked("perm:1")])), ["perm:1"]);
});
// The break this catches: a reconnect keeping the last connection's prompts, which the snapshot
// sends again if they're still open, so one answered meanwhile lingers on the phone
test("a new connection starts with nothing waiting", () => {
const pending = fold([asked("perm:1"), frame("ready", {})]);
pending.steered();
pending.apply(frame("ready", {}));
assert.deepEqual(ids(pending), []);
assert.equal(pending.steering.value, 0);
});
// The break this catches: a delivery clearing only some of the tray, or a turn ending clearing
// steering the engine holds for the next turn, as the TUI's tray keeps it
test("steering waits through a turn's end, and a checkpoint delivers all of it", () => {
const pending = createPending();
pending.steered();
pending.steered();
pending.apply(frame("turn_ended", { reason: "end_turn" }));
assert.equal(pending.steering.value, 2);
pending.apply(frame("steering_delivered", { count: 1 }));
assert.equal(pending.steering.value, 0);
});
// The break this catches: Stop or withdraw leaving the tray saying messages wait that the engine
// has thrown away
test("dropping steering empties the tray", () => {
const pending = createPending();
pending.steered();
pending.dropSteering();
assert.equal(pending.steering.value, 0);
});
// The break this catches: a reply frame the host's decoder doesn't know, which it rejects, so a
// tap on the phone answers nothing; shapes as `rpc.md` documents them
test("replies are the protocol's frames", () => {
assert.deepEqual(permissionReply("perm:1", "always"), { kind: "respond_permission", content: { id: "perm:1", reply: "always" } });
assert.deepEqual(questionReply("ask:1", ["postgres", "my own"]), {
kind: "answer_question", content: { id: "ask:1", reply: { answered: ["postgres", "my own"] } },
});
assert.deepEqual(questionReply("ask:1", null), { kind: "answer_question", content: { id: "ask:1", reply: "cancelled" } });
});
// The break this catches: writing while a turn runs sent as a new message, which waits for the
// turn to end, instead of steering the one running
test("a message steers while a turn runs, and starts one otherwise", () => {
assert.deepEqual(messageFrame("hi", false), { kind: "submit_user_message", content: { text: "hi" } });
assert.deepEqual(messageFrame("hi", true), { kind: "steer_turn", content: { text: "hi" } });
});
// The break this catches: "remember" offered for a call with no pattern to remember, which the
// engine can only treat as once; or the options out of the TUI's order
test("the remembering answers appear only when the call has a pattern", () => {
/** @param {string[]} always_patterns */
const asking = (always_patterns) => permissionChoices({ kind: "permission", id: "p", tool: "bash", summary: "", always_patterns });
const replies = (patterns) => asking(patterns).map((choice) => choice.reply);
assert.deepEqual(replies([]), ["once", "reject"]);
assert.deepEqual(replies(["rm *"]), ["once", "always", "always_persist", "reject"]);
assert.match(asking(["rm *"])[1].hint, /rm \*/);
});
// The break this catches: ticking an option twice leaving it ticked, so it can't be taken back
test("ticking an option again unticks it", () => {
assert.deepEqual(toggled(["a"], "b"), ["a", "b"]);
assert.deepEqual(toggled(["a", "b"], "a"), ["b"]);
});

View File

@@ -0,0 +1,40 @@
// Photos in the composer: their size, the frame that carries them, and the button's word.
import assert from "node:assert/strict";
import { test } from "node:test";
import { sendLabel } from "../app/composer.js";
import { messageFrame } from "../app/pending.js";
import { LONGEST_EDGE, dataOf, fitWithin, forTheWire } from "../app/photos.js";
// The break this catches: a photo sent at full size (12 megapixels, megabytes over the phone's
// network), squashed out of shape, or a small screenshot blown up past its own pixels
test("a photo fits the longest edge, keeps its shape, and is never enlarged", () => {
assert.deepEqual(fitWithin(4032, 3024), { width: LONGEST_EDGE, height: 1176 });
assert.deepEqual(fitWithin(3024, 4032), { width: 1176, height: LONGEST_EDGE });
assert.deepEqual(fitWithin(800, 600), { width: 800, height: 600 });
});
// The break this catches: the preview sent along, doubling every photo's size, or the data URL's
// header sent as part of the base64, which no provider can decode
test("on the wire a photo is its base64, its type and its name", () => {
const preview = "data:image/jpeg;base64,QUJD";
assert.equal(dataOf(preview), "QUJD");
const photo = { data: "QUJD", mime: "image/jpeg", name: "IMG_1.HEIC", preview };
assert.deepEqual(forTheWire([photo]), [{ data: "QUJD", mime: "image/jpeg", name: "IMG_1.HEIC" }]);
});
// The break this catches: photos sent as steering, which carries only words, so they're dropped;
// a message with photos starts a turn, waiting for a running one to end
test("a message with photos is always a new turn", () => {
const images = [{ data: "QUJD", mime: "image/jpeg", name: null }];
const frame = { kind: "submit_user_message", content: { text: "what's this?", images } };
assert.deepEqual(messageFrame("what's this?", true, images), frame);
assert.deepEqual(messageFrame("what's this?", false, images), frame);
});
// The break this catches: the button saying Steer for a message that will wait for the next turn
test("the send button says what will happen", () => {
assert.equal(sendLabel(false, true), "Send");
assert.equal(sendLabel(true, false), "Steer");
assert.equal(sendLabel(true, true), "Queue");
});

View File

@@ -0,0 +1,87 @@
// What the box offers as you type, and what a pick does to the draft.
import assert from "node:assert/strict";
import { test } from "node:test";
import { COMMANDS } from "../app/commands.js";
import { afterPick, pickerNote, suggestions } from "../app/picker.js";
/** @import { Entry, Listing } from "../app/mentions.js" */
/** @param {string} text */
const at = (text) => ({ text, caret: text.length });
/** @type {Entry} */
const MAIN = { name: "main.rs", kind: "file" };
/** @type {Listing} */
const SRC = { state: "listed", entries: [{ name: "cli", kind: "directory" }, MAIN] };
/** @type {Listing} */
const ASKING = { state: "asking", entries: [] };
/** @type {Listing} */
const FAILED = { state: "failed", entries: [] };
/** @param {string} name */
const command = (name) => COMMANDS.find((entry) => entry.name === name);
// The break this catches: commands labeled without their slash, or without the TUI's title
test("a slash offers commands, labeled as the TUI's", () => {
const offered = suggestions(at("/co"), {});
assert.deepEqual(offered.map((item) => [item.label, item.hint]), [["/compact", "Compact the conversation"], ["/cost", "Session cost"]]);
});
// The break this catches: a folder shown like a file, so it's not clear a tap opens it
test("a mention offers the folder's entries, folders marked with a slash", () => {
const offered = suggestions(at("@src/"), { src: SRC });
assert.deepEqual(offered.map((item) => item.label), ["cli/", "main.rs"]);
});
// The break this catches: suggestions for a folder that hasn't been listed taken from another
test("nothing is offered from a folder not listed yet", () => {
assert.deepEqual(suggestions(at("@lib/"), { src: SRC }), []);
});
// The break this catches: a plain message offering anything
test("a plain message offers nothing", () => {
assert.deepEqual(suggestions(at("hello"), { src: SRC }), []);
});
// The break this catches: a command that takes words run before they're written
test("a command that takes words goes into the box to finish", () => {
assert.deepEqual(afterPick(at("/co"), { key: "compact", label: "", hint: "", command: command("compact") }), {
text: "/compact ",
caret: 9,
placed: true,
});
});
// The break this catches: a command that takes nothing put in the box, a second tap to run it
test("a command that takes nothing runs", () => {
assert.equal(afterPick(at("/mo"), { key: "model", label: "", hint: "", command: command("model") }), null);
});
// The break this catches: the caret not placed after the pick, so typing goes in before it
test("a picked file replaces the mention and places the caret after it", () => {
assert.deepEqual(afterPick(at("@src/ma"), { key: "main.rs", label: "", hint: "", entry: MAIN }), {
text: "`src/main.rs` ",
caret: 14,
placed: true,
});
});
// The break this catches: a folder on its way shown as empty, which reads as no files
test("a folder being listed says so", () => {
assert.equal(pickerNote(at("@src/"), { src: ASKING }), "Listing files…");
});
// The break this catches: an empty folder showing no picker at all, which reads as broken, or a
// folder with files said to be empty
test("an empty folder says so", () => {
/** @type {Listing} */
const empty = { state: "listed", entries: [] };
assert.equal(pickerNote(at("@.luxe/"), { ".luxe": empty }), "No files in .luxe");
assert.equal(pickerNote(at("@src/zz"), { src: SRC }), "");
});
// The break this catches: a folder that can't be listed shown as empty, or the project root named
// as nothing
test("a folder that can't be listed is named", () => {
assert.equal(pickerNote(at("@gone/"), { gone: FAILED }), "Couldn't list gone");
assert.equal(pickerNote(at("@"), { "": FAILED }), "Couldn't list the project");
});

View File

@@ -0,0 +1,20 @@
// `node --import ./register.mjs --test`: resolves the app's bare imports through index.html's
// import map, as the browser does, so the tests run the vendored files the phone runs rather than
// whatever npm would find.
import { readFileSync } from "node:fs";
import { registerHooks } from "node:module";
const app = new URL("../app/", import.meta.url);
const page = readFileSync(new URL("index.html", app), "utf8");
const block = /<script type="importmap">([\s\S]*?)<\/script>/.exec(page);
if (!block) throw new Error("index.html has no import map");
const imports = JSON.parse(block[1]).imports;
registerHooks({
resolve(specifier, context, next) {
const mapped = imports[specifier];
if (!mapped) return next(specifier, context);
return next(new URL(mapped.replace(/^\/app\//, ""), app).href, context);
},
});

View File

@@ -0,0 +1,64 @@
// Asking the host for rendered text: batching, keeping, and failing.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createRenderer } from "../app/render.js";
/** A host that answers each piece with its own JSON, and remembers every batch it was sent. */
function fakeHost() {
const batches = [];
const post = async (pieces) => {
batches.push(pieces);
return pieces.map((piece) => `<p>${JSON.stringify(piece)}</p>`);
};
return { batches, post };
}
/** @param {string} text @returns {import("../app/render.js").Piece} */
const answer = (text) => ({ kind: "answer", text });
// The break this catches: a request per piece, so a transcript of a hundred messages costs a
// hundred round trips; or answers handed back by position wrongly, so one message shows another's
test("pieces asked for together go in one request and come back to their askers", async () => {
const host = fakeHost();
const renderer = createRenderer(host.post);
const [first, second] = await Promise.all([
renderer.render(answer("one"), { keep: false }),
renderer.render(answer("two"), { keep: false }),
]);
assert.equal(host.batches.length, 1);
assert.equal(first, '<p>{"kind":"answer","text":"one"}</p>');
assert.equal(second, '<p>{"kind":"answer","text":"two"}</p>');
});
// The break this catches: finished messages asked for again on every redraw and reconnect
test("a finished piece is kept and not asked for again", async () => {
const host = fakeHost();
const renderer = createRenderer(host.post);
await renderer.render(answer("done"), { keep: true });
const again = await renderer.render(answer("done"), { keep: true });
assert.equal(host.batches.length, 1);
assert.equal(again, renderer.peek(answer("done")));
});
// The break this catches: every version of a streaming reply kept, which fills the cache with
// prefixes nobody will see again
test("a growing piece isn't kept", async () => {
const host = fakeHost();
const renderer = createRenderer(host.post);
await renderer.render(answer("grow"), { keep: false });
assert.equal(renderer.peek(answer("grow")), undefined);
await renderer.render(answer("grow"), { keep: false });
assert.equal(host.batches.length, 2);
});
// The break this catches: a failed request leaving its askers waiting forever, so those messages
// never fall back from plain text and never ask again
test("a failed request fails every piece in it", async () => {
const renderer = createRenderer(async () => {
throw new Error("rendering failed: 502");
});
const asked = [renderer.render(answer("a"), { keep: true }), renderer.render(answer("b"), { keep: true })];
for (const one of asked) await assert.rejects(one, /502/);
assert.equal(renderer.peek(answer("a")), undefined);
});

View File

@@ -0,0 +1,211 @@
// @ts-check
// The Review tab's state: joining the open review, loading one when none is, keeping up when any
// client changes it, and the pieces it asks the host to draw.
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyReview, chapterPiece, createReview, guidePiece, nextChapter, targetName, withoutLines } from "../app/review.js";
import { tapChapter } from "../app/review-view.js";
/** @param {string} id @param {string} text */
const hunk = (id, text) => ({ id, lines: [{ kind: "addition", text }] });
/** Two chapters: the first names one hunk of `a.rs` and all of `b.png`; the second `c.rs`'s hunk. */
function review() {
return {
id: "review:1",
target: { kind: "working_tree" },
chapters: [
{ id: "chapter:1", items: [{ kind: "hunk", id: "hunk:a1" }, { kind: "file", id: "file:b" }] },
{ id: "chapter:2", items: [{ kind: "hunk", id: "hunk:c1" }] },
],
files: [
{ id: "file:a", hunks: [hunk("hunk:a1", "one"), hunk("hunk:a2", "two")] },
{ id: "file:b", hunks: [] },
{ id: "file:c", hunks: [hunk("hunk:c1", "three")] },
],
};
}
/** A review tab and everything it sent. */
function tab() {
/** @type {any[]} */
const sent = [];
const state = createReview();
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
return { state, sent, send, last: () => sent[sent.length - 1] };
}
/** The answer to the last `show_open_review` sent. @param {any[]} sent @param {any} content */
function answer(sent, content) {
const asked = [...sent].reverse().find((frame) => frame.kind === "show_open_review");
return { kind: "open_review_shown", content: { request_id: asked.content.request_id, ...content } };
}
// The break this catches: taking another phone's answer for this one's, or ignoring this one's
test("an answer shows only for the request that asked", () => {
const { state, sent, send } = tab();
state.ask(send);
assert.equal(state.shown.value.state, "asking");
state.apply({ kind: "open_review_shown", content: { request_id: "phone-review:show:other", review: review() } });
assert.equal(state.shown.value.review, null);
state.apply(answer(sent, { review: review(), reading: [{ chapter_id: "chapter:1", needs_review: 1 }] }));
assert.equal(state.shown.value.state, "shown");
assert.equal(state.shown.value.review?.id, "review:1");
assert.equal(state.shown.value.reading.length, 1);
});
// The break this catches: two phones asking with the same id, each taking the other's answer
test("each ask carries an id of its own", () => {
const { state, sent, send } = tab();
state.ask(send);
state.ask(send);
assert.notEqual(sent[0].content.request_id, sent[1].content.request_id);
});
// The break this catches: a review with nothing open read as still loading, so the button to
// review the changes never shows
test("nothing open is shown as nothing open", () => {
const { state, sent, send } = tab();
state.ask(send);
state.apply(answer(sent, { review: null, session: null, reading: [] }));
assert.deepEqual([state.shown.value.state, state.shown.value.review], ["shown", null]);
});
// The break this catches: the guide's piece sent with every line of the review, or the lines
// stripped from the review itself, leaving a chapter nothing to show
test("the guide goes without lines and the review keeps them", () => {
const full = review();
const guide = withoutLines(full);
assert.deepEqual(guide.files[0].hunks.map((/** @type {any} */ it) => [it.id, it.lines]), [["hunk:a1", []], ["hunk:a2", []]]);
assert.equal(full.files[0].hunks[0].lines.length, 1);
});
// The break this catches: progress walked on the terminal not showing here, or the guide piece
// leaving out what it marks
test("walked chapters come from the session and reach the guide", () => {
const { state, sent, send } = tab();
state.ask(send);
state.apply(answer(sent, { review: review(), session: { progress: { walked_chapter_ids: ["chapter:2"] } } }));
const piece = guidePiece(state.shown.value);
assert.deepEqual([piece.kind, piece.walked, piece.review.files[2].hunks[0].lines], ["review_guide", ["chapter:2"], []]);
});
// The break this catches: a review another client loaded or re-guided left stale here, or the
// tab asking before anyone opened it
test("a review loaded or re-guided anywhere is asked for again", () => {
const { state, sent, send } = tab();
state.apply({ kind: "guided_review_loaded", content: { request_id: "elsewhere" } });
assert.equal(sent.length, 0, "not before the tab has asked");
state.ask(send);
state.apply(answer(sent, { review: review() }));
state.apply({ kind: "guided_review_loaded", content: { request_id: "elsewhere" } });
assert.equal(sent.length, 2);
state.apply({ kind: "guided_review_guide_updated", content: {} });
assert.equal(sent.length, 3);
assert.equal(sent[2].kind, "show_open_review");
});
// The break this catches: loading something other than the working changes, or a failure of
// another client's load shown as this one's
test("loading reviews the working changes and says when it fails", () => {
const { state, sent, send, last } = tab();
state.load(send);
assert.deepEqual([last().kind, last().content.target], ["load_guided_review", { kind: "working_tree" }]);
assert.equal(state.shown.value.state, "loading");
state.apply({ kind: "guided_review_failed", content: { request_id: "elsewhere", error: { message: "no" } } });
assert.equal(state.shown.value.state, "loading");
state.apply({ kind: "guided_review_failed", content: { request_id: sent[0].content.request_id, error: { message: "Not a repository" } } });
assert.deepEqual([state.shown.value.state, state.shown.value.error], ["failed", "Not a repository"]);
});
// The break this catches: a lost connection leaving "Loading…" up forever, or a shown review
// thrown away when the connection comes back
test("a new connection loses only what was waiting", () => {
const asking = tab();
asking.state.ask(asking.send);
asking.state.apply({ kind: "ready", content: {} });
assert.equal(asking.state.shown.value.state, "lost");
const shown = tab();
shown.state.ask(shown.send);
shown.state.apply(answer(shown.sent, { review: review() }));
shown.state.apply({ kind: "ready", content: {} });
assert.equal(shown.state.shown.value.state, "shown");
});
// The break this catches: a send that didn't go read as asking, so the tab waits on nothing
test("an ask that couldn't be sent is lost", () => {
const state = createReview();
state.ask(() => false);
assert.equal(state.shown.value.state, "lost");
});
// The break this catches: a chapter from a replaced review left open, or the open one closed by a
// fresh answer for the same review
test("a chapter stays open only while the review has it", () => {
const { state, sent, send } = tab();
state.ask(send);
state.apply(answer(sent, { review: review() }));
state.pick("chapter:2");
state.apply(answer(sent, { review: review() }));
assert.equal(state.open.value, "chapter:2");
const other = { ...review(), chapters: [{ id: "chapter:9", items: [] }] };
state.apply(answer(sent, { review: other }));
assert.equal(state.open.value, null);
});
// The break this catches: marking a chapter sending only that one (the session keeps the list it's
// sent, so the others would be unwalked), or unmarking doing nothing
test("marking a chapter reviewed sends every chapter walked, and unmarks", () => {
const { state, sent, send, last } = tab();
state.ask(send);
state.apply(answer(sent, { review: review(), session: { progress: { walked_chapter_ids: ["chapter:2"] } } }));
state.walk("chapter:1", send);
assert.deepEqual(last(), { kind: "record_review_progress", content: { review_id: "review:1", walked_chapter_ids: ["chapter:2", "chapter:1"] } });
state.walk("chapter:2", send);
assert.deepEqual(last().content.walked_chapter_ids, ["chapter:1"]);
assert.deepEqual(state.shown.value.walked, ["chapter:1"]);
});
// The break this catches: a chapter's piece carrying the whole review, a hunk from another
// chapter, or the wrong place in the list
test("a chapter's piece holds only its files and hunks", () => {
const shown = /** @type {any} */ ({ review: review(), reading: [{ chapter_id: "chapter:1", needs_review: 2 }], walked: ["chapter:1"] });
const piece = chapterPiece(shown, "chapter:1");
assert.deepEqual(piece.files.map((/** @type {any} */ file) => [file.id, file.hunks.map((/** @type {any} */ it) => it.id)]), [["file:a", ["hunk:a1"]], ["file:b", []]]);
assert.deepEqual(piece.place, { number: 1, total: 2, walked: true });
assert.equal(piece.reading?.needs_review, 2);
assert.equal(chapterPiece(shown, "chapter:2").reading, null);
});
// The break this catches: Next skipping a chapter, or offered past the last one
test("next is the chapter after, and nothing after the last", () => {
assert.equal(nextChapter(review(), "chapter:1"), "chapter:2");
assert.equal(nextChapter(review(), "chapter:2"), null);
});
// The break this catches: every review called the same thing, so the tab can't say what it's of
test("a review says what it's of", () => {
assert.equal(targetName({ kind: "working_tree" }), "Working changes");
assert.equal(targetName({ kind: "pull_request", number: 230 }), "Pull request #230");
assert.equal(targetName({ kind: "commit", oid: "842ffb60c0ffee" }), "Commit 842ffb60");
assert.equal(targetName({ kind: "base", reference: "main" }), "Changes since main");
});
// The break this catches: a chapter tap leaving a file or pull request in the pane, or a tap
// between chapters opening something
test("tapping a chapter opens it in place of the other panes", () => {
const closed = /** @type {string[]} */ ([]);
const state = createReview();
const hooks = /** @type {any} */ ({ review: state, files: { close: () => closed.push("file") }, github: { close: () => closed.push("item") } });
const event = (/** @type {any} */ found) => /** @type {any} */ ({ target: { closest: () => found } });
tapChapter(event(null), hooks);
assert.deepEqual([state.open.value, closed], [null, []]);
tapChapter(event({ dataset: { chapter: "chapter:2" } }), hooks);
assert.deepEqual([state.open.value, closed], ["chapter:2", ["file", "item"]]);
});
// The break this catches: a frame for nothing this tab asked changing it
test("other frames leave the tab alone", () => {
const shown = /** @type {any} */ ({ state: "shown", review: null, guide: null, reading: [], walked: [] });
assert.deepEqual(applyReview(shown, { kind: "turn_started", content: {} }, { id: "a", load: "b" }), { next: shown, again: false });
});

View File

@@ -0,0 +1,73 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import vm from "node:vm";
const source = readFileSync(new URL("../app/worker/service-worker.js", import.meta.url), "utf8");
/** Runs the worker against a stand-in for the browser, with `windows` open. */
function worker(windows = []) {
const listeners = {};
const shown = [];
const opened = [];
const self = {
addEventListener: (type, listener) => (listeners[type] = listener),
registration: { showNotification: async (title, options) => shown.push({ title, options }) },
clients: { matchAll: async () => windows, openWindow: async (url) => opened.push(url) },
};
vm.runInNewContext(source, { self });
const fire = async (type, event) => {
let pending;
listeners[type]({ ...event, waitUntil: (promise) => (pending = promise) });
await pending;
};
return { fire, shown, opened };
}
// objects made in the worker's context have its own Object, which strict equality tells apart
const plain = (value) => JSON.parse(JSON.stringify(value));
const push = (payload) => ({ data: { json: () => (typeof payload === "string" ? JSON.parse(payload) : payload) } });
// The break this catches: a notice shown without its folder or what's waiting, or with the
// session it should open lost.
test("a push shows what the bridge sent", async () => {
const { fire, shown } = worker();
await fire("push", push({ title: "luxe-dev", body: "Approve bash", session: "s-1" }));
const options = { body: "Approve bash", icon: "/icons/192.png", data: { session: "s-1" } };
assert.deepEqual(plain(shown), [{ title: "luxe-dev", options }]);
});
// The break this catches: a push that shows nothing, which iOS answers by ending the subscription.
test("a push it can't read still shows a notification", async () => {
const { fire, shown } = worker();
await fire("push", push("not json"));
await fire("push", { data: null });
assert.deepEqual(shown.map((notice) => notice.title), ["Luxe", "Luxe"]);
});
const click = (session) => {
const closed = [];
return { closed, event: { notification: { data: { session }, close: () => closed.push(true) } } };
};
// The break this catches: a tap that opens the app's list instead of the session, or opens nothing
// when the app isn't running.
test("a tap with the app closed opens it on the session", async () => {
const { fire, opened } = worker();
const { closed, event } = click("s 1");
await fire("notificationclick", event);
assert.deepEqual(opened, ["/#/session/s%201"]);
assert.deepEqual(closed, [true]);
});
// The break this catches: a second copy of the app opened beside the first, or the open one
// brought forward without being told which session to show.
test("a tap with the app open brings it forward on the session", async () => {
const told = [];
const open = { focus: async () => told.push("focus"), postMessage: (message) => told.push(message) };
const { fire, opened } = worker([open]);
await fire("notificationclick", click("s-1").event);
assert.deepEqual(plain(told), ["focus", { kind: "open_session", session: "s-1" }]);
assert.deepEqual(opened, []);
});

View File

@@ -0,0 +1,39 @@
// The status line's facts, folded from frames, and the mode switch.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createStatus, nextModeFrame } from "../app/status.js";
const frame = (kind, content) => ({ kind, content });
const model = { provider: "github-copilot", model: "claude-haiku-4.5", display_name: "Claude Haiku 4.5 (latest)" };
// The break this catches: each frame replacing the facts rather than adding to them, so a
// thinking change wipes the context reading until the next call reports it again
test("each frame updates its own facts and keeps the rest", () => {
const status = createStatus();
status.apply(frame("context_usage", { used_tokens: 9613, context_window: 200000 }));
status.apply(frame("state_changed", { model, streaming: false, mode: "plan", thinking: "high" }));
assert.deepEqual(status.facts.value, {
context: { used_tokens: 9613, context_window: 200000 },
model,
thinking: "high",
});
assert.equal(status.mode.value, "plan");
});
// The break this catches: the plan's allowance or the session's spend never reaching the host,
// so the cost slot stays empty; the spend goes as its total, which is all the line shows
test("the plan and the spend are kept for the cost slot", () => {
const status = createStatus();
const plan = { plan: "individual", primary: { used_percent: 22.3, window_minutes: 43200 } };
const total = { calls: 14, cost_usd: 0, unpriced_calls: 0, plan_usd: 0.045, plan_calls: 14 };
status.apply(frame("plan_usage", plan));
status.apply(frame("session_usage", { total, by_source: [{ source: "agent", totals: total }] }));
assert.deepEqual(status.facts.value, { plan, session: { total } });
});
// The break this catches: the mode switch sending the mode already on, so a tap does nothing
test("a tap on the mode switches to the other one", () => {
assert.deepEqual(nextModeFrame("build"), { kind: "set_mode", content: "plan" });
assert.deepEqual(nextModeFrame("plan"), { kind: "set_mode", content: "build" });
});

View File

@@ -0,0 +1,220 @@
// The transcript fold, against a real recorded session and against one frame at a time.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { WINDOW, elapsed, windowOf } from "../app/items.js";
import { createTranscript, formatTokens } from "../app/transcript.js";
/** A session joined through the bridge: the snapshot, then a live turn with two tool calls. */
const recorded = readFileSync(new URL("fixtures/turn.jsonl", import.meta.url), "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line));
function fold(frames) {
const transcript = createTranscript();
frames.forEach(transcript.apply);
return transcript;
}
function shape(transcript) {
return transcript.items.value.map((item) => {
if (item.card) return `tool ${item.card.value.name} ${item.card.value.state}`;
return `${item.kind}${item.provisional ? " (streaming)" : ""}`;
});
}
/** @import { Item, TextItem, ToolItem } from "../app/transcript.js" */
/** `item`, which the test expects to be text. @param {Item} item @returns {TextItem} */
function asText(item) {
assert.ok(item.kind !== "tool", `${item.key} is a tool card`);
return item;
}
/** `item`, which the test expects to be a tool card. @param {Item} item @returns {ToolItem} */
function asTool(item) {
assert.ok(item.kind === "tool", `${item.key} isn't a tool card`);
return item;
}
const frame = (kind, content) => ({ kind, content });
const reply = (...content) => frame("message_committed", { message: { role: "assistant", content } });
const card = (revision, state) =>
frame("tool_activity_updated", { call_id: "c1", name: "bash", label: "ls", state, revision });
// The break this catches: a photo's bytes kept for the render request, sent back to the host on
// every redraw; or the blocks that aren't text dropped, which moves hook context to block 0, where
// the host reads it as the reader's own words
test("a user message keeps its blocks for rendering, an image as just its type", () => {
const image = { type: "image", content: { media_type: "image/png", data: "iVBORw0KGgo=" } };
const words = { type: "text", content: "what's this?" };
const message = { role: "user", content: [image, words] };
const transcript = fold([frame("message_committed", { message })]);
const item = asText(transcript.items.value[0]);
assert.equal(item.text.value, "what's this?");
assert.deepEqual(item.content, [{ type: "image" }, words]);
});
// The break this catches: a commit that adds the saved reply beside the streamed one, so every
// answer shows twice; or a turn whose question never arrives, so the phone shows answers alone.
test("a recorded turn folds into what the TUI shows", () => {
const items = shape(fold(recorded));
const lastTurn = items.slice(items.lastIndexOf("user"));
assert.deepEqual(lastTurn, ["user", "thinking", "tool bash succeeded", "tool read succeeded", "assistant"]);
assert.equal(items.filter((item) => item === "user").length, 4);
});
// The break this catches: lining blocks up by position whatever their kind, so the saved
// reasoning lands in the reply's place and the reply goes missing.
test("streamed blocks that don't match the saved ones are replaced by them", () => {
const transcript = fold([
frame("token_delta", { block: 0, delta: "Hel" }),
reply({ type: "thinking", content: { text: "why", signature: "" } }, { type: "text", content: "Hello" }),
]);
assert.deepEqual(shape(transcript), ["thinking", "assistant"]);
assert.deepEqual(transcript.items.value.map((item) => asText(item).text.value), ["why", "Hello"]);
});
// The break this catches: swapping a streamed reply for a new item on commit, which redraws it,
// so a long answer flickers and the page jumps as it finishes.
test("streamed blocks that match keep their place and take the saved text", () => {
const transcript = fold([
frame("token_delta", { block: 0, delta: "Hello wor" }),
]);
const streamed = asText(transcript.items.value[0]);
transcript.apply(reply({ type: "text", content: "Hello world\n\n" }));
assert.equal(transcript.items.value[0], streamed);
assert.equal(streamed.text.value, "Hello world");
assert.deepEqual(shape(transcript), ["assistant"]);
});
// The break this catches: a rejoin, which replays the snapshot, adding the whole history again
// under what is already there.
test("joining again starts the transcript over", () => {
const once = shape(fold(recorded)).length;
assert.equal(shape(fold([...recorded, ...recorded])).length, once);
});
// The break this catches: taking whatever card update arrives last, so a late, older update puts a
// finished call back to running.
test("an older card update doesn't undo a newer one", () => {
assert.deepEqual(shape(fold([card(3, "succeeded"), card(2, "running")])), ["tool bash succeeded"]);
});
// The break this catches: a call the session never finished showing as running forever.
test("a call without a result when the session loads shows as interrupted", () => {
const call = { type: "tool_call", content: { id: "c1", name: "bash", arguments: { command: "make" } } };
const loaded = frame("session_loaded", { messages: [{ message: { role: "assistant", content: [call] } }] });
assert.deepEqual(shape(fold([loaded])), ["tool bash interrupted"]);
});
// The break this catches: reading every saved result as a success, so a failed call looks fine.
test("a saved result settles its card, failures as failures", () => {
const call = { type: "tool_call", content: { id: "c1", name: "bash", arguments: { command: "make" } } };
const result = {
type: "tool_result",
content: { call_id: "c1", content: [{ type: "text", content: "no rule" }], is_error: true },
};
const loaded = frame("session_loaded", {
messages: [{ message: { role: "assistant", content: [call] } }, { message: { role: "tool", content: [result] } }],
});
const transcript = fold([loaded]);
assert.deepEqual(shape(transcript), ["tool bash failed"]);
assert.equal(asTool(transcript.items.value[0]).card.value.output_preview, "no rule");
});
// The break this catches: a frame the host refused vanishing, so a reply or a message sent from
// the phone seems to go nowhere
test("a refused action shows as an error, with the host's reason", () => {
const transcript = fold([frame("action_rejected", { kind: "respond_permission", reason: "no such prompt" })]);
assert.deepEqual(shape(transcript), ["error"]);
assert.match(asText(transcript.items.value[0]).text.value, /no such prompt/);
});
// The break this catches: the composer never offering to steer, since the engine announces no
// turn's start; or a turn kept running after it ended, so a new message is sent as steering
test("a turn runs from its first sign until it ends", () => {
const transcript = createTranscript();
const user = frame("message_committed", { message: { role: "user", content: [{ type: "text", content: "hi" }] } });
/** @type {[import("../app/connection.js").Frame, boolean][]} */
const steps = [
[user, true],
[frame("turn_ended", { reason: "end_turn" }), false],
[frame("thinking_delta", { block: 0, delta: "hm" }), true],
[frame("error", "provider down"), false],
[frame("tool_call_composing", { call_id: "c", name: "bash" }), true],
[frame("state_changed", { streaming: false }), false],
[frame("token_delta", { block: 0, delta: "a" }), true],
[frame("turn_ended", { reason: "end_turn" }), false],
[frame("turn_started"), true],
];
for (const [step, busy] of steps) {
transcript.apply(step);
assert.equal(transcript.busy.value, busy, step.kind);
}
});
// The break this catches: a photo sent with no words dropped from the conversation, or its bytes
// kept in what's sent to the host to render
test("a photo sent on its own is still a message", () => {
const photo = { role: "user", content: [{ type: "image", content: { data: "QUJD", mime: "image/jpeg" } }] };
const transcript = fold([frame("message_committed", { message: photo })]);
assert.deepEqual(shape(transcript), ["user"]);
assert.deepEqual(asText(transcript.items.value[0]).content, [{ type: "image" }]);
});
// The break this catches: a hook's note, committed between turns, taken for a turn starting
test("a system message doesn't start a turn", () => {
const note = { role: "system", content: [{ type: "text", content: "hook says hi" }] };
assert.equal(fold([frame("message_committed", { message: note })]).busy.value, false);
});
/** The text of each of `transcript`'s lines. */
const texts = (transcript) => transcript.items.value.map((item) => asText(item).text.value);
// The break this catches: a minute of summary with nothing on the phone to say so, or a second
// line added beside the first when it's done
test("a compaction shows as it starts, and its line becomes the result", () => {
const transcript = fold([frame("compaction_started", { tokens_before: 579_400 })]);
assert.deepEqual(texts(transcript), ["Compacting the conversation — 579.4k of context…"]);
transcript.apply(frame("compaction_done", { tokens_before: 579_400, tokens_after: 28_700 }));
assert.deepEqual(texts(transcript), ["Compacted the conversation — 579.4k → 28.7k of context."]);
});
// The break this catches: "Compacting…" left standing after a cancel or failure, or the end
// written onto whatever line came last rather than the one that announced it
test("a stopped compaction settles the line that announced it", () => {
const started = frame("compaction_started", { tokens_before: 1000 });
const transcript = fold([started, frame("notice", "between"), frame("compaction_stopped")]);
assert.deepEqual(texts(transcript), ["Compaction stopped.", "between"]);
});
// The break this catches: the phone writing a count differently from the TUI beside it.
test("token counts read as the TUI writes them", () => {
assert.deepEqual([812, 1000, 579_400, 1_240_000].map(formatTokens), ["812", "1.0k", "579.4k", "1.2M"]);
});
// The break this catches: a long session drawing every item it ever had, which in WebKit slows
// each keystroke past 100ms, or the window dropping the newest items rather than the oldest
test("a long transcript draws its latest items and says how many wait above", () => {
const items = Array.from({ length: WINDOW + 5 }, (_, index) => index);
const { hidden, drawn } = windowOf(items, WINDOW);
assert.equal(hidden, 5);
assert.equal(drawn.length, WINDOW);
assert.deepEqual([drawn[0], drawn.at(-1)], [5, WINDOW + 4]);
});
// The break this catches: a short session losing its first items to the window, or told there's
// history above that isn't there
test("a transcript that fits is drawn whole", () => {
const items = [1, 2, 3];
assert.deepEqual(windowOf(items, WINDOW), { hidden: 0, drawn: items });
assert.deepEqual(windowOf(items, 3), { hidden: 0, drawn: items });
});
// The break this catches: a duration written differently from the TUI's card beside it.
test("durations read as the TUI writes them", () => {
assert.deepEqual([0.4, 19, 1500, 63000].map(elapsed), ["<1ms", "19ms", "1.5s", "1m 3s"]);
});

View File

@@ -0,0 +1,24 @@
{
// Type-checks the phone app from its JSDoc; nothing is emitted, since the app ships as written.
// The vendored libraries resolve to the same versions installed here, whose declarations stand in
// for the minified files the browser runs. The tests have their own, looser, tsconfig.tests.json.
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"lib": ["es2023", "dom", "dom.iterable"],
"types": [],
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"paths": {
"preact": ["./node_modules/preact"],
"preact/hooks": ["./node_modules/preact/hooks"],
"htm": ["./node_modules/htm"],
"@preact/signals": ["./node_modules/@preact/signals"]
}
},
"include": ["../app/*.js"]
}

View File

@@ -0,0 +1,11 @@
{
// The tests, checked against the app's types: a call with the wrong shape fails here, while a
// fixture or a callback needs no annotation, since an assertion already catches what a null
// check would.
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["node"],
"strict": false
},
"include": ["../app/*.js", "*.mjs", "e2e/*.mjs"]
}

View File

@@ -0,0 +1,15 @@
{
// Type-checks the service worker, which runs with the worker globals rather than a page's.
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"lib": ["es2023", "webworker"],
"types": [],
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true
},
"include": ["../app/worker/*.js"]
}

View File

@@ -0,0 +1,17 @@
// The libraries installed here only lend their type declarations to the check of the vendored
// files the phone runs, so the two have to be the same versions.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
const read = (path) => JSON.parse(readFileSync(new URL(path, import.meta.url), "utf8"));
// The break this catches: `scripts/remote-vendor.sh` moving Preact on while package.json stays
// behind (or a bump here alone), so the app is checked against an API it doesn't run
test("the type packages are the vendored versions", () => {
const installed = read("package.json").devDependencies;
for (const { package: name, version } of read("../app/vendor/manifest.json")) {
assert.equal(installed[name], version, `${name} in package.json`);
}
});

View File

@@ -0,0 +1,47 @@
// Keeping iOS from zooming into a focused field, and nothing else from pinching.
import assert from "node:assert/strict";
import { test } from "node:test";
import { holdFieldZoom, isAppleTouch } from "../app/viewport.js";
const IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15";
const MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15";
const ANDROID = "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 Chrome/139.0";
const START = "width=device-width, initial-scale=1, viewport-fit=cover";
/** A page with one viewport tag, and what it says after `holdFieldZoom`. */
function zoomHeldOn(device, content = START) {
const viewport = { content };
const page = { querySelector: (selector) => (selector === 'meta[name="viewport"]' ? viewport : null) };
holdFieldZoom(/** @type {any} */ (page), /** @type {any} */ (device));
return viewport.content;
}
// The break this catches: the iPhone's own name missed, so every field zooms the page on focus
test("an iPhone is an Apple touch device", () => {
assert.equal(isAppleTouch({ userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 }), true);
});
// The break this catches: an iPad, which names itself a Mac, taken for one, so its fields zoom
test("an iPad is told from a Mac by its touch screen", () => {
assert.equal(isAppleTouch({ userAgent: MAC, platform: "MacIntel", maxTouchPoints: 5 }), true);
assert.equal(isAppleTouch({ userAgent: MAC, platform: "MacIntel", maxTouchPoints: 0 }), false);
});
// The break this catches: the hold applied everywhere, which stops Android from pinching at all
test("Android is left able to pinch", () => {
const device = { userAgent: ANDROID, platform: "Linux armv8l", maxTouchPoints: 5 };
assert.equal(zoomHeldOn(device), START);
});
// The break this catches: the hold left out of the viewport tag on iOS, so a field still zooms
test("iOS gets maximum-scale added to the viewport", () => {
const device = { userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 };
assert.equal(zoomHeldOn(device), `${START}, maximum-scale=1`);
});
// The break this catches: a second run adding the setting again, which a reload or a test would do
test("the hold is added once", () => {
const device = { userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 };
assert.equal(zoomHeldOn(device, `${START}, maximum-scale=1`), `${START}, maximum-scale=1`);
});

View File

@@ -0,0 +1,53 @@
// The wordmark, read from the file the terminal's art generates.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { driftPhase, loadWordmark, readDrawing } from "../app/wordmark.js";
const GENERATED = readFileSync(new URL("../app/generated/wordmark.svg", import.meta.url), "utf8");
// The break this catches: a letter, the box or the drift's depth lost between the generated file
// and the page, which draws a mark missing a letter or swinging by nothing
test("the generated wordmark gives its box, its depth and every letter", () => {
const drawing = readDrawing(GENERATED);
assert.equal(drawing.viewBox, "0 0 440 154");
assert.equal(drawing.depth, "0.55");
assert.equal(drawing.paths.length, 5);
assert.ok(drawing.paths.every((d) => d.startsWith("M")), "each path is geometry, not a fill");
});
// The break this catches: a file without the depth drawn anyway, its letters never moving
test("a file without the drift's depth isn't drawn", () => {
assert.equal(readDrawing(GENERATED.replace(/ data-drift-depth="[^"]+"/, "")), null);
});
// The break this catches: a file with no letters drawn as an empty box where the name was
test("a file without letters isn't drawn", () => {
assert.equal(readDrawing(GENERATED.replace(/<path[^>]*>/g, "")), null);
});
// The break this catches: the letters in step, which pulses the whole mark, or spread over a whole
// swing, which makes it symmetrical about its middle the way the terminal's never is
test("half a swing is spread from the first letter to the last", () => {
assert.equal(driftPhase(0, 5), -1);
assert.equal(driftPhase(4, 5), -0.5);
assert.equal(driftPhase(2, 5), -0.75);
});
// The break this catches: a one-letter mark dividing by nothing and losing its animation to NaN
test("a single letter still has a phase", () => {
assert.equal(driftPhase(0, 1), -1);
});
// The break this catches: the drawing asked for somewhere the bridge doesn't serve it, or a
// refusal taken for a drawing
test("the wordmark is read from the app's generated folder", async () => {
const asked = [];
const get = async (url) => {
asked.push(url);
return new Response("missing", { status: 404 });
};
await assert.rejects(loadWordmark(get), { message: "the wordmark answered 404" });
assert.deepEqual(asked, ["/app/generated/wordmark.svg"]);
});

View File

@@ -0,0 +1,116 @@
// The dock's state: what `workspace_updated` says, and the one diff open.
import assert from "node:assert/strict";
import { test } from "node:test";
import { createWorkspace, diffRequest, hasDock, planScroll } from "../app/workspace.js";
/** Ten todos a line (10px) each, in `statuses` order, then pending. @param {string[]} statuses */
const plan = (...statuses) => Array.from({ length: 10 }, (_, index) => ({ bottom: (index + 1) * 10, status: statuses[index] ?? "pending" }));
// The break this catches: a long plan scrolled to its end, or left at the top with the work in
// hand below the box, or the follow keeping no lookahead, so the next todo is always out of view
test("a long plan keeps the todo in hand and the next two in view", () => {
const statuses = ["completed", "completed", "completed", "completed", "completed", "in-progress"];
assert.equal(planScroll(plan(...statuses), 40), 40, "rows 6 to 8 end at 80, so 40 above a 40px box");
});
// The break this catches: a short plan or one barely begun scrolled away from its first rows
test("a plan whose work in hand fits stays at the top", () => {
assert.equal(planScroll(plan("in-progress"), 40), 0);
assert.equal(planScroll([], 40), 0);
});
// The break this catches: a plan with nothing in progress following nothing, or following a done
// todo, so the next thing to do isn't what shows
test("with nothing in progress, the plan follows the first todo not done, then the last", () => {
assert.equal(planScroll(plan("completed", "completed", "completed", "completed"), 40), 30);
assert.equal(planScroll(plan(...Array(10).fill("completed")), 40), 60);
});
// A `workspace_updated` frame's todos and changes, cut down from a live session
const TODOS = { current: null, items: [{ id: "1", subject: "Read the notes", status: "completed", blocked_by: [] }], pending: 0, in_progress: 0, completed: 1, blocked: 0, total: 1, truncated: false };
const CHANGES = { files: [{ path: "notes.txt", status: "added", additions: 1, deletions: 0, binary: false }], total_files: 1, additions: 1, deletions: 0, truncated: false };
const DIFF = { path: "notes.txt", file: null, untracked: false };
const frame = (kind, content) => ({ kind, content });
function opened(path = "notes.txt") {
const workspace = createWorkspace();
const request = diffRequest(path);
workspace.opened(request);
return { workspace, id: request.content.request_id };
}
// The break this catches: the dock left on the first snapshot, or todos and changes crossed
test("the latest snapshot is what the dock shows", () => {
const workspace = createWorkspace();
workspace.apply(frame("workspace_updated", { todos: { total: 0 }, changes: { total_files: 0 } }));
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES }));
assert.equal(workspace.todos.value, TODOS);
assert.equal(workspace.changes.value, CHANGES);
});
// The break this catches: the project panel's branch left on the first snapshot, so a checkout or
// a commit never shows
test("the latest snapshot's project is the one the panel names", () => {
const workspace = createWorkspace();
const project = (branch, dirty) => ({ display_name: "luxe", git_branch: branch, git_dirty: dirty });
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES, project: project("main", true) }));
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES, project: project("remote-access", false) }));
assert.deepEqual(workspace.project.value, project("remote-access", false));
});
// The break this catches: another request's answer (a TUI's, or one this page gave up on) shown
// as this file's diff
test("a diff is matched to its answer by request id", () => {
const { workspace, id } = opened();
workspace.apply(frame("file_diff_loaded", { request_id: "someone-else", diff: DIFF }));
assert.equal(workspace.diff.value.waiting, true);
workspace.apply(frame("file_diff_loaded", { request_id: id, diff: DIFF }));
assert.deepEqual(workspace.diff.value, { path: "notes.txt", requestId: id, waiting: false, diff: DIFF });
});
// The break this catches: a failure left loading forever, or shown without core's reason
test("a failed diff keeps the reason", () => {
const { workspace, id } = opened();
workspace.apply(frame("file_diff_failed", { request_id: id, path: "notes.txt", error: "too_large" }));
assert.equal(workspace.diff.value.waiting, false);
assert.equal(workspace.diff.value.error, "too_large");
});
// The break this catches: a diff closed while loading reopened by its late answer
test("a closed diff stays closed", () => {
const { workspace, id } = opened();
workspace.close();
workspace.apply(frame("file_diff_loaded", { request_id: id, diff: DIFF }));
assert.equal(workspace.diff.value, null);
});
// The break this catches: a request lost with a dropped socket left loading forever, or a diff
// already shown thrown away by reconnecting
test("reconnecting gives up only on a diff still loading", () => {
const { workspace, id } = opened();
workspace.apply(frame("ready", {}));
assert.equal(workspace.diff.value.lost, true);
const shown = opened();
shown.workspace.apply(frame("file_diff_loaded", { request_id: shown.id, diff: DIFF }));
shown.workspace.apply(frame("ready", {}));
assert.equal(shown.workspace.diff.value.lost, undefined);
assert.notEqual(id, shown.id, "each request has its own id");
});
// The break this catches: the request's path or kind wrong, so the host answers a different file
test("a diff request names its file", () => {
const request = diffRequest("src/a b.rs");
assert.equal(request.kind, "load_file_diff");
assert.equal(request.content.path, "src/a b.rs");
});
// The break this catches: an empty dock taking the wide screen's right side, or a dock with only
// a plan, or only changes, not shown
test("the dock shows when there's a plan or a change", () => {
assert.equal(hasDock(null, null), false);
assert.equal(hasDock({ total: 0 }, { total_files: 0 }), false);
assert.equal(hasDock(TODOS, { total_files: 0 }), true);
assert.equal(hasDock({ total: 0 }, CHANGES), true);
});