// 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 { BACKGROUND_TASKS_TITLE, BACKGROUND_TASK_VISIBLE_ROWS, CHAT_ACTIONS_LABEL, CHAT_COMMANDS, CHAT_COMMAND_DISMISS_LABEL, CHAT_COMMAND_FAILED_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMMAND_LABEL, CHAT_CREATE_BACK_LABEL, CHAT_CREATE_CANCEL, CHAT_CREATE_CONFIRM, DEFAULT_CHAT_INSTRUCTIONS, CHAT_CREATE_LOADING, CHAT_CREATE_MODEL_NOTE, CHAT_CREATE_PROMPT, CHAT_CREATE_TITLE, CHAT_FOLLOW_THRESHOLD_PX, CHAT_HIDE_ACTION, CHAT_QUEUED_NOTICE, CHAT_REMOVED_MESSAGE, CHAT_RENAME_ACTION, CHAT_RENAME_DISMISS, CHAT_RENAME_FIELD_LABEL, CHAT_RENAME_HELPER, CHAT_RENAME_SAVE, CHAT_RENAME_TITLE, CHAT_UNDO_ACTION, COMPOSER_SEND, COMPOSER_STOP, ChatTurn, APPROVAL_ANSWERED, APPROVAL_HEADLINE_RESOLVED, APPROVAL_PENDING, APPROVAL_RESOLVED, APPROVAL_STATUS_ANSWERED, APPROVAL_STATUS_PENDING, APPROVAL_STATUS_RESOLVED, DECISION_ALWAYS, DECISION_LABEL_ALWAYS, DECISION_LABEL_ONCE, DECISION_LABEL_REJECT, DECISION_LABEL_RESOLVED, DECISION_ONCE, DECISION_REJECT, MAX_APPROVAL_RESOURCE_LINES, MAX_ATTACHMENT_BYTES, MAX_RENDERED_DIFF_LINES, OBSERVED_SHELL_LIMIT, SHELL_DETAILS_LABEL, SHELL_EXITED, SHELL_OUTPUT_EMPTY, SHELL_OUTPUT_ERROR, SHELL_OUTPUT_LABELS, SHELL_OUTPUT_LOADING, SHELL_OUTPUT_READY, SHELL_OUTPUT_UNAVAILABLE, SHELL_ROW_LABEL, SHELL_RUNNING, TOOL_DETAIL_MAX_LENGTH, TOOL_LONG_RUNNING_MILLIS, TURN_PHASE_THINKING, TURN_PHASE_TOOL, TURN_PHASE_WAITING, appendChatNotice, applyChatEvent, applyChatForm, applyChatOverrides, applyChatPermission, approvalCard, approvalResources, approvalResourceText, attachmentDisplayName, attachmentError, attachmentFiles, HOME_DIRECTORY, HOME_LABEL, backgroundTasksRunningLabel, chatBottomDistancePx, chatCommandEffect, chatCommandForEnter, chatCommandHelp, chatCommandSuggestions, chatCreateFailed, chatCreateSucceeded, chatFirstScroll, chatFollowsAt, chatHeaderMeta, chatNoMatchMessage, chatNoticeLabel, chatOpensAtNewest, chatSeenWatermark, chatShowJumpToLatest, chatStartInLabel, chatStreamState, closeChatConfirmation, composerAction, composerCanSend, composerSendEnabled, composerSubmit, decisionLabel, decodeChatOverrides, decodeChatSeen, defaultDirectoryChoice, deltaPartId, directoryChoices, directoryLabel, filterChatModels, homeDirectoryFor, abbreviateHome, dismissChatNotice, emptyChatOverrides, emptyChatSeen, encodeChatOverrides, encodeChatSeen, filterSessions, formatToolDuration, groupSessionsByDirectory, hideChatOverride, historyResync, isChatSessionUnseen, lineDiff, makeChatNotice, markChatUnseen, mergeHistoryPage, mergeShellFrame, mergeToolPart, newChatCreateState, newChatThread, parseChatInput, partRendering, permissionRiskText, prettyToolInput, queuedAfterFrame, readChatSeen, reasoningLabel, relativeSessionTime, renameChatOverride, restoreChatOverride, resumedThread, runningAfterFrame, runningBackgroundShells, runningToolElapsedMillis, runningToolStamps, seedChatSeen, selectChatDirectory, sessionActivity, sessionActivityBadge, sessionChipLabel, sessionMatchesQuery, sessionMeta, sessionStatusLabel, sessionTitle, sessionWorkLabel, settledThread, shellCommandSummary, shellOutputState, shellsLoaded, takeChatNoticeOffer, threadElapsedMillis, threadPhase, threadRunningTools, threadToolElapsedMillis, toolCallCount, toolCallRow, toolCallsAnnouncement, toolCallsLabel, toolDetail, toolDurationMillis, toolEditDiff, toolErrorText, toolFailed, toolLongRunning, toolOutputText, toolRunning, toolsRunning, transcriptRows, turnElapsedMillis, turnPhase, turnPhaseLabel, } from "../src/chat.js"; import { ChangeLineKind } from "../src/changes.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"); assert.equal(toolCallsLabel(4), "4 tools"); }); test("reasoningLabel is Thinking/Reasoning with the step count and streaming word", () => { assert.equal(reasoningLabel(1, false), "Reasoning"); assert.equal(reasoningLabel(1, true), "Thinking…"); assert.equal(reasoningLabel(3, false), "Reasoning · 3 steps"); assert.equal(reasoningLabel(3, true), "Thinking · 3 steps"); assert.equal(reasoningLabel(1), "Reasoning"); assert.equal(reasoningLabel(3), "Reasoning · 3 steps"); }); // --- Tool-call lifecycle, detail and the edit diff (C6) --------------------- test("toolRunning treats streaming and running as in flight, completed/error as settled", () => { assert.equal(toolRunning({ type: "tool", state: { status: "streaming" } }), true); assert.equal(toolRunning({ type: "tool", state: { status: "running" } }), true); assert.equal(toolRunning({ type: "tool", state: { status: "completed" } }), false); assert.equal(toolRunning({ type: "tool", state: { status: "error" } }), false); assert.equal(toolRunning({ type: "tool" }), false); assert.equal(toolRunning({ type: "text", state: { status: "running" } }), false); }); test("toolsRunning and toolFailed summarise the lifecycle", () => { const call = (status) => ({ type: "tool", state: { status } }); assert.equal(toolsRunning([call("completed"), call("running")]), true); assert.equal(toolsRunning([call("completed"), call("error")]), false); assert.equal(toolsRunning([]), false); assert.equal(toolFailed({ status: "error" }), true); assert.equal(toolFailed({ status: "completed" }), false); assert.equal(toolFailed(undefined), false); }); test("toolCallCount counts only tool parts and toolCallsAnnouncement matches the plural", () => { const parts = [{ type: "tool" }, { type: "text" }, { type: "reasoning" }, { type: "tool" }]; assert.equal(toolCallCount(parts), 2); assert.equal(toolCallCount([]), 0); assert.equal(toolCallsAnnouncement(1), "1 tool call, expand for details"); assert.equal(toolCallsAnnouncement(3), "3 tool calls, expand for details"); }); test("toolDetail takes the first present detail key, collapsed and trimmed to 72", () => { const part = (input) => ({ type: "tool", state: { input } }); assert.equal(toolDetail(part({ command: "ls -la" })), "ls -la"); assert.equal(toolDetail(part({ description: "do a thing", command: "x" })), "do a thing"); assert.equal(toolDetail(part({ filePath: "/a/b.ts" })), "/a/b.ts"); assert.equal(toolDetail(part({ path: "p", command: "c" })), "c"); assert.equal(toolDetail(part({ command: " a b\tc\n d " })), "a b c d"); const detail = toolDetail(part({ command: "x".repeat(100) })); assert.equal(detail.length, TOOL_DETAIL_MAX_LENGTH); assert.ok(detail.endsWith("…")); assert.equal(toolDetail(part({ other: "nope" })), null); assert.equal(toolDetail(part("partial json")), null); assert.equal(toolDetail(part({ command: 42 })), null); assert.equal(toolDetail({ type: "tool" }), null); }); test("formatToolDuration renders ms, one-decimal seconds and minutes", () => { assert.equal(formatToolDuration(340), "340ms"); assert.equal(formatToolDuration(999), "999ms"); assert.equal(formatToolDuration(1000), "1.0s"); assert.equal(formatToolDuration(1200), "1.2s"); assert.equal(formatToolDuration(59600), "59.6s"); assert.equal(formatToolDuration(60000), "1m 0s"); assert.equal(formatToolDuration(123000), "2m 3s"); }); test("toolDurationMillis reads ran-else-created to completed, null when unusable", () => { assert.equal(toolDurationMillis({ time: { created: 10, ran: 20, completed: 120 } }), 100); assert.equal(toolDurationMillis({ time: { created: 10, ran: 0, completed: 110 } }), 100); assert.equal(toolDurationMillis({ time: { created: 10, ran: 20 } }), null); assert.equal(toolDurationMillis({ time: { created: 10, ran: 20, completed: 5 } }), null); assert.equal(toolDurationMillis({}), null); }); test("runningToolElapsedMillis prefers the protocol start and falls back to the local stamp", () => { const part = { type: "tool", time: { created: 100, ran: 500 } }; assert.equal(runningToolElapsedMillis(part, 999, 1500), 1000); assert.equal(runningToolElapsedMillis({ type: "tool" }, 1000, 4000), 3000); assert.equal(runningToolElapsedMillis({ type: "tool" }, 0, 4000), 0); assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS), true); assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1), false); }); test("toolOutputText joins text content, (no output) when settled-empty and '' in flight", () => { const state = (status, content) => ({ status, content }); assert.equal( toolOutputText(state("completed", [{ type: "text", text: "a" }, { type: "text", text: "b" }])), "a\nb", ); assert.equal(toolOutputText(state("completed", [{ type: "text", text: " " }])), "(no output)"); assert.equal(toolOutputText(state("running", [])), ""); assert.equal(toolOutputText(state("streaming", [])), ""); assert.equal(toolOutputText(state("error", [])), "(no output)"); assert.equal(toolOutputText(null), ""); }); test("toolErrorText prefers the server's error message over the output", () => { assert.equal( toolErrorText({ status: "error", error: { message: "boom" }, content: [{ type: "text", text: "partial" }] }), "boom", ); assert.equal(toolErrorText({ status: "error", content: [{ type: "text", text: "partial" }] }), "partial"); assert.equal(toolErrorText({ status: "error", error: { message: " " }, content: [] }), "(no output)"); }); test("prettyToolInput pretty-prints objects, keeps a partial string and blanks nothing", () => { assert.equal(prettyToolInput(null), ""); assert.equal(prettyToolInput("{\"a\":"), "{\"a\":"); assert.equal(prettyToolInput({ a: 1 }), '{\n "a": 1\n}'); assert.equal(prettyToolInput([1, 2]), "[\n 1,\n 2\n]"); }); test("lineDiff LCS marks only changed lines and carries ChangeLineKind values", () => { const lines = lineDiff(["one", "two", "three"], ["one", "TWO", "three"]); assert.deepEqual(lines, [ { kind: ChangeLineKind.Context, text: "one" }, { kind: ChangeLineKind.Remove, text: "two" }, { kind: ChangeLineKind.Add, text: "TWO" }, { kind: ChangeLineKind.Context, text: "three" }, ]); }); test("toolEditDiff derives the file, true counts and the LCS line kinds", () => { const diff = toolEditDiff({ filePath: "a.ts", oldString: "one\ntwo\nthree", newString: "one\nTWO\nthree" }); assert.equal(diff.file, "a.ts"); assert.equal(diff.added, 1); assert.equal(diff.removed, 1); assert.equal(diff.omitted, 0); assert.deepEqual(diff.lines, [ { kind: ChangeLineKind.Context, text: "one" }, { kind: ChangeLineKind.Remove, text: "two" }, { kind: ChangeLineKind.Add, text: "TWO" }, { kind: ChangeLineKind.Context, text: "three" }, ]); assert.equal(toolEditDiff({ oldString: "", newString: "" }), null); assert.equal(toolEditDiff({ oldString: "x" }), null); assert.equal(toolEditDiff({ command: "ls" }), null); assert.equal(toolEditDiff("nope"), null); }); test("toolEditDiff caps rendered lines at MAX_RENDERED_DIFF_LINES and counts the rest", () => { const oldLines = Array.from({ length: 300 }, (_, i) => `old-${i}`); const newLines = Array.from({ length: 300 }, (_, i) => `new-${i}`); const diff = toolEditDiff({ oldString: oldLines.join("\n"), newString: newLines.join("\n") }); assert.equal(diff.lines.length, MAX_RENDERED_DIFF_LINES); assert.equal(diff.added, 300); assert.equal(diff.removed, 300); assert.equal(diff.omitted, 600 - MAX_RENDERED_DIFF_LINES); }); test("lineDiff falls back to remove-then-add past the algorithm guard", () => { const lines = lineDiff(Array.from({ length: 401 }, () => "a"), ["b"]); assert.equal(lines.length, 402); assert.equal(lines[0].kind, ChangeLineKind.Remove); assert.equal(lines.at(-1).kind, ChangeLineKind.Add); }); test("toolCallRow composes the name, detail, duration, input, output, error and diff", () => { const part = { type: "tool", id: "t1", name: "edit", state: { status: "completed", input: { filePath: "a.ts", oldString: "one", newString: "two" }, content: [{ type: "text", text: "done" }], }, time: { created: 10, ran: 20, completed: 120 }, }; const row = toolCallRow(part); assert.equal(row.name, "edit"); assert.equal(row.detail, "a.ts"); assert.equal(row.duration, "100ms"); assert.equal(row.input, '{\n "filePath": "a.ts",\n "oldString": "one",\n "newString": "two"\n}'); assert.equal(row.output, "done"); assert.equal(row.error, null); assert.equal(row.diff.file, "a.ts"); assert.equal(row.diff.added, 1); assert.equal(row.diff.removed, 1); }); test("toolCallRow marks a failed call with its error text and no diff", () => { const row = toolCallRow({ type: "tool", id: "t2", name: "shell", state: { status: "error", input: { command: "false" }, error: { message: "exit 1" } }, }); assert.equal(row.name, "shell"); assert.equal(row.detail, "false"); assert.equal(row.duration, null); assert.equal(row.error, "exit 1"); assert.equal(row.diff, null); }); test("turnElapsedMillis spans earliest start to latest completion and is null when unusable", () => { const parts = [ { time: { created: 1000, ran: 1200, completed: 5000 } }, { time: { created: 800, ran: 0, completed: 4000 } }, ]; assert.equal(turnElapsedMillis(parts), 4200); assert.equal(turnElapsedMillis([{ time: { created: 1000, ran: 1200 } }]), null); assert.equal(turnElapsedMillis([{}]), null); assert.equal(turnElapsedMillis([{ time: { created: 1000, ran: 1000, completed: 1000 } }]), null); }); // --- 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), "Idle"); }); test("relativeSessionTime names the latest chat update, not a meaningless idle state", () => { const now = Date.UTC(2026, 9, 20, 12, 0, 0); assert.equal(relativeSessionTime(0, now), ""); assert.equal(relativeSessionTime(now - 20_000, now), "just now"); assert.equal(relativeSessionTime(now - 50_000, now), "1 min ago"); assert.equal(relativeSessionTime(now - 2 * 60_000, now), "2 min ago"); assert.equal(relativeSessionTime(now - 3 * 60 * 60_000, now), "3 hr ago"); assert.equal(relativeSessionTime(now - 26 * 60 * 60_000, now), "1 day ago"); assert.equal(relativeSessionTime(now - 3 * 24 * 60 * 60_000, now), "3 days ago"); assert.equal(relativeSessionTime(Date.UTC(2026, 8, 12, 9, 0, 0), now), "12 Sept"); }); 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"); }); test("filterChatModels matches name, id or provider case-insensitively", () => { const models = [ { id: "deepseek-v4.1-flash", provider: "opencode-go", name: "DeepSeek V4.1 Flash" }, { id: "gpt-6-luna", provider: "openai", name: "GPT-6 Luna" }, { id: "beam-free", provider: "opencode-go", name: "Beam Free" }, ]; assert.deepEqual(filterChatModels(models, "").map((m) => m.id), models.map((m) => m.id)); assert.deepEqual(filterChatModels(models, "LUNA").map((m) => m.id), ["gpt-6-luna"]); assert.deepEqual(filterChatModels(models, "deepseek").map((m) => m.id), ["deepseek-v4.1-flash"]); assert.deepEqual(filterChatModels(models, "opencode-go").map((m) => m.id), ["deepseek-v4.1-flash", "beam-free"]); assert.deepEqual(filterChatModels(models, "nothing"), []); }); test("directory labels abbreviate the user's home to ~", () => { const home = homeDirectoryFor(["/Users/alan/repos/pipelines", "/Users/alan/notes"]); assert.equal(home, "/Users/alan"); assert.equal(abbreviateHome("/Users/alan", "/Users/alan"), "~"); assert.equal(abbreviateHome("/Users/alan/repos/pipelines", home), "~/repos/pipelines"); assert.equal(abbreviateHome("/Users/alanother/x", home), "/Users/alanother/x"); assert.equal(abbreviateHome("/srv/work", home), "/srv/work"); assert.equal(homeDirectoryFor(["/srv/work"]), ""); assert.equal(abbreviateHome("/home/alan/x", homeDirectoryFor(["/home/alan/x"])), "~/x"); }); // --- 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", }); }); // --------------------------------------------------------------------------- // The composer and its attachments (C8) // --------------------------------------------------------------------------- const thread = (overrides = {}) => ({ draft: "", attachments: [], running: false, queued: false, directory: "/tmp/work", ...overrides, }); const attachment = (overrides = {}) => ({ id: "a1", uri: "a.txt", name: "a.txt", size: 3, error: null, ...overrides }); test("composerAction is Stop while a turn runs and Send otherwise", () => { assert.equal(composerAction(thread({ running: true })), COMPOSER_STOP); assert.equal(composerAction(thread()), COMPOSER_SEND); assert.equal(composerAction(null), COMPOSER_SEND); }); test("composerCanSend requires a non-blank draft and no flagged attachment", () => { assert.equal(composerCanSend(thread({ draft: "hi" })), true); assert.equal(composerCanSend(thread({ draft: " " })), false); assert.equal(composerCanSend(thread({ draft: "hi", attachments: [attachment({ error: "nope" })] })), false); }); test("composerSendEnabled also allows a slash draft with a failed attachment", () => { assert.equal(composerSendEnabled(thread({ draft: "/help" })), true); assert.equal(composerSendEnabled(thread({ draft: "/help", attachments: [attachment({ error: "nope" })] })), true); assert.equal(composerSendEnabled(thread({ draft: "hi", attachments: [attachment({ error: "nope" })] })), false); assert.equal(composerSendEnabled(thread({ draft: "" })), false); }); test("composerSubmit runs an offer row, a slash draft, and a send even while running", () => { assert.deepEqual(composerSubmit(thread({ draft: "hello" }), 0), { kind: "send" }); assert.deepEqual(composerSubmit(thread({ draft: "/" }), 1), { kind: "command", text: "/close" }); assert.deepEqual(composerSubmit(thread({ draft: "/ren" }), 0), { kind: "command", text: "/rename" }); assert.deepEqual(composerSubmit(thread({ draft: "/stop" }), 0), { kind: "command", text: "/stop" }); // A running turn queues the follow-up rather than blocking Send. assert.deepEqual(composerSubmit(thread({ draft: "hello", running: true }), 0), { kind: "send" }); assert.deepEqual(composerSubmit(thread({ draft: "/stop extra", running: true }), 0), { kind: "command", text: "/stop extra", }); }); test("queuedAfterFrame clears the queued flag on any incoming frame", () => { // The flag itself is set from the prompt reply's `chat_queued` (see the // repository test); any frame for the session then clears it, and a null frame // (no push) leaves it as it was. assert.equal(queuedAfterFrame(true, { kind: "text", session_id: "s1" }), false); assert.equal(queuedAfterFrame(true, { kind: "step", step: { status: "ended" } }), false); assert.equal(queuedAfterFrame(true, null), true); assert.equal(queuedAfterFrame(false, { kind: "text" }), false); }); test("runningAfterFrame settles the running bit on a step that ended", () => { assert.equal(runningAfterFrame(true, { kind: "step", step: { status: "ended" } }), false); assert.equal(runningAfterFrame(true, { kind: "step", step: { status: "started" } }), true); assert.equal(runningAfterFrame(true, { kind: "text" }), true); assert.equal(runningAfterFrame(false, { kind: "step", step: { status: "ended" } }), false); }); test("attachmentDisplayName prefers the name, then the uri's basename, then file", () => { assert.equal(attachmentDisplayName("Report.pdf", "content://x/y"), "Report.pdf"); assert.equal(attachmentDisplayName("", "content:///tmp/notes.txt"), "notes.txt"); assert.equal(attachmentDisplayName(" ", "notes.txt"), "notes.txt"); assert.equal(attachmentDisplayName("", ""), "file"); }); test("intermediate tool steps preserve Stop and the running turn", () => { let thread = applyChatEvent(newChatThread("ses_1"), { kind: "step", step: { status: "started" } }, 100); for (let index = 0; index < 3; index++) { const frame = { kind: "step", step: { status: "ended", intermediate: true, index } }; thread = applyChatEvent(thread, frame, 200 + index); assert.equal(thread.running, true); assert.equal(runningAfterFrame(true, frame), true); assert.equal(composerAction(thread), "stop"); } thread = applyChatEvent(thread, { kind: "step", step: { status: "ended" } }, 300); assert.equal(thread.running, false); }); test("attachmentError reports an unreadable file and the server's 1 MiB limit by name", () => { assert.equal(attachmentError("a.txt", 3, true), null); assert.equal(attachmentError("a.txt", 3, false), '"a.txt" could not be read.'); assert.equal(attachmentError("", 3, false), '"file" could not be read.'); assert.equal(MAX_ATTACHMENT_BYTES, 1024 * 1024); assert.equal( attachmentError("big.bin", MAX_ATTACHMENT_BYTES + 1, true), '"big.bin" is too large (1.0 MiB limit).', ); // Exactly at the limit is allowed; the limit reads through the shared humanBytes. assert.equal(attachmentError("big.bin", MAX_ATTACHMENT_BYTES, true), null); }); test("attachmentFiles keeps only the error-free attachments, in order", () => { assert.deepEqual( attachmentFiles([ attachment({ uri: "one.txt" }), attachment({ uri: "bad.txt", error: "nope" }), attachment({ uri: "two.txt" }), ]), ["one.txt", "two.txt"], ); assert.deepEqual(attachmentFiles([]), []); }); test("CHAT_QUEUED_NOTICE is the app's own queued sentence", () => { assert.equal(CHAT_QUEUED_NOTICE, "Queued — it will send when the current turn finishes."); }); test("a command notice carries one terminal glyph for both states", () => { // Android draws Icons.Default.Terminal for a Command and a Command failed // notice and only changes the tint, so the two share this glyph. assert.equal(CHAT_COMMAND_GLYPH, ">_"); }); // --------------------------------------------------------------------------- // Local command notices (C12) — ChatStore.kt notice/dismissNotice/takeNoticeOffer // and ChatCommandUi.kt's labels // --------------------------------------------------------------------------- test("chatNoticeLabel names a command and its failure", () => { assert.equal(CHAT_COMMAND_LABEL, "Command"); assert.equal(CHAT_COMMAND_FAILED_LABEL, "Command failed"); assert.equal(chatNoticeLabel(false), "Command"); assert.equal(chatNoticeLabel(true), "Command failed"); // Anything that is not the literal failed flag keeps the ordinary label. assert.equal(chatNoticeLabel(undefined), "Command"); assert.equal(chatNoticeLabel("failed"), "Command"); }); test("the offerless notice's dismiss control has an accessible name", () => { assert.equal(CHAT_COMMAND_DISMISS_LABEL, "Dismiss command notice"); }); test("makeChatNotice keeps the id, text, failure flag and offer", () => { assert.deepEqual(makeChatNotice("notice-1", "No turn is running in this chat."), { id: "notice-1", text: "No turn is running in this chat.", failed: false, offer: null, }); assert.deepEqual( makeChatNotice("notice-2", "Started a new session.", { failed: true, offer: "/nope" }), { id: "notice-2", text: "Started a new session.", failed: true, offer: "/nope" }, ); }); test("appendChatNotice appends one notice and preserves order", () => { const first = makeChatNotice("notice-1", "Command one"); const second = makeChatNotice("notice-2", "Command two", { failed: true }); const afterFirst = appendChatNotice([], first); const afterSecond = appendChatNotice(afterFirst, second); assert.deepEqual(afterSecond, [first, second]); // The previous list is never mutated. assert.deepEqual(afterFirst, [first]); assert.deepEqual(appendChatNotice(undefined, first), [first]); }); test("dismissChatNotice removes exactly the named notice", () => { const first = makeChatNotice("notice-1", "Command one"); const second = makeChatNotice("notice-2", "Command two", { failed: true }); const third = makeChatNotice("notice-3", "Command three"); assert.deepEqual(dismissChatNotice([first, second, third], "notice-2"), [first, third]); // An unknown id leaves the list as it was. assert.deepEqual(dismissChatNotice([first, third], "notice-9"), [first, third]); assert.deepEqual(dismissChatNotice(undefined, "notice-1"), []); }); test("takeChatNoticeOffer removes the notice and returns its draft", () => { const offerless = makeChatNotice("notice-1", "Command one"); const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" }); const taken = takeChatNoticeOffer([offerless, offered], "notice-2"); assert.equal(taken.offer, "/nope"); assert.deepEqual(taken.notices, [offerless]); }); test("takeChatNoticeOffer returns null and leaves the list for a stale or offerless notice", () => { const offerless = makeChatNotice("notice-1", "Command one"); const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" }); for (const id of ["notice-1", "notice-9"]) { const taken = takeChatNoticeOffer([offerless, offered], id); assert.equal(taken.offer, null); assert.deepEqual(taken.notices, [offerless, offered]); } // A second take of an already-taken id is stale and sends nothing. const firstTake = takeChatNoticeOffer([offered], "notice-2"); const secondTake = takeChatNoticeOffer(firstTake.notices, "notice-2"); assert.equal(secondTake.offer, null); assert.deepEqual(secondTake.notices, []); }); test("notice lists are scoped per conversation and never share state", () => { // Two conversations' notice lists are independent arrays: appending or // dismissing in one cannot touch the other (the app keeps one per thread). const operator = []; const throwaway = []; const operatorNotice = makeChatNotice("notice-1", "Operator command"); const throwawayNotice = makeChatNotice("notice-2", "Throwaway command", { failed: true }); const operatorAfter = appendChatNotice(operator, operatorNotice); const throwawayAfter = appendChatNotice(throwaway, throwawayNotice); assert.deepEqual(operatorAfter, [operatorNotice]); assert.deepEqual(throwawayAfter, [throwawayNotice]); assert.deepEqual(dismissChatNotice(operatorAfter, "notice-1"), []); assert.deepEqual(throwawayAfter, [throwawayNotice]); const taken = takeChatNoticeOffer( appendChatNotice(throwawayAfter, makeChatNotice("notice-3", "Offer", { offer: "/help" })), "notice-3", ); assert.equal(taken.offer, "/help"); assert.deepEqual(operatorAfter, [operatorNotice]); }); // --------------------------------------------------------------------------- // Slash commands (C9) // --------------------------------------------------------------------------- test("CHAT_COMMANDS is exactly the five commands with their usage and summary", () => { assert.deepEqual( CHAT_COMMANDS.map((command) => [command.name, command.usage, command.summary]), [ ["new", "/new", "Start a fresh session in this directory"], ["close", "/close", "Finish this session for every client, keeping its history"], ["rename", "/rename ", "Rename this session on this device"], ["stop", "/stop", "Stop the turn that is running"], ["help", "/help", "List every command"], ], ); }); test("chatCommandHelp is one `usage — summary` line per command", () => { assert.equal( chatCommandHelp(), "/new — Start a fresh session in this directory\n" + "/close — Finish this session for every client, keeping its history\n" + "/rename <title> — Rename this session on this device\n" + "/stop — Stop the turn that is running\n" + "/help — List every command", ); }); test("parseChatInput recognises the five commands case-insensitively", () => { for (const name of ["new", "close", "rename", "stop", "help"]) { const parsed = parseChatInput(`/${name.toUpperCase()}`); assert.equal(parsed.kind, "invocation"); assert.equal(parsed.command.name, name); } const withArg = parseChatInput("/rename My title"); assert.equal(withArg.argument, "My title"); assert.equal(parseChatInput("hello").kind, "plain"); }); test("parseChatInput returns Unknown with the token for a slash word that is not a command", () => { const parsed = parseChatInput(" /nope "); assert.equal(parsed.kind, "unknown"); assert.equal(parsed.token, "/nope"); assert.equal(parsed.text, "/nope"); }); test("chatCommandSuggestions offers only a bare slash word, case-insensitively by prefix", () => { assert.deepEqual(chatCommandSuggestions("hello"), []); assert.deepEqual(chatCommandSuggestions(" /rename x"), []); assert.deepEqual( chatCommandSuggestions("/").map((command) => command.name), ["new", "close", "rename", "stop", "help"], ); assert.deepEqual( chatCommandSuggestions("/ST").map((command) => command.name), ["stop"], ); assert.deepEqual(chatCommandSuggestions("/c").map((command) => command.name), ["close"]); }); test("chatCommandForEnter clamps the highlighted row and is null without a list", () => { assert.equal(chatCommandForEnter("/", 0), "/new"); assert.equal(chatCommandForEnter("/", 4), "/help"); assert.equal(chatCommandForEnter("/", 99), "/new"); assert.equal(chatCommandForEnter("/rename x", 0), null); assert.equal(chatCommandForEnter("hello", 0), null); }); test("chatCommandEffect routes each command to its effect", () => { const view = thread({ draft: "/x", directory: "/repo" }); assert.deepEqual(chatCommandEffect(parseChatInput("/new"), view), { kind: "start-session", directory: "/repo", }); assert.deepEqual(chatCommandEffect(parseChatInput("/close"), view), { kind: "finish-session" }); assert.deepEqual(chatCommandEffect(parseChatInput("/rename My chat"), view), { kind: "rename-session", title: "My chat", }); assert.deepEqual(chatCommandEffect(parseChatInput("/stop"), thread({ running: true })), { kind: "stop-turn" }); assert.deepEqual(chatCommandEffect(parseChatInput("/help"), view), { kind: "show-help" }); assert.equal(chatCommandEffect(parseChatInput("hello"), view), null); }); test("chatCommandEffect reports the exact Android error strings", () => { const view = thread({ directory: "/repo" }); assert.deepEqual(chatCommandEffect(parseChatInput("/nope"), view), { kind: "report", text: "“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.", offer: "/nope", }); assert.deepEqual(chatCommandEffect(parseChatInput("/new extra"), view), { kind: "report", text: "/new does not take an argument.", }); assert.deepEqual(chatCommandEffect(parseChatInput("/rename"), view), { kind: "report", text: "Usage: /rename <title> — renames this session on this device.", }); assert.deepEqual(chatCommandEffect(parseChatInput("/stop"), thread({ running: false })), { kind: "report", text: "No turn is running in this chat.", }); assert.deepEqual(chatCommandEffect(parseChatInput("/new"), thread({ directory: " " })), { kind: "report", text: "Can't start a new session here: the server reported no directory for this chat.", }); }); // --- C5: live stream folding ------------------------------------------------ // Every frame below is the server's `chat_event` shape (internal/protocol/chat.go // ChatEventFrame). The synthetic frames prove the pure fold; the ui-smoke replays // the same shapes against the real page. const evt = (kind, extra = {}) => ({ session_id: "s1", kind, ...extra }); test("a text delta appends to the part the first frame started", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "a1#text#0" }, delta: "Hel" }), 1000); thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "a1#text#0" }, delta: "lo" }), 1001); assert.equal(thread.messages.length, 1); assert.equal(thread.messages[0].role, "assistant"); assert.equal(thread.messages[0].parts.length, 1); assert.equal(thread.messages[0].parts[0].text, "Hello"); assert.equal(thread.running, true); assert.equal(thread.runningSince, 1000); assert.equal(thread.lastDeltaAt, 1001); }); test("a remote user turn carries its file attachments into the message", () => { let thread = newChatThread("s1"); thread = applyChatEvent( thread, evt("user", { message_id: "u1", operation_id: "op1", client: "Phone", part: { type: "text", text: "See attached" }, attachments: [{ type: "file", name: "note.txt", mime: "text/plain", uri: "file:///tmp/note.txt" }], }), 1000, ); const message = thread.messages[0]; assert.equal(message.role, "user"); assert.equal(message.parts[0].text, "See attached"); assert.deepEqual(message.parts[1], { type: "file", name: "note.txt", mime: "text/plain", uri: "file:///tmp/note.txt", }); }); test("a text delta and a reasoning delta sharing a bare id land in separate parts", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "x" }, delta: "answer" }), 1000); thread = applyChatEvent(thread, evt("reasoning", { message_id: "a1", part: { id: "x" }, delta: "think" }), 1001); const parts = thread.messages[0].parts; assert.equal(parts.length, 2); const text = parts.find((part) => part.type === "text"); const reasoning = parts.find((part) => part.type === "reasoning"); assert.equal(text.id, "x"); assert.equal(text.text, "answer"); assert.equal(reasoning.id, "x#reasoning"); assert.equal(reasoning.text, "think"); // The id derivation is the one the broker uses once the kinds are distinct. assert.equal(deltaPartId(parts, "text", "x"), "x"); assert.equal(deltaPartId(parts, "reasoning", "x"), "x#reasoning"); }); test("tool frames merge field by field without blanking what an earlier frame taught", () => { let thread = newChatThread("s1"); thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", name: "read", state: { status: "running", input: { filePath: "a.js" } } }, }), 1000, ); // A later frame carries the result but no name and no input: both are retained. thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "completed", content: [{ type: "text", text: "done" }] } }, }), 1001, ); // A final frame carries the error but no content: the content is retained too. thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "error", error: { message: "boom" } } }, }), 1002, ); const tool = thread.messages[0].parts.find((part) => part.type === "tool"); assert.equal(tool.name, "read"); assert.deepEqual(tool.state.input, { filePath: "a.js" }); assert.equal(tool.state.content[0].text, "done"); assert.equal(tool.state.error.message, "boom"); assert.equal(tool.state.status, "error"); // And the pure merge keeps a non-empty incoming field while retaining the prior. const merged = mergeToolPart( { type: "tool", id: "t1", name: "read", executed: true, state: { status: "running", input: { a: 1 } } }, { type: "tool", id: "t1", name: "", state: { status: "", input: { b: 2 } } }, ); assert.equal(merged.name, "read"); assert.equal(merged.executed, true); assert.equal(merged.state.status, "running"); assert.deepEqual(merged.state.input, { b: 2 }); }); test("a repeated user message id adds no second turn and keeps a non-blank client", () => { let thread = newChatThread("s1"); const frame = evt("user", { message_id: "u9", part: { text: "hi there" }, client: "Pixel" }); thread = applyChatEvent(thread, frame, 1000); thread = applyChatEvent(thread, frame, 1001); assert.equal(thread.messages.filter((message) => message.role === "user").length, 1); assert.equal(thread.messages[0].client, "Pixel"); assert.equal(thread.messages[0].parts[0].text, "hi there"); // Another id with no text or no id at all is ignored. thread = applyChatEvent(thread, evt("user", { message_id: "u10", part: { text: "" } }), 1002); thread = applyChatEvent(thread, evt("user", { part: { text: "no id" } }), 1003); assert.equal(thread.messages.length, 1); }); test("step started runs the turn and step ended settles it", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("step", { step: { status: "started", index: 1 } }), 1000); assert.equal(thread.running, true); assert.equal(thread.runningSince, 1000); // A tool call in flight leaves a stamp; ending the step clears running and the stamp. thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "running" } } }), 1001, ); assert.equal(thread.toolStartedAt.t1, 1001); thread = applyChatEvent(thread, evt("step", { step: { status: "ended" } }), 2000); assert.equal(thread.running, false); assert.equal(thread.runningSince, 0); assert.deepEqual(thread.toolStartedAt, {}); assert.equal(thread.lastDeltaAt, 0); }); test("turn-content frames clear the queued flag", () => { for (const frame of [ evt("text", { message_id: "a1", part: { id: "p" }, delta: "x" }), evt("step", { step: { status: "started" } }), evt("shell", { shell: { id: "sh1", status: "running" } }), ]) { const queued = { ...newChatThread("s1"), queued: true }; assert.equal(applyChatEvent(queued, frame, 1000).queued, false); } }); test("a shell frame never marks the thread running", () => { const thread = applyChatEvent( newChatThread("s1"), evt("shell", { shell: { id: "sh1", status: "running", command: "go test ./..." } }), 1000, ); assert.equal(thread.running, false); assert.equal(thread.runningSince, 0); }); test("a usage frame changes nothing", () => { const before = newChatThread("s1"); const after = applyChatEvent(before, evt("usage", { usage: { input_tokens: 5, cost: 0.01 } }), 1000); assert.deepEqual(after, before); }); test("settling a thread (a socket drop) clears running, its stamps and queued", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "p" }, delta: "x" }), 1000); thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "running" } } }), 1001, ); assert.equal(thread.running, true); assert.equal(thread.toolStartedAt.t1, 1001); const settled = settledThread(thread); assert.equal(settled.running, false); assert.equal(settled.runningSince, 0); assert.deepEqual(settled.toolStartedAt, {}); assert.equal(settled.lastDeltaAt, 0); assert.equal(settled.queued, false); // The conversation itself is untouched by settling. assert.equal(settled.messages.length, 1); }); test("historyResync replaces the turn wholesale and settles it", () => { const held = { ...newChatThread("s1"), messages: [assistant("a1", [{ type: "text", text: "stale" }])], nextCursor: "old", hasMore: true, loaded: true, running: true, runningSince: 555, toolStartedAt: { t1: 555 }, lastDeltaAt: 600, }; const page = { messages: [user("u1", "hi"), assistant("a2", [{ type: "text", text: "fresh" }])], nextCursor: "", hasMore: false, }; const resynced = historyResync(held, page); assert.deepEqual(resynced.messages, page.messages); assert.ok(!resynced.messages.some((message) => message.id === "a1")); assert.equal(resynced.nextCursor, ""); assert.equal(resynced.hasMore, false); assert.equal(resynced.loaded, true); assert.equal(resynced.running, false); assert.equal(resynced.runningSince, 0); assert.deepEqual(resynced.toolStartedAt, {}); assert.equal(resynced.lastDeltaAt, 0); }); test("the chat stream badge uses the live / reconnecting / not live words", () => { assert.deepEqual(chatStreamState("connected", true), { tone: "live", label: "live" }); assert.equal(chatStreamState("connected", false).label, "not live"); assert.equal(chatStreamState("connecting", true).label, "reconnecting"); assert.equal(chatStreamState("disconnected", true).label, "reconnecting"); assert.equal(chatStreamState("idle", false).label, "not live"); }); test("the turn phase names what is happening", () => { assert.equal(turnPhase([]), TURN_PHASE_THINKING); assert.equal(turnPhaseLabel(TURN_PHASE_THINKING), "Thinking…"); assert.equal(turnPhase([{ type: "tool", id: "t", state: { status: "running" } }]), TURN_PHASE_TOOL); assert.equal(turnPhaseLabel(TURN_PHASE_TOOL), "Running a tool…"); assert.equal(turnPhaseLabel(TURN_PHASE_WAITING), "Waiting…"); }); test("a running turn reads as thinking at any silence; a queued prompt waits", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("step", { step: { status: "started" } }), 1000); // Two minutes without a delta: still the model's own work, not idle. assert.equal(threadPhase(thread, 121000), TURN_PHASE_THINKING); const queued = { ...thread, queued: true }; assert.equal(threadPhase(queued, 121000), TURN_PHASE_WAITING); assert.equal(threadPhase({ ...thread, running: false }, 121000), null); }); test("only a call at or past 60s reads as long", () => { assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1), false); assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS), true); assert.equal(TOOL_LONG_RUNNING_MILLIS, 60000); }); test("a live turn interleaving reasoning, text and tool frames folds to one agent row", () => { let thread = newChatThread("live"); const frames = [ evt("reasoning", { message_id: "a1", part: { id: "r0" }, delta: "think" }), evt("text", { message_id: "a1", part: { id: "t0" }, delta: "Hel" }), evt("tool", { message_id: "a1", part: { type: "tool", id: "tool1", name: "read", state: { status: "running" } } }), evt("tool", { message_id: "a1", part: { type: "tool", id: "tool1", state: { status: "completed", content: [{ type: "text", text: "ok" }] } }, }), evt("reasoning", { message_id: "a2", part: { id: "r0" }, delta: "more" }), evt("text", { message_id: "a2", part: { id: "t0" }, delta: "lo" }), ]; for (const frame of frames) thread = applyChatEvent(thread, frame, 1000); const rows = transcriptRows(thread.messages); const agentRows = rows.filter((row) => row.kind === "agent"); assert.equal(agentRows.length, 1); assert.equal(agentRows[0].key, "a1"); assert.deepEqual(agentRows[0].turn.reasoningSteps, ["think", "more"]); assert.equal(agentRows[0].turn.tools.length, 1); assert.equal(agentRows[0].turn.answer, "Hel\n\nlo"); assert.equal(threadRunningTools(thread.messages).length, 0); }); test("the running indicator's elapsed and per-tool timing use the thread's own stamps", () => { let thread = newChatThread("s1"); thread = applyChatEvent(thread, evt("step", { step: { status: "started" } }), 1000); thread = applyChatEvent( thread, evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", name: "shell", state: { status: "running", input: { command: "go build" } } }, }), 1500, ); assert.equal(threadElapsedMillis(thread, 3000), 2000); assert.equal(formatToolDuration(threadToolElapsedMillis(thread, thread.messages[0].parts[0], 3000)), "1.5s"); assert.equal(threadPhase(thread, 3000), TURN_PHASE_TOOL); // runningToolStamps keeps a stamp it already had and drops one that settled. assert.deepEqual(runningToolStamps({ t1: 42 }, thread.messages, 9999), { t1: 42 }); assert.deepEqual(runningToolStamps({ t1: 42 }, [], 9999), {}); }); // ---- Permission approvals (C10) ------------------------------------------- /** A `chat_permission` frame (internal/protocol/chat.go ChatPermissionFrame). */ const permissionFrame = (extra = {}) => ({ session_id: "s1", request_id: "req-1", action: "bash", ...extra, }); test("approvalCard names the action while pending, a blank action falling back to tool call", () => { const card = approvalCard(permissionFrame(), ""); assert.equal(card.state, APPROVAL_PENDING); assert.equal(card.actionable, true); assert.equal(card.showRisk, true); assert.equal(card.headline, "Approve bash"); assert.equal(card.statusLine, APPROVAL_STATUS_PENDING); assert.equal(approvalCard(permissionFrame({ action: " " }), "").headline, "Approve tool call"); assert.equal(approvalCard(permissionFrame({ resources: ["r1", "r2"] }), "").resourceText, "r1\nr2"); // No request to show. assert.equal(approvalCard(null, ""), null); assert.equal(approvalCard({ request_id: " " }, ""), null); }); test("an answered card reads its decision label and waits for the agent", () => { assert.equal(approvalCard(permissionFrame(), DECISION_ONCE).headline, DECISION_LABEL_ONCE); assert.equal(approvalCard(permissionFrame(), DECISION_ALWAYS).headline, DECISION_LABEL_ALWAYS); const rejected = approvalCard(permissionFrame(), DECISION_REJECT); assert.equal(rejected.headline, DECISION_LABEL_REJECT); assert.equal(rejected.statusLine, APPROVAL_STATUS_ANSWERED); assert.equal(rejected.actionable, false); // Risk box: the app shows it while pending and after a deny, not for an accept. assert.equal(rejected.showRisk, true); assert.equal(approvalCard(permissionFrame(), DECISION_ONCE).showRisk, false); // An unknown decision still settles to the blank-safe label. assert.equal(approvalCard(permissionFrame(), "whatever").headline, DECISION_LABEL_RESOLVED); }); test("a server-resolved card uses its decision label and note, else Already resolved", () => { const resolvedWith = approvalCard( permissionFrame({ resolved: true, decision: DECISION_ALWAYS, message: "Another client allowed this." }), DECISION_ONCE, ); assert.equal(resolvedWith.state, APPROVAL_RESOLVED); assert.equal(resolvedWith.headline, DECISION_LABEL_ALWAYS); assert.equal(resolvedWith.statusLine, "Another client allowed this."); assert.equal(resolvedWith.actionable, false); assert.equal(resolvedWith.showRisk, false); // A non-blank decision alone counts as resolved; a blank one reads Already resolved. const bare = approvalCard(permissionFrame({ decision: DECISION_REJECT }), ""); assert.equal(bare.state, APPROVAL_RESOLVED); assert.equal(bare.headline, DECISION_LABEL_REJECT); assert.equal(bare.statusLine, APPROVAL_STATUS_RESOLVED); const noDecision = approvalCard(permissionFrame({ resolved: true }), DECISION_ONCE); assert.equal(noDecision.headline, APPROVAL_HEADLINE_RESOLVED); assert.equal(noDecision.statusLine, APPROVAL_STATUS_RESOLVED); // The server resolution outranks the local answer. assert.equal(noDecision.decision, ""); }); test("decisionLabel is blank-safe", () => { assert.equal(decisionLabel(DECISION_ONCE), DECISION_LABEL_ONCE); assert.equal(decisionLabel(DECISION_ALWAYS), DECISION_LABEL_ALWAYS); assert.equal(decisionLabel(DECISION_REJECT), DECISION_LABEL_REJECT); assert.equal(decisionLabel(""), DECISION_LABEL_RESOLVED); assert.equal(decisionLabel(undefined), DECISION_LABEL_RESOLVED); }); test("permissionRiskText prefers the server message, else names the action, else a tool call", () => { assert.equal( permissionRiskText(permissionFrame({ message: "Runs a shell as root." })), "Runs a shell as root.", ); assert.equal( permissionRiskText(permissionFrame()), "The agent is asking to run bash; review the request before allowing.", ); assert.equal( permissionRiskText(permissionFrame({ action: " " })), "The agent is asking to run a tool call; review the request before allowing.", ); }); test("approvalResources drops blanks but keeps every resource entry", () => { const shown = approvalResources({ resources: ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", " "] }); assert.deepEqual(shown, ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"]); assert.deepEqual(approvalResources({}), []); }); test("approvalResourceText joins the resources and caps the visible lines at six", () => { // A blank resource is no line; an embedded newline is its own line. assert.equal(approvalResourceText({ resources: ["a", " ", "b\nc"] }), "a\nb\nc"); // Eight resources cap to six lines, the sixth carrying the ellipsis so the // elided remainder is not silent (Android's maxLines = 6, Ellipsis). assert.equal( approvalResourceText({ resources: ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"] }), "r1\nr2\nr3\nr4\nr5\nr6\u2026", ); // A resource carrying embedded newlines counts toward the cap too: six lines // from one entry plus one more entry still yields six lines. const capped = approvalResourceText({ resources: ["a\nb\nc\nd\ne\nf", "g"] }); assert.equal(capped.split("\n").length, MAX_APPROVAL_RESOURCE_LINES); assert.equal(capped.split("\n")[MAX_APPROVAL_RESOURCE_LINES - 1], "f\u2026"); assert.equal(approvalResourceText({}), ""); }); test("applyChatPermission keeps the answer for the same request and clears it for a new one", () => { let thread = newChatThread("s1"); thread = applyChatPermission(thread, permissionFrame()); assert.equal(thread.permission.request_id, "req-1"); assert.equal(thread.permissionAnswer, ""); thread = { ...thread, permissionAnswer: DECISION_ONCE }; // The same request re-pushed keeps the operator's local answer. thread = applyChatPermission(thread, permissionFrame()); assert.equal(thread.permissionAnswer, DECISION_ONCE); // A resolved re-push of the same request applies the outcome (which wins) and // still keeps the stored answer. thread = applyChatPermission( thread, permissionFrame({ resolved: true, decision: DECISION_ALWAYS, message: "done elsewhere" }), ); assert.equal(thread.permissionAnswer, DECISION_ONCE); const card = approvalCard(thread.permission, thread.permissionAnswer); assert.equal(card.state, APPROVAL_RESOLVED); assert.equal(card.headline, DECISION_LABEL_ALWAYS); assert.equal(card.statusLine, "done elsewhere"); // A new request replaces the settled card and clears the answer. thread = applyChatPermission(thread, permissionFrame({ request_id: "req-2" })); assert.equal(thread.permission.request_id, "req-2"); assert.equal(thread.permissionAnswer, ""); }); // --- C11: background tasks (shells) ----------------------------------------- // The pure model the background-tasks bar is built on: running-only filtering, // the visible-row cap, the one-line command summary, shell-frame folding and the // detail pane's state selection and wording. Mirror of // ChatFormat.runningBackgroundShells/shellCommandSummary, ChatStore.applyShell/ // shellsLoaded and ChatTranscript.BackgroundProcessBar/-Detail. const shell = (overrides = {}) => ({ id: "sh1", status: "running", command: "go test ./...", ...overrides }); test("runningBackgroundShells lists only non-blank running shells, in order", () => { const shells = [ shell({ id: "a", command: "one" }), shell({ id: "b", status: SHELL_EXITED, command: "two" }), shell({ id: "", command: "three" }), shell({ id: "d", status: "running", command: "four" }), shell({ id: "e", status: undefined }), ]; assert.deepEqual( runningBackgroundShells(shells).map((s) => s.id), ["a", "d"], ); assert.deepEqual(runningBackgroundShells([]), []); assert.deepEqual(runningBackgroundShells(undefined), []); }); test("the visible-row cap is three and never truncates the model", () => { assert.equal(BACKGROUND_TASK_VISIBLE_ROWS, 3); const running = Array.from({ length: 5 }, (_, i) => shell({ id: `s${i}` })); // The cap is a view/CSS concern; every running shell stays in the model. assert.equal(runningBackgroundShells(running).length, 5); }); test("shellCommandSummary collapses whitespace, names a blank command and elides past 72", () => { assert.equal(SHELL_ROW_LABEL, "Running"); assert.equal(shellCommandSummary(""), "background process"); assert.equal(shellCommandSummary(" "), "background process"); assert.equal(shellCommandSummary(null), "background process"); assert.equal(shellCommandSummary(" go test\n./...\t-x "), "go test ./... -x"); // Exactly 72 characters is not elided. const seventyTwo = "a".repeat(TOOL_DETAIL_MAX_LENGTH); assert.equal(shellCommandSummary(seventyTwo), seventyTwo); // Longer: 71 kept characters, trailing whitespace trimmed, then one ellipsis. const long = `${"b".repeat(TOOL_DETAIL_MAX_LENGTH)} tail`; const elided = shellCommandSummary(long); assert.equal(elided, `${"b".repeat(TOOL_DETAIL_MAX_LENGTH - 1)}…`); assert.equal(elided.length, TOOL_DETAIL_MAX_LENGTH); assert.ok(elided.endsWith("…")); // A 71-char word followed by a space then more trims the trailing space first. const word = `${"c".repeat(TOOL_DETAIL_MAX_LENGTH - 1)} rest`; assert.equal(shellCommandSummary(word), `${"c".repeat(TOOL_DETAIL_MAX_LENGTH - 1)}…`); }); test("mergeShellFrame keeps a blank command from the previous frame and caps the list", () => { const first = mergeShellFrame([], shell({ id: "a", command: "go build" })); assert.deepEqual(first, [shell({ id: "a", command: "go build" })]); // A later frame that omits the command never blanks the retained one. const merged = mergeShellFrame(first, shell({ id: "a", command: "" })); assert.equal(merged.length, 1); assert.equal(merged[0].command, "go build"); // A frame that carries a command replaces it; the position is preserved. const renamed = mergeShellFrame(merged, shell({ id: "a", command: "go vet" })); assert.equal(renamed[0].command, "go vet"); // A blank id (or null shell) is ignored outright. assert.equal(mergeShellFrame(renamed, shell({ id: "" })).length, 1); assert.deepEqual(mergeShellFrame(renamed, null), renamed); // The retained list is capped at OBSERVED_SHELL_LIMIT, keeping the newest. let many = []; for (let i = 0; i < OBSERVED_SHELL_LIMIT + 4; i += 1) { many = mergeShellFrame(many, shell({ id: `s${i}`, command: `c${i}` })); } assert.equal(many.length, OBSERVED_SHELL_LIMIT); assert.equal(many.at(-1).id, `s${OBSERVED_SHELL_LIMIT + 3}`); assert.equal(many[0].id, "s4"); }); test("shellsLoaded replaces the live set but retains exits this client observed", () => { const existing = [ shell({ id: "r1", status: SHELL_RUNNING, command: "old run" }), shell({ id: "e1", status: SHELL_EXITED, command: "finished" }), ]; const loaded = shellsLoaded(existing, [shell({ id: "r2", status: SHELL_RUNNING, command: "new run" })]); assert.deepEqual(loaded.map((s) => s.id), ["e1", "r2"]); // r1 is neither in the snapshot nor a locally observed exit, so it drops out. assert.ok(!loaded.some((s) => s.id === "r1")); // An exit the client never saw exit is not invented. assert.ok(!loaded.some((s) => s.id === "r1")); }); test("shellOutputState picks the detail pane's branch in the app's order", () => { assert.equal(shellOutputState(null), null); assert.equal(shellOutputState(undefined), null); assert.equal(shellOutputState({}), null); assert.equal(shellOutputState({ loading: true }), SHELL_OUTPUT_LOADING); assert.equal(shellOutputState({ error: "boom" }), SHELL_OUTPUT_ERROR); // Error outranks a page if both were set. assert.equal(shellOutputState({ error: "boom", page: { output: "x" } }), SHELL_OUTPUT_ERROR); assert.equal(shellOutputState({ page: { unavailable: true } }), SHELL_OUTPUT_UNAVAILABLE); assert.equal(shellOutputState({ page: { output: "" } }), SHELL_OUTPUT_EMPTY); assert.equal(shellOutputState({ page: { output: "line\n" } }), SHELL_OUTPUT_READY); assert.equal(shellOutputState({ page: { output: "x", truncated: true } }), SHELL_OUTPUT_READY); }); test("the detail pane's wording is the app's verbatim copy", () => { assert.equal(BACKGROUND_TASKS_TITLE, "Background tasks"); assert.equal(backgroundTasksRunningLabel(3), "3 running"); assert.equal(SHELL_DETAILS_LABEL, "Details"); assert.deepEqual(SHELL_OUTPUT_LABELS, { COMMAND: "Command", UNAVAILABLE: "Unavailable", TASK_IDENTITY: "Task identity", STATUS_RUNNING: "Status: running", OUTPUT_UNAVAILABLE: "Output unavailable for this task.", NO_OUTPUT: "No output yet.", OUTPUT: "Output", OUTPUT_BOUNDED: "Output is bounded to 64 KiB.", RETRY: "Retry", REFRESH: "Refresh", }); }); test("a shell frame folds into the thread and never marks the turn running", () => { const folded = applyChatEvent( newChatThread("s1"), evt("shell", { shell: { id: "sh1", status: "running", command: "sleep 5" } }), 1000, ); assert.equal(folded.running, false); assert.equal(folded.runningSince, 0); assert.deepEqual(folded.shells, [{ id: "sh1", status: "running", command: "sleep 5" }]); // A shell frame that ends the shell removes it from the running set at once. const exited = applyChatEvent( folded, evt("shell", { shell: { id: "sh1", status: "exited", command: "" } }), 1001, ); assert.equal(exited.shells[0].status, "exited"); assert.equal(exited.shells[0].command, "sleep 5"); assert.equal(runningBackgroundShells(exited.shells).length, 0); }); test("a step that ends does not clear a background shell that outlives the turn", () => { let thread = applyChatEvent( newChatThread("s1"), evt("shell", { shell: { id: "sh1", status: "running", command: "sleep 5" } }), 1000, ); thread = applyChatEvent(thread, evt("step", { step: { status: "started" } }), 1000); thread = applyChatEvent(thread, evt("step", { step: { status: "ended" } }), 2000); assert.equal(thread.running, false); assert.equal(runningBackgroundShells(thread.shells).length, 1); // settledThread alone keeps the shell; only the reconnect repair drops it. assert.equal(settledThread(thread).shells.length, 1); const resumed = resumedThread(thread); assert.deepEqual(resumed.shells, []); assert.equal(resumed.selectedShellId, null); assert.equal(resumed.shellOutput, null); }); // ---- The create flow's directory picker (C2, ChatDirectories.kt) ----------- test("directoryChoices makes the first non-blank directory home and keeps recents in server order", () => { const choices = directoryChoices(["/Users/alan", "", "/work/one", " ", "/work/two"]); assert.deepEqual(choices, [ { label: "Home (~)", path: "/Users/alan", home: true, createDirectory: "~", secondary: "/Users/alan", }, { label: "/work/one", path: "/work/one", home: false, createDirectory: "/work/one", secondary: null, }, { label: "/work/two", path: "/work/two", home: false, createDirectory: "/work/two", secondary: null, }, ]); }); test("directoryChoices always yields home first, even for an empty or blank reply", () => { for (const reply of [[], ["", " "], null, undefined]) { const choices = directoryChoices(reply); assert.equal(choices.length, 1); assert.deepEqual(choices[0], { label: HOME_LABEL, path: HOME_DIRECTORY, home: true, createDirectory: HOME_DIRECTORY, secondary: HOME_DIRECTORY, }); } }); test("the home row is the only one with a secondary path; recents are labelled by full path", () => { const choices = directoryChoices(["/home/operator", "/repo/a", "/repo/b"]); assert.deepEqual( choices.map((choice) => [choice.label, choice.secondary]), [ ["Home (~)", "/home/operator"], ["/repo/a", null], ["/repo/b", null], ], ); assert.equal(defaultDirectoryChoice(choices)?.label, HOME_LABEL); assert.equal(defaultDirectoryChoice([]), null); }); test("newChatCreateState starts on home, not sending, with the caller's operation id", () => { assert.deepEqual(newChatCreateState("web-chat-op"), { directory: HOME_DIRECTORY, backend: "opencode", instructions: DEFAULT_CHAT_INSTRUCTIONS, operationId: "web-chat-op", creating: false, error: "", }); }); test("selectChatDirectory sends the chosen value and clears a previous refusal", () => { const state = { ...newChatCreateState("op"), error: "refused" }; const recent = { label: "/repo/a", path: "/repo/a", home: false, createDirectory: "/repo/a", secondary: null }; assert.deepEqual(selectChatDirectory(state, recent), { directory: "/repo/a", backend: "opencode", instructions: DEFAULT_CHAT_INSTRUCTIONS, operationId: "op", creating: false, error: "", }); assert.equal(selectChatDirectory(state, "~").directory, "~"); assert.deepEqual(selectChatDirectory(state, ""), state); }); test("chatCreateFailed keeps the pane open with the server's message; success stops sending", () => { const creating = { ...newChatCreateState("op"), creating: true }; assert.deepEqual(chatCreateFailed(creating, "the directory is not available"), { directory: "~", backend: "opencode", instructions: DEFAULT_CHAT_INSTRUCTIONS, operationId: "op", creating: false, error: "the directory is not available", }); }); test("chatCreateSucceeded puts the created session at the head and dedupes by id", () => { const a = { id: "a", title: "A" }; const b = { id: "b", title: "B" }; const created = { id: "b", title: "New chat" }; assert.deepEqual(chatCreateSucceeded([a, b], created), [created, a]); assert.deepEqual(chatCreateSucceeded([], created), [created]); assert.deepEqual(chatCreateSucceeded([a], null), [a]); }); test("the create flow's wording is the app's verbatim", () => { assert.equal(CHAT_CREATE_TITLE, "Start a chat"); assert.equal(CHAT_CREATE_BACK_LABEL, "Cancel new chat"); assert.equal(CHAT_CREATE_LOADING, "Loading directories…"); assert.equal(CHAT_CREATE_PROMPT, "Where should this chat live?"); assert.equal( CHAT_CREATE_MODEL_NOTE, "This server has no request for choosing a chat's model, so a new chat uses the server's default.", ); assert.equal(CHAT_CREATE_CONFIRM, "New chat"); assert.equal(CHAT_CREATE_CANCEL, "Cancel"); assert.equal(chatStartInLabel(HOME_DIRECTORY), "Start in ~"); assert.equal(chatStartInLabel("/repo/a"), "Start in /repo/a"); }); // --------------------------------------------------------------------------- // C13: the local overrides and the seen state (ChatOverrides.kt / ChatSeen.kt) // --------------------------------------------------------------------------- const sess = (id, title, updated_at) => ({ id, title, updated_at }); test("local overrides: a local title wins on every refresh, trimmed, blanks ignored", () => { const sessions = [sess("a", "Server A", 100), sess("b", "Server B", 200)]; // No overrides: the server's own list is returned untouched. assert.equal(applyChatOverrides(sessions, emptyChatOverrides()), sessions); let overrides = renameChatOverride(emptyChatOverrides(), "a", " My A "); assert.deepEqual(overrides.titles, { a: "My A" }); const applied = applyChatOverrides(sessions, overrides); assert.equal(applied[0].title, "My A"); assert.equal(applied[1].title, "Server B"); // A later refresh (the server's own title still "Server A") keeps the local name. assert.equal(applyChatOverrides(sessions, overrides)[0].title, "My A"); // A blank id or a blank/whitespace title changes nothing (identity preserved). assert.equal(renameChatOverride(overrides, "a", " "), overrides); assert.equal(renameChatOverride(overrides, " ", "Nope"), overrides); // A rename for another id is recorded without touching the first. const both = renameChatOverride(overrides, "b", "Bee"); assert.deepEqual(both.titles, { a: "My A", b: "Bee" }); assert.equal(applyChatOverrides(sessions, both)[1].title, "Bee"); // Re-recording the same trimmed title is a no-op (same object). assert.equal(renameChatOverride(both, "b", " Bee "), both); }); test("hide + undo: one entry per id, blank ignored, restore returns the prior state", () => { const overrides = emptyChatOverrides(); const hidden = hideChatOverride(overrides, "s1"); assert.deepEqual(hidden.hidden, ["s1"]); // Already hidden: nothing changes, and no duplicate is appended. assert.equal(hideChatOverride(hidden, "s1"), hidden); assert.equal(hideChatOverride(hidden, " "), hidden); const sessions = [sess("s1", "One", 1), sess("s2", "Two", 2)]; assert.deepEqual(applyChatOverrides(sessions, hidden).map((s) => s.id), ["s2"]); const restored = restoreChatOverride(hidden, "s1"); assert.deepEqual(restored.hidden, []); assert.deepEqual(applyChatOverrides(sessions, restored).map((s) => s.id), ["s1", "s2"]); // Restoring something that was never hidden changes nothing. assert.equal(restoreChatOverride(restored, "s9"), restored); // Hide then undo returns the original model. assert.deepEqual(restoreChatOverride(hideChatOverride(overrides, "s1"), "s1"), overrides); }); test("overrides JSON round-trips, and unreadable/wrong-typed input decodes to empty", () => { const overrides = renameChatOverride(hideChatOverride(emptyChatOverrides(), "gone"), "kept", "Name"); assert.deepEqual(decodeChatOverrides(encodeChatOverrides(overrides)), overrides); for (const corrupt of [null, "", "not json", "{", "[]", '"x"', "42"]) { assert.deepEqual(decodeChatOverrides(corrupt), emptyChatOverrides()); } // Wrong-typed fields fall back to the empty model rather than throwing. assert.deepEqual(decodeChatOverrides('{"titles":[],"hidden":"x"}'), emptyChatOverrides()); assert.deepEqual(decodeChatOverrides('{"titles":{"a":3},"hidden":[7,"ok","ok"]}').hidden, ["ok"]); assert.deepEqual(decodeChatOverrides('{"titles":{"":"x","b":" B "}}'), { titles: { b: "B" }, hidden: [] }); }); test("seen JSON round-trips, de-duplicates unseen, and tolerates corrupt input", () => { let seen = markChatUnseen(emptyChatSeen(), "s1"); seen = markChatUnseen(seen, "s1"); // duplicate seen = readChatSeen(seen, "s2", 500); const decoded = decodeChatSeen(encodeChatSeen(seen)); assert.deepEqual(decoded.seenAt, { s2: 500 }); assert.deepEqual(decoded.unseen, ["s1"]); for (const corrupt of [null, "", "not json", "{", "[]", "true"]) { assert.deepEqual(decodeChatSeen(corrupt), emptyChatSeen()); } assert.deepEqual(decodeChatSeen('{"seenAt":[],"unseen":"x"}'), emptyChatSeen()); const tolerated = decodeChatSeen('{"seenAt":{"a":10,"b":"x","":5},"unseen":["u","u",""]}'); assert.deepEqual(tolerated.seenAt, { a: 10 }); assert.deepEqual(tolerated.unseen, ["u"]); }); test("first sight seeding: a baseline is set once and never clears an explicit unseen", () => { const sessions = [sess("a", "A", 100), sess("b", "B", 0)]; const seeded = seedChatSeen(emptyChatSeen(), sessions, null); assert.deepEqual(seeded.seenAt, { a: 100 }); // An absent or zero recency is never recorded. assert.equal(seeded.seenAt.b, undefined); // A later, higher recency is not re-seeded over the existing baseline. const later = seedChatSeen(seeded, [sess("a", "A", 300)], null); assert.deepEqual(later.seenAt, { a: 100 }); // Seeding never clears an unseen mark. const marked = markChatUnseen(seeded, "a"); const reseeded = seedChatSeen(marked, [sess("a", "A", 400)], null); assert.deepEqual(reseeded.unseen, ["a"]); // The active session is read (watermark advances, the mark clears). const active = seedChatSeen(markChatUnseen(emptyChatSeen(), "a"), [sess("a", "A", 900)], "a"); assert.deepEqual(active.seenAt, { a: 900 }); assert.deepEqual(active.unseen, []); }); test("reading advances the watermark monotonically and always clears the mark", () => { const first = readChatSeen(emptyChatSeen(), "s", 100); assert.equal(chatSeenWatermark(first, "s"), 100); // A stale read cannot rewind it... assert.equal(readChatSeen(first, "s", 50), first); // ...an equal read is not "newer" either... assert.equal(readChatSeen(first, "s", 100), first); // ...but a strictly newer one advances. assert.equal(chatSeenWatermark(readChatSeen(first, "s", 101), "s"), 101); // A mark is cleared even when the recency does not advance. const marked = markChatUnseen(first, "s"); const read = readChatSeen(marked, "s", 100); assert.deepEqual(read.unseen, []); assert.equal(read.seenAt.s, 100); // A blank id is a no-op. assert.equal(readChatSeen(first, " ", 500), first); }); test("the unseen rule: not active, explicit mark or never-opened-and-strictly-newer", () => { let seen = readChatSeen(emptyChatSeen(), "opened", 100); seen = readChatSeen(seen, "equal", 100); // A watermark ahead of the session's own recency: not newer, so not new. seen = readChatSeen(seen, "old", 120); const opened = sess("opened", "Opened", 200); // moved on after it was read const fresh = sess("fresh", "Fresh", 150); const equal = sess("equal", "Equal", 100); const old = sess("old", "Old", 50); // The active session is never new, even with an explicit mark. assert.equal( isChatSessionUnseen(opened, { activeId: "opened", seen: markChatUnseen(seen, "opened"), opened: true }), false, ); // A never-opened session is new only while strictly newer than the watermark. assert.equal(isChatSessionUnseen(fresh, { seen, opened: false }), true); assert.equal(isChatSessionUnseen(equal, { seen, opened: false }), false); assert.equal(isChatSessionUnseen(old, { seen, opened: false }), false); // A session already opened here is judged by the explicit mark alone. assert.equal(isChatSessionUnseen(opened, { seen, opened: true }), false); assert.equal(isChatSessionUnseen(opened, { seen: markChatUnseen(seen, "opened"), opened: true }), true); }); test("the C13 wording matches the Android sources verbatim", () => { assert.equal(CHAT_RENAME_ACTION, "Rename…"); assert.equal(CHAT_HIDE_ACTION, "Hide on this device"); assert.equal(CHAT_ACTIONS_LABEL, "Chat actions"); assert.equal(CHAT_REMOVED_MESSAGE, "Hidden on this device; the chat stays on the server."); assert.equal(CHAT_UNDO_ACTION, "Undo"); assert.equal(CHAT_RENAME_TITLE, "Rename chat"); assert.equal(CHAT_RENAME_FIELD_LABEL, "Name"); assert.equal( CHAT_RENAME_HELPER, "This name is shared with every device.", ); assert.equal(CHAT_RENAME_SAVE, "Save"); assert.equal(CHAT_RENAME_DISMISS, "Cancel"); // The badge precedence words, with Open only while the conversation is open. assert.equal(sessionActivityBadge(sessionActivity(true, true), true), "Streaming"); assert.equal(sessionActivityBadge(sessionActivity(false, true), true), "New"); assert.equal(sessionActivityBadge(sessionActivity(false, false), true), "Open"); assert.equal(sessionActivityBadge(sessionActivity(false, false), false), "Idle"); }); test("applyChatForm keeps one pending question and clears it on resolve", () => { const form = { id: "f1", session_id: "s1", kind: "question", title: "Pick", fields: [] }; let thread = newChatThread("s1"); thread = applyChatEvent(thread, { kind: "form", session_id: "s1", form }, 1); assert.equal(thread.form?.id, "f1"); assert.equal(thread.form?.title, "Pick"); // A different form replaces the card; the old id cannot revive. thread = applyChatForm(thread, { id: "f2", session_id: "s1", title: "Next" }); assert.equal(thread.form?.id, "f2"); thread = applyChatForm(thread, { id: "f1", session_id: "s1", resolved: true }); assert.equal(thread.form?.id, "f2"); thread = applyChatForm(thread, { id: "f2", session_id: "s1", resolved: true }); assert.equal(thread.form?.id, "f2"); assert.equal(thread.form?.resolved, true); thread = applyChatForm(thread, { id: "f2", session_id: "s1", cancelled: true }); assert.equal(thread.form, null); });