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
+932
View File
@@ -185,9 +185,60 @@ import {
retryDialogTitle,
retryRequestKey,
} from "./actions.js";
import {
CHAT_EMPTY,
CHAT_FOLLOW_THRESHOLD_PX,
CHAT_LOADING,
CHAT_NEW_ACTION,
CHAT_NO_MATCH_ACTION,
CHAT_SEARCH_LABEL,
CHAT_TAB_TITLE,
CLOSED_CHIP_LABEL,
CLOSED_SECTION_LABEL,
CLOSE_CHAT_ACTION,
CLOSE_CHAT_CONFIRM,
CLOSE_CHAT_DISMISS,
CLOSE_CHAT_TITLE,
CONVERSATION_EMPTY,
CONVERSATION_LOADING,
LOAD_OLDER_ACTION,
REOPEN_ACTION,
SELECT_CHAT_HINT,
chatBottomDistancePx,
chatFirstScroll,
chatFollowsAt,
chatHeaderMeta,
chatNoMatchMessage,
chatOpensAtNewest,
chatShowJumpToLatest,
closeChatConfirmation,
directoryLabel,
filterSessions,
groupSessionsByDirectory,
mergeHistoryPage,
reasoningLabel,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
sessionMeta,
sessionStatusLabel,
sessionTitle,
sessionWorkLabel,
toolCallsLabel,
transcriptRows,
} from "./chat.js";
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
/**
* The per-session chat scroll positions (C14). Persisted in localStorage, the
* browser analogue of the Android `ChatThread.scroll`: a position the operator
* deliberately left — including the very top — is restored, while an absent one
* opens the conversation at its newest message.
*/
const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1";
/** Shown where tiles exist but the configured server URL cannot resolve them. */
const ARTIFACT_SERVER_HINT =
"Set the server URL in Settings to open or copy artifact links.";
@@ -288,6 +339,37 @@ const state = {
renameValue: null,
renameBusy: false,
actionError: "",
// Chat (C1/C3/C4/C7/C14): the server's operator-session list and its load
// state, the operator's narrowing, one open thread per session id and the
// active one. The transcript is untrusted model output, so every server string
// is set with textContent and the markdown renderer builds DOM nodes, never
// innerHTML.
chatSessions: [],
chatLoading: false,
chatLoaded: false,
chatError: "",
chatQuery: "",
chatThreads: new Map(),
chatActiveId: null,
chatPlaced: null,
chatFollowing: true,
chatReasoning: new Set(),
chatScroll: readChatScrollStore(),
// The scroll restore across a prepended older page, the position captured
// from the live transcript just before a re-render (so a dialog, a refresh or
// the loading frame of a paging fetch never loses the operator's place), and
// the debounced save.
chatAnchor: null,
chatPending: null,
chatScrollTimer: null,
// True only while the operator's own gesture (wheel/pointer/touch) is the
// reason the transcript moved, so a programmatic placement or follow can never
// be mistaken for the operator leaving the bottom.
chatUserIntent: false,
// The session awaiting the Close chat? confirm, and the shared Action-failed
// report for a refused close/reopen.
chatClose: null,
chatBusy: false,
};
let runPoll = null;
@@ -498,6 +580,7 @@ function renderContent() {
tabButton("pipelines", `Pipelines (${state.pipelines.length})`),
tabButton("runs", `Runs (${state.runs.length})`),
tabButton("templates", "Templates"),
tabButton("chat", CHAT_TAB_TITLE),
h("span", { class: "spacer" }),
h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }),
),
@@ -508,11 +591,23 @@ function renderContent() {
split.append(renderPipelineList(), renderPipelineDetail());
} else if (state.view === "runs") {
split.append(renderRunList(), renderRunDetail());
} else if (state.view === "chat") {
split.append(renderChatList(), renderChatConversation());
} else {
split.append(renderTemplateGallery(), renderTemplateDetail());
}
nodes.push(split);
// Capture the live transcript's position before it is replaced, so the very
// next render can put the operator back exactly where they were (a dialog, a
// refresh or a paging frame must not move them).
captureChatPosition();
content.replaceChildren(...nodes);
if (state.view === "chat") {
afterChatRender();
stopListClock();
stopDetailClock();
return;
}
if (state.view === "runs") {
refreshListClock();
refreshDetailClock();
@@ -533,6 +628,7 @@ function tabButton(view, label) {
if (view === "runs" && !state.runs.length) loadCurrentView();
if (view === "pipelines" && !state.pipelines.length) loadCurrentView();
if (view === "templates" && !state.templates.length) loadCurrentView();
if (view === "chat" && !state.chatLoaded) loadCurrentView();
},
});
}
@@ -2808,6 +2904,833 @@ function kvMono(key, value) {
);
}
// ---------------------------------------------------------------------------
// Chat (C1 · C3 · C4 · C7 · C14)
// ---------------------------------------------------------------------------
/** The persisted per-session scroll positions, or an empty map when unreadable. */
function readChatScrollStore() {
try {
const parsed = JSON.parse(localStorage.getItem(CHAT_SCROLL_STORAGE_KEY) ?? "{}");
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
return {};
}
}
/** Remember one conversation's scroll position (index of the first visible row). */
function saveChatScroll(sessionId, position) {
if (!sessionId) return;
state.chatScroll[sessionId] = { index: position.index, offset: position.offset };
try {
localStorage.setItem(CHAT_SCROLL_STORAGE_KEY, JSON.stringify(state.chatScroll));
} catch {
// storage may be full or disabled; the in-memory position still holds
}
}
/**
* The pixels the transcript still sits above its end (0 when at the bottom), via
* the same pure decision the unit tests cover. `chatBottomDistancePx` measures
* from the last row's bottom edge to the viewport's bottom edge; the live
* analogue passes the last row as the last visible one.
*/
function transcriptDistance(el) {
if (!el) return null;
const rows = el.children;
const count = rows.length;
if (count === 0) return null;
const last = rows[count - 1];
return chatBottomDistancePx({
lastVisibleIndex: count - 1,
lastVisibleEndPx: last.offsetTop + last.offsetHeight,
itemCount: count,
viewportEndPx: el.scrollTop + el.clientHeight,
});
}
/**
* Remember the live transcript's position (and follow intent) just before a
* re-render replaces it, so `afterChatRender` can put the operator back exactly
* where they were. A no-op when no transcript is mounted.
*/
function captureChatPosition() {
const el = document.getElementById("chatTranscript");
if (!el || !el.dataset.session) return;
state.chatPending = {
sessionId: el.dataset.session,
position: currentChatPosition(el),
following: state.chatFollowing,
};
}
/** The first visible row's index and the pixels scrolled into it. */
function currentChatPosition(el) {
const rows = [...el.children];
let index = 0;
let offset = 0;
for (let i = 0; i < rows.length; i += 1) {
const row = rows[i];
if (row.offsetTop + row.offsetHeight > el.scrollTop + 1) {
index = i;
offset = Math.max(0, el.scrollTop - row.offsetTop);
break;
}
index = i;
}
return { index, offset };
}
/** The list of the server's operator sessions, narrowed by the search field. */
async function loadChatSessions(force = false) {
if (state.connection.kind !== "connected") {
state.chatError = "Connect to the server first.";
state.chatLoading = false;
renderContent();
return;
}
if (state.chatLoading) return;
state.chatLoading = true;
state.chatError = "";
renderContent();
try {
state.chatSessions = await repo.chatSessions();
state.chatLoaded = true;
} catch (error) {
state.chatError = describeError(error);
}
state.chatLoading = false;
renderContent();
}
/** Open a session: select it and load its newest history page. */
async function openChatSession(id) {
if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return;
// Remember where the operator left the conversation being closed.
const leaving = document.getElementById("chatTranscript");
if (leaving && state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(leaving));
state.chatActiveId = id;
state.chatPlaced = null;
state.chatFollowing = true;
state.chatReasoning = new Set();
const existing = state.chatThreads.get(id);
state.chatThreads.set(id, {
messages: existing?.messages ?? [],
nextCursor: existing?.nextCursor ?? "",
hasMore: existing?.hasMore ?? false,
loaded: false,
loading: true,
error: "",
});
renderContent();
await loadChatHistory(id);
}
/** Load (or reload) a session's newest history page and merge it in. */
async function loadChatHistory(id) {
const previous = state.chatThreads.get(id) ?? { messages: [] };
try {
const page = await repo.chatHistory(id);
state.chatThreads.set(id, mergeHistoryPage(previous, page, { older: false }));
} catch (error) {
state.chatThreads.set(id, {
...previous,
loading: false,
loaded: true,
error: describeError(error),
});
}
renderContent();
}
/**
* Fetch the next opaque older page. Only offered while the server reports
* `has_more`; the cursor is the server's own `next_cursor`, passed back verbatim
* and never interpreted. Nothing auto-loads on scroll.
*/
async function loadOlderChatHistory(id) {
const thread = state.chatThreads.get(id);
if (!thread?.hasMore || thread.loading) return;
const scroller = document.getElementById("chatTranscript");
state.chatAnchor = scroller
? { sessionId: id, scrollHeight: scroller.scrollHeight, scrollTop: scroller.scrollTop }
: null;
state.chatThreads.set(id, { ...thread, loading: true });
renderContent();
try {
const page = await repo.chatHistory(id, { cursor: thread.nextCursor });
const current = state.chatThreads.get(id) ?? thread;
state.chatThreads.set(id, mergeHistoryPage(current, page, { older: true }));
} catch (error) {
state.chatThreads.set(id, {
...(state.chatThreads.get(id) ?? thread),
loading: false,
error: describeError(error),
});
}
renderContent();
}
/** Open the Close chat? confirm for [session] (the mutation only on confirm). */
function openChatClose(session) {
state.chatClose = session;
renderContent();
}
function dismissChatClose() {
state.chatClose = null;
renderContent();
}
/**
* Run the confirmed close, then refresh the list from the server. The confirm is
* the only path that mutates the session; the dialog itself never sends.
*/
async function acceptChatClose(session) {
state.chatClose = null;
state.chatBusy = true;
renderContent();
try {
const { session: updated } = await repo.closeChat(session.id);
applyChatSessionUpdate(session.id, updated, true);
} catch (error) {
state.actionError = describeError(error);
}
state.chatBusy = false;
await loadChatSessions();
}
/** Clear a finished chat's closed state again, so it can be resumed. */
async function reopenChatSession(id) {
if (state.chatBusy) return;
state.chatBusy = true;
renderContent();
try {
const { session: updated } = await repo.reopenChat(id);
applyChatSessionUpdate(id, updated, false);
} catch (error) {
state.actionError = describeError(error);
}
state.chatBusy = false;
await loadChatSessions();
}
/** Apply the echoed session (or the local closed flag) to the held row. */
function applyChatSessionUpdate(id, updated, closed) {
state.chatSessions = state.chatSessions.map((session) =>
session.id === id ? { ...session, ...(updated ?? {}), closed } : session,
);
}
function renderChatList() {
const list = h("div", { class: "list chat-list" });
const toolbar = h("div", { class: "list-toolbar chat-toolbar" });
toolbar.append(
h("input", {
id: "chatSearch",
class: "chat-search",
type: "text",
placeholder: CHAT_SEARCH_LABEL,
"aria-label": CHAT_SEARCH_LABEL,
value: state.chatQuery,
spellcheck: "false",
autocomplete: "off",
oninput: (event) => {
state.chatQuery = event.target.value;
fillChatRows(rows);
},
}),
);
list.append(toolbar);
const rows = h("div", { id: "chatRows", class: "chat-rows" });
fillChatRows(rows);
list.append(rows);
return list;
}
/** The list body: the loading/error/empty states or the grouped session rows. */
function fillChatRows(rows) {
rows.replaceChildren();
if (state.chatLoading && state.chatSessions.length === 0 && !state.chatLoaded) {
rows.append(chatEmpty(CHAT_LOADING));
return;
}
if (state.chatError && state.chatSessions.length === 0) {
const empty = chatEmpty(state.chatError);
empty.append(
h("button", { class: "ghost", type: "button", text: "Retry", onclick: () => loadChatSessions(true) }),
);
rows.append(empty);
return;
}
const filtered = filterSessions(state.chatSessions, state.chatQuery);
if (filtered.length === 0 && state.chatQuery.trim() !== "") {
const empty = chatEmpty(chatNoMatchMessage(state.chatQuery));
empty.append(
h("button", {
class: "ghost",
type: "button",
text: CHAT_NO_MATCH_ACTION,
onclick: () => {
state.chatQuery = "";
renderContent();
},
}),
);
rows.append(empty);
return;
}
if (filtered.length === 0) {
// The create path is the C2 item; the action is shown but deliberately not
// wired here, exactly as the item says.
const empty = chatEmpty(CHAT_EMPTY);
empty.append(
h("button", {
class: "ghost chat-new",
type: "button",
text: CHAT_NEW_ACTION,
disabled: true,
title: "Creating a chat lands with the C2 item",
}),
);
rows.append(empty);
return;
}
const active = filtered.filter((session) => !session.closed);
const closed = filtered.filter((session) => session.closed);
const groups = groupSessionsByDirectory(active);
if (groups.length > 1) {
for (const group of groups) {
rows.append(h("div", { class: "chat-group-header", text: directoryLabel(group.directory) }));
for (const session of group.sessions) rows.append(renderChatRow(session));
}
} else {
for (const session of active) rows.append(renderChatRow(session));
}
if (closed.length > 0) {
rows.append(h("div", { class: "chat-group-header", text: CLOSED_SECTION_LABEL }));
for (const session of closed) rows.append(renderChatRow(session));
}
if (state.chatError) {
rows.append(h("div", { class: "chat-error muted", text: state.chatError }));
}
}
function chatEmpty(message) {
return h("div", { class: "empty" }, h("span", { class: "muted", text: message }));
}
/**
* One session row: title, kind chip, a Closed chip only when closed, the
* activity badge word, the work-label meta line and the close/reopen action.
* Every server string is set with textContent.
*/
function renderChatRow(session) {
const open = state.chatActiveId === session.id;
const thread = state.chatThreads.get(session.id) ?? null;
const activity = sessionActivity(thread?.running === true, false);
const badge = sessionActivityBadge(activity, open);
const row = h("div", {
class: `row chat-row${open ? " selected" : ""}`,
role: "button",
tabindex: "0",
"data-session": session.id,
onclick: () => openChatSession(session.id),
onkeydown: (event) => {
// Only the row itself opens on Enter/Space; a nested Close chat…/Reopen
// button handles its own keyboard activation (and must not double-fire).
if (event.target !== event.currentTarget) return;
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
openChatSession(session.id);
}
},
});
const head = h("div", { class: "row-head" });
head.append(h("span", { class: "row-title chat-row-title", text: sessionTitle(session) }));
const chip = sessionChipLabel(session);
if (chip) head.append(h("span", { class: "chip chat-kind-chip", text: chip }));
if (session.closed) head.append(h("span", { class: "chip chat-closed-chip", text: CLOSED_CHIP_LABEL }));
if (badge) {
head.append(
h("span", { class: `chat-activity chat-activity-${activity}` },
h("span", { class: "chat-activity-dot", "aria-hidden": "true" }),
h("span", { class: "chat-activity-word", text: badge }),
),
);
}
row.append(head);
row.append(
h("span", {
class: "row-meta chat-row-meta",
text: sessionMeta(session, sessionWorkLabel(session.busy === true, thread)),
}),
);
const actions = h("div", { class: "chat-row-actions" });
if (session.closed) {
actions.append(
h("button", {
class: "ghost chat-reopen",
type: "button",
text: REOPEN_ACTION,
disabled: state.chatBusy,
onclick: (event) => {
event.stopPropagation();
reopenChatSession(session.id);
},
}),
);
} else {
actions.append(
h("button", {
class: "ghost chat-close",
type: "button",
text: CLOSE_CHAT_ACTION,
disabled: state.chatBusy,
onclick: (event) => {
event.stopPropagation();
openChatClose(session);
},
}),
);
}
row.append(actions);
return row;
}
/** The active conversation: identity, context, transcript and its controls. */
function renderChatConversation() {
const pane = h("div", { class: "detail chat-detail" });
if (!state.chatActiveId) {
pane.append(chatEmpty(SELECT_CHAT_HINT));
appendChatDialogs(pane);
return pane;
}
const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null;
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
const title = session ? sessionTitle(session) : state.chatActiveId.slice(0, 18);
const bar = h("div", { class: "chat-bar" });
const titles = h("div", { class: "chat-bar-titles" });
titles.append(h("h2", { class: "chat-bar-title", text: title }));
const meta = chatHeaderMeta({
model: session?.model,
tag: session?.tag,
directory: session?.directory,
});
if (meta !== "") titles.append(h("div", { class: "chat-bar-meta muted", text: meta }));
bar.append(titles);
if (thread?.hasMore) {
bar.append(
h("button", {
class: "ghost chat-load-older",
type: "button",
text: LOAD_OLDER_ACTION,
disabled: thread.loading,
onclick: () => loadOlderChatHistory(state.chatActiveId),
}),
);
}
pane.append(bar);
// The context line: the kind chip, the activity word and directory · model.
const context = h("div", { class: "chat-context" });
const chip = session ? sessionChipLabel(session) : null;
if (chip) context.append(h("span", { class: "chip chat-kind-chip", text: chip }));
context.append(
h("span", {
class: "chat-context-activity",
text: sessionStatusLabel(thread?.running === true, session?.closed === true),
}),
);
const contextMeta = [session?.directory, session?.model]
.map((value) => String(value ?? "").trim())
.filter((value) => value !== "")
.join(" · ");
if (contextMeta !== "") context.append(h("span", { class: "chat-context-meta muted", text: contextMeta }));
pane.append(context);
if (thread?.loading && !thread?.loaded) {
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_LOADING }));
} else if (thread?.error && !thread?.loaded) {
const empty = chatEmpty(thread.error);
empty.append(
h("button", {
class: "ghost",
type: "button",
text: "Retry",
onclick: () => loadChatHistory(state.chatActiveId),
}),
);
pane.append(empty);
} else {
const rows = transcriptRows(thread?.messages ?? []);
if (rows.length === 0) {
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
} else {
pane.append(renderChatTranscript(state.chatActiveId, rows));
}
if (thread?.error && thread?.loaded) {
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
}
}
appendChatDialogs(pane);
return pane;
}
/**
* The chat overlays, appended to the conversation pane whether or not a
* conversation is open: the row's own `Close chat…` action is offered on every
* open row, so its confirm must appear even when no chat is selected.
*/
function appendChatDialogs(pane) {
if (state.chatClose) pane.append(renderChatCloseDialog(state.chatClose));
if (state.actionError) pane.append(renderActionFailedDialog());
}
/**
* The transcript: one column of turns. An operator message is its own
* right-aligned bubble (with the sending client's label when the server echoed
* one); consecutive assistant messages are one left-aligned agent bubble, drawn
* in order as the reasoning block, then the tool-call chip, then the answer
* markdown. No timestamps, model or agent are shown inside the transcript.
*/
function renderChatTranscript(sessionId, rows) {
const wrap = h("div", { class: "chat-transcript-wrap" });
const transcript = h("div", {
class: "chat-transcript",
id: "chatTranscript",
"data-session": sessionId,
});
for (const row of rows) {
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
else transcript.append(renderChatAgentTurn(row.turn));
}
wrap.append(transcript);
wrap.append(
h("button", {
class: "ghost chat-jump",
id: "chatJump",
type: "button",
text: "Jump to latest",
hidden: true,
onclick: () => {
state.chatFollowing = true;
const el = document.getElementById("chatTranscript");
if (el) el.scrollTop = el.scrollHeight;
updateChatJump(el);
},
}),
);
return wrap;
}
/** One operator turn, right-aligned, carrying its sender label when present. */
function renderChatUserMessage(message) {
const turn = h("div", { class: "chat-turn chat-turn-user" });
const bubble = h("div", { class: "chat-bubble user-bubble" });
const client = String(message?.client ?? "").trim();
if (client !== "") bubble.append(h("div", { class: "chat-client", text: message.client }));
const text = (message?.parts ?? [])
.filter((part) => part?.type === "text" || !part?.type)
.map((part) => String(part?.text ?? ""))
.join("\n")
.trim();
if (text !== "") bubble.append(h("div", { class: "chat-user-text", text }));
turn.append(bubble);
return turn;
}
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
function renderChatAgentTurn(turn) {
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
const bubble = h("div", { class: "chat-bubble agent-bubble" });
const steps = turn.reasoningSteps;
if (steps.length > 0) bubble.append(renderChatReasoning(turn));
if (turn.tools.length > 0) {
bubble.append(
h("div", { class: "chat-tools" }, h("span", { class: "chip chat-tool-chip", text: toolCallsLabel(turn.tools.length) })),
);
}
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
wrap.append(bubble);
return wrap;
}
/**
* The turn's one collapsible reasoning block. The open/closed state lives on the
* conversation keyed by the turn, so it survives a re-render; toggling it never
* rebuilds the transcript (and so never moves the operator's scroll).
*/
function renderChatReasoning(turn) {
const expanded = state.chatReasoning.has(turn.key);
const block = h("div", { class: "chat-reasoning" });
const toggle = h("button", {
class: "chat-reasoning-toggle",
type: "button",
"aria-expanded": String(expanded),
});
toggle.append(
h("span", { class: "chat-reasoning-icon", "aria-hidden": "true", text: expanded ? "\u25be" : "\u25b8" }),
);
toggle.append(h("span", { class: "chat-reasoning-label", text: reasoningLabel(turn.reasoningSteps.length) }));
const body = h("div", { class: "chat-reasoning-body", text: turn.reasoning });
body.hidden = !expanded;
toggle.addEventListener("click", () => {
const next = body.hidden;
body.hidden = !next;
toggle.setAttribute("aria-expanded", String(next));
toggle.querySelector(".chat-reasoning-icon").textContent = next ? "\u25be" : "\u25b8";
if (next) state.chatReasoning.add(turn.key);
else state.chatReasoning.delete(turn.key);
});
block.append(toggle, body);
return block;
}
/**
* Render assistant markdown by building DOM nodes, never by assigning innerHTML.
* Exported so the live UI smoke can exercise the page's own renderer for the
* fenced-code path the live transcript does not carry; the page itself calls it
* directly.
*/
export function renderMarkdown(text) {
const wrap = h("div", { class: "markdown" });
for (const block of parseMarkdown(text)) wrap.append(renderMarkdownBlock(block));
return wrap;
}
function renderMarkdownBlock(block) {
if (block.kind === "heading") {
const level = Math.min(Math.max(block.level, 1), 4) + 2; // h3..h6, never h1/h2
return h(`h${level}`, { class: "md-heading" }, ...renderInlineNodes(parseInline(block.text)));
}
if (block.kind === "paragraph") {
return h("p", { class: "md-paragraph" }, ...renderInlineNodes(parseInline(block.text)));
}
if (block.kind === "code") {
const code = h("div", { class: "md-code-block" });
code.append(h("div", { class: "md-code-label", text: codeBlockLabel(block.language) }));
code.append(h("pre", { class: "md-pre" }, h("code", { text: block.code })));
return code;
}
if (block.kind === "rule") return h("hr", { class: "md-rule" });
if (block.kind === "quote") {
const quote = h("blockquote", { class: "md-quote" });
for (const line of block.lines) {
if (line.trim() !== "") quote.append(h("p", {}, ...renderInlineNodes(parseInline(line))));
}
return quote;
}
if (block.kind === "list") {
const list = h(block.ordered ? "ol" : "ul", { class: "md-list" });
for (const item of block.items) {
list.append(h("li", {}, ...renderInlineNodes(parseInline(item))));
}
return list;
}
if (block.kind === "table") {
const table = h("table", { class: "md-table" });
const head = h("thead");
const headRow = h("tr");
for (const cell of block.header) headRow.append(h("th", {}, ...renderInlineNodes(parseInline(cell))));
head.append(headRow);
table.append(head);
const body = h("tbody");
for (const row of block.rows) {
const tr = h("tr");
for (const cell of row) tr.append(h("td", {}, ...renderInlineNodes(parseInline(cell))));
body.append(tr);
}
table.append(body);
return table;
}
// Anything outside the subset stays plain text and is never dropped.
return h("p", { class: "md-paragraph", text: block.text ?? "" });
}
function renderInlineNodes(spans) {
return (spans ?? []).map((span) => {
if (span.kind === "code") return h("code", { class: "md-code", text: span.text });
if (span.kind === "strong") return h("strong", {}, ...renderInlineNodes(span.spans));
if (span.kind === "emphasis") return h("em", {}, ...renderInlineNodes(span.spans));
if (span.kind === "link") {
// Only http(s) targets become links: the transcript is untrusted model
// output, so a javascript:/data: target is shown as its label, never made
// clickable. Nothing is dropped either way.
if (/^https?:\/\//i.test(span.url)) {
return h(
"a",
{ class: "md-link", href: span.url, rel: "noreferrer noopener", target: "_blank" },
...renderInlineNodes(span.spans),
);
}
return h("span", { class: "md-link-plain" }, ...renderInlineNodes(span.spans));
}
return document.createTextNode(String(span.text ?? ""));
});
}
/** The Close chat? confirm: the exact Android body naming the session title. */
function renderChatCloseDialog(session) {
const overlay = h("div", {
class: "confirm-dialog confirm-chat-close",
role: "dialog",
"aria-modal": "true",
"aria-label": CLOSE_CHAT_TITLE,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissChatClose();
});
const panel = h("div", { class: "confirm-panel" });
panel.append(h("h2", { class: "confirm-title", text: CLOSE_CHAT_TITLE }));
panel.append(
h("p", { class: "confirm-message", text: closeChatConfirmation(sessionTitle(session)) }),
);
const actions = h("div", { class: "confirm-actions" });
actions.append(
h("button", {
class: "ghost confirm-dismiss",
type: "button",
text: CLOSE_CHAT_DISMISS,
onclick: dismissChatClose,
}),
);
actions.append(
h("button", {
class: "confirm-accept confirm-close-chat",
type: "button",
text: CLOSE_CHAT_CONFIRM,
onclick: () => acceptChatClose(session),
}),
);
panel.append(actions);
overlay.append(panel);
return overlay;
}
/**
* Wire the freshly rendered transcript: restore the operator's saved position
* (or open at the newest message when they have none), preserve the visual
* position across a prepended older page, follow new content while following,
* and offer "Jump to latest" only when not following and something is below the
* fold. Only the operator's own wheel/drag changes that intent; nothing here ever
* auto-loads older history on scroll.
*/
function afterChatRender() {
const el = document.getElementById("chatTranscript");
if (!el) {
state.chatPending = null;
return;
}
const sessionId = el.dataset.session;
const itemCount = el.children.length;
const thread = state.chatThreads.get(sessionId) ?? null;
// The position captured from the previous render (if it was this session), and
// the paging anchor (if an older page is being fetched). Both are consumed once.
const pending = state.chatPending?.sessionId === sessionId ? state.chatPending : null;
state.chatPending = null;
const anchor = state.chatAnchor?.sessionId === sessionId ? state.chatAnchor : null;
// A re-render is not the operator's gesture: the intent flag is re-armed only
// by a wheel/drag on the transcript below.
state.chatUserIntent = false;
if (anchor && thread?.loading !== true) {
// The render that actually carries the prepended older page: keep the same
// message at the same place by the height the page added. The loading frame
// itself is skipped, so the anchor survives until the content arrives.
const delta = el.scrollHeight - anchor.scrollHeight;
el.scrollTop = anchor.scrollTop + Math.max(0, delta);
state.chatAnchor = null;
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
} else if (state.chatPlaced === sessionId) {
// A re-render of a conversation already placed (a dialog, a refresh, the
// loading frame of a paging fetch): put the operator back exactly where they
// were, so nothing they did not do moves their view.
const restore = pending ? pending.position : state.chatScroll[sessionId] ?? null;
const follow = pending ? pending.following : state.chatFollowing;
if (follow || restore == null) {
el.scrollTop = el.scrollHeight;
state.chatFollowing = true;
} else {
const first = chatFirstScroll(restore, itemCount);
const row = el.children[first.index];
el.scrollTop = row ? row.offsetTop + first.offset : el.scrollHeight;
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
}
} else {
const saved = state.chatScroll[sessionId] ?? null;
if (chatOpensAtNewest(saved)) {
// No position of the operator's own: land on the newest content instantly —
// the end of the transcript, so a last turn taller than the viewport opens
// at its newest part rather than its first — and follow.
el.scrollTop = el.scrollHeight;
state.chatFollowing = true;
} else {
const first = chatFirstScroll(saved, itemCount);
const row = el.children[first.index];
el.scrollTop = row ? row.offsetTop + first.offset : el.scrollHeight;
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
}
state.chatPlaced = sessionId;
}
// Only a scroll that happens during the operator's own gesture (a wheel, or a
// pointer/touch press that is still down) is theirs; a programmatic placement,
// follow or anchor restore never changes the intent. A plain click that never
// scrolls therefore leaves the intent alone.
let gesture = false;
const beginGesture = () => {
gesture = true;
};
const endGesture = () => {
gesture = false;
};
el.addEventListener("wheel", () => {
state.chatUserIntent = true;
state.chatFollowing = false;
updateChatJump(el);
});
el.addEventListener("pointerdown", beginGesture);
el.addEventListener("pointerup", endGesture);
el.addEventListener("pointercancel", endGesture);
el.addEventListener("touchstart", beginGesture, { passive: true });
el.addEventListener("touchend", endGesture);
el.addEventListener("touchcancel", endGesture);
el.addEventListener("scroll", () => {
if (state.chatUserIntent || gesture) {
state.chatUserIntent = true;
state.chatFollowing = chatFollowsAt(
transcriptDistance(el),
CHAT_FOLLOW_THRESHOLD_PX,
el.children.length,
);
}
updateChatJump(el);
clearTimeout(state.chatScrollTimer);
state.chatScrollTimer = setTimeout(() => {
if (state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(el));
}, 200);
});
updateChatJump(el);
}
/** Offer "Jump to latest" only when not following and something is below the fold. */
function updateChatJump(el) {
const jump = document.getElementById("chatJump");
if (!jump) return;
const count = el ? el.children.length : 0;
jump.hidden = !chatShowJumpToLatest(
state.chatFollowing,
transcriptDistance(el),
CHAT_FOLLOW_THRESHOLD_PX,
count,
);
}
// ---------------------------------------------------------------------------
// Omni-search (S1/S2)
// ---------------------------------------------------------------------------
@@ -3234,6 +4157,10 @@ async function loadCurrentView(force = false) {
await loadTemplates(force);
return;
}
if (state.view === "chat") {
await loadChatSessions(force);
return;
}
state.loading = true;
state.error = "";
renderContent();
@@ -3453,6 +4380,11 @@ document.addEventListener("keydown", (event) => {
dismissActionError();
return;
}
if (state.chatClose) {
event.preventDefault();
dismissChatClose();
return;
}
if (state.confirmKind) {
event.preventDefault();
dismissConfirm();
+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 };
}
+341
View File
@@ -0,0 +1,341 @@
// Pure, DOM-free CommonMark subset for assistant prose (C7), ported from the
// Android client's ui/chat/Markdown.kt so the browser renders exactly the same
// blocks and inline spans. The brokered protocol carries assistant text as
// markdown, and the reference experience renders it:
// paragraphs, `#`..`######` headings, fenced code (``` / ~~~, language label
// else `code`), block quotes, bullet and ordered lists, `|` tables with a
// `---` delimiter row, thematic rules, and inline code / bold / italic /
// links / bare http(s) autolinks.
//
// Anything outside the subset renders as plain text and is never dropped. There
// is deliberately no HTML, no reference links, no nested lists and no
// strikethrough — the same subset the app implements.
//
// The parser is pure (no DOM, no transport) so it is unit-testable; the caller
// turns the same blocks into text nodes with textContent, never innerHTML.
/**
* Decodes the HTML entities an assistant message can carry. The server's own
* session export escapes text with Go's `html.EscapeString`, so a message that
* quotes an export arrives with `&#x27;`, `&quot;`, `&amp;` and friends still in
* it. The common named entities plus numeric decimal and hex references are
* decoded; an unknown or malformed reference is left exactly as written so no
* visible text is invented. A single left-to-right pass never re-decodes an
* entity produced by decoding another (`&amp;lt;` stays `&lt;`).
*/
const NAMED_ENTITIES = {
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
nbsp: "\u00A0",
hellip: "\u2026",
mdash: "\u2014",
ndash: "\u2013",
lsquo: "\u2018",
rsquo: "\u2019",
ldquo: "\u201C",
rdquo: "\u201D",
};
const HTML_ENTITY = /&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g;
export function decodeHtmlEntities(text) {
if (!text.includes("&")) return text;
return text.replace(HTML_ENTITY, (match, body) => {
if (Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, body)) return NAMED_ENTITIES[body];
return numericReference(body) ?? match;
});
}
/** The character one numeric entity's body (`#27`/`#x1b`) names, or null. */
function numericReference(body) {
let codePoint = null;
if (body.startsWith("#x") || body.startsWith("#X")) {
if (/^#x[0-9A-Fa-f]+$/.test(body)) codePoint = parseInt(body.slice(2), 16);
} else if (body.startsWith("#")) {
if (/^#[0-9]+$/.test(body)) codePoint = parseInt(body.slice(1), 10);
}
if (codePoint == null || !Number.isFinite(codePoint)) return null;
if (codePoint < 1 || codePoint > 0x10ffff) return null;
return String.fromCodePoint(codePoint);
}
// ---- Blocks -----------------------------------------------------------------
/**
* Parses [source] into the block list the renderer walks. Never throws. Blocks:
* {kind:"heading", level, text} {kind:"paragraph", text}
* {kind:"code", language, code} {kind:"quote", lines}
* {kind:"list", ordered, items} {kind:"table", header, rows}
* {kind:"rule"}
*/
export function parseMarkdown(source) {
const lines = decodeHtmlEntities(String(source ?? ""))
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.split("\n");
const blocks = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
if (trimmed === "") {
i += 1;
continue;
}
const fence = fenceRun(trimmed);
if (fence != null) {
const language = trimmed.slice(fence.length).trim().split(" ")[0];
const code = [];
i += 1;
while (i < lines.length && fenceRun(lines[i].trim()) == null) {
code.push(lines[i]);
i += 1;
}
if (i < lines.length) i += 1; // consume the closing fence
blocks.push({ kind: "code", language, code: code.join("\n") });
continue;
}
const level = headingLevel(trimmed);
if (level > 0) {
blocks.push({ kind: "heading", level, text: trimEndHashes(trimmed.slice(level).trim()) });
i += 1;
continue;
}
if (isRule(trimmed)) {
blocks.push({ kind: "rule" });
i += 1;
continue;
}
if (trimmed.startsWith(">")) {
const quote = [];
while (i < lines.length && lines[i].trim().startsWith(">")) {
quote.push(lines[i].trim().replace(/^>/, "").replace(/^ /, "").replace(/\s+$/, ""));
i += 1;
}
blocks.push({ kind: "quote", lines: quote });
continue;
}
if (isTableStart(lines, i)) {
const header = splitRow(lines[i]);
i += 2; // header + delimiter row
const rows = [];
while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
rows.push(fitRow(splitRow(lines[i]), header.length));
i += 1;
}
blocks.push({ kind: "table", header, rows });
continue;
}
const marker = listMarker(line);
if (marker != null) {
const ordered = marker.ordered;
const items = [];
while (i < lines.length && listMarker(lines[i])?.ordered === ordered) {
items.push(listMarker(lines[i]).text);
i += 1;
}
blocks.push({ kind: "list", ordered, items });
continue;
}
const paragraph = [line.trim()];
i += 1;
while (i < lines.length && lines[i].trim() !== "" && !startsBlock(lines, i)) {
paragraph.push(lines[i].trim());
i += 1;
}
blocks.push({ kind: "paragraph", text: paragraph.join(" ") });
}
return blocks;
}
/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */
function fenceRun(trimmed) {
const first = trimmed[0];
if (first !== "`" && first !== "~") return null;
let run = "";
for (const char of trimmed) {
if (char !== first) break;
run += char;
}
return run.length >= 3 ? run : null;
}
function headingLevel(trimmed) {
let hashes = 0;
while (hashes < trimmed.length && trimmed[hashes] === "#") hashes += 1;
if (hashes === 0 || hashes > 6) return 0;
return trimmed.length === hashes || trimmed[hashes] === " " ? hashes : 0;
}
function trimEndHashes(text) {
return text.replace(/#+$/, "");
}
function isRule(trimmed) {
if (trimmed.length < 3) return false;
const first = trimmed[0];
if (!"-*_".includes(first)) return false;
for (const char of trimmed) if (char !== first) return false;
return true;
}
/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */
function isTableStart(lines, index) {
if (index + 1 >= lines.length || !lines[index].includes("|")) return false;
const delimiter = splitRow(lines[index + 1]);
if (delimiter.length === 0 || splitRow(lines[index]).length < 2) return false;
return delimiter.every(
(cell) => cell.length > 0 && [...cell].every((char) => char === "-" || char === ":") && cell.includes("-"),
);
}
/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */
function splitRow(line) {
return line
.trim()
.replace(/^\|/, "")
.replace(/\|$/, "")
.split("|")
.map((cell) => cell.replace(/\\\|/g, "|").trim());
}
function fitRow(row, size) {
return Array.from({ length: size }, (_, index) => row[index] ?? "");
}
const ORDERED_ITEM = /^(\d{1,9})[.)]\s+(.*)$/;
const BULLET_ITEM = /^([-*+])\s+(.*)$/;
/** The ordered flag and item text of a list line, or null for a non-item line. */
function listMarker(line) {
const trimmed = line.replace(/^\s+/, "");
const orderedMatch = ORDERED_ITEM.exec(trimmed);
if (orderedMatch) return { ordered: true, text: orderedMatch[2] };
const bulletMatch = BULLET_ITEM.exec(trimmed);
if (bulletMatch) return { ordered: false, text: bulletMatch[2] };
return null;
}
/** True when [lines] at [index] begins a block that must interrupt a paragraph. */
function startsBlock(lines, index) {
const trimmed = lines[index].trim();
return (
fenceRun(trimmed) != null ||
headingLevel(trimmed) > 0 ||
isRule(trimmed) ||
trimmed.startsWith(">") ||
listMarker(lines[index]) != null ||
isTableStart(lines, index)
);
}
// ---- Inline -----------------------------------------------------------------
const WORD_CHAR = /[\p{L}\p{N}]/u;
/**
* Parses inline markup in [text] into a flat span tree. Handles `` `code` ``,
* `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
* `http(s)://` autolinks; everything else stays plain text. Underscore emphasis
* requires word boundaries so `snake_case` is never italicised.
*/
export function parseInline(text) {
const source = String(text ?? "");
const spans = [];
let buffer = "";
let i = 0;
const flush = () => {
if (buffer.length > 0) {
spans.push({ kind: "plain", text: buffer });
buffer = "";
}
};
while (i < source.length) {
const c = source[i];
if (c === "`") {
const end = source.indexOf("`", i + 1);
if (end > i) {
flush();
spans.push({ kind: "code", text: source.slice(i + 1, end) });
i = end + 1;
} else {
buffer += c;
i += 1;
}
} else if (c === "*" || c === "_") {
const doubled = i + 1 < source.length && source[i + 1] === c;
const marker = doubled ? c + c : c;
const boundOk = c !== "_" || i === 0 || !WORD_CHAR.test(source[i - 1]);
const end = boundOk ? source.indexOf(marker, i + marker.length) : -1;
const closes =
end > i + marker.length &&
(c !== "_" || end + 1 >= source.length || !WORD_CHAR.test(source[end + 1]));
if (closes) {
flush();
const inner = parseInline(source.slice(i + marker.length, end));
spans.push(doubled ? { kind: "strong", spans: inner } : { kind: "emphasis", spans: inner });
i = end + marker.length;
} else {
buffer += c;
i += 1;
}
} else if (c === "[") {
const close = source.indexOf("]", i + 1);
if (close > i && close + 1 < source.length && source[close + 1] === "(") {
const urlEnd = source.indexOf(")", close + 2);
const url = urlEnd > close ? source.slice(close + 2, urlEnd).trim() : "";
if (url !== "") {
flush();
spans.push({ kind: "link", spans: parseInline(source.slice(i + 1, close)), url });
i = urlEnd + 1;
} else {
buffer += c;
i += 1;
}
} else {
buffer += c;
i += 1;
}
} else {
const url = autolinkAt(source, i);
if (url != null) {
flush();
spans.push({ kind: "link", spans: [{ kind: "plain", text: url }], url });
i += url.length;
} else {
buffer += c;
i += 1;
}
}
}
flush();
return spans;
}
/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */
function autolinkAt(text, index) {
if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null;
let end = index;
while (end < text.length && !/\s/.test(text[end]) && !"<>\"'".includes(text[end])) end += 1;
let url = text.slice(index, end);
while (url.length > 0 && ".,;:!?)]}".includes(url[url.length - 1])) url = url.slice(0, -1);
return url.length > "https://".length ? url : null;
}
/** The label a fenced code block shows: its language, or `code` when unnamed. */
export function codeBlockLabel(language) {
const value = String(language ?? "").trim();
return value === "" ? "code" : value;
}
+24
View File
@@ -34,10 +34,34 @@ export const Protocol = Object.freeze({
DECIDE_RUN: "decide_run",
SET_RUN_TITLE: "set_run_title",
// Brokered OpenCode chat (C1/C3/C4), mirroring internal/protocol/chat.go and
// Message.kt. The session-scoped commands carry their body in `chat_query`;
// the list replies in `chat_sessions`, history in `chat_history` (an opaque
// `next_cursor` + `has_more`) and a close/reopen echoes the updated session in
// `chat_session` (with the `chat_close` outcome alongside).
CHAT_SESSIONS: "chat_sessions",
CHAT_MESSAGES: "chat_messages",
CHAT_CLOSE: "chat_close",
CHAT_REOPEN: "chat_reopen",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
});
/**
* The envelope field names the chat commands read and write
* (internal/protocol/message.go). Kept beside the command constants so a rename
* in the Go envelope cannot drift silently.
*/
export const ChatKeys = Object.freeze({
SESSIONS: "chat_sessions",
SESSION: "chat_session",
QUERY: "chat_query",
HISTORY: "chat_history",
MESSAGES: "chat_messages",
CLOSE: "chat_close",
});
/**
* The integer wire protocol this page speaks. Mirrors `ProtocolVersion` in
* internal/protocol/identity.go and the value the Android client compares in
+67 -1
View File
@@ -1,9 +1,12 @@
// Typed access to the existing WebSocket protocol. Request builders and id
// matching live here so the app never constructs frames by hand or invents
// divergent field names. Mirrors android/.../data/PipelinesRepository.kt.
import { Protocol } from "./protocol.js";
import { ChatKeys, Protocol } from "./protocol.js";
import { ProtocolError } from "./client.js";
/** The server default history page the app asks for (CHAT_HISTORY_LIMIT, 200). */
export const CHAT_HISTORY_LIMIT = 200;
export class PipelinesRepository {
#client;
@@ -153,4 +156,67 @@ export class PipelinesRepository {
}
return response.run_detail;
}
// ---- Brokered OpenCode chat (C1/C3/C4) -----------------------------------
// The browser never speaks OpenCode directly and never holds its credentials;
// it talks only to the Pipelines server. Mirrors PipelinesRepository.chat*.
/**
* Lists the sessions this server owns. The server already returns operator
* sessions only, so the app never filters the list by ownership.
*/
async chatSessions() {
return (await this.#client.call({ type: Protocol.CHAT_SESSIONS }))[ChatKeys.SESSIONS] ?? [];
}
/**
* Loads a bounded chronological history page. `cursor` is the opaque
* continuation the server returned as `next_cursor`; it is passed back
* verbatim and never interpreted. The reply is `chat_history`
* (`{messages,next_cursor,has_more}`); an older server that only knows
* `chat_messages` exposes no continuation, so the page is that list with
* `hasMore:false` and an empty cursor — exactly like
* PipelinesRepository.chatMessages.
*/
async chatHistory(sessionId, { limit = CHAT_HISTORY_LIMIT, cursor = "" } = {}) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_MESSAGES,
[ChatKeys.QUERY]: { session_id: sessionId, limit, cursor },
});
const page = response[ChatKeys.HISTORY];
if (page) {
return {
messages: page.messages ?? [],
nextCursor: page.next_cursor ?? "",
hasMore: Boolean(page.has_more),
};
}
return { messages: response[ChatKeys.MESSAGES] ?? [], nextCursor: "", hasMore: false };
}
/**
* Finishes a session and records it closed on the server (nothing is
* deleted). The reply echoes the updated session (`chat_session`) and the
* close outcome (`chat_close`: the id, the close time and whether an
* in-flight turn was interrupted).
*/
async closeChat(sessionId) {
const response = await this.#client.call({
type: Protocol.CHAT_CLOSE,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null };
}
/** Clears the closed state again, so a finished chat can be resumed. */
async reopenChat(sessionId) {
const response = await this.#client.call({
type: Protocol.CHAT_REOPEN,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null };
}
}