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:
+17
-5
@@ -88,20 +88,32 @@ the pipeline list already carries — rather than a pluralised verb.
|
||||
## Chat
|
||||
| # | Feature | Protocol | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| C1 | Session list (operator sessions, closed grouped as history) | `chat_sessions` | todo |
|
||||
| C1 | Session list (operator sessions, closed grouped as history) | `chat_sessions` | done — captured 2026-10-19: `captures/44-chat-sessions.png` (the live server's one operator session: "New chat", the `Operator` kind chip, the meta line `Idle · /Users/alan/repos/pipelines` and a `Close chat…` row action) and `captures/50-chat-no-match.png` (the narrowed-to-nothing state `No chats match "zzz-no-such-chat".` with its `Clear search` action). A row is the title (`sessionTitle`: the server title, else the id's first 18 characters, else `Untitled chat`), the kind chip derived from the server tag (`operator` → `Operator`, any other tag verbatim, a blank tag no chip), a `Closed` chip only when closed, the activity badge word (`Streaming` / `New` / `Open`, `Open` only while its conversation is open), and meta = work label · directory · model with blanks omitted (`Running` / `Running {tool}` / `Running {N} tools` while a turn is in flight, else `Busy · read-only`, else `Idle`). Active sessions are grouped by directory only when there is more than one group (header = the directory or `No directory`); closed sessions sit below under a `Closed` header, each reopenable. The search field is labelled `Search chats` and narrows by title or directory, case-insensitively, never re-sorting; the empties are `Loading chats…`, `No chat sessions on this server yet.` with a `New chat` action placeholder (wired by C2) and `No chats match "{query}".` with `Clear search`. The `Loading chats…` and `No chat sessions on this server yet.`/`New chat` states are implemented but not captured: the live server always lists its one operator session, so neither state is reachable against it |
|
||||
| C2 | Create a chat (directory picker) | `chat_directories`, `chat_create` | todo |
|
||||
| C3 | Open / close / reopen a session | `chat_close`, `chat_reopen` | todo |
|
||||
| C4 | History with paging / "load older" | `chat_messages` | todo |
|
||||
| C3 | Open / close / reopen a session | `chat_close`, `chat_reopen` | done — captured 2026-10-19: `captures/49-chat-close-confirm.png`. Selecting a row opens the conversation (see C4); an open row offers `Close chat…` and a closed row offers `Reopen`. The confirm is the Android copy verbatim: title `Close chat?`, the body naming the session title (`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.`), confirm `Close chat`, dismiss `Cancel`; only the confirm sends `chat_close` (and `Reopen` sends `chat_reopen`), then the list is refreshed from the server. The `Close chat…` action is offered on every open row, so its confirm is rendered from the pane's overlays **whether or not a conversation is open** — the smoke exercises the row-level path with no session selected (`ui-smoke` asserts the confirm appears and dismisses it), not only the path after opening the row. **Shown, not executed**: the live server has exactly one session — `ses_eae413f50ffeLQDExlg8cYnscN`, the operator's own — so the dialog was shown, captured and dismissed with `Cancel`; **no `chat_close` was sent** and that session was not closed or reopened by this stage |
|
||||
| C4 | History with paging / "load older" | `chat_messages` | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the opened `ses_eae413f50ffeLQDExlg8cYnscN` transcript with the `Load older messages` control beside the conversation's identity while the server reports `has_more`) and `captures/48-chat-load-older-empty.png` (after pressing it: the live session's own opaque cursor returned an empty older page, so `has_more` went false and the control disappeared — the honest result of the server's cursor, distinct from 45). The request is exactly `{type:"chat_messages",chat_query:{session_id,limit:200,cursor}}`; the newest page is read with an empty cursor and an older page with the server's own opaque `next_cursor` passed back verbatim (never interpreted), and the reply is `chat_history.{messages,next_cursor,has_more}` with an older server's bare `chat_messages` falling back to `hasMore:false`. `mergeHistoryPage` prepends an older page, dedupes by id (order-preserving, the page's copy winning) and replaces `nextCursor`/`hasMore`; the prepend itself is unit-tested (`test/chat.test.mjs`) because the live server returned no older rows. Nothing auto-loads on scroll and there is no end-of-history row |
|
||||
| C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | todo |
|
||||
| C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | todo |
|
||||
| C7 | Markdown rendering + code blocks | — | todo |
|
||||
| C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `<pre>` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link |
|
||||
| C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | todo |
|
||||
| C9 | Slash commands | client-side | todo |
|
||||
| C10 | Permission/approval cards (allow once/always/reject) | `chat_permission`, `chat_reply` | todo |
|
||||
| C11 | Background tasks bar: running shells only, capped + scrollable, bounded output page | `chat_shells`, `chat_shell_output` | todo |
|
||||
| C12 | Human-decision notices inside chat + dismiss | `chat_event` | todo |
|
||||
| C13 | Local rename/hide, seen state, persistence to `localStorage` | client-side | todo |
|
||||
| C14 | Scroll behaviour: follow newest, "jump to newest", restored position | client-side | todo |
|
||||
| C14 | Scroll behaviour: follow newest, "jump to newest", restored position | client-side | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the conversation opens at its newest content instantly — the only live session has no saved position, so it lands at the end rather than at the top of a turn taller than the viewport) and `captures/46-chat-transcript-top.png` (after a **real wheel gesture** on the transcript — the app's own listener, not a programmatic scroll, which by the implementation's own rule cannot change intent — `Jump to latest` is offered; the smoke asserts the control and performs the gesture, `ui-smoke` log line "after a real wheel gesture (scrollTop 0) 'Jump to latest' is offered at the top"). A thread with a saved position is restored to it (a saved top, index 0, is a real position and is never treated as "new"); while within the 32 px bottom threshold the view follows, and only the operator's own wheel/drag changes that intent (a programmatic placement or follow cannot); `Jump to latest` is offered only when not following and something is below the fold; the position is saved per session in `localStorage` (`pipelines.web.chatScroll.v1`). A re-render (opening/dismissing a dialog, a refresh, or the loading frame of a paging fetch) captures the live position first and puts the operator back exactly where they were — the smoke asserts the transcript stays put across the `Close chat?` dialog (`ui-smoke` log line "the transcript stayed put across the dialog (top 7141 -> 7141)"); the paging anchor is held until the frame that actually carries the older page, so a real prepend stays on the previously visible message. No auto-load on scroll. The pure decisions are unit-tested (`chatBottomDistancePx`, `chatFollowsAt`, `chatShowJumpToLatest`, `chatOpensAtNewest`, `chatFirstScroll`) in `test/chat.test.mjs`, and the live measurement uses `chatBottomDistancePx` itself |
|
||||
|
||||
Three decisions in Chat, recorded here as the browser client's own choices where
|
||||
the app has no exact counterpart. The list's `New chat` action is rendered but
|
||||
deliberately disabled (with a note that C2 wires it), because C2's create dialog
|
||||
is a separate item. The conversation pane outside a selection reads
|
||||
`Select a chat to open it.`: the browser always shows a two-pane split (the app's
|
||||
narrow layout covers the list instead), so this stands in for `PaneIdentity`'s
|
||||
covered-pane title rather than a second feature. And the markdown renderer only
|
||||
makes `http(s)` targets clickable, because a transcript is untrusted model
|
||||
output: a `javascript:`/`data:` target renders as its label, never dropped and
|
||||
never a live link. The transcript, the session rows and every server string are
|
||||
built from DOM nodes and set with `textContent`, never `innerHTML`.
|
||||
|
||||
## Settings, layout, platform
|
||||
| # | Feature | Protocol | Status |
|
||||
|
||||
+932
@@ -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
@@ -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 };
|
||||
}
|
||||
@@ -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 `'`, `"`, `&` 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 (`&lt;` stays `<`).
|
||||
*/
|
||||
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;
|
||||
}
|
||||
@@ -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
@@ -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 };
|
||||
}
|
||||
}
|
||||
|
||||
+120
@@ -1269,3 +1269,123 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
|
||||
}
|
||||
.rename-input:focus { outline: none; border-color: var(--accent); }
|
||||
.rename-save { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
Chat (C1/C3/C4/C7/C14): the session list, the conversation and its rendered
|
||||
markdown transcript. Hand-written, on the app's dark palette; the transcript
|
||||
is untrusted model output, so every node is built with textContent.
|
||||
--------------------------------------------------------------------------- */
|
||||
|
||||
.chat-list { display: flex; flex-direction: column; }
|
||||
.chat-search { flex: 1 1 auto; min-width: 0; }
|
||||
|
||||
.chat-group-header {
|
||||
padding: 8px 12px 4px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.chat-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 2px 8px;
|
||||
align-items: start;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.chat-row .row-head { grid-column: 1; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||
.chat-row .row-title { min-width: 0; }
|
||||
.chat-row .row-meta { grid-column: 1; }
|
||||
.chat-row-actions { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
|
||||
.chat-row-actions button { padding: 3px 10px; font-size: 12px; }
|
||||
.chat-close { border-color: var(--warn); color: var(--warn); }
|
||||
.chat-reopen { border-color: var(--accent); color: var(--accent); }
|
||||
.chat-closed-chip { opacity: 0.8; }
|
||||
|
||||
.chat-activity { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--muted); }
|
||||
.chat-activity-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
|
||||
.chat-activity-streaming { color: var(--accent); }
|
||||
.chat-activity-new { color: #7fb2f0; }
|
||||
|
||||
.chat-detail { display: flex; flex-direction: column; gap: 10px; }
|
||||
.chat-bar { display: flex; gap: 10px; align-items: flex-start; justify-content: space-between; }
|
||||
.chat-bar-titles { display: grid; gap: 2px; min-width: 0; }
|
||||
.chat-bar-title { margin: 0; font-size: 16px; }
|
||||
.chat-bar-meta { font-size: 12px; }
|
||||
.chat-context { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 12px; color: var(--muted); }
|
||||
.chat-load-older { white-space: nowrap; font-size: 12px; }
|
||||
.chat-transcript-empty { padding: 24px 12px; }
|
||||
|
||||
.chat-transcript-wrap { position: relative; flex: 1 1 auto; min-height: 320px; }
|
||||
.chat-transcript {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-height: min(62vh, 660px);
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
.chat-turn { display: flex; }
|
||||
.chat-turn-user { justify-content: flex-end; }
|
||||
.chat-turn-agent { justify-content: flex-start; }
|
||||
.chat-bubble { max-width: min(560px, 100%); padding: 10px 12px; border-radius: 10px; }
|
||||
.user-bubble { background: var(--surface-2); border: 1px solid var(--border); }
|
||||
.agent-bubble { background: var(--surface); border: 1px solid var(--border); }
|
||||
.chat-client { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
|
||||
.chat-user-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.chat-tools { margin: 4px 0 8px; }
|
||||
|
||||
.chat-reasoning { margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px dashed var(--border); }
|
||||
.chat-reasoning-toggle {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
padding: 2px 0;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.chat-reasoning-toggle:hover { color: var(--text); }
|
||||
.chat-reasoning-body {
|
||||
margin: 6px 0 2px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.chat-jump { position: absolute; right: 14px; bottom: 14px; border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
/* The rendered markdown subset. Every node is created, never parsed from HTML. */
|
||||
.markdown { display: grid; gap: 8px; min-width: 0; }
|
||||
.markdown > * { margin: 0; }
|
||||
.md-heading { font-size: 15px; }
|
||||
.md-paragraph { line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.md-code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; background: var(--surface-2); padding: 1px 4px; border-radius: 4px; }
|
||||
.md-code-block { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--bg); }
|
||||
.md-code-label {
|
||||
padding: 4px 10px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
background: var(--surface-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.md-pre { margin: 0; padding: 10px; overflow-x: auto; }
|
||||
.md-pre code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
||||
.md-quote { display: grid; gap: 6px; padding-left: 10px; border-left: 3px solid var(--border); color: var(--muted); }
|
||||
.md-list { display: grid; gap: 4px; margin: 0; padding-left: 20px; }
|
||||
.md-table { border-collapse: collapse; width: 100%; font-size: 13px; }
|
||||
.md-table th, .md-table td { border: 1px solid var(--border); padding: 4px 8px; text-align: left; }
|
||||
.md-table th { background: var(--surface-2); }
|
||||
.md-rule { border: 0; border-top: 1px solid var(--border); }
|
||||
.md-link { color: var(--accent); }
|
||||
.md-link-plain { color: var(--muted); }
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
// Pure chat logic (C1/C3/C4/C14) and the chat request builders. Every wording
|
||||
// and decision below is the same one the browser view uses, so the view cannot
|
||||
// silently drift from what is asserted here.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
CHAT_FOLLOW_THRESHOLD_PX,
|
||||
ChatTurn,
|
||||
chatBottomDistancePx,
|
||||
chatFirstScroll,
|
||||
chatFollowsAt,
|
||||
chatHeaderMeta,
|
||||
chatNoMatchMessage,
|
||||
chatOpensAtNewest,
|
||||
chatShowJumpToLatest,
|
||||
closeChatConfirmation,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
groupSessionsByDirectory,
|
||||
mergeHistoryPage,
|
||||
partRendering,
|
||||
reasoningLabel,
|
||||
sessionActivity,
|
||||
sessionActivityBadge,
|
||||
sessionChipLabel,
|
||||
sessionMatchesQuery,
|
||||
sessionMeta,
|
||||
sessionStatusLabel,
|
||||
sessionTitle,
|
||||
sessionWorkLabel,
|
||||
toolCallsLabel,
|
||||
transcriptRows,
|
||||
} from "../src/chat.js";
|
||||
|
||||
import { PipelinesClient, ProtocolError } from "../src/client.js";
|
||||
import { PipelinesRepository } from "../src/repository.js";
|
||||
import { validateServerUrl } from "../src/serverUrl.js";
|
||||
|
||||
const assistant = (id, parts) => ({ id, role: "assistant", parts });
|
||||
const user = (id, text) => ({ id, role: "user", parts: [{ type: "text", text }] });
|
||||
|
||||
// --- Transcript folding -----------------------------------------------------
|
||||
|
||||
test("transcriptRows folds consecutive assistant messages into one turn keyed by the first id", () => {
|
||||
const rows = transcriptRows([
|
||||
user("u1", "hello"),
|
||||
assistant("a1", [{ type: "text", text: "one" }, { type: "tool", id: "t1", name: "read" }]),
|
||||
assistant("a2", [{ type: "reasoning", text: "think" }, { type: "text", text: "two" }]),
|
||||
user("u2", "bye"),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
rows.map((row) => `${row.kind}:${row.key}`),
|
||||
["user:u1", "agent:a1", "user:u2"],
|
||||
);
|
||||
const turn = rows[1].turn;
|
||||
assert.ok(turn instanceof ChatTurn);
|
||||
assert.equal(turn.reasoning, "think");
|
||||
assert.equal(turn.tools.length, 1);
|
||||
assert.equal(turn.answer, "one\n\ntwo");
|
||||
});
|
||||
|
||||
test("transcriptRows gives each user message its own row and never folds two runs together", () => {
|
||||
const rows = transcriptRows([
|
||||
user("u1", "a"),
|
||||
assistant("a1", [{ type: "text", text: "x" }]),
|
||||
user("u2", "b"),
|
||||
assistant("a2", [{ type: "text", text: "y" }]),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
rows.map((row) => row.kind),
|
||||
["user", "agent", "user", "agent"],
|
||||
);
|
||||
});
|
||||
|
||||
test("transcriptRows drops an assistant run with nothing to draw", () => {
|
||||
const rows = transcriptRows([
|
||||
user("u1", "hi"),
|
||||
assistant("a1", []),
|
||||
assistant("a2", [{ type: "tool", id: "t1", name: "" }]),
|
||||
]);
|
||||
assert.deepEqual(rows.map((row) => row.key), ["u1", "a1"]);
|
||||
assert.equal(rows[1].turn.visible, true);
|
||||
assert.equal(new ChatTurn("k", []).visible, false);
|
||||
});
|
||||
|
||||
test("partRendering classifies text, reasoning, other text and empty parts", () => {
|
||||
assert.equal(partRendering({ type: "text", text: "hi" }), "markdown");
|
||||
assert.equal(partRendering({ type: "reasoning", text: "hmm" }), "reasoning");
|
||||
assert.equal(partRendering({ type: "file", text: "f.txt" }), "plain");
|
||||
assert.equal(partRendering({ type: "text", text: " " }), "hidden");
|
||||
assert.equal(partRendering(null), "hidden");
|
||||
});
|
||||
|
||||
test("toolCallsLabel never pluralises a count of one", () => {
|
||||
assert.equal(toolCallsLabel(1), "1 tool called");
|
||||
assert.equal(toolCallsLabel(4), "4 tools called");
|
||||
});
|
||||
|
||||
test("reasoningLabel keeps the one-block wording and counts multiple steps", () => {
|
||||
assert.equal(reasoningLabel(1), "Reasoning");
|
||||
assert.equal(reasoningLabel(3), "Reasoning · 3 steps");
|
||||
});
|
||||
|
||||
// --- Session identity -------------------------------------------------------
|
||||
|
||||
test("sessionTitle falls back from the title to the first 18 characters of the id", () => {
|
||||
assert.equal(sessionTitle({ id: "ses_1", title: "Named chat" }), "Named chat");
|
||||
assert.equal(sessionTitle({ id: "ses_abcdefghijklmnopqrstuv", title: "" }), "ses_abcdefghijklmn");
|
||||
assert.equal(sessionTitle({ id: "ses_abcdefghijklmnopqrstuv", title: " " }), "ses_abcdefghijklmn");
|
||||
assert.equal(sessionTitle({ id: "", title: "" }), "Untitled chat");
|
||||
assert.equal(sessionTitle(null), "Untitled chat");
|
||||
});
|
||||
|
||||
test("sessionTagLabel maps operator and keeps an unknown tag verbatim", () => {
|
||||
assert.equal(sessionChipLabel({ tag: "operator" }), "Operator");
|
||||
assert.equal(sessionChipLabel({ tag: "run" }), "run");
|
||||
assert.equal(sessionChipLabel({ tag: " " }), null);
|
||||
assert.equal(sessionChipLabel({}), null);
|
||||
});
|
||||
|
||||
test("sessionWorkLabel names the running tool, the count, busy and idle", () => {
|
||||
assert.equal(sessionWorkLabel(false, null), "Idle");
|
||||
assert.equal(sessionWorkLabel(true, null), "Busy · read-only");
|
||||
assert.equal(sessionWorkLabel(true, { running: true, runningTools: [] }), "Running");
|
||||
assert.equal(
|
||||
sessionWorkLabel(true, { running: true, runningTools: [{ name: "read" }] }),
|
||||
"Running read",
|
||||
);
|
||||
assert.equal(
|
||||
sessionWorkLabel(true, { running: true, runningTools: [{ name: "" }] }),
|
||||
"Running tool",
|
||||
);
|
||||
assert.equal(
|
||||
sessionWorkLabel(true, { running: true, runningTools: [{ name: "a" }, { name: "b" }] }),
|
||||
"Running 2 tools",
|
||||
);
|
||||
});
|
||||
|
||||
test("sessionMeta joins only the non-blank work label, directory and model", () => {
|
||||
assert.equal(sessionMeta({ directory: "/repo", model: "m1" }, "Idle"), "Idle · /repo · m1");
|
||||
assert.equal(sessionMeta({ directory: "", model: "m1" }, "Idle"), "Idle · m1");
|
||||
assert.equal(sessionMeta({}, ""), "");
|
||||
});
|
||||
|
||||
test("chatHeaderMeta joins model, kind tag and directory, omitting blanks", () => {
|
||||
assert.equal(
|
||||
chatHeaderMeta({ model: "m1", tag: "operator", directory: "/repo" }),
|
||||
"m1 · Operator · /repo",
|
||||
);
|
||||
assert.equal(chatHeaderMeta({ model: "", tag: "", directory: "/repo" }), "/repo");
|
||||
assert.equal(chatHeaderMeta({}), "");
|
||||
});
|
||||
|
||||
test("sessionActivity and its badge word follow streaming, unseen then open", () => {
|
||||
assert.equal(sessionActivity(true, true), "streaming");
|
||||
assert.equal(sessionActivity(false, true), "new");
|
||||
assert.equal(sessionActivity(false, false), "idle");
|
||||
assert.equal(sessionActivityBadge("streaming", false), "Streaming");
|
||||
assert.equal(sessionActivityBadge("new", false), "New");
|
||||
assert.equal(sessionActivityBadge("idle", true), "Open");
|
||||
assert.equal(sessionActivityBadge("idle", false), null);
|
||||
});
|
||||
|
||||
test("sessionStatusLabel reads Closed first, then Running or Idle", () => {
|
||||
assert.equal(sessionStatusLabel(true, true), "Closed");
|
||||
assert.equal(sessionStatusLabel(true, false), "Running");
|
||||
assert.equal(sessionStatusLabel(false, false), "Idle");
|
||||
});
|
||||
|
||||
// --- Narrowing and grouping -------------------------------------------------
|
||||
|
||||
test("filterSessions is a case-insensitive substring over title or directory", () => {
|
||||
const sessions = [
|
||||
{ id: "a", title: "Fix the parser", directory: "/repo/one" },
|
||||
{ id: "b", title: "Docs", directory: "/repo/two" },
|
||||
];
|
||||
assert.deepEqual(filterSessions(sessions, "PARSER").map((s) => s.id), ["a"]);
|
||||
assert.deepEqual(filterSessions(sessions, "REPO/TWO").map((s) => s.id), ["b"]);
|
||||
assert.deepEqual(filterSessions(sessions, "zzz"), []);
|
||||
});
|
||||
|
||||
test("filterSessions is a no-op for a blank query and never reorders", () => {
|
||||
const sessions = [{ id: "b", title: "b" }, { id: "a", title: "a" }];
|
||||
assert.equal(filterSessions(sessions, " "), sessions);
|
||||
assert.deepEqual(filterSessions(sessions, ""), sessions);
|
||||
assert.deepEqual(filterSessions(sessions, "b").map((s) => s.id), ["b"]);
|
||||
});
|
||||
|
||||
test("sessionMatchesQuery tests the truncated title too", () => {
|
||||
const session = { id: "ses_abcdefghijklmnopqrstuv", title: "" };
|
||||
assert.equal(sessionMatchesQuery(session, "abcdefghij"), true);
|
||||
assert.equal(sessionMatchesQuery(session, "nope"), false);
|
||||
});
|
||||
|
||||
test("groupSessionsByDirectory groups in first-occurrence order and labels a blank directory", () => {
|
||||
const sessions = [
|
||||
{ id: "1", directory: "/a" },
|
||||
{ id: "2", directory: "/b" },
|
||||
{ id: "3", directory: "/a" },
|
||||
{ id: "4", directory: "" },
|
||||
];
|
||||
const groups = groupSessionsByDirectory(sessions);
|
||||
assert.deepEqual(groups.map((g) => g.directory), ["/a", "/b", ""]);
|
||||
assert.deepEqual(groups[0].sessions.map((s) => s.id), ["1", "3"]);
|
||||
assert.deepEqual(groupSessionsByDirectory([]), []);
|
||||
assert.equal(directoryLabel(""), "No directory");
|
||||
assert.equal(directoryLabel("/a"), "/a");
|
||||
});
|
||||
|
||||
// --- History paging ---------------------------------------------------------
|
||||
|
||||
test("mergeHistoryPage prepends an older page and dedupes by id", () => {
|
||||
const previous = { messages: [{ id: "m3" }, { id: "m4" }], nextCursor: "c1", hasMore: true };
|
||||
const page = { messages: [{ id: "m1" }, { id: "m2" }, { id: "m3" }], nextCursor: "c0", hasMore: false };
|
||||
const merged = mergeHistoryPage(previous, page, { older: true });
|
||||
assert.deepEqual(merged.messages.map((m) => m.id), ["m1", "m2", "m3", "m4"]);
|
||||
assert.equal(merged.nextCursor, "c0");
|
||||
assert.equal(merged.hasMore, false);
|
||||
assert.equal(merged.loaded, true);
|
||||
assert.equal(merged.loading, false);
|
||||
});
|
||||
|
||||
test("mergeHistoryPage keeps turns already held in front of a newest page", () => {
|
||||
const previous = { messages: [{ id: "m1" }, { id: "m2" }], nextCursor: "c1", hasMore: true };
|
||||
const page = { messages: [{ id: "m2" }, { id: "m3" }], nextCursor: "", hasMore: false };
|
||||
const merged = mergeHistoryPage(previous, page, { older: false });
|
||||
assert.deepEqual(merged.messages.map((m) => m.id), ["m1", "m2", "m3"]);
|
||||
assert.equal(merged.nextCursor, "");
|
||||
assert.equal(merged.hasMore, false);
|
||||
});
|
||||
|
||||
test("mergeHistoryPage replaces the cursor and hasMore even when the page omits them", () => {
|
||||
const merged = mergeHistoryPage({ messages: [] }, { messages: [{ id: "m1" }] });
|
||||
assert.equal(merged.nextCursor, "");
|
||||
assert.equal(merged.hasMore, false);
|
||||
assert.deepEqual(merged.messages.map((m) => m.id), ["m1"]);
|
||||
});
|
||||
|
||||
// --- Scroll behaviour -------------------------------------------------------
|
||||
|
||||
test("chatBottomDistancePx is null until the last item is in view", () => {
|
||||
assert.equal(
|
||||
chatBottomDistancePx({ lastVisibleIndex: 2, lastVisibleEndPx: 900, itemCount: 3, viewportEndPx: 800 }),
|
||||
100,
|
||||
);
|
||||
assert.equal(
|
||||
chatBottomDistancePx({ lastVisibleIndex: 1, lastVisibleEndPx: 900, itemCount: 3, viewportEndPx: 800 }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
chatBottomDistancePx({ lastVisibleIndex: 0, lastVisibleEndPx: 0, itemCount: 0, viewportEndPx: 0 }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
chatBottomDistancePx({ lastVisibleIndex: 2, lastVisibleEndPx: 700, itemCount: 3, viewportEndPx: 800 }),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test("chatFollowsAt is at-the-bottom only for a measured distance within the threshold", () => {
|
||||
assert.equal(chatFollowsAt(0, CHAT_FOLLOW_THRESHOLD_PX, 3), true);
|
||||
assert.equal(chatFollowsAt(32, CHAT_FOLLOW_THRESHOLD_PX, 3), true);
|
||||
assert.equal(chatFollowsAt(33, CHAT_FOLLOW_THRESHOLD_PX, 3), false);
|
||||
assert.equal(chatFollowsAt(null, CHAT_FOLLOW_THRESHOLD_PX, 3), false);
|
||||
assert.equal(chatFollowsAt(0, CHAT_FOLLOW_THRESHOLD_PX, 0), false);
|
||||
});
|
||||
|
||||
test("chatShowJumpToLatest needs not-following, content and something below the fold", () => {
|
||||
assert.equal(chatShowJumpToLatest(false, 400, CHAT_FOLLOW_THRESHOLD_PX, 5), true);
|
||||
assert.equal(chatShowJumpToLatest(false, null, CHAT_FOLLOW_THRESHOLD_PX, 5), true);
|
||||
assert.equal(chatShowJumpToLatest(true, 400, CHAT_FOLLOW_THRESHOLD_PX, 5), false);
|
||||
assert.equal(chatShowJumpToLatest(false, 0, CHAT_FOLLOW_THRESHOLD_PX, 5), false);
|
||||
assert.equal(chatShowJumpToLatest(false, 400, CHAT_FOLLOW_THRESHOLD_PX, 0), false);
|
||||
});
|
||||
|
||||
test("chatOpensAtNewest is true only for an absent saved position", () => {
|
||||
assert.equal(chatOpensAtNewest(null), true);
|
||||
assert.equal(chatOpensAtNewest(undefined), true);
|
||||
assert.equal(chatOpensAtNewest({ index: 0, offset: 0 }), false);
|
||||
assert.equal(chatOpensAtNewest({ index: 4, offset: 80 }), false);
|
||||
});
|
||||
|
||||
test("chatFirstScroll opens newest when unsaved and restores a saved top exactly", () => {
|
||||
assert.deepEqual(chatFirstScroll(null, 5), { index: 4, offset: 0 });
|
||||
assert.deepEqual(chatFirstScroll({ index: 0, offset: 0 }, 5), { index: 0, offset: 0 });
|
||||
assert.deepEqual(chatFirstScroll({ index: 1, offset: 40 }, 3), { index: 1, offset: 40 });
|
||||
assert.deepEqual(chatFirstScroll({ index: 9, offset: 40 }, 3), { index: 2, offset: 0 });
|
||||
assert.deepEqual(chatFirstScroll(null, 0), { index: 0, offset: 0 });
|
||||
});
|
||||
|
||||
// --- Wording ----------------------------------------------------------------
|
||||
|
||||
test("closeChatConfirmation is the app's exact sentence", () => {
|
||||
assert.equal(
|
||||
closeChatConfirmation("New chat"),
|
||||
'Closes "New chat" and marks it closed on every device. A turn that is running is stopped first. ' +
|
||||
"Nothing is deleted — the chat and its history are kept, and you can reopen it from the list.",
|
||||
);
|
||||
});
|
||||
|
||||
test("chatNoMatchMessage names the trimmed query", () => {
|
||||
assert.equal(chatNoMatchMessage(" fix parser "), 'No chats match "fix parser".');
|
||||
});
|
||||
|
||||
// --- Request builders -------------------------------------------------------
|
||||
|
||||
/** The same minimal fake the repository tests use (test files are not importable). */
|
||||
class FakeWebSocket {
|
||||
static instances = [];
|
||||
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.sent = [];
|
||||
this.onopen = null;
|
||||
this.onmessage = null;
|
||||
this.onclose = null;
|
||||
this.onerror = null;
|
||||
this.reply = null;
|
||||
FakeWebSocket.instances.push(this);
|
||||
}
|
||||
|
||||
send(data) {
|
||||
const frame = JSON.parse(data);
|
||||
this.sent.push(frame);
|
||||
const response = this.reply?.(frame);
|
||||
if (response !== undefined) this.onmessage?.({ data: JSON.stringify(response) });
|
||||
}
|
||||
|
||||
close(code, reason) {
|
||||
this.onclose?.({ code, reason });
|
||||
}
|
||||
|
||||
open() {
|
||||
this.onopen?.({});
|
||||
}
|
||||
}
|
||||
|
||||
const VALID = validateServerUrl("ws://host:8080/connect");
|
||||
|
||||
function connected() {
|
||||
FakeWebSocket.instances = [];
|
||||
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
|
||||
const repo = new PipelinesRepository(client);
|
||||
client.connect(VALID);
|
||||
const ws = FakeWebSocket.instances.at(-1);
|
||||
ws.open();
|
||||
return { repo, ws, client };
|
||||
}
|
||||
|
||||
function lastFrame(ws) {
|
||||
const { id, ...frame } = ws.sent.at(-1);
|
||||
assert.match(id, /^web-\d+$/);
|
||||
return frame;
|
||||
}
|
||||
|
||||
test("chatSessions sends exactly {type:'chat_sessions'} and returns the list", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_sessions", chat_sessions: [{ id: "s1" }] });
|
||||
const sessions = await repo.chatSessions();
|
||||
assert.deepEqual(lastFrame(ws), { type: "chat_sessions" });
|
||||
assert.deepEqual(sessions, [{ id: "s1" }]);
|
||||
});
|
||||
|
||||
test("chatSessions returns [] when the reply carries none", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_sessions" });
|
||||
assert.deepEqual(await repo.chatSessions(), []);
|
||||
});
|
||||
|
||||
test("chatHistory sends {session_id,limit,cursor} and reads chat_history", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({
|
||||
id: frame.id,
|
||||
type: "chat_messages",
|
||||
chat_history: { messages: [{ id: "m1" }], next_cursor: "c1", has_more: true },
|
||||
});
|
||||
const page = await repo.chatHistory("s1");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_messages",
|
||||
chat_query: { session_id: "s1", limit: 200, cursor: "" },
|
||||
});
|
||||
assert.deepEqual(page, { messages: [{ id: "m1" }], nextCursor: "c1", hasMore: true });
|
||||
});
|
||||
|
||||
test("chatHistory passes the cursor back verbatim", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_messages", chat_history: { messages: [] } });
|
||||
await repo.chatHistory("s1", { cursor: "opaque/+/=", limit: 200 });
|
||||
const { chat_query: query } = lastFrame(ws);
|
||||
assert.equal(query.cursor, "opaque/+/=");
|
||||
});
|
||||
|
||||
test("chatHistory falls back to chat_messages with no continuation on an older server", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_messages", chat_messages: [{ id: "m1" }] });
|
||||
const page = await repo.chatHistory("s1");
|
||||
assert.deepEqual(page, { messages: [{ id: "m1" }], nextCursor: "", hasMore: false });
|
||||
});
|
||||
|
||||
test("closeChat and reopenChat send the session id and read the echoed session and close", async () => {
|
||||
for (const [method, type] of [["closeChat", "chat_close"], ["reopenChat", "chat_reopen"]]) {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({
|
||||
id: frame.id,
|
||||
type,
|
||||
chat_session: { id: "s1", closed: type === "chat_close" },
|
||||
chat_close: { session_id: "s1", closed_at: 1, interrupted: false },
|
||||
});
|
||||
const result = await repo[method]("s1");
|
||||
assert.deepEqual(lastFrame(ws), { type, chat_query: { session_id: "s1" } });
|
||||
assert.deepEqual(result.session, { id: "s1", closed: type === "chat_close" });
|
||||
assert.equal(result.close.session_id, "s1");
|
||||
}
|
||||
});
|
||||
|
||||
test("chatHistory rejects a blank session id without sending", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.chatHistory(" "), ProtocolError);
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("a chat command rejects a server error envelope with the server's own text", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_messages" });
|
||||
await assert.rejects(() => repo.chatHistory("s1"), {
|
||||
name: "ProtocolError",
|
||||
message: "unknown command: chat_messages",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
// The markdown subset (C7), ported from ui/chat/Markdown.kt. The parser is pure,
|
||||
// so the exact block/span shapes are asserted without a browser; anything outside
|
||||
// the subset must render as plain text and never be dropped.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { codeBlockLabel, decodeHtmlEntities, parseInline, parseMarkdown } from "../src/markdown.js";
|
||||
|
||||
/** Every text run in a span tree, in order, so nothing dropped can hide. */
|
||||
function spanText(spans) {
|
||||
return spans
|
||||
.map((span) => {
|
||||
if (span.kind === "plain" || span.kind === "code") return span.text;
|
||||
if (span.kind === "strong" || span.kind === "emphasis" || span.kind === "link") {
|
||||
return spanText(span.spans);
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Every text run in a block list, so nothing dropped can hide. */
|
||||
function blockText(blocks) {
|
||||
return blocks
|
||||
.map((block) => {
|
||||
if (block.kind === "heading" || block.kind === "paragraph") return block.text;
|
||||
if (block.kind === "code") return block.code;
|
||||
if (block.kind === "quote") return block.lines.join("\n");
|
||||
if (block.kind === "list") return block.items.join("\n");
|
||||
if (block.kind === "table") return [...block.header, ...block.rows.flat()].join("|");
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
// --- Entities ---------------------------------------------------------------
|
||||
|
||||
test("decodeHtmlEntities decodes the named, decimal and hex references", () => {
|
||||
assert.equal(decodeHtmlEntities("a & b < c > d "e" 'f'"), "a & b < c > d \"e\" 'f'");
|
||||
assert.equal(decodeHtmlEntities("AB"), "AB");
|
||||
assert.equal(decodeHtmlEntities("…— "), "…—\u00A0");
|
||||
});
|
||||
|
||||
test("decodeHtmlEntities is a single pass, so a decoded ampersand is not re-decoded", () => {
|
||||
assert.equal(decodeHtmlEntities("&lt;"), "<");
|
||||
assert.equal(decodeHtmlEntities("&amp;"), "&");
|
||||
});
|
||||
|
||||
test("decodeHtmlEntities leaves an unknown or malformed reference literal", () => {
|
||||
assert.equal(decodeHtmlEntities("&nope; &doesnotexist;"), "&nope; &doesnotexist;");
|
||||
assert.equal(decodeHtmlEntities("&#xZZ; &#; &"), "&#xZZ; &#; &");
|
||||
});
|
||||
|
||||
test("parseMarkdown decodes entities before parsing", () => {
|
||||
const blocks = parseMarkdown("a & b");
|
||||
assert.deepEqual(blocks, [{ kind: "paragraph", text: "a & b" }]);
|
||||
});
|
||||
|
||||
// --- Blocks -----------------------------------------------------------------
|
||||
|
||||
test("parseMarkdown parses headings, paragraphs and thematic rules", () => {
|
||||
const blocks = parseMarkdown("# Title\n\nA paragraph\nspanning lines.\n\n---\n\n## Sub ##");
|
||||
assert.deepEqual(blocks, [
|
||||
{ kind: "heading", level: 1, text: "Title" },
|
||||
{ kind: "paragraph", text: "A paragraph spanning lines." },
|
||||
{ kind: "rule" },
|
||||
{ kind: "heading", level: 2, text: "Sub " },
|
||||
]);
|
||||
});
|
||||
|
||||
test("parseMarkdown parses a fenced block and keeps its language", () => {
|
||||
const blocks = parseMarkdown("```js\nconst x = 1;\n```");
|
||||
assert.deepEqual(blocks, [{ kind: "code", language: "js", code: "const x = 1;" }]);
|
||||
assert.equal(codeBlockLabel("js"), "js");
|
||||
});
|
||||
|
||||
test("a fenced block with no language is labelled code", () => {
|
||||
const blocks = parseMarkdown("```\nplain\n```");
|
||||
assert.deepEqual(blocks, [{ kind: "code", language: "", code: "plain" }]);
|
||||
assert.equal(codeBlockLabel(""), "code");
|
||||
assert.equal(codeBlockLabel(" "), "code");
|
||||
});
|
||||
|
||||
test("tilde fences are code fences too", () => {
|
||||
const blocks = parseMarkdown("~~~python\nprint(1)\n~~~");
|
||||
assert.deepEqual(blocks, [{ kind: "code", language: "python", code: "print(1)" }]);
|
||||
});
|
||||
|
||||
test("parseMarkdown parses block quotes, bullet lists and ordered lists", () => {
|
||||
assert.deepEqual(parseMarkdown("> one\n> two"), [{ kind: "quote", lines: ["one", "two"] }]);
|
||||
assert.deepEqual(parseMarkdown("- a\n- b"), [{ kind: "list", ordered: false, items: ["a", "b"] }]);
|
||||
assert.deepEqual(parseMarkdown("1. one\n2. two"), [{ kind: "list", ordered: true, items: ["one", "two"] }]);
|
||||
});
|
||||
|
||||
test("parseMarkdown parses a table with a --- delimiter row", () => {
|
||||
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 | 2 |");
|
||||
assert.deepEqual(blocks, [{ kind: "table", header: ["a", "b"], rows: [["1", "2"]] }]);
|
||||
});
|
||||
|
||||
test("a table row shorter than the header is padded, never truncated", () => {
|
||||
const blocks = parseMarkdown("| a | b |\n| --- | --- |\n| 1 |");
|
||||
assert.deepEqual(blocks[0].rows, [["1", ""]]);
|
||||
});
|
||||
|
||||
test("a nested list is flattened into its run, never dropped", () => {
|
||||
const blocks = parseMarkdown("- a\n - b");
|
||||
assert.deepEqual(blocks, [{ kind: "list", ordered: false, items: ["a", "b"] }]);
|
||||
assert.equal(blockText(blocks), "a\nb");
|
||||
});
|
||||
|
||||
test("more than six hashes is a paragraph, not a heading", () => {
|
||||
assert.deepEqual(parseMarkdown("####### x"), [{ kind: "paragraph", text: "####### x" }]);
|
||||
});
|
||||
|
||||
// --- Inline -----------------------------------------------------------------
|
||||
|
||||
test("snake_case is never italicised", () => {
|
||||
assert.deepEqual(parseInline("snake_case_name"), [{ kind: "plain", text: "snake_case_name" }]);
|
||||
assert.deepEqual(parseInline("a_b_c"), [{ kind: "plain", text: "a_b_c" }]);
|
||||
});
|
||||
|
||||
test("underscore emphasis works only at word boundaries", () => {
|
||||
assert.deepEqual(parseInline("_italic_"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "italic" }] }]);
|
||||
assert.deepEqual(parseInline("a _b_ c"), [
|
||||
{ kind: "plain", text: "a " },
|
||||
{ kind: "emphasis", spans: [{ kind: "plain", text: "b" }] },
|
||||
{ kind: "plain", text: " c" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("bold, italic and inline code become their spans", () => {
|
||||
assert.deepEqual(parseInline("**bold**"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
|
||||
assert.deepEqual(parseInline("__bold__"), [{ kind: "strong", spans: [{ kind: "plain", text: "bold" }] }]);
|
||||
assert.deepEqual(parseInline("*it*"), [{ kind: "emphasis", spans: [{ kind: "plain", text: "it" }] }]);
|
||||
assert.deepEqual(parseInline("`code`"), [{ kind: "code", text: "code" }]);
|
||||
});
|
||||
|
||||
test("links and bare http(s) autolinks become link spans", () => {
|
||||
assert.deepEqual(parseInline("[site](https://example.com)"), [
|
||||
{ kind: "link", spans: [{ kind: "plain", text: "site" }], url: "https://example.com" },
|
||||
]);
|
||||
assert.deepEqual(parseInline("see https://example.com now"), [
|
||||
{ kind: "plain", text: "see " },
|
||||
{ kind: "link", spans: [{ kind: "plain", text: "https://example.com" }], url: "https://example.com" },
|
||||
{ kind: "plain", text: " now" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("autolinks trim trailing punctuation", () => {
|
||||
const spans = parseInline("go to https://example.com.");
|
||||
const link = spans.find((span) => span.kind === "link");
|
||||
assert.equal(link.url, "https://example.com");
|
||||
});
|
||||
|
||||
// --- Out-of-subset text is never dropped ------------------------------------
|
||||
|
||||
test("out-of-subset HTML renders as plain text and is never dropped", () => {
|
||||
assert.deepEqual(parseInline("<b>hi</b>"), [{ kind: "plain", text: "<b>hi</b>" }]);
|
||||
assert.equal(blockText(parseMarkdown("<div>x</div>")), "<div>x</div>");
|
||||
});
|
||||
|
||||
test("reference links and strikethrough render as plain text", () => {
|
||||
assert.deepEqual(parseInline("[label][ref]"), [{ kind: "plain", text: "[label][ref]" }]);
|
||||
assert.deepEqual(parseInline("~~gone~~"), [{ kind: "plain", text: "~~gone~~" }]);
|
||||
});
|
||||
|
||||
test("a malformed inline marker is kept literally", () => {
|
||||
assert.deepEqual(parseInline("a * b ` c"), [{ kind: "plain", text: "a * b ` c" }]);
|
||||
});
|
||||
|
||||
test("every out-of-subset paragraph's text survives the round trip", () => {
|
||||
const source = "<section>\n[ref][id] and ~~strike~~\n</section>";
|
||||
const blocks = parseMarkdown(source);
|
||||
const text = blockText(blocks);
|
||||
assert.ok(text.includes("[ref][id] and ~~strike~~"));
|
||||
});
|
||||
|
||||
test("spanText of a mixed inline run keeps every character", () => {
|
||||
const spans = parseInline("plain **bold** `code` [link](https://e.com) tail");
|
||||
assert.equal(spanText(spans), "plain bold code link tail");
|
||||
});
|
||||
@@ -1924,6 +1924,285 @@ try {
|
||||
});
|
||||
}
|
||||
|
||||
// C1/C3/C4/C7/C14: the chat list, its transcript (markdown + the code the live
|
||||
// session carries), paging and the close dialog. The one live operator session
|
||||
// is never mutated: the close confirm is shown and dismissed with Cancel.
|
||||
step("C1/C3/C4/C7/C14: the chat list, transcript, paging and close dialog");
|
||||
await ensureConnected();
|
||||
await page.clickText("nav.tabs button.tab", "Chat");
|
||||
await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 });
|
||||
|
||||
const chatList = await page.evaluate(`(() => ({
|
||||
label: document.querySelector("#chatSearch")?.getAttribute("aria-label") ?? "",
|
||||
placeholder: document.querySelector("#chatSearch")?.getAttribute("placeholder") ?? "",
|
||||
rows: [...document.querySelectorAll("#chatRows .chat-row")].map((row) => ({
|
||||
id: row.dataset.session ?? "",
|
||||
title: row.querySelector(".chat-row-title")?.textContent ?? "",
|
||||
chips: [...row.querySelectorAll(".chip")].map((chip) => chip.textContent),
|
||||
meta: row.querySelector(".chat-row-meta")?.textContent ?? "",
|
||||
close: !!row.querySelector(".chat-close"),
|
||||
})),
|
||||
}))()`);
|
||||
if (chatList.label !== "Search chats") throw new Error(`chat search label: ${chatList.label}`);
|
||||
if (chatList.placeholder !== "Search chats") throw new Error(`chat search placeholder: ${chatList.placeholder}`);
|
||||
if (chatList.rows.length === 0) throw new Error("no chat sessions rendered");
|
||||
if (!chatList.rows[0].title) throw new Error("the first chat row has no title");
|
||||
if (!chatList.rows[0].chips.includes("Operator")) {
|
||||
throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`);
|
||||
}
|
||||
if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action");
|
||||
console.log(
|
||||
` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` +
|
||||
`[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`,
|
||||
);
|
||||
await shot("44-chat-sessions.png");
|
||||
|
||||
// The row's own Close chat… action with NO conversation open: the list offers
|
||||
// it on every open row, so the confirm must still appear. Shown and dismissed
|
||||
// with Cancel; no chat_close is ever sent for the operator's live session.
|
||||
await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`);
|
||||
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
|
||||
const listClose = await page.evaluate(
|
||||
`document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`,
|
||||
);
|
||||
if (!listClose.startsWith('Closes "')) {
|
||||
throw new Error(`row-level close message with no conversation open: ${listClose}`);
|
||||
}
|
||||
await page.click(".confirm-chat-close .confirm-dismiss");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
|
||||
timeout: 5000,
|
||||
what: "the row-level close dialog to close",
|
||||
});
|
||||
console.log(
|
||||
" row-level 'Close chat…' (no conversation open) showed its confirm; dismissed with Cancel",
|
||||
);
|
||||
|
||||
// The narrowed-to-nothing empty state and its Clear search action (the field
|
||||
// itself is the narrowing; the list's order is never touched).
|
||||
await page.fill("#chatSearch", "zzz-no-such-chat");
|
||||
await page.waitForText('No chats match "zzz-no-such-chat".', { timeout: 10000 });
|
||||
await shot("50-chat-no-match.png");
|
||||
await page.clickText(".chat-rows .empty button", "Clear search");
|
||||
await page.waitForSelector("#chatRows .chat-row", { timeout: 10000 });
|
||||
const cleared = await page.evaluate(`document.querySelector("#chatSearch")?.value ?? null`);
|
||||
if (cleared !== "") throw new Error(`Clear search left the query: ${JSON.stringify(cleared)}`);
|
||||
|
||||
const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN";
|
||||
const openedId = chatList.rows[0].id;
|
||||
if (openedId !== expectedSession) {
|
||||
console.log(` -- the live server's first session is ${openedId}, not the expected ${expectedSession}`);
|
||||
}
|
||||
await page.click(`#chatRows .chat-row[data-session="${openedId}"]`);
|
||||
await page.waitForSelector("#chatTranscript", { timeout: 25000 });
|
||||
|
||||
const transcript = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
if (!el) return null;
|
||||
return {
|
||||
userBubbles: el.querySelectorAll(".chat-turn-user").length,
|
||||
agentBubbles: el.querySelectorAll(".chat-turn-agent").length,
|
||||
markdown: el.querySelectorAll(".markdown").length,
|
||||
tables: el.querySelectorAll(".md-table").length,
|
||||
inlineCode: el.querySelectorAll(".md-code").length,
|
||||
codeBlocks: el.querySelectorAll(".md-code-block").length,
|
||||
toolChips: [...el.querySelectorAll(".chat-tool-chip")].map((chip) => chip.textContent),
|
||||
reasoning: el.querySelectorAll(".chat-reasoning").length,
|
||||
client: el.querySelector(".chat-turn-user .chat-client")?.textContent ?? "",
|
||||
hasLoadOlder: !!document.querySelector(".chat-load-older"),
|
||||
};
|
||||
})()`);
|
||||
if (!transcript) throw new Error("the opened transcript did not render");
|
||||
if (transcript.userBubbles !== 1) throw new Error(`expected one user bubble, got ${transcript.userBubbles}`);
|
||||
if (transcript.agentBubbles !== 1) {
|
||||
throw new Error(`expected one folded agent turn, got ${transcript.agentBubbles}`);
|
||||
}
|
||||
if (transcript.markdown === 0) throw new Error("the agent turn rendered no markdown");
|
||||
if (transcript.tables === 0) throw new Error("the agent answer rendered no markdown table");
|
||||
if (transcript.inlineCode === 0) throw new Error("the agent answer rendered no inline code");
|
||||
if (transcript.toolChips.length !== 1) {
|
||||
throw new Error(`expected one tool-call chip, got ${transcript.toolChips.length}`);
|
||||
}
|
||||
console.log(
|
||||
` transcript: ${transcript.userBubbles} user + ${transcript.agentBubbles} folded agent turn; ` +
|
||||
`markdown ${transcript.tables} table(s), ${transcript.inlineCode} inline code span(s), ` +
|
||||
`${transcript.toolChips[0]}; client label "${transcript.client}"`,
|
||||
);
|
||||
await shot("45-chat-transcript-newest.png");
|
||||
|
||||
// The top of the conversation, reached by a genuine operator wheel gesture on
|
||||
// the transcript (the app's own listener). Only the operator's gesture changes
|
||||
// follow intent — a programmatic scrollTo cannot — so this is the only way
|
||||
// "Jump to latest" may appear; the control is asserted, not assumed.
|
||||
const wheelGesture = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
if (!el) return null;
|
||||
el.scrollTop = 0;
|
||||
el.dispatchEvent(new WheelEvent("wheel", { deltaY: -240, bubbles: true }));
|
||||
return {
|
||||
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
|
||||
top: el.scrollTop,
|
||||
};
|
||||
})()`);
|
||||
if (!wheelGesture || wheelGesture.jumpHidden !== false) {
|
||||
throw new Error(`Jump to latest was not offered after a real wheel gesture: ${JSON.stringify(wheelGesture)}`);
|
||||
}
|
||||
await shot("46-chat-transcript-top.png");
|
||||
console.log(
|
||||
` after a real wheel gesture (scrollTop ${wheelGesture.top}) 'Jump to latest' is offered at the top`,
|
||||
);
|
||||
|
||||
// The live assistant answer carries markdown but no fenced block: the session's
|
||||
// fenced code lives in its reasoning, which the app renders as plain text
|
||||
// (Markdown.kt draws reasoning with a plain Text, never the markdown subset).
|
||||
if (transcript.reasoning > 0) {
|
||||
const expanded = await page.evaluate(`(() => {
|
||||
const block = document.querySelector("#chatTranscript .chat-reasoning");
|
||||
if (!block) return null;
|
||||
block.querySelector(".chat-reasoning-toggle")?.click();
|
||||
const body = block.querySelector(".chat-reasoning-body");
|
||||
if (!body) return null;
|
||||
// Bring the reasoning's own fenced block into view, so the capture shows
|
||||
// the code the live session actually carries.
|
||||
const fence = String.fromCharCode(96).repeat(3);
|
||||
const text = body.textContent ?? "";
|
||||
const index = text.indexOf(fence);
|
||||
const transcript = document.querySelector("#chatTranscript");
|
||||
if (index >= 0 && transcript && body.firstChild && body.firstChild.nodeType === 3) {
|
||||
const range = document.createRange();
|
||||
range.setStart(body.firstChild, index);
|
||||
range.setEnd(body.firstChild, index + fence.length);
|
||||
const rect = range.getBoundingClientRect();
|
||||
const tRect = transcript.getBoundingClientRect();
|
||||
transcript.scrollTop += Math.round(rect.top - tRect.top) - 120;
|
||||
}
|
||||
return {
|
||||
label: block.querySelector(".chat-reasoning-label")?.textContent ?? "",
|
||||
hasFence: index >= 0,
|
||||
};
|
||||
})()`);
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`(() => { const b = document.querySelector("#chatTranscript .chat-reasoning-body"); return !!b && !b.hidden; })()`,
|
||||
),
|
||||
{ timeout: 5000, what: "the reasoning block to expand" },
|
||||
);
|
||||
if (expanded) {
|
||||
console.log(` reasoning block "${expanded.label}" expanded; carries a fenced block: ${expanded.hasFence}`);
|
||||
}
|
||||
await shot("47-chat-reasoning-code.png");
|
||||
}
|
||||
|
||||
// C7's code-block path. The live assistant answer carries no fenced block (its
|
||||
// fences live in the reasoning transcript, drawn as plain text — capture 47),
|
||||
// so exercise the page's own markdown renderer on a labelled sample and capture
|
||||
// the rendered <pre> block; the sample is removed again straight after.
|
||||
const fence = String.fromCharCode(96).repeat(3);
|
||||
const codeSample = `${fence}js\nconst answer = 42;\n${fence}`;
|
||||
const codeBlock = await page.evaluate(`(async () => {
|
||||
const mod = await import("/src/app.js");
|
||||
const node = mod.renderMarkdown(${JSON.stringify(codeSample)});
|
||||
node.id = "markdownCodeSample";
|
||||
const wrap = document.querySelector(".chat-detail .chat-transcript-wrap");
|
||||
if (!wrap || !wrap.parentNode) return null;
|
||||
wrap.parentNode.insertBefore(node, wrap);
|
||||
return {
|
||||
label: node.querySelector(".md-code-label")?.textContent ?? "",
|
||||
hasPre: !!node.querySelector("pre.md-pre code"),
|
||||
text: node.querySelector("pre.md-pre code")?.textContent ?? "",
|
||||
};
|
||||
})()`);
|
||||
if (!codeBlock || !codeBlock.hasPre) {
|
||||
throw new Error("the page's markdown renderer drew no fenced code block");
|
||||
}
|
||||
if (codeBlock.label !== "js") throw new Error(`code block label: ${codeBlock.label}`);
|
||||
console.log(
|
||||
` markdown code block (page renderer sample): label "${codeBlock.label}", text ${JSON.stringify(codeBlock.text)}`,
|
||||
);
|
||||
await shot("47b-chat-markdown-code.png");
|
||||
await page.evaluate(`document.querySelector("#markdownCodeSample")?.remove()`);
|
||||
|
||||
if (transcript.hasLoadOlder) {
|
||||
// The control was present in capture 45. Press it and capture the honest
|
||||
// result: the live session's own cursor returns an empty older page, so the
|
||||
// control disappears (the prepend path itself is unit-tested).
|
||||
await page.evaluate(`document.querySelector(".chat-load-older")?.click()`);
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".chat-load-older")`), {
|
||||
timeout: 15000,
|
||||
what: "the empty older history page to settle",
|
||||
});
|
||||
await shot("48-chat-load-older-empty.png");
|
||||
console.log(
|
||||
" 'Load older messages' was shown while has_more (capture 45); the server's own next_cursor returned an empty older page and the control disappeared",
|
||||
);
|
||||
} else {
|
||||
console.log(" -- no 'Load older messages' control: the server did not report has_more");
|
||||
}
|
||||
|
||||
// The close confirm: shown, then dismissed with Cancel. The operator's only
|
||||
// live session is never mutated, so no chat_close is sent. The transcript is
|
||||
// mid-scroll (following false), so this also asserts the C14 fix: opening and
|
||||
// dismissing the dialog must not move the operator's view.
|
||||
const beforeDialog = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
return {
|
||||
top: el ? Math.round(el.scrollTop) : null,
|
||||
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
|
||||
};
|
||||
})()`);
|
||||
if (!beforeDialog || beforeDialog.top == null || beforeDialog.top === 0) {
|
||||
throw new Error(`the transcript was not mid-scroll before the dialog: ${JSON.stringify(beforeDialog)}`);
|
||||
}
|
||||
await page.click(`#chatRows .chat-row[data-session="${openedId}"] .chat-close`);
|
||||
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
|
||||
const closeDialog = await page.evaluate(`(() => ({
|
||||
title: document.querySelector(".confirm-chat-close .confirm-title")?.textContent ?? "",
|
||||
message: document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? "",
|
||||
confirm: document.querySelector(".confirm-chat-close .confirm-accept")?.textContent ?? "",
|
||||
dismiss: document.querySelector(".confirm-chat-close .confirm-dismiss")?.textContent ?? "",
|
||||
}))()`);
|
||||
if (closeDialog.title !== "Close chat?") throw new Error(`close title: ${closeDialog.title}`);
|
||||
if (!closeDialog.message.startsWith("Closes \"")) throw new Error(`close message: ${closeDialog.message}`);
|
||||
if (!closeDialog.message.includes("marks it closed on every device")) {
|
||||
throw new Error(`close message: ${closeDialog.message}`);
|
||||
}
|
||||
if (!closeDialog.message.includes("Nothing is deleted")) {
|
||||
throw new Error(`close message: ${closeDialog.message}`);
|
||||
}
|
||||
if (closeDialog.confirm !== "Close chat") throw new Error(`close confirm: ${closeDialog.confirm}`);
|
||||
if (closeDialog.dismiss !== "Cancel") throw new Error(`close dismiss: ${closeDialog.dismiss}`);
|
||||
const whileDialog = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
return {
|
||||
top: el ? Math.round(el.scrollTop) : null,
|
||||
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
|
||||
};
|
||||
})()`);
|
||||
if (Math.abs((whileDialog.top ?? -1) - beforeDialog.top) > 2 || whileDialog.jumpHidden !== false) {
|
||||
throw new Error(
|
||||
`opening the close dialog moved the transcript: ${JSON.stringify(beforeDialog)} -> ${JSON.stringify(whileDialog)}`,
|
||||
);
|
||||
}
|
||||
console.log(` close dialog (shown, NOT executed): "${closeDialog.title}" — ${closeDialog.message}`);
|
||||
console.log(` the transcript stayed put across the dialog (top ${beforeDialog.top} -> ${whileDialog.top})`);
|
||||
await shot("49-chat-close-confirm.png");
|
||||
await page.click(".confirm-chat-close .confirm-dismiss");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
|
||||
timeout: 5000,
|
||||
what: "the close dialog to close",
|
||||
});
|
||||
const afterDialog = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
return el ? Math.round(el.scrollTop) : null;
|
||||
})()`);
|
||||
if (afterDialog == null || Math.abs(afterDialog - beforeDialog.top) > 2) {
|
||||
throw new Error(`dismissing the close dialog moved the transcript: ${beforeDialog.top} -> ${afterDialog}`);
|
||||
}
|
||||
console.log(
|
||||
" the mutating confirm was NOT executed: no chat_close was sent for the operator's live session " +
|
||||
`${openedId}`,
|
||||
);
|
||||
|
||||
console.log("\nUI SMOKE PASS");
|
||||
for (const shot of shots) console.log(` ${shot}`);
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user