web: chat — session list, open/close, history paging, markdown, scroll (C1/C3/C4/C7/C14)

Browser Chat destination for parity with the Android app:
- session list grouped by directory (closed grouped under "Closed"), kind
  chip, activity badge, work-label meta line, "Search chats" filter (C1)
- open/close/reopen with the Android copy verbatim (C3)
- conversation history paging via the opaque next_cursor (C4)
- markdown subset renderer + code blocks (C7)
- scroll follow / "Jump to latest" / per-session saved position (C14)

Request builders in src/repository.js; pure merge/format/markdown/paging
logic in src/chat.js and src/markdown.js; view in app.js. Every server
string set with textContent, markdown built as DOM nodes.
This commit is contained in:
2026-10-19 05:39:29 +01:00
parent 3d98c60de6
commit 0688127253
10 changed files with 2863 additions and 6 deletions
+430
View File
@@ -0,0 +1,430 @@
// Pure chat logic (C1/C3/C4/C14) and the chat request builders. Every wording
// and decision below is the same one the browser view uses, so the view cannot
// silently drift from what is asserted here.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
CHAT_FOLLOW_THRESHOLD_PX,
ChatTurn,
chatBottomDistancePx,
chatFirstScroll,
chatFollowsAt,
chatHeaderMeta,
chatNoMatchMessage,
chatOpensAtNewest,
chatShowJumpToLatest,
closeChatConfirmation,
directoryLabel,
filterSessions,
groupSessionsByDirectory,
mergeHistoryPage,
partRendering,
reasoningLabel,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
sessionMatchesQuery,
sessionMeta,
sessionStatusLabel,
sessionTitle,
sessionWorkLabel,
toolCallsLabel,
transcriptRows,
} from "../src/chat.js";
import { PipelinesClient, ProtocolError } from "../src/client.js";
import { PipelinesRepository } from "../src/repository.js";
import { validateServerUrl } from "../src/serverUrl.js";
const assistant = (id, parts) => ({ id, role: "assistant", parts });
const user = (id, text) => ({ id, role: "user", parts: [{ type: "text", text }] });
// --- Transcript folding -----------------------------------------------------
test("transcriptRows folds consecutive assistant messages into one turn keyed by the first id", () => {
const rows = transcriptRows([
user("u1", "hello"),
assistant("a1", [{ type: "text", text: "one" }, { type: "tool", id: "t1", name: "read" }]),
assistant("a2", [{ type: "reasoning", text: "think" }, { type: "text", text: "two" }]),
user("u2", "bye"),
]);
assert.deepEqual(
rows.map((row) => `${row.kind}:${row.key}`),
["user:u1", "agent:a1", "user:u2"],
);
const turn = rows[1].turn;
assert.ok(turn instanceof ChatTurn);
assert.equal(turn.reasoning, "think");
assert.equal(turn.tools.length, 1);
assert.equal(turn.answer, "one\n\ntwo");
});
test("transcriptRows gives each user message its own row and never folds two runs together", () => {
const rows = transcriptRows([
user("u1", "a"),
assistant("a1", [{ type: "text", text: "x" }]),
user("u2", "b"),
assistant("a2", [{ type: "text", text: "y" }]),
]);
assert.deepEqual(
rows.map((row) => row.kind),
["user", "agent", "user", "agent"],
);
});
test("transcriptRows drops an assistant run with nothing to draw", () => {
const rows = transcriptRows([
user("u1", "hi"),
assistant("a1", []),
assistant("a2", [{ type: "tool", id: "t1", name: "" }]),
]);
assert.deepEqual(rows.map((row) => row.key), ["u1", "a1"]);
assert.equal(rows[1].turn.visible, true);
assert.equal(new ChatTurn("k", []).visible, false);
});
test("partRendering classifies text, reasoning, other text and empty parts", () => {
assert.equal(partRendering({ type: "text", text: "hi" }), "markdown");
assert.equal(partRendering({ type: "reasoning", text: "hmm" }), "reasoning");
assert.equal(partRendering({ type: "file", text: "f.txt" }), "plain");
assert.equal(partRendering({ type: "text", text: " " }), "hidden");
assert.equal(partRendering(null), "hidden");
});
test("toolCallsLabel never pluralises a count of one", () => {
assert.equal(toolCallsLabel(1), "1 tool called");
assert.equal(toolCallsLabel(4), "4 tools called");
});
test("reasoningLabel keeps the one-block wording and counts multiple steps", () => {
assert.equal(reasoningLabel(1), "Reasoning");
assert.equal(reasoningLabel(3), "Reasoning · 3 steps");
});
// --- Session identity -------------------------------------------------------
test("sessionTitle falls back from the title to the first 18 characters of the id", () => {
assert.equal(sessionTitle({ id: "ses_1", title: "Named chat" }), "Named chat");
assert.equal(sessionTitle({ id: "ses_abcdefghijklmnopqrstuv", title: "" }), "ses_abcdefghijklmn");
assert.equal(sessionTitle({ id: "ses_abcdefghijklmnopqrstuv", title: " " }), "ses_abcdefghijklmn");
assert.equal(sessionTitle({ id: "", title: "" }), "Untitled chat");
assert.equal(sessionTitle(null), "Untitled chat");
});
test("sessionTagLabel maps operator and keeps an unknown tag verbatim", () => {
assert.equal(sessionChipLabel({ tag: "operator" }), "Operator");
assert.equal(sessionChipLabel({ tag: "run" }), "run");
assert.equal(sessionChipLabel({ tag: " " }), null);
assert.equal(sessionChipLabel({}), null);
});
test("sessionWorkLabel names the running tool, the count, busy and idle", () => {
assert.equal(sessionWorkLabel(false, null), "Idle");
assert.equal(sessionWorkLabel(true, null), "Busy · read-only");
assert.equal(sessionWorkLabel(true, { running: true, runningTools: [] }), "Running");
assert.equal(
sessionWorkLabel(true, { running: true, runningTools: [{ name: "read" }] }),
"Running read",
);
assert.equal(
sessionWorkLabel(true, { running: true, runningTools: [{ name: "" }] }),
"Running tool",
);
assert.equal(
sessionWorkLabel(true, { running: true, runningTools: [{ name: "a" }, { name: "b" }] }),
"Running 2 tools",
);
});
test("sessionMeta joins only the non-blank work label, directory and model", () => {
assert.equal(sessionMeta({ directory: "/repo", model: "m1" }, "Idle"), "Idle · /repo · m1");
assert.equal(sessionMeta({ directory: "", model: "m1" }, "Idle"), "Idle · m1");
assert.equal(sessionMeta({}, ""), "");
});
test("chatHeaderMeta joins model, kind tag and directory, omitting blanks", () => {
assert.equal(
chatHeaderMeta({ model: "m1", tag: "operator", directory: "/repo" }),
"m1 · Operator · /repo",
);
assert.equal(chatHeaderMeta({ model: "", tag: "", directory: "/repo" }), "/repo");
assert.equal(chatHeaderMeta({}), "");
});
test("sessionActivity and its badge word follow streaming, unseen then open", () => {
assert.equal(sessionActivity(true, true), "streaming");
assert.equal(sessionActivity(false, true), "new");
assert.equal(sessionActivity(false, false), "idle");
assert.equal(sessionActivityBadge("streaming", false), "Streaming");
assert.equal(sessionActivityBadge("new", false), "New");
assert.equal(sessionActivityBadge("idle", true), "Open");
assert.equal(sessionActivityBadge("idle", false), null);
});
test("sessionStatusLabel reads Closed first, then Running or Idle", () => {
assert.equal(sessionStatusLabel(true, true), "Closed");
assert.equal(sessionStatusLabel(true, false), "Running");
assert.equal(sessionStatusLabel(false, false), "Idle");
});
// --- Narrowing and grouping -------------------------------------------------
test("filterSessions is a case-insensitive substring over title or directory", () => {
const sessions = [
{ id: "a", title: "Fix the parser", directory: "/repo/one" },
{ id: "b", title: "Docs", directory: "/repo/two" },
];
assert.deepEqual(filterSessions(sessions, "PARSER").map((s) => s.id), ["a"]);
assert.deepEqual(filterSessions(sessions, "REPO/TWO").map((s) => s.id), ["b"]);
assert.deepEqual(filterSessions(sessions, "zzz"), []);
});
test("filterSessions is a no-op for a blank query and never reorders", () => {
const sessions = [{ id: "b", title: "b" }, { id: "a", title: "a" }];
assert.equal(filterSessions(sessions, " "), sessions);
assert.deepEqual(filterSessions(sessions, ""), sessions);
assert.deepEqual(filterSessions(sessions, "b").map((s) => s.id), ["b"]);
});
test("sessionMatchesQuery tests the truncated title too", () => {
const session = { id: "ses_abcdefghijklmnopqrstuv", title: "" };
assert.equal(sessionMatchesQuery(session, "abcdefghij"), true);
assert.equal(sessionMatchesQuery(session, "nope"), false);
});
test("groupSessionsByDirectory groups in first-occurrence order and labels a blank directory", () => {
const sessions = [
{ id: "1", directory: "/a" },
{ id: "2", directory: "/b" },
{ id: "3", directory: "/a" },
{ id: "4", directory: "" },
];
const groups = groupSessionsByDirectory(sessions);
assert.deepEqual(groups.map((g) => g.directory), ["/a", "/b", ""]);
assert.deepEqual(groups[0].sessions.map((s) => s.id), ["1", "3"]);
assert.deepEqual(groupSessionsByDirectory([]), []);
assert.equal(directoryLabel(""), "No directory");
assert.equal(directoryLabel("/a"), "/a");
});
// --- History paging ---------------------------------------------------------
test("mergeHistoryPage prepends an older page and dedupes by id", () => {
const previous = { messages: [{ id: "m3" }, { id: "m4" }], nextCursor: "c1", hasMore: true };
const page = { messages: [{ id: "m1" }, { id: "m2" }, { id: "m3" }], nextCursor: "c0", hasMore: false };
const merged = mergeHistoryPage(previous, page, { older: true });
assert.deepEqual(merged.messages.map((m) => m.id), ["m1", "m2", "m3", "m4"]);
assert.equal(merged.nextCursor, "c0");
assert.equal(merged.hasMore, false);
assert.equal(merged.loaded, true);
assert.equal(merged.loading, false);
});
test("mergeHistoryPage keeps turns already held in front of a newest page", () => {
const previous = { messages: [{ id: "m1" }, { id: "m2" }], nextCursor: "c1", hasMore: true };
const page = { messages: [{ id: "m2" }, { id: "m3" }], nextCursor: "", hasMore: false };
const merged = mergeHistoryPage(previous, page, { older: false });
assert.deepEqual(merged.messages.map((m) => m.id), ["m1", "m2", "m3"]);
assert.equal(merged.nextCursor, "");
assert.equal(merged.hasMore, false);
});
test("mergeHistoryPage replaces the cursor and hasMore even when the page omits them", () => {
const merged = mergeHistoryPage({ messages: [] }, { messages: [{ id: "m1" }] });
assert.equal(merged.nextCursor, "");
assert.equal(merged.hasMore, false);
assert.deepEqual(merged.messages.map((m) => m.id), ["m1"]);
});
// --- Scroll behaviour -------------------------------------------------------
test("chatBottomDistancePx is null until the last item is in view", () => {
assert.equal(
chatBottomDistancePx({ lastVisibleIndex: 2, lastVisibleEndPx: 900, itemCount: 3, viewportEndPx: 800 }),
100,
);
assert.equal(
chatBottomDistancePx({ lastVisibleIndex: 1, lastVisibleEndPx: 900, itemCount: 3, viewportEndPx: 800 }),
null,
);
assert.equal(
chatBottomDistancePx({ lastVisibleIndex: 0, lastVisibleEndPx: 0, itemCount: 0, viewportEndPx: 0 }),
null,
);
assert.equal(
chatBottomDistancePx({ lastVisibleIndex: 2, lastVisibleEndPx: 700, itemCount: 3, viewportEndPx: 800 }),
0,
);
});
test("chatFollowsAt is at-the-bottom only for a measured distance within the threshold", () => {
assert.equal(chatFollowsAt(0, CHAT_FOLLOW_THRESHOLD_PX, 3), true);
assert.equal(chatFollowsAt(32, CHAT_FOLLOW_THRESHOLD_PX, 3), true);
assert.equal(chatFollowsAt(33, CHAT_FOLLOW_THRESHOLD_PX, 3), false);
assert.equal(chatFollowsAt(null, CHAT_FOLLOW_THRESHOLD_PX, 3), false);
assert.equal(chatFollowsAt(0, CHAT_FOLLOW_THRESHOLD_PX, 0), false);
});
test("chatShowJumpToLatest needs not-following, content and something below the fold", () => {
assert.equal(chatShowJumpToLatest(false, 400, CHAT_FOLLOW_THRESHOLD_PX, 5), true);
assert.equal(chatShowJumpToLatest(false, null, CHAT_FOLLOW_THRESHOLD_PX, 5), true);
assert.equal(chatShowJumpToLatest(true, 400, CHAT_FOLLOW_THRESHOLD_PX, 5), false);
assert.equal(chatShowJumpToLatest(false, 0, CHAT_FOLLOW_THRESHOLD_PX, 5), false);
assert.equal(chatShowJumpToLatest(false, 400, CHAT_FOLLOW_THRESHOLD_PX, 0), false);
});
test("chatOpensAtNewest is true only for an absent saved position", () => {
assert.equal(chatOpensAtNewest(null), true);
assert.equal(chatOpensAtNewest(undefined), true);
assert.equal(chatOpensAtNewest({ index: 0, offset: 0 }), false);
assert.equal(chatOpensAtNewest({ index: 4, offset: 80 }), false);
});
test("chatFirstScroll opens newest when unsaved and restores a saved top exactly", () => {
assert.deepEqual(chatFirstScroll(null, 5), { index: 4, offset: 0 });
assert.deepEqual(chatFirstScroll({ index: 0, offset: 0 }, 5), { index: 0, offset: 0 });
assert.deepEqual(chatFirstScroll({ index: 1, offset: 40 }, 3), { index: 1, offset: 40 });
assert.deepEqual(chatFirstScroll({ index: 9, offset: 40 }, 3), { index: 2, offset: 0 });
assert.deepEqual(chatFirstScroll(null, 0), { index: 0, offset: 0 });
});
// --- Wording ----------------------------------------------------------------
test("closeChatConfirmation is the app's exact sentence", () => {
assert.equal(
closeChatConfirmation("New chat"),
'Closes "New chat" and marks it closed on every device. A turn that is running is stopped first. ' +
"Nothing is deleted — the chat and its history are kept, and you can reopen it from the list.",
);
});
test("chatNoMatchMessage names the trimmed query", () => {
assert.equal(chatNoMatchMessage(" fix parser "), 'No chats match "fix parser".');
});
// --- Request builders -------------------------------------------------------
/** The same minimal fake the repository tests use (test files are not importable). */
class FakeWebSocket {
static instances = [];
constructor(url) {
this.url = url;
this.sent = [];
this.onopen = null;
this.onmessage = null;
this.onclose = null;
this.onerror = null;
this.reply = null;
FakeWebSocket.instances.push(this);
}
send(data) {
const frame = JSON.parse(data);
this.sent.push(frame);
const response = this.reply?.(frame);
if (response !== undefined) this.onmessage?.({ data: JSON.stringify(response) });
}
close(code, reason) {
this.onclose?.({ code, reason });
}
open() {
this.onopen?.({});
}
}
const VALID = validateServerUrl("ws://host:8080/connect");
function connected() {
FakeWebSocket.instances = [];
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
const repo = new PipelinesRepository(client);
client.connect(VALID);
const ws = FakeWebSocket.instances.at(-1);
ws.open();
return { repo, ws, client };
}
function lastFrame(ws) {
const { id, ...frame } = ws.sent.at(-1);
assert.match(id, /^web-\d+$/);
return frame;
}
test("chatSessions sends exactly {type:'chat_sessions'} and returns the list", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_sessions", chat_sessions: [{ id: "s1" }] });
const sessions = await repo.chatSessions();
assert.deepEqual(lastFrame(ws), { type: "chat_sessions" });
assert.deepEqual(sessions, [{ id: "s1" }]);
});
test("chatSessions returns [] when the reply carries none", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_sessions" });
assert.deepEqual(await repo.chatSessions(), []);
});
test("chatHistory sends {session_id,limit,cursor} and reads chat_history", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type: "chat_messages",
chat_history: { messages: [{ id: "m1" }], next_cursor: "c1", has_more: true },
});
const page = await repo.chatHistory("s1");
assert.deepEqual(lastFrame(ws), {
type: "chat_messages",
chat_query: { session_id: "s1", limit: 200, cursor: "" },
});
assert.deepEqual(page, { messages: [{ id: "m1" }], nextCursor: "c1", hasMore: true });
});
test("chatHistory passes the cursor back verbatim", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_messages", chat_history: { messages: [] } });
await repo.chatHistory("s1", { cursor: "opaque/+/=", limit: 200 });
const { chat_query: query } = lastFrame(ws);
assert.equal(query.cursor, "opaque/+/=");
});
test("chatHistory falls back to chat_messages with no continuation on an older server", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_messages", chat_messages: [{ id: "m1" }] });
const page = await repo.chatHistory("s1");
assert.deepEqual(page, { messages: [{ id: "m1" }], nextCursor: "", hasMore: false });
});
test("closeChat and reopenChat send the session id and read the echoed session and close", async () => {
for (const [method, type] of [["closeChat", "chat_close"], ["reopenChat", "chat_reopen"]]) {
const { repo, ws } = connected();
ws.reply = (frame) => ({
id: frame.id,
type,
chat_session: { id: "s1", closed: type === "chat_close" },
chat_close: { session_id: "s1", closed_at: 1, interrupted: false },
});
const result = await repo[method]("s1");
assert.deepEqual(lastFrame(ws), { type, chat_query: { session_id: "s1" } });
assert.deepEqual(result.session, { id: "s1", closed: type === "chat_close" });
assert.equal(result.close.session_id, "s1");
}
});
test("chatHistory rejects a blank session id without sending", async () => {
const { repo, ws } = connected();
await assert.rejects(() => repo.chatHistory(" "), ProtocolError);
assert.equal(ws.sent.length, 0);
});
test("a chat command rejects a server error envelope with the server's own text", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_messages" });
await assert.rejects(() => repo.chatHistory("s1"), {
name: "ProtocolError",
message: "unknown command: chat_messages",
});
});
+181
View File
@@ -0,0 +1,181 @@
// The markdown subset (C7), ported from ui/chat/Markdown.kt. The parser is pure,
// so the exact block/span shapes are asserted without a browser; anything outside
// the subset must render as plain text and never be dropped.
import { test } from "node:test";
import assert from "node:assert/strict";
import { codeBlockLabel, decodeHtmlEntities, parseInline, parseMarkdown } from "../src/markdown.js";
/** Every text run in a span tree, in order, so nothing dropped can hide. */
function spanText(spans) {
return spans
.map((span) => {
if (span.kind === "plain" || span.kind === "code") return span.text;
if (span.kind === "strong" || span.kind === "emphasis" || span.kind === "link") {
return spanText(span.spans);
}
return "";
})
.join("");
}
/** Every text run in a block list, so nothing dropped can hide. */
function blockText(blocks) {
return blocks
.map((block) => {
if (block.kind === "heading" || block.kind === "paragraph") return block.text;
if (block.kind === "code") return block.code;
if (block.kind === "quote") return block.lines.join("\n");
if (block.kind === "list") return block.items.join("\n");
if (block.kind === "table") return [...block.header, ...block.rows.flat()].join("|");
return "";
})
.join("\n");
}
// --- Entities ---------------------------------------------------------------
test("decodeHtmlEntities decodes the named, decimal and hex references", () => {
assert.equal(decodeHtmlEntities("a &amp; b &lt; c &gt; d &quot;e&quot; &#x27;f&#39;"), "a & b < c > d \"e\" 'f'");
assert.equal(decodeHtmlEntities("&#65;&#x42;"), "AB");
assert.equal(decodeHtmlEntities("&hellip;&mdash;&nbsp;"), "…—\u00A0");
});
test("decodeHtmlEntities is a single pass, so a decoded ampersand is not re-decoded", () => {
assert.equal(decodeHtmlEntities("&amp;lt;"), "&lt;");
assert.equal(decodeHtmlEntities("&amp;amp;"), "&amp;");
});
test("decodeHtmlEntities leaves an unknown or malformed reference literal", () => {
assert.equal(decodeHtmlEntities("&nope; &doesnotexist;"), "&nope; &doesnotexist;");
assert.equal(decodeHtmlEntities("&#xZZ; &#; &"), "&#xZZ; &#; &");
});
test("parseMarkdown decodes entities before parsing", () => {
const blocks = parseMarkdown("a &amp; b");
assert.deepEqual(blocks, [{ kind: "paragraph", text: "a & b" }]);
});
// --- Blocks -----------------------------------------------------------------
test("parseMarkdown parses headings, paragraphs and thematic rules", () => {
const blocks = parseMarkdown("# Title\n\nA paragraph\nspanning lines.\n\n---\n\n## Sub ##");
assert.deepEqual(blocks, [
{ kind: "heading", level: 1, text: "Title" },
{ kind: "paragraph", text: "A paragraph spanning lines." },
{ kind: "rule" },
{ kind: "heading", level: 2, text: "Sub " },
]);
});
test("parseMarkdown parses a fenced block and keeps its language", () => {
const blocks = parseMarkdown("```js\nconst x = 1;\n```");
assert.deepEqual(blocks, [{ kind: "code", language: "js", code: "const x = 1;" }]);
assert.equal(codeBlockLabel("js"), "js");
});
test("a fenced block with no language is labelled code", () => {
const blocks = parseMarkdown("```\nplain\n```");
assert.deepEqual(blocks, [{ kind: "code", language: "", code: "plain" }]);
assert.equal(codeBlockLabel(""), "code");
assert.equal(codeBlockLabel(" "), "code");
});
test("tilde fences are code fences too", () => {
const blocks = parseMarkdown("~~~python\nprint(1)\n~~~");
assert.deepEqual(blocks, [{ kind: "code", language: "python", code: "print(1)" }]);
});
test("parseMarkdown parses block quotes, bullet lists and ordered lists", () => {
assert.deepEqual(parseMarkdown("> one\n> two"), [{ kind: "quote", lines: ["one", "two"] }]);
assert.deepEqual(parseMarkdown("- a\n- b"), [{ kind: "list", ordered: false, items: ["a", "b"] }]);
assert.deepEqual(parseMarkdown("1. one\n2. two"), [{ kind: "list", ordered: true, items: ["one", "two"] }]);
});
test("parseMarkdown parses a table with a --- delimiter row", () => {
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 | 2 |");
assert.deepEqual(blocks, [{ kind: "table", header: ["a", "b"], rows: [["1", "2"]] }]);
});
test("a table row shorter than the header is padded, never truncated", () => {
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 |");
assert.deepEqual(blocks[0].rows, [["1", ""]]);
});
test("a nested list is flattened into its run, never dropped", () => {
const blocks = parseMarkdown("- a\n - b");
assert.deepEqual(blocks, [{ kind: "list", ordered: false, items: ["a", "b"] }]);
assert.equal(blockText(blocks), "a\nb");
});
test("more than six hashes is a paragraph, not a heading", () => {
assert.deepEqual(parseMarkdown("####### x"), [{ kind: "paragraph", text: "####### x" }]);
});
// --- Inline -----------------------------------------------------------------
test("snake_case is never italicised", () => {
assert.deepEqual(parseInline("snake_case_name"), [{ kind: "plain", text: "snake_case_name" }]);
assert.deepEqual(parseInline("a_b_c"), [{ kind: "plain", text: "a_b_c" }]);
});
test("underscore emphasis works only at word boundaries", () => {
assert.deepEqual(parseInline("_italic_"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "italic" }] }]);
assert.deepEqual(parseInline("a _b_ c"), [
{ kind: "plain", text: "a " },
{ kind: "emphasis", spans: [{ kind: "plain", text: "b" }] },
{ kind: "plain", text: " c" },
]);
});
test("bold, italic and inline code become their spans", () => {
assert.deepEqual(parseInline("**bold**"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
assert.deepEqual(parseInline("__bold__"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
assert.deepEqual(parseInline("*it*"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "it" }] }]);
assert.deepEqual(parseInline("`code`"), [{ kind: "code", text: "code" }]);
});
test("links and bare http(s) autolinks become link spans", () => {
assert.deepEqual(parseInline("[site](https://example.com)"), [
{ kind: "link", spans: [{ kind: "plain", text: "site" }], url: "https://example.com" },
]);
assert.deepEqual(parseInline("see https://example.com now"), [
{ kind: "plain", text: "see " },
{ kind: "link", spans: [{ kind: "plain", text: "https://example.com" }], url: "https://example.com" },
{ kind: "plain", text: " now" },
]);
});
test("autolinks trim trailing punctuation", () => {
const spans = parseInline("go to https://example.com.");
const link = spans.find((span) => span.kind === "link");
assert.equal(link.url, "https://example.com");
});
// --- Out-of-subset text is never dropped ------------------------------------
test("out-of-subset HTML renders as plain text and is never dropped", () => {
assert.deepEqual(parseInline("<b>hi</b>"), [{ kind: "plain", text: "<b>hi</b>" }]);
assert.equal(blockText(parseMarkdown("<div>x</div>")), "<div>x</div>");
});
test("reference links and strikethrough render as plain text", () => {
assert.deepEqual(parseInline("[label][ref]"), [{ kind: "plain", text: "[label][ref]" }]);
assert.deepEqual(parseInline("~~gone~~"), [{ kind: "plain", text: "~~gone~~" }]);
});
test("a malformed inline marker is kept literally", () => {
assert.deepEqual(parseInline("a * b ` c"), [{ kind: "plain", text: "a * b ` c" }]);
});
test("every out-of-subset paragraph's text survives the round trip", () => {
const source = "<section>\n[ref][id] and ~~strike~~\n</section>";
const blocks = parseMarkdown(source);
const text = blockText(blocks);
assert.ok(text.includes("[ref][id] and ~~strike~~"));
});
test("spanText of a mixed inline run keeps every character", () => {
const spans = parseInline("plain **bold** `code` [link](https://e.com) tail");
assert.equal(spanText(spans), "plain bold code link tail");
});
+279
View File
@@ -1924,6 +1924,285 @@ try {
});
}
// C1/C3/C4/C7/C14: the chat list, its transcript (markdown + the code the live
// session carries), paging and the close dialog. The one live operator session
// is never mutated: the close confirm is shown and dismissed with Cancel.
step("C1/C3/C4/C7/C14: the chat list, transcript, paging and close dialog");
await ensureConnected();
await page.clickText("nav.tabs button.tab", "Chat");
await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 });
const chatList = await page.evaluate(`(() => ({
label: document.querySelector("#chatSearch")?.getAttribute("aria-label") ?? "",
placeholder: document.querySelector("#chatSearch")?.getAttribute("placeholder") ?? "",
rows: [...document.querySelectorAll("#chatRows .chat-row")].map((row) => ({
id: row.dataset.session ?? "",
title: row.querySelector(".chat-row-title")?.textContent ?? "",
chips: [...row.querySelectorAll(".chip")].map((chip) => chip.textContent),
meta: row.querySelector(".chat-row-meta")?.textContent ?? "",
close: !!row.querySelector(".chat-close"),
})),
}))()`);
if (chatList.label !== "Search chats") throw new Error(`chat search label: ${chatList.label}`);
if (chatList.placeholder !== "Search chats") throw new Error(`chat search placeholder: ${chatList.placeholder}`);
if (chatList.rows.length === 0) throw new Error("no chat sessions rendered");
if (!chatList.rows[0].title) throw new Error("the first chat row has no title");
if (!chatList.rows[0].chips.includes("Operator")) {
throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`);
}
if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action");
console.log(
` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` +
`[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`,
);
await shot("44-chat-sessions.png");
// The row's own Close chat… action with NO conversation open: the list offers
// it on every open row, so the confirm must still appear. Shown and dismissed
// with Cancel; no chat_close is ever sent for the operator's live session.
await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`);
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
const listClose = await page.evaluate(
`document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`,
);
if (!listClose.startsWith('Closes "')) {
throw new Error(`row-level close message with no conversation open: ${listClose}`);
}
await page.click(".confirm-chat-close .confirm-dismiss");
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
timeout: 5000,
what: "the row-level close dialog to close",
});
console.log(
" row-level 'Close chat…' (no conversation open) showed its confirm; dismissed with Cancel",
);
// The narrowed-to-nothing empty state and its Clear search action (the field
// itself is the narrowing; the list's order is never touched).
await page.fill("#chatSearch", "zzz-no-such-chat");
await page.waitForText('No chats match "zzz-no-such-chat".', { timeout: 10000 });
await shot("50-chat-no-match.png");
await page.clickText(".chat-rows .empty button", "Clear search");
await page.waitForSelector("#chatRows .chat-row", { timeout: 10000 });
const cleared = await page.evaluate(`document.querySelector("#chatSearch")?.value ?? null`);
if (cleared !== "") throw new Error(`Clear search left the query: ${JSON.stringify(cleared)}`);
const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN";
const openedId = chatList.rows[0].id;
if (openedId !== expectedSession) {
console.log(` -- the live server's first session is ${openedId}, not the expected ${expectedSession}`);
}
await page.click(`#chatRows .chat-row[data-session="${openedId}"]`);
await page.waitForSelector("#chatTranscript", { timeout: 25000 });
const transcript = await page.evaluate(`(() => {
const el = document.querySelector("#chatTranscript");
if (!el) return null;
return {
userBubbles: el.querySelectorAll(".chat-turn-user").length,
agentBubbles: el.querySelectorAll(".chat-turn-agent").length,
markdown: el.querySelectorAll(".markdown").length,
tables: el.querySelectorAll(".md-table").length,
inlineCode: el.querySelectorAll(".md-code").length,
codeBlocks: el.querySelectorAll(".md-code-block").length,
toolChips: [...el.querySelectorAll(".chat-tool-chip")].map((chip) => chip.textContent),
reasoning: el.querySelectorAll(".chat-reasoning").length,
client: el.querySelector(".chat-turn-user .chat-client")?.textContent ?? "",
hasLoadOlder: !!document.querySelector(".chat-load-older"),
};
})()`);
if (!transcript) throw new Error("the opened transcript did not render");
if (transcript.userBubbles !== 1) throw new Error(`expected one user bubble, got ${transcript.userBubbles}`);
if (transcript.agentBubbles !== 1) {
throw new Error(`expected one folded agent turn, got ${transcript.agentBubbles}`);
}
if (transcript.markdown === 0) throw new Error("the agent turn rendered no markdown");
if (transcript.tables === 0) throw new Error("the agent answer rendered no markdown table");
if (transcript.inlineCode === 0) throw new Error("the agent answer rendered no inline code");
if (transcript.toolChips.length !== 1) {
throw new Error(`expected one tool-call chip, got ${transcript.toolChips.length}`);
}
console.log(
` transcript: ${transcript.userBubbles} user + ${transcript.agentBubbles} folded agent turn; ` +
`markdown ${transcript.tables} table(s), ${transcript.inlineCode} inline code span(s), ` +
`${transcript.toolChips[0]}; client label "${transcript.client}"`,
);
await shot("45-chat-transcript-newest.png");
// The top of the conversation, reached by a genuine operator wheel gesture on
// the transcript (the app's own listener). Only the operator's gesture changes
// follow intent — a programmatic scrollTo cannot — so this is the only way
// "Jump to latest" may appear; the control is asserted, not assumed.
const wheelGesture = await page.evaluate(`(() => {
const el = document.querySelector("#chatTranscript");
if (!el) return null;
el.scrollTop = 0;
el.dispatchEvent(new WheelEvent("wheel", { deltaY: -240, bubbles: true }));
return {
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
top: el.scrollTop,
};
})()`);
if (!wheelGesture || wheelGesture.jumpHidden !== false) {
throw new Error(`Jump to latest was not offered after a real wheel gesture: ${JSON.stringify(wheelGesture)}`);
}
await shot("46-chat-transcript-top.png");
console.log(
` after a real wheel gesture (scrollTop ${wheelGesture.top}) 'Jump to latest' is offered at the top`,
);
// The live assistant answer carries markdown but no fenced block: the session's
// fenced code lives in its reasoning, which the app renders as plain text
// (Markdown.kt draws reasoning with a plain Text, never the markdown subset).
if (transcript.reasoning > 0) {
const expanded = await page.evaluate(`(() => {
const block = document.querySelector("#chatTranscript .chat-reasoning");
if (!block) return null;
block.querySelector(".chat-reasoning-toggle")?.click();
const body = block.querySelector(".chat-reasoning-body");
if (!body) return null;
// Bring the reasoning's own fenced block into view, so the capture shows
// the code the live session actually carries.
const fence = String.fromCharCode(96).repeat(3);
const text = body.textContent ?? "";
const index = text.indexOf(fence);
const transcript = document.querySelector("#chatTranscript");
if (index >= 0 && transcript && body.firstChild && body.firstChild.nodeType === 3) {
const range = document.createRange();
range.setStart(body.firstChild, index);
range.setEnd(body.firstChild, index + fence.length);
const rect = range.getBoundingClientRect();
const tRect = transcript.getBoundingClientRect();
transcript.scrollTop += Math.round(rect.top - tRect.top) - 120;
}
return {
label: block.querySelector(".chat-reasoning-label")?.textContent ?? "",
hasFence: index >= 0,
};
})()`);
await eventually(
() =>
page.evaluate(
`(() => { const b = document.querySelector("#chatTranscript .chat-reasoning-body"); return !!b && !b.hidden; })()`,
),
{ timeout: 5000, what: "the reasoning block to expand" },
);
if (expanded) {
console.log(` reasoning block "${expanded.label}" expanded; carries a fenced block: ${expanded.hasFence}`);
}
await shot("47-chat-reasoning-code.png");
}
// C7's code-block path. The live assistant answer carries no fenced block (its
// fences live in the reasoning transcript, drawn as plain text — capture 47),
// so exercise the page's own markdown renderer on a labelled sample and capture
// the rendered <pre> block; the sample is removed again straight after.
const fence = String.fromCharCode(96).repeat(3);
const codeSample = `${fence}js\nconst answer = 42;\n${fence}`;
const codeBlock = await page.evaluate(`(async () => {
const mod = await import("/src/app.js");
const node = mod.renderMarkdown(${JSON.stringify(codeSample)});
node.id = "markdownCodeSample";
const wrap = document.querySelector(".chat-detail .chat-transcript-wrap");
if (!wrap || !wrap.parentNode) return null;
wrap.parentNode.insertBefore(node, wrap);
return {
label: node.querySelector(".md-code-label")?.textContent ?? "",
hasPre: !!node.querySelector("pre.md-pre code"),
text: node.querySelector("pre.md-pre code")?.textContent ?? "",
};
})()`);
if (!codeBlock || !codeBlock.hasPre) {
throw new Error("the page's markdown renderer drew no fenced code block");
}
if (codeBlock.label !== "js") throw new Error(`code block label: ${codeBlock.label}`);
console.log(
` markdown code block (page renderer sample): label "${codeBlock.label}", text ${JSON.stringify(codeBlock.text)}`,
);
await shot("47b-chat-markdown-code.png");
await page.evaluate(`document.querySelector("#markdownCodeSample")?.remove()`);
if (transcript.hasLoadOlder) {
// The control was present in capture 45. Press it and capture the honest
// result: the live session's own cursor returns an empty older page, so the
// control disappears (the prepend path itself is unit-tested).
await page.evaluate(`document.querySelector(".chat-load-older")?.click()`);
await eventually(() => page.evaluate(`!document.querySelector(".chat-load-older")`), {
timeout: 15000,
what: "the empty older history page to settle",
});
await shot("48-chat-load-older-empty.png");
console.log(
" 'Load older messages' was shown while has_more (capture 45); the server's own next_cursor returned an empty older page and the control disappeared",
);
} else {
console.log(" -- no 'Load older messages' control: the server did not report has_more");
}
// The close confirm: shown, then dismissed with Cancel. The operator's only
// live session is never mutated, so no chat_close is sent. The transcript is
// mid-scroll (following false), so this also asserts the C14 fix: opening and
// dismissing the dialog must not move the operator's view.
const beforeDialog = await page.evaluate(`(() => {
const el = document.querySelector("#chatTranscript");
return {
top: el ? Math.round(el.scrollTop) : null,
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
};
})()`);
if (!beforeDialog || beforeDialog.top == null || beforeDialog.top === 0) {
throw new Error(`the transcript was not mid-scroll before the dialog: ${JSON.stringify(beforeDialog)}`);
}
await page.click(`#chatRows .chat-row[data-session="${openedId}"] .chat-close`);
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
const closeDialog = await page.evaluate(`(() => ({
title: document.querySelector(".confirm-chat-close .confirm-title")?.textContent ?? "",
message: document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? "",
confirm: document.querySelector(".confirm-chat-close .confirm-accept")?.textContent ?? "",
dismiss: document.querySelector(".confirm-chat-close .confirm-dismiss")?.textContent ?? "",
}))()`);
if (closeDialog.title !== "Close chat?") throw new Error(`close title: ${closeDialog.title}`);
if (!closeDialog.message.startsWith("Closes \"")) throw new Error(`close message: ${closeDialog.message}`);
if (!closeDialog.message.includes("marks it closed on every device")) {
throw new Error(`close message: ${closeDialog.message}`);
}
if (!closeDialog.message.includes("Nothing is deleted")) {
throw new Error(`close message: ${closeDialog.message}`);
}
if (closeDialog.confirm !== "Close chat") throw new Error(`close confirm: ${closeDialog.confirm}`);
if (closeDialog.dismiss !== "Cancel") throw new Error(`close dismiss: ${closeDialog.dismiss}`);
const whileDialog = await page.evaluate(`(() => {
const el = document.querySelector("#chatTranscript");
return {
top: el ? Math.round(el.scrollTop) : null,
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
};
})()`);
if (Math.abs((whileDialog.top ?? -1) - beforeDialog.top) > 2 || whileDialog.jumpHidden !== false) {
throw new Error(
`opening the close dialog moved the transcript: ${JSON.stringify(beforeDialog)} -> ${JSON.stringify(whileDialog)}`,
);
}
console.log(` close dialog (shown, NOT executed): "${closeDialog.title}" — ${closeDialog.message}`);
console.log(` the transcript stayed put across the dialog (top ${beforeDialog.top} -> ${whileDialog.top})`);
await shot("49-chat-close-confirm.png");
await page.click(".confirm-chat-close .confirm-dismiss");
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
timeout: 5000,
what: "the close dialog to close",
});
const afterDialog = await page.evaluate(`(() => {
const el = document.querySelector("#chatTranscript");
return el ? Math.round(el.scrollTop) : null;
})()`);
if (afterDialog == null || Math.abs(afterDialog - beforeDialog.top) > 2) {
throw new Error(`dismissing the close dialog moved the transcript: ${beforeDialog.top} -> ${afterDialog}`);
}
console.log(
" the mutating confirm was NOT executed: no chat_close was sent for the operator's live session " +
`${openedId}`,
);
console.log("\nUI SMOKE PASS");
for (const shot of shots) console.log(` ${shot}`);
} catch (error) {