Files
pipelines/web/test/chat.test.mjs
T
alan 0688127253 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.
2026-10-19 05:39:29 +01:00

431 lines
17 KiB
JavaScript

// 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",
});
});