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

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

Request builders in src/repository.js; pure merge/format/markdown/paging
logic in src/chat.js and src/markdown.js; view in app.js. Every server
string set with textContent, markdown built as DOM nodes.
This commit is contained in:
2026-10-19 05:39:29 +01:00
parent 3d98c60de6
commit 0688127253
10 changed files with 2863 additions and 6 deletions
+472
View File
@@ -0,0 +1,472 @@
// Pure, DOM-free logic for the browser client's chat surface (C1/C3/C4/C7/C14).
// Ported from the Android client so the browser shows exactly the same words and
// makes exactly the same decisions:
// ui/chat/ChatFormat.kt sessionTitle, sessionTagLabel, sessionWorkLabel,
// sessionMeta, sessionActivity, sessionStatusLabel,
// chatHeaderMeta, transcriptRows, ChatTurn,
// partRendering, closeChatConfirmation
// ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions,
// groupChatSessionsByDirectory
// ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt,
// chatShowJumpToLatest, chatOpensAtNewest,
// chatFirstScroll
// ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an
// older page, replace nextCursor/hasMore)
//
// Nothing here touches the DOM or imports the app: every wording and decision is
// unit-tested without a browser. The caller sets each server string with
// textContent, never innerHTML.
/** ChatMessage.Role values (internal/protocol/chat.go). */
export const ROLE_USER = "user";
export const ROLE_ASSISTANT = "assistant";
/** ChatPart.Type values. */
export const PART_TEXT = "text";
export const PART_REASONING = "reasoning";
export const PART_TOOL = "tool";
/** ChatSession.Tag values, and the one display label derived from them. */
export const TAG_OPERATOR = "operator";
export const OPERATOR_TAG_LABEL = "Operator";
/** The row chip and the section heading for a chat the operator finished with. */
export const CLOSED_CHIP_LABEL = "Closed";
export const CLOSED_SECTION_LABEL = "Closed";
/** The section heading for sessions the server reported without a directory. */
export const NO_DIRECTORY_LABEL = "No directory";
/** The fallback title, when a session has neither a title nor an id. */
export const UNTITLED_TITLE = "Untitled chat";
/** How long a session id is truncated to when a session has no title. */
export const SESSION_ID_TITLE_LENGTH = 18;
/** The pixels within which the transcript still counts as at the bottom. */
export const CHAT_FOLLOW_THRESHOLD_PX = 32;
/** The reasoning block's settled label, and its multi-step form. */
export const REASONING_LABEL = "Reasoning";
export function reasoningLabel(count) {
return count > 1 ? `${REASONING_LABEL} · ${count} steps` : REASONING_LABEL;
}
// ---------------------------------------------------------------------------
// Wording (ChatListPane.kt / ChatConversationPane.kt / ChatFormat.kt), verbatim
// ---------------------------------------------------------------------------
export const CHAT_TAB_TITLE = "Chat";
export const CHAT_LOADING = "Loading chats…";
export const CHAT_EMPTY = "No chat sessions on this server yet.";
export const CHAT_NEW_ACTION = "New chat";
export const CHAT_NO_MATCH_ACTION = "Clear search";
export const CHAT_SEARCH_LABEL = "Search chats";
export const CLOSE_CHAT_ACTION = "Close chat…";
export const CLOSE_CHAT_TITLE = "Close chat?";
export const CLOSE_CHAT_CONFIRM = "Close chat";
export const CLOSE_CHAT_DISMISS = "Cancel";
export const REOPEN_ACTION = "Reopen";
export const CONVERSATION_LOADING = "Loading conversation…";
export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something below.";
export const LOAD_OLDER_ACTION = "Load older messages";
export const SELECT_CHAT_HINT = "Select a chat to open it.";
/** The listing's narrowed-to-nothing message: `No chats match "{query}".` */
export function chatNoMatchMessage(query) {
return `No chats match "${str(query).trim()}".`;
}
/** A blank-safe string read of a wire value. */
function str(value) {
return value == null ? "" : String(value);
}
function isBlank(value) {
return str(value).trim() === "";
}
// ---------------------------------------------------------------------------
// Session identity (ChatFormat.kt)
// ---------------------------------------------------------------------------
/**
* A session's short title: the server title, or a truncated id when untitled, so
* a row never renders as a blank line.
*/
export function sessionTitle(session) {
const title = str(session?.title);
if (!isBlank(title)) return title;
const short = str(session?.id).slice(0, SESSION_ID_TITLE_LENGTH);
if (!isBlank(short)) return short;
return UNTITLED_TITLE;
}
/**
* The kind chip label for a session's own tag: an `operator` tag reads
* `Operator`, any other tag is shown verbatim (a kind this client does not know
* is never silently dropped) and a blank tag shows no chip.
*/
export function sessionTagLabel(tag) {
const value = str(tag);
if (isBlank(value)) return null;
return value === TAG_OPERATOR ? OPERATOR_TAG_LABEL : value;
}
/** The chip label for a session, from its own tag (see [sessionTagLabel]). */
export function sessionChipLabel(session) {
return sessionTagLabel(session?.tag);
}
/** The chip label for a tool call: its name, or `tool` when unnamed. */
export function toolLabel(part) {
const name = str(part?.name);
return isBlank(name) ? "tool" : name;
}
/**
* A turn's one summary chip: `N tools called`, and `1 tool called` for a single
* call — a count of one is never pluralised.
*/
export function toolCallsLabel(count) {
return count === 1 ? "1 tool called" : `${count} tools called`;
}
/** True while [part] is a tool call the stream still reports as running. */
export function toolRunning(part) {
return part?.type === PART_TOOL && str(part?.state?.status) === "running";
}
/** The tool calls of [parts] that are still in flight, in transcript order. */
export function runningTools(parts) {
return (parts ?? []).filter((part) => toolRunning(part));
}
/**
* The status a session row reports while a turn is in flight: it names the tool
* call it is parked on (or how many, when several run at once), so a working chat
* says what it is doing rather than just `Running`; a chat only generating text
* still reads as plain `Running`. A chat with nothing running falls back to the
* ordinary busy/idle label.
*/
export function sessionWorkLabel(busy, thread) {
if (thread?.running) return runningSessionLabel(thread.runningTools ?? []);
if (busy) return "Busy · read-only";
return "Idle";
}
function runningSessionLabel(tools) {
if (tools.length === 0) return "Running";
if (tools.length === 1) return `Running ${toolLabel(tools[0])}`;
return `Running ${tools.length} tools`;
}
/** The one-line meta under a session row's title: work label · directory · model. */
export function sessionMeta(session, workLabel) {
const parts = [];
if (!isBlank(workLabel)) parts.push(str(workLabel));
if (!isBlank(session?.directory)) parts.push(str(session.directory));
if (!isBlank(session?.model)) parts.push(str(session.model));
return parts.join(" · ");
}
/**
* The one-line meta under a conversation's own title: the model the server
* reports is answering, the session's kind tag and its directory. Every part is a
* value the server reported; a blank part is omitted.
*/
export function chatHeaderMeta(thread) {
const parts = [];
if (!isBlank(thread?.model)) parts.push(str(thread.model));
const tag = sessionTagLabel(thread?.tag);
if (tag != null) parts.push(tag);
if (!isBlank(thread?.directory)) parts.push(str(thread.directory));
return parts.join(" · ");
}
/**
* The activity a session row signals beyond its open/tag/directory state:
* `streaming` (a turn producing a reply now), `new` (finished since last read),
* or `idle`.
*/
export function sessionActivity(running, unseen) {
if (running) return "streaming";
if (unseen) return "new";
return "idle";
}
/**
* The activity badge word, or null when the row shows none. An idle session
* shows `Open` only while its conversation is open; a streaming or unseen one
* always shows its word.
*/
export function sessionActivityBadge(activity, open) {
if (activity === "streaming") return "Streaming";
if (activity === "new") return "New";
if (activity === "idle" && open) return "Open";
return null;
}
/**
* The status a conversation header shows: a closed session reads `Closed` first,
* otherwise `Running` while this client has a turn in flight, else `Idle`.
*/
export function sessionStatusLabel(runningLocally, closed = false) {
if (closed) return "Closed";
if (runningLocally) return "Running";
return "Idle";
}
/**
* The close confirmation's body: it says exactly what closing does — stops a
* running turn, marks the chat closed on every device — and what it does not do:
* nothing is deleted, the chat and its history are kept and can be reopened.
* Kept pure so the confirmation wording and its unit test share one string.
*/
export function closeChatConfirmation(title) {
return (
`Closes "${title}" 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."
);
}
// ---------------------------------------------------------------------------
// Session narrowing and grouping (ChatListFilter.kt)
// ---------------------------------------------------------------------------
/**
* Whether [session] matches [query]: a case-insensitive substring over the
* session's title or its directory. A blank query matches everything.
*/
export function sessionMatchesQuery(session, query) {
const needle = str(query).trim();
if (needle === "") return true;
const haystack = `${sessionTitle(session)}\u0000${str(session?.directory)}`.toLowerCase();
return haystack.includes(needle.toLowerCase());
}
/**
* Narrows [sessions] to those matching [query] over their title and directory. A
* blank query changes nothing, and the surviving sessions keep their original
* relative order, so a narrowing never re-sorts.
*/
export function filterSessions(sessions, query) {
const list = sessions ?? [];
if (isBlank(query)) return list;
return list.filter((session) => sessionMatchesQuery(session, query));
}
/**
* Groups [sessions] by directory so sessions in the same repository sit together.
* The sessions keep their incoming recency order (within each group), and the
* groups are ordered by the first session they contain, so the top of the list
* still leads with the newest activity. A blank directory is its own group.
*/
export function groupSessionsByDirectory(sessions) {
const list = sessions ?? [];
if (list.length === 0) return [];
const order = new Map();
for (const session of list) {
const directory = str(session?.directory);
if (!order.has(directory)) order.set(directory, []);
order.get(directory).push(session);
}
return [...order.entries()].map(([directory, grouped]) => ({ directory, sessions: grouped }));
}
/** The visible label of a directory group header. */
export function directoryLabel(directory) {
return isBlank(directory) ? NO_DIRECTORY_LABEL : str(directory);
}
// ---------------------------------------------------------------------------
// Transcript (ChatFormat.kt)
// ---------------------------------------------------------------------------
/**
* How the transcript renders one part: assistant text is markdown, reasoning
* feeds the turn's one folded block, any other part with text is plain, and an
* empty part renders nothing.
*/
export function partRendering(part) {
if (part?.type === PART_TEXT && !isBlank(part?.text)) return "markdown";
if (part?.type === PART_REASONING && !isBlank(part?.text)) return "reasoning";
if (!isBlank(part?.text)) return "plain";
return "hidden";
}
/**
* One agent reply: everything the agent produced between two of the operator's
* messages, however many model steps that took. `key` is the first assistant
* message's id, so a reply stays one stable turn as it grows.
*/
export class ChatTurn {
constructor(key, parts = []) {
this.key = key;
this.parts = parts;
}
/** The turn's reasoning, steps in order. */
get reasoningSteps() {
return this.parts
.filter((part) => part?.type === PART_REASONING && !isBlank(part.text))
.map((part) => part.text);
}
/** The turn's reasoning as its one block reads it, steps joined by a blank line. */
get reasoning() {
return this.reasoningSteps.join("\n\n");
}
/** The turn's tool calls, in the order the agent made them. */
get tools() {
return this.parts.filter((part) => part?.type === PART_TOOL);
}
/**
* The turn's answer: just its text (and any other non-tool, non-reasoning)
* parts, joined in order. Reasoning feeds the folded block and a tool call its
* chip, so the answer never carries thinking or a command.
*/
get answer() {
return this.parts
.filter((part) => part?.type !== PART_TOOL && partRendering(part) !== "reasoning")
.map((part) => str(part?.text))
.filter((text) => text.trim() !== "")
.join("\n\n");
}
/** Whether the turn has anything to draw; an empty turn renders no bubble. */
get visible() {
return this.reasoningSteps.length > 0 || this.tools.length > 0 || this.answer.trim() !== "";
}
}
/**
* The transcript's rows for [messages]: each run of consecutive assistant
* messages folds into one `{kind:"agent", key, turn}`, and each of the operator's
* own messages is its own `{kind:"user", key, message}`. An assistant run with
* nothing to draw produces no row.
*/
export function transcriptRows(messages) {
const rows = [];
let turnKey = null;
let parts = [];
const flush = () => {
if (turnKey != null) {
const turn = new ChatTurn(turnKey, parts);
if (turn.visible) rows.push({ kind: "agent", key: turnKey, turn });
}
turnKey = null;
parts = [];
};
for (const message of messages ?? []) {
if (message?.role === ROLE_ASSISTANT) {
if (turnKey == null) turnKey = message.id;
parts.push(...(message.parts ?? []));
} else {
flush();
rows.push({ kind: "user", key: message?.id, message });
}
}
flush();
return rows;
}
// ---------------------------------------------------------------------------
// History paging (ChatStore.kt)
// ---------------------------------------------------------------------------
/**
* Merges an authoritative history page with the turns already held. The result
* is one ordered, id-deduplicated list; the page's own copy wins for an id it
* carries, which is what keeps a refreshed turn authoritative without moving it.
*
* An older page (the operator pressed "Load older") is prepended before
* everything held; a newest page keeps the turns already held in front of it, so
* turns loaded from an older page stay older. `nextCursor`, `hasMore`, `loaded`
* and `loading` are replaced from the page, never merged.
*/
export function mergeHistoryPage(previous, page, { older = false } = {}) {
const held = previous?.messages ?? [];
const incoming = page?.messages ?? [];
const incomingById = new Map();
for (const message of incoming) {
if (message?.id != null) incomingById.set(message.id, message);
}
const combined = older ? [...incoming, ...held] : [...held, ...incoming];
const seen = new Set();
const messages = [];
for (const message of combined) {
const id = message?.id;
if (id == null || seen.has(id)) continue;
seen.add(id);
messages.push(incomingById.has(id) ? incomingById.get(id) : message);
}
return {
messages,
nextCursor: str(page?.nextCursor),
hasMore: Boolean(page?.hasMore),
loaded: true,
loading: false,
};
}
// ---------------------------------------------------------------------------
// Scroll behaviour (ChatScroll.kt)
// ---------------------------------------------------------------------------
/**
* The pixels the end of the transcript still sits below the viewport's bottom
* edge, or null when the viewport does not show the last item at all or the list
* has not been measured yet. A value of 0 means the end is in view.
*/
export function chatBottomDistancePx({ lastVisibleIndex, lastVisibleEndPx, itemCount, viewportEndPx }) {
if (itemCount <= 0 || lastVisibleIndex !== itemCount - 1) return null;
return Math.max(0, lastVisibleEndPx - viewportEndPx);
}
/**
* Whether the view sits at the bottom: the end is in view and within
* [thresholdPx] of the bottom edge.
*/
export function chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount) {
return itemCount > 0 && distanceFromBottomPx != null && distanceFromBottomPx <= thresholdPx;
}
/**
* Whether the jump-to-latest affordance is offered: only while the transcript is
* not following and there is genuinely something below the fold to return to.
* Never shown for an empty transcript.
*/
export function chatShowJumpToLatest(following, distanceFromBottomPx, thresholdPx, itemCount) {
return !following && itemCount > 0 && !chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount);
}
/**
* Whether opening a conversation should land on its newest message: only when
* the operator has no position of their own there yet (a null [saved]). A
* position they deliberately left — including the very top, `{index:0,offset:0}`
* — is restored instead.
*/
export function chatOpensAtNewest(saved) {
return saved == null;
}
/**
* The position a conversation's transcript is placed at when it first shows: the
* newest message for a conversation with no position of the operator's own,
* otherwise the position they left, clamped to the messages that still exist. The
* saved pixel offset is kept only when the saved item itself survived.
*/
export function chatFirstScroll(saved, itemCount) {
if (itemCount <= 0) return { index: 0, offset: 0 };
if (saved == null) return { index: itemCount - 1, offset: 0 };
const rawIndex = Number(saved.index) || 0;
const index = Math.min(Math.max(rawIndex, 0), itemCount - 1);
const offset = index === rawIndex ? Number(saved.offset) || 0 : 0;
return { index, offset };
}