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:
+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();
|
||||
|
||||
Reference in New Issue
Block a user