3228 lines
119 KiB
JavaScript
3228 lines
119 KiB
JavaScript
// The Chat destination: the session list and create pane, the live transcript,
|
||
// reasoning/tool panels, markdown, approval cards, background tasks, composer,
|
||
// slash commands, notices and the local rename/hide/seen store. Pure models live
|
||
// in chat.js and markdown.js; this module owns the DOM and the chat wire wiring.
|
||
|
||
import { h, renderLiveBadge } from "../dom.js";
|
||
import { describeError } from "../format.js";
|
||
import { SHELL_OUTPUT_LIMIT, newChatOperationId } from "../repository.js";
|
||
import { codeBlockLabel, parseInline, parseMarkdown } from "../markdown.js";
|
||
import { formatDuration } from "../runs.js";
|
||
import { humanBytes } from "../artifacts.js";
|
||
import { changeStat, diffLineClass, diffLineSymbol } from "../changes.js";
|
||
import {
|
||
BACKGROUND_TASKS_TITLE,
|
||
CHAT_ACTIONS_LABEL,
|
||
CHAT_ATTACH_LABEL,
|
||
CHAT_COMMAND_DISMISS_LABEL,
|
||
CHAT_COMMAND_GLYPH,
|
||
CHAT_COMPOSER_PLACEHOLDER,
|
||
CHAT_CREATE_BACK_LABEL,
|
||
CHAT_CREATE_CANCEL,
|
||
CHAT_CREATE_CONFIRM,
|
||
CHAT_CREATE_LOADING,
|
||
CHAT_CREATE_MODEL_NOTE,
|
||
CHAT_CREATE_PROMPT,
|
||
CHAT_CREATE_TITLE,
|
||
CHAT_EMPTY,
|
||
CHAT_FOLLOW_THRESHOLD_PX,
|
||
CHAT_HIDE_ACTION,
|
||
CHAT_LOADING,
|
||
CHAT_NEW_ACTION,
|
||
CHAT_NO_MATCH_ACTION,
|
||
CHAT_QUEUED_NOTICE,
|
||
CHAT_REMOVED_MESSAGE,
|
||
CHAT_RENAME_ACTION,
|
||
CHAT_RENAME_DISMISS,
|
||
CHAT_RENAME_FIELD_LABEL,
|
||
CHAT_RENAME_HELPER,
|
||
CHAT_RENAME_SAVE,
|
||
CHAT_RENAME_TITLE,
|
||
CHAT_SEARCH_LABEL,
|
||
CHAT_SEND_LABEL,
|
||
CHAT_STOP_LABEL,
|
||
CHAT_TAB_TITLE,
|
||
CHAT_UNDO_ACTION,
|
||
CLOSED_CHIP_LABEL,
|
||
CLOSED_SECTION_LABEL,
|
||
CLOSE_CHAT_ACTION,
|
||
CLOSE_CHAT_CONFIRM,
|
||
CLOSE_CHAT_DISMISS,
|
||
CLOSE_CHAT_TITLE,
|
||
COMPOSER_SEND,
|
||
COMPOSER_STOP,
|
||
CONVERSATION_EMPTY,
|
||
CONVERSATION_LOADING,
|
||
LOAD_OLDER_ACTION,
|
||
REOPEN_ACTION,
|
||
SELECT_CHAT_HINT,
|
||
APPROVAL_CONTROL_ALWAYS,
|
||
APPROVAL_CONTROL_ONCE,
|
||
APPROVAL_CONTROL_REJECT,
|
||
DECISION_ALWAYS,
|
||
DECISION_ONCE,
|
||
DECISION_REJECT,
|
||
RISK_REVIEW_LABEL,
|
||
WAITING_FOR_APPROVAL_LABEL,
|
||
SHELL_DETAILS_LABEL,
|
||
SHELL_OUTPUT_EMPTY,
|
||
SHELL_OUTPUT_ERROR,
|
||
SHELL_OUTPUT_LABELS,
|
||
SHELL_OUTPUT_LOADING,
|
||
SHELL_OUTPUT_READY,
|
||
SHELL_OUTPUT_UNAVAILABLE,
|
||
SHELL_ROW_LABEL,
|
||
applyChatEvent,
|
||
applyChatOverrides,
|
||
applyChatPermission,
|
||
appendChatNotice,
|
||
approvalCard,
|
||
attachmentDisplayName,
|
||
attachmentError,
|
||
attachmentFiles,
|
||
backgroundTasksRunningLabel,
|
||
chatBottomDistancePx,
|
||
chatCommandEffect,
|
||
chatCommandHelp,
|
||
chatCommandSuggestions,
|
||
chatCreateFailed,
|
||
chatCreateSucceeded,
|
||
chatFirstScroll,
|
||
chatFollowsAt,
|
||
chatHeaderMeta,
|
||
chatNoMatchMessage,
|
||
chatNoticeLabel,
|
||
chatOpensAtNewest,
|
||
chatShowJumpToLatest,
|
||
chatStartInLabel,
|
||
chatStreamState,
|
||
closeChatConfirmation,
|
||
composerAction,
|
||
composerCanSend,
|
||
composerSendEnabled,
|
||
composerSubmit,
|
||
decodeChatOverrides,
|
||
decodeChatSeen,
|
||
defaultDirectoryChoice,
|
||
directoryChoices,
|
||
directoryLabel,
|
||
dismissChatNotice as dismissChatNoticeModel,
|
||
emptyChatOverrides,
|
||
emptyChatSeen,
|
||
encodeChatOverrides,
|
||
encodeChatSeen,
|
||
filterSessions,
|
||
groupSessionsByDirectory,
|
||
hideChatOverride,
|
||
historyResync,
|
||
isChatSessionUnseen,
|
||
makeChatNotice,
|
||
markChatUnseen,
|
||
mergeHistoryPage,
|
||
mergeShellFrame,
|
||
newChatCreateState,
|
||
newChatThread,
|
||
parseChatInput,
|
||
queuedAfterFrame,
|
||
readChatSeen,
|
||
reasoningLabel,
|
||
renameChatOverride,
|
||
restoreChatOverride,
|
||
resumedThread,
|
||
runningAfterFrame,
|
||
runningBackgroundShells,
|
||
runningToolElapsedMillis,
|
||
seedChatSeen,
|
||
sessionActivity,
|
||
sessionActivityBadge,
|
||
sessionChipLabel,
|
||
sessionMeta,
|
||
sessionStatusLabel,
|
||
selectChatDirectory as selectChatDirectoryModel,
|
||
sessionTitle,
|
||
sessionWorkLabel,
|
||
settledThread,
|
||
shellCommandSummary,
|
||
shellOutputState,
|
||
shellsLoaded,
|
||
takeChatNoticeOffer as takeChatNoticeOfferModel,
|
||
formatToolDuration,
|
||
threadElapsedMillis,
|
||
threadPhase,
|
||
threadRunningTools,
|
||
threadToolElapsedMillis,
|
||
TURN_PHASE_WAITING,
|
||
toolCallCount,
|
||
toolCallRow,
|
||
toolCallsAnnouncement,
|
||
toolCallsLabel,
|
||
toolDetail,
|
||
toolFailed,
|
||
toolLabel,
|
||
toolLongRunning,
|
||
toolRunning,
|
||
toolsRunning,
|
||
transcriptRows,
|
||
turnElapsedMillis,
|
||
turnPhaseLabel,
|
||
} from "../chat.js";
|
||
|
||
const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1";
|
||
|
||
/**
|
||
* The per-chat composer drafts (C8). Mirrored into localStorage, the browser
|
||
* analogue of the Android store's per-device draft: a draft survives a reload,
|
||
* keyed by session id (attachments are memory-only — a File handle cannot be
|
||
* serialised). The in-memory `thread.draft` is the source of truth while the page
|
||
* is open; this is only the persistence beside it.
|
||
*/
|
||
const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1";
|
||
|
||
/**
|
||
* The operator's own chat changes (C13): local renames and hidden session ids,
|
||
* the web analogue of Android's `chat_overrides` preference. One JSON value:
|
||
* `{titles:{"<id>":"<title>"},hidden:["<id>"]}`. A local title wins over the
|
||
* server's on every later list refresh; a hidden id only disappears here.
|
||
*/
|
||
const CHAT_OVERRIDES_STORAGE_KEY = "pipelines.web.chatOverrides.v1";
|
||
|
||
/**
|
||
* What the operator has already seen of the session list (C13), the web analogue
|
||
* of Android's `chat_seen` preference. One JSON value:
|
||
* `{seenAt:{"<id>":<updated_at ms>},unseen:["<id>"]}`. The watermark is advanced
|
||
* only by opening a chat (or first-sight seeding), never by a stale list.
|
||
*/
|
||
const CHAT_SEEN_STORAGE_KEY = "pipelines.web.chatSeen.v1";
|
||
|
||
/** The sessionStorage key for this tab's verification-chat ids. */
|
||
const EPHEMERAL_CHATS_KEY = "pipelines.web.ephemeralChats.v1";
|
||
|
||
/** This tab's verification-chat ids (never listed), or an empty set. */
|
||
export function readEphemeralChatIds() {
|
||
try {
|
||
const raw = sessionStorage.getItem(EPHEMERAL_CHATS_KEY);
|
||
const ids = raw ? JSON.parse(raw) : [];
|
||
return Array.isArray(ids) ? ids.filter((id) => typeof id === "string" && id.trim() !== "") : [];
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/** The persisted per-session scroll positions, or an empty map when unreadable. */
|
||
export function readChatScrollStore() {
|
||
try {
|
||
const parsed = JSON.parse(localStorage.getItem(CHAT_SCROLL_STORAGE_KEY) ?? "{}");
|
||
return parsed && typeof parsed === "object" ? parsed : {};
|
||
} catch {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
|
||
/** The persisted per-chat drafts, or an empty map when unreadable. */
|
||
export function readChatDraftStore() {
|
||
try {
|
||
const parsed = JSON.parse(localStorage.getItem(CHAT_DRAFT_STORAGE_KEY) ?? "{}");
|
||
return parsed && typeof parsed === "object" ? parsed : {};
|
||
} catch {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
/** The persisted draft for one conversation, or "" when there is none. */
|
||
export function readChatDraft(sessionId) {
|
||
const value = readChatDraftStore()[sessionId];
|
||
return typeof value === "string" ? value : "";
|
||
}
|
||
|
||
/** The persisted local chat overrides; unreadable storage means no overrides. */
|
||
export function readChatOverridesStore() {
|
||
try {
|
||
return decodeChatOverrides(localStorage.getItem(CHAT_OVERRIDES_STORAGE_KEY));
|
||
} catch {
|
||
return emptyChatOverrides();
|
||
}
|
||
}
|
||
|
||
/** The persisted seen state; unreadable storage means nothing seen. */
|
||
export function readChatSeenStore() {
|
||
try {
|
||
return decodeChatSeen(localStorage.getItem(CHAT_SEEN_STORAGE_KEY));
|
||
} catch {
|
||
return emptyChatSeen();
|
||
}
|
||
}
|
||
|
||
export function createChatView(rt) {
|
||
const { state, repo } = rt;
|
||
let chatClock = null;
|
||
let chatNow = Date.now();
|
||
const renderContent = (...args) => rt.renderContent(...args);
|
||
const renderActionFailedDialog = (...args) => rt.views.dialogs.renderActionFailedDialog(...args);
|
||
|
||
/** 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
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Mirror one conversation's draft into localStorage. A blank draft clears its
|
||
* entry so the store cannot grow without bound; the in-memory `thread.draft`
|
||
* stays the source of truth, this is only the persistence beside it.
|
||
*/
|
||
function saveChatDraft(sessionId, text) {
|
||
if (!sessionId) return;
|
||
try {
|
||
const store = readChatDraftStore();
|
||
if (String(text ?? "") === "") delete store[sessionId];
|
||
else store[sessionId] = String(text);
|
||
localStorage.setItem(CHAT_DRAFT_STORAGE_KEY, JSON.stringify(store));
|
||
} catch {
|
||
// storage may be full or disabled; the in-memory draft still holds
|
||
}
|
||
}
|
||
|
||
/** Persist the current local overrides; storage failure leaves memory authoritative. */
|
||
function saveChatOverrides() {
|
||
try {
|
||
localStorage.setItem(CHAT_OVERRIDES_STORAGE_KEY, encodeChatOverrides(state.chatOverrides));
|
||
} catch {
|
||
// storage may be full or disabled; the in-memory overrides still hold
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* Persist the seen state only when it actually changed. Every frame and refresh
|
||
* would otherwise rewrite localStorage for no reason.
|
||
*/
|
||
function saveChatSeen(next) {
|
||
if (next === state.chatSeen) return;
|
||
state.chatSeen = next;
|
||
try {
|
||
localStorage.setItem(CHAT_SEEN_STORAGE_KEY, encodeChatSeen(state.chatSeen));
|
||
} catch {
|
||
// storage may be full or disabled; the in-memory state still holds
|
||
}
|
||
}
|
||
|
||
|
||
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 {
|
||
const listed = await repo.chatSessions();
|
||
// Keep this page's own verification chats, which the server intentionally
|
||
// never returns, at the head of the in-memory list (memory-only; see
|
||
// chatEphemeralIds). Everything else is the server's list, in its order.
|
||
const held = state.chatSessions.filter(
|
||
(session) =>
|
||
state.chatEphemeralIds.has(session.id) && !listed.some((entry) => entry.id === session.id),
|
||
);
|
||
state.chatSessions = [...held, ...listed];
|
||
state.chatLoaded = true;
|
||
// Fold this device's seen state in: the active chat has been read, and every
|
||
// session seen for the first time gets a baseline so pre-existing chats are
|
||
// not all reported as new.
|
||
saveChatSeen(seedChatSeen(state.chatSeen, state.chatSessions, state.chatActiveId));
|
||
} catch (error) {
|
||
state.chatError = describeError(error);
|
||
}
|
||
state.chatLoading = false;
|
||
renderContent();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// The create flow (C2, ChatCreatePane.kt)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Open the create pane with a fresh operation id. The id is minted once per
|
||
* intent, so a retry after a refusal reuses it and the server can dedupe the
|
||
* create rather than starting a second session.
|
||
*/
|
||
function startNewChat() {
|
||
state.chatCreate = newChatCreateState(newChatOperationId());
|
||
state.chatDirectoriesError = "";
|
||
renderContent();
|
||
loadChatDirectories();
|
||
}
|
||
|
||
/**
|
||
* Fetch `chat_directories` for the open picker. A failure keeps the reason for the
|
||
* pane's error state; blank entries are dropped here as well as in the pure model
|
||
* so a malformed reply can never produce an empty row. An already-loaded list is
|
||
* reused unless [force] (the error state's Retry) asks again.
|
||
*/
|
||
async function loadChatDirectories(force = false) {
|
||
if (!state.chatCreate || state.chatDirectoriesLoading) return;
|
||
if (state.chatDirectoriesLoaded && !force) return;
|
||
state.chatDirectoriesLoading = true;
|
||
state.chatDirectoriesError = "";
|
||
renderContent();
|
||
try {
|
||
const directories = await repo.chatDirectories();
|
||
state.chatDirectories = (directories ?? []).filter((entry) => String(entry ?? "").trim() !== "");
|
||
state.chatDirectoriesLoaded = true;
|
||
} catch (error) {
|
||
state.chatDirectoriesError = describeError(error);
|
||
}
|
||
state.chatDirectoriesLoading = false;
|
||
renderContent();
|
||
}
|
||
|
||
/** Select one directory row (the value is what chat_create will send). */
|
||
function selectChatDirectory(value) {
|
||
if (!state.chatCreate) return;
|
||
state.chatCreate = selectChatDirectoryModel(state.chatCreate, value);
|
||
renderContent();
|
||
}
|
||
|
||
/** Leave the create flow without creating anything. */
|
||
function cancelNewChat() {
|
||
state.chatCreate = null;
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Create the chat in the chosen directory. Guarded against a double submit: the
|
||
* guard reads the held state, so a second click while the request is in flight
|
||
* sends nothing. On success the pane closes, the created session goes to the head
|
||
* of the list, becomes the open conversation and loads its (empty) history; on
|
||
* failure the server's own reason stays in the pane, which does not close.
|
||
*/
|
||
async function createNewChat() {
|
||
const create = state.chatCreate;
|
||
if (!create || create.creating) return;
|
||
state.chatCreate = { ...create, creating: true, error: "" };
|
||
renderContent();
|
||
try {
|
||
// Not ephemeral: this is the operator's own create path (the UI smoke uses the
|
||
// same path for its one real session and closes it afterwards).
|
||
const created = await repo.chatCreate("New chat", create.directory, create.operationId);
|
||
state.chatCreate = null;
|
||
state.chatSessions = chatCreateSucceeded(state.chatSessions, created);
|
||
await openChatSession(created.id);
|
||
await loadChatSessions();
|
||
} catch (error) {
|
||
if (!state.chatCreate) return;
|
||
state.chatCreate = chatCreateFailed(state.chatCreate, describeError(error));
|
||
renderContent();
|
||
}
|
||
}
|
||
|
||
/** Open a session: select it, subscribe its stream 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.chatMenu = null;
|
||
state.chatPlaced = null;
|
||
state.chatFollowing = true;
|
||
state.chatReasoning = new Set();
|
||
state.chatToolPanels = new Set();
|
||
state.chatToolRows = new Set();
|
||
// Opening reads the conversation: advance the watermark to its current recency
|
||
// and clear the explicit unseen mark (a row that is absent has no recency).
|
||
const session = state.chatSessions.find((candidate) => candidate.id === id) ?? null;
|
||
saveChatSeen(readChatSeen(state.chatSeen, id, session?.updated_at ?? 0));
|
||
const existing = state.chatThreads.get(id);
|
||
state.chatThreads.set(id, {
|
||
...newChatThread(id),
|
||
...(existing ?? {}),
|
||
// The composer's own per-chat state (C8/C9) survives a switch; the draft is
|
||
// seeded from localStorage on the first open (the per-device analogue). The
|
||
// live-stream fields (C5) come from `newChatThread`.
|
||
draft: existing ? existing.draft ?? "" : readChatDraft(id),
|
||
attachments: existing?.attachments ?? [],
|
||
notices: existing?.notices ?? [],
|
||
loaded: false,
|
||
loading: true,
|
||
error: "",
|
||
});
|
||
renderContent();
|
||
// Attach the shared live stream once per session per connection; its failure is
|
||
// non-fatal — history stays usable and the badge reads "not live".
|
||
subscribeChatSession(id);
|
||
// Load the session's background shells (C11) so the bar appears on open, not
|
||
// only after the next pushed shell frame.
|
||
loadChatShells(id);
|
||
await loadChatHistory(id);
|
||
}
|
||
|
||
/** Replace one conversation's fields, keeping every other field intact. */
|
||
function setThread(sessionId, patch) {
|
||
const current = state.chatThreads.get(sessionId);
|
||
if (!current) return;
|
||
state.chatThreads.set(sessionId, { ...current, ...patch });
|
||
}
|
||
|
||
/**
|
||
* Attach one session's shared live stream (C5): `chat_subscribe` with the session
|
||
* id as the body. Idempotent per connection — a session already subscribed is not
|
||
* asked for again. A refusal (an older server that does not know the command, or
|
||
* any other error) leaves history usable and the live badge `not live`.
|
||
*/
|
||
async function subscribeChatSession(id) {
|
||
if (!id || state.connection.kind !== "connected") return;
|
||
if (state.chatSubscriptions.has(id)) return;
|
||
try {
|
||
await repo.subscribeChat(id);
|
||
state.chatSubscriptions = new Set(state.chatSubscriptions).add(id);
|
||
} catch {
|
||
// The subscription is not live; nothing else changes. The badge says so.
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Drop the per-connection subscriptions (the server detaches them on close). */
|
||
function clearChatSubscriptions() {
|
||
if (state.chatSubscriptions.size > 0) state.chatSubscriptions = new Set();
|
||
}
|
||
|
||
/**
|
||
* Settle every conversation that was running, and drop its observed shells. A
|
||
* socket drop (or a close) removes the frames feeding the turn, so no thread
|
||
* keeps claiming to run until a fresh frame proves otherwise; a shell's exit may
|
||
* have been swallowed by the same gap, so the retained shells are forgotten and
|
||
* re-learned from `chat_shells` on reconnect (mirrors ChatStore.streamResumed).
|
||
*/
|
||
function settleChatThreads() {
|
||
for (const [id, thread] of state.chatThreads) {
|
||
const hasShells = (thread?.shells ?? []).length > 0;
|
||
if (thread?.running || thread?.queued || hasShells) {
|
||
state.chatThreads.set(id, resumedThread(thread));
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Fold one pushed `chat_event` frame into its conversation. Only a conversation
|
||
* this client has open is folded (a frame for a session nobody opened is
|
||
* ignored); the server only pushes frames for sessions this connection subscribed
|
||
* to, so this is a no-op in practice until a chat is opened.
|
||
*/
|
||
function onChatEvent(frame) {
|
||
const sessionId = String(frame?.session_id ?? "").trim();
|
||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||
markBackgroundChatUnseen(sessionId);
|
||
const thread = state.chatThreads.get(sessionId);
|
||
state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now()));
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* A frame for a conversation that is not on screen marks it explicitly unseen,
|
||
* so its live activity is visible in the list even though a pushed stream carries
|
||
* no wall-clock recency to compare. The active chat is read as it arrives and is
|
||
* never marked.
|
||
*/
|
||
function markBackgroundChatUnseen(sessionId) {
|
||
if (!sessionId || sessionId === state.chatActiveId) return;
|
||
saveChatSeen(markChatUnseen(state.chatSeen, sessionId));
|
||
}
|
||
|
||
/**
|
||
* Fold one pushed `chat_permission` frame into its conversation (C10). Only a
|
||
* conversation this client has open is folded — the server only pushes a
|
||
* permission frame for sessions this connection is subscribed to, but the guard
|
||
* keeps a frame for a session nobody opened from creating a thread. The card is
|
||
* derived from the stored frame plus the local answer, so a resolved re-push
|
||
* always clears the controls.
|
||
*/
|
||
function onChatPermission(frame) {
|
||
const sessionId = String(frame?.session_id ?? "").trim();
|
||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||
const thread = state.chatThreads.get(sessionId);
|
||
const next = applyChatPermission(thread, frame);
|
||
// A different request replaces the card, so the previous refusal's reason (and
|
||
// the error line it owns) no longer describes what is on screen.
|
||
const replaced =
|
||
String(thread?.permission?.request_id ?? "") !== String(next.permission?.request_id ?? "");
|
||
if (replaced && thread?.permissionError) {
|
||
next.error = thread.error === thread.permissionError ? "" : next.error;
|
||
next.permissionError = "";
|
||
}
|
||
state.chatThreads.set(sessionId, next);
|
||
if (sessionId === state.chatActiveId) renderContent();
|
||
}
|
||
|
||
/**
|
||
* Answer the pending permission request (C10): settle the matching card
|
||
* optimistically so the buttons are never left offering a decision already made,
|
||
* then send `chat_reply`. A refused reply reopens the same request (the local
|
||
* answer is cleared) and surfaces the server's reason through the thread's own
|
||
* error line, so an unaccepted decision is never shown as accepted. A refusal
|
||
* that arrives after a different request replaced the card is ignored.
|
||
*/
|
||
async function answerPermission(sessionId, requestId, decision) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
const permission = thread?.permission;
|
||
if (!thread || String(permission?.request_id ?? "") !== requestId) return;
|
||
setThread(sessionId, { permissionAnswer: decision });
|
||
renderContent();
|
||
try {
|
||
await repo.chatReply(sessionId, requestId, decision);
|
||
// A retried answer the server accepted clears the reason a previous refusal
|
||
// left on the thread's error line — and only that reason, never an unrelated
|
||
// error the conversation is carrying.
|
||
const settled = state.chatThreads.get(sessionId);
|
||
if (settled?.permissionError && settled.error === settled.permissionError) {
|
||
setThread(sessionId, { error: "", permissionError: "" });
|
||
renderContent();
|
||
}
|
||
} catch (error) {
|
||
const current = state.chatThreads.get(sessionId);
|
||
if (!current || String(current.permission?.request_id ?? "") !== requestId) return;
|
||
const reason = describeError(error);
|
||
setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason });
|
||
renderContent();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The reconnect repair (C5): re-attach the open chat's stream and replace its
|
||
* conversation with the newest history page wholesale. Everything the gap could
|
||
* have missed is repaired; a turn that was in flight is settled. Only the open
|
||
* conversation is repaired — the others are not on screen.
|
||
* Fetch a session's currently verified shells (C11) and retain only the exits
|
||
* this client itself observed, so an exited task never reappears as running and a
|
||
* shell the server no longer lists drops out. Called when the conversation opens
|
||
* and on every stream reconnect (a gap may have swallowed an exit). A failure is
|
||
* non-fatal: the transcript stays usable and the bar keeps its last known state.
|
||
*/
|
||
async function loadChatShells(id) {
|
||
if (!id || state.connection.kind !== "connected") return;
|
||
try {
|
||
const running = await repo.chatShells(id);
|
||
const thread = state.chatThreads.get(id);
|
||
if (!thread) return;
|
||
state.chatThreads.set(id, { ...thread, shells: shellsLoaded(thread.shells, running) });
|
||
renderContent();
|
||
} catch {
|
||
// The shell list is a background convenience; leave the thread untouched.
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Toggle a running task's detail pane (C11). Selecting a shell fetches its
|
||
* bounded output page; selecting the selected one again closes it. Mirrors
|
||
* ChatStore.selectShell: an id that is not a known shell is ignored.
|
||
*/
|
||
function selectChatShell(shellId) {
|
||
const sessionId = state.chatActiveId;
|
||
const thread = sessionId ? state.chatThreads.get(sessionId) : null;
|
||
if (!thread) return;
|
||
const closing = thread.selectedShellId === shellId;
|
||
if (!closing && !(thread.shells ?? []).some((shell) => shell.id === shellId)) return;
|
||
const next = closing ? null : shellId;
|
||
state.chatThreads.set(sessionId, { ...thread, selectedShellId: next, shellOutput: null });
|
||
renderContent();
|
||
if (next) refreshChatShellOutput(next);
|
||
}
|
||
|
||
/**
|
||
* Reread a selected task's bounded output page (C11) from the page's start. The
|
||
* cursor is always 0 and the limit is the server's 64 KiB bound, so the client
|
||
* never grows output unbounded and a Refresh never appends. A reply for a shell
|
||
* that is no longer selected is ignored, exactly like ChatStore.shellOutput*.
|
||
*/
|
||
async function refreshChatShellOutput(shellId) {
|
||
const sessionId = state.chatActiveId;
|
||
if (!sessionId || !shellId) return;
|
||
shellOutputLoading(sessionId, shellId);
|
||
renderContent();
|
||
try {
|
||
const page = await repo.chatShellOutput(sessionId, shellId, { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
|
||
shellOutputLoaded(sessionId, shellId, page);
|
||
} catch (error) {
|
||
shellOutputFailed(sessionId, shellId, describeError(error));
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Mark a selected task's output pane loading (ignored for a stale selection). */
|
||
function shellOutputLoading(sessionId, shellId) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || thread.selectedShellId !== shellId) return;
|
||
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: true, error: "", page: null } });
|
||
}
|
||
|
||
/**
|
||
* Apply a loaded output page, merging a shell the page reports back into the
|
||
* retained list (keeping the command already learned when the page omits it).
|
||
*/
|
||
function shellOutputLoaded(sessionId, shellId, page) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || thread.selectedShellId !== shellId) return;
|
||
const reported = page?.shell;
|
||
const shells = reported && String(reported.id ?? "").trim() !== ""
|
||
? mergeShellFrame(thread.shells, reported)
|
||
: thread.shells ?? [];
|
||
state.chatThreads.set(sessionId, { ...thread, shells, shellOutput: { loading: false, error: "", page } });
|
||
}
|
||
|
||
/** Report a failed output read against the still-selected task (Retry is offered). */
|
||
function shellOutputFailed(sessionId, shellId, message) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || thread.selectedShellId !== shellId) return;
|
||
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: false, error: message, page: null } });
|
||
}
|
||
|
||
/**
|
||
* The reconnect repair (C5/C11): re-attach the open chat's stream, replace its
|
||
* conversation with the newest history page wholesale and re-learn its shells.
|
||
* Everything the gap could have missed is repaired; a turn that was in flight is
|
||
* settled and the retained shells are dropped before the fresh snapshot arrives.
|
||
* Only the open conversation is repaired — the others are not on screen.
|
||
*/
|
||
async function resyncOpenChat() {
|
||
const id = state.chatActiveId;
|
||
if (!id || state.connection.kind !== "connected") return;
|
||
await subscribeChatSession(id);
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
state.chatThreads.set(id, resumedThread(previous));
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
state.chatThreads.set(id, historyResync(previous, page));
|
||
} catch {
|
||
// The history refresh failed; the settled thread stands and the badge is honest.
|
||
}
|
||
await loadChatShells(id);
|
||
renderContent();
|
||
}
|
||
|
||
/** Load (or reload) a session's newest history page and merge it in. */
|
||
async function loadChatHistory(id) {
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
// The merged page replaces only the history fields; spreading it over the
|
||
// held thread keeps the composer's draft, attachments and flags intact (a
|
||
// draft typed while the page was loading is not lost).
|
||
setThread(id, mergeHistoryPage(previous, page, { older: false }));
|
||
} catch (error) {
|
||
setThread(id, { 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;
|
||
setThread(id, mergeHistoryPage(current, page, { older: true }));
|
||
} catch (error) {
|
||
setThread(id, { loading: false, error: describeError(error) });
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Open the Close chat? confirm for [session] (the mutation only on confirm). */
|
||
function openChatClose(session) {
|
||
state.chatMenu = null;
|
||
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);
|
||
// A closed chat's turn was stopped on the server: settle its conversation and
|
||
// stop treating it as a live subscription. Nothing is deleted and it can be
|
||
// reopened from the list.
|
||
const thread = state.chatThreads.get(session.id);
|
||
if (thread) state.chatThreads.set(session.id, settledThread(thread));
|
||
if (state.chatSubscriptions.has(session.id)) {
|
||
state.chatSubscriptions = new Set(state.chatSubscriptions);
|
||
state.chatSubscriptions.delete(session.id);
|
||
}
|
||
// Closing also finishes the session for this client: the conversation leaves
|
||
// the pane, back to the list (mirrors Android's `finishSession` calling
|
||
// `chatStore.close`). A rejection above leaves the conversation exactly as it
|
||
// was; `settledThread` has already cleared the running/queued bits.
|
||
if (state.chatActiveId === session.id) {
|
||
state.chatActiveId = null;
|
||
}
|
||
} 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;
|
||
state.chatMenu = null;
|
||
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,
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// This device's chat changes (C13): local rename, hide + undo, row menu
|
||
// ---------------------------------------------------------------------------
|
||
|
||
|
||
/** Persist this tab's verification-chat ids for a reload of the same tab. */
|
||
function writeEphemeralChatIds(ids) {
|
||
try {
|
||
sessionStorage.setItem(EPHEMERAL_CHATS_KEY, JSON.stringify([...ids]));
|
||
} catch {
|
||
// Storage may be unavailable; the in-memory set still covers this page.
|
||
}
|
||
}
|
||
|
||
/** The server row with this device's local title applied (for the open pane). */
|
||
function effectiveChatSession(session) {
|
||
if (!session) return null;
|
||
return applyChatOverrides([session], state.chatOverrides)[0] ?? session;
|
||
}
|
||
|
||
|
||
function openChatMenu(sessionId) {
|
||
state.chatMenu = state.chatMenu === sessionId ? null : sessionId;
|
||
renderContent();
|
||
if (state.chatMenu) {
|
||
// The panel hangs below its button. Near the bottom of the window that would
|
||
// put the items off-screen (a real hit-test failure, not just clipping), so
|
||
// flip the panel above the row when it does not fit below.
|
||
const row = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"]`);
|
||
const panel = row?.querySelector(".chat-menu-panel");
|
||
if (panel && panel.getBoundingClientRect().bottom > window.innerHeight - 8) {
|
||
panel.style.top = "auto";
|
||
panel.style.bottom = "calc(100% + 4px)";
|
||
}
|
||
// The re-render replaced the focused button; move focus into the panel so a
|
||
// keyboard operator can walk the items without hunting for the next Tab stop.
|
||
const first = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"] .chat-menu-item`);
|
||
first?.focus();
|
||
}
|
||
}
|
||
|
||
/** Open the Rename chat dialog for [session] (its current effective title). */
|
||
function openChatRename(session) {
|
||
state.chatMenu = null;
|
||
state.chatRename = session;
|
||
renderContent();
|
||
// Same re-render note as the menu: put the cursor in the Name field.
|
||
document.getElementById("chatRenameInput")?.focus();
|
||
}
|
||
|
||
function dismissChatRename() {
|
||
state.chatRename = null;
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Record a local rename, persist it and reflect it at once: the row shows the
|
||
* local title on the next render (and every later refresh), and an open
|
||
* conversation's own title follows. Nothing is sent to the server — the
|
||
* brokered protocol has no chat rename.
|
||
*/
|
||
function applyLocalChatRename(sessionId, title) {
|
||
const next = renameChatOverride(state.chatOverrides, sessionId, title);
|
||
if (next === state.chatOverrides) return false;
|
||
state.chatOverrides = next;
|
||
saveChatOverrides();
|
||
const local = next.titles[String(sessionId)];
|
||
if (local != null) setThread(sessionId, { title: local });
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* The dialog's Save: trim, record the override, close the dialog and re-render.
|
||
* A blank title is ignored (Save is already disabled while trimmed-blank).
|
||
*/
|
||
function acceptChatRename(session, title) {
|
||
const trimmed = String(title ?? "").trim();
|
||
if (trimmed === "") return;
|
||
applyLocalChatRename(session.id, trimmed);
|
||
state.chatRename = null;
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Hide a session on this device only. The server is not asked to delete
|
||
* anything: the row disappears from this list, its conversation closes, and the
|
||
* one snackbar says exactly that with an Undo. A new hide replaces the previous
|
||
* report (one snackbar slot), never queues behind it.
|
||
*/
|
||
function hideChatLocally(sessionId) {
|
||
const id = String(sessionId ?? "");
|
||
if (!id) return;
|
||
const next = hideChatOverride(state.chatOverrides, id);
|
||
if (next === state.chatOverrides) return;
|
||
state.chatOverrides = next;
|
||
saveChatOverrides();
|
||
state.chatMenu = null;
|
||
state.chatRename = null;
|
||
// Hiding closes the conversation, exactly as Android's remove does: the thread
|
||
// is dropped, the active id cleared and the subscription forgotten.
|
||
state.chatThreads.delete(id);
|
||
if (state.chatActiveId === id) {
|
||
state.chatActiveId = null;
|
||
state.chatPlaced = null;
|
||
}
|
||
if (state.chatSubscriptions.has(id)) {
|
||
state.chatSubscriptions = new Set(state.chatSubscriptions);
|
||
state.chatSubscriptions.delete(id);
|
||
}
|
||
installChatSnackbar(id);
|
||
renderContent();
|
||
}
|
||
|
||
/** Replace the one in-flight hide report and (re)start its auto-dismiss timer. */
|
||
function installChatSnackbar(sessionId) {
|
||
if (state.chatSnackbarTimer != null) clearTimeout(state.chatSnackbarTimer);
|
||
state.chatSnackbarSeq += 1;
|
||
const id = state.chatSnackbarSeq;
|
||
state.chatSnackbar = { id, sessionId };
|
||
state.chatSnackbarTimer = setTimeout(() => {
|
||
state.chatSnackbarTimer = null;
|
||
if (state.chatSnackbar?.id !== id) return;
|
||
state.chatSnackbar = null;
|
||
renderContent();
|
||
}, 6000);
|
||
}
|
||
|
||
/** Undo the last hide: restore its row and clear the report (nothing server-side). */
|
||
function undoHideChat() {
|
||
const sessionId = state.chatSnackbar?.sessionId;
|
||
if (!sessionId) return;
|
||
const next = restoreChatOverride(state.chatOverrides, sessionId);
|
||
if (next !== state.chatOverrides) {
|
||
state.chatOverrides = next;
|
||
saveChatOverrides();
|
||
}
|
||
clearChatSnackbar();
|
||
renderContent();
|
||
}
|
||
|
||
/** Drop the hide report and its timer (Undo, expiry, or leaving the list). */
|
||
function clearChatSnackbar() {
|
||
if (state.chatSnackbarTimer != null) {
|
||
clearTimeout(state.chatSnackbarTimer);
|
||
state.chatSnackbarTimer = null;
|
||
}
|
||
state.chatSnackbar = null;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// The composer and its slash commands (C8 · C9)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
// The per-conversation attachment and notice ids. An id is unique across the
|
||
// page, so a chip or a command line is unambiguously removable after a re-render.
|
||
let chatAttachmentSeq = 0;
|
||
let chatNoticeSeq = 0;
|
||
|
||
/** Revoke an attachment's image object URL, if it created one. */
|
||
function releaseAttachment(attachment) {
|
||
if (attachment?.thumbUrl) {
|
||
try {
|
||
URL.revokeObjectURL(attachment.thumbUrl);
|
||
} catch {
|
||
// already gone
|
||
}
|
||
}
|
||
}
|
||
|
||
/** Revoke every attachment's object URL (used once the message is sent/gone). */
|
||
function releaseAttachments(attachments) {
|
||
for (const attachment of attachments ?? []) releaseAttachment(attachment);
|
||
}
|
||
|
||
/**
|
||
* Fold one server push into its session's thread: any frame for the session
|
||
* clears the queued notice (the turn it waited behind moved on), and a settled
|
||
* step clears the running bit the Stop control reads. The live transcript owns
|
||
* the rest of the frame fold; this only keeps the composer honest while C5 is
|
||
* still to land.
|
||
*/
|
||
function onChatFrame(message) {
|
||
const frame = message?.chat_event;
|
||
if (!frame || !frame.session_id) return;
|
||
const sessionId = frame.session_id;
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const queued = queuedAfterFrame(thread.queued, frame);
|
||
const running = runningAfterFrame(thread.running, frame);
|
||
if (queued === thread.queued && running === thread.running) return;
|
||
setThread(sessionId, { queued, running });
|
||
if (sessionId === state.chatActiveId) renderContent();
|
||
}
|
||
|
||
/** Add one local command line to a conversation's transcript. */
|
||
function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
chatNoticeSeq += 1;
|
||
const notice = makeChatNotice(`notice-${chatNoticeSeq}`, text, { failed, offer });
|
||
setThread(sessionId, { notices: appendChatNotice(thread.notices, notice) });
|
||
}
|
||
|
||
/** Remove one local command line (the operator cancelled or dismissed it). */
|
||
function dismissChatNotice(sessionId, noticeId) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
setThread(sessionId, { notices: dismissChatNoticeModel(thread.notices, noticeId) });
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Take an unknown-command offer's draft, removing the notice first so a stale
|
||
* tap can neither send the same draft twice nor send anything at all.
|
||
*/
|
||
function takeChatNoticeOffer(sessionId, noticeId) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return null;
|
||
const taken = takeChatNoticeOfferModel(thread.notices, noticeId);
|
||
if (taken.offer == null) return null;
|
||
setThread(sessionId, { notices: taken.notices });
|
||
return taken.offer;
|
||
}
|
||
|
||
/**
|
||
* The composer's draft field, updated in place on every keystroke: the draft is
|
||
* mirrored into localStorage, the textarea grows to fit (1–6 rows), and the
|
||
* palette and the send/stop control are refreshed without rebuilding the DOM (so
|
||
* the operator keeps focus and caret).
|
||
*/
|
||
function onComposerInput(event, sessionId, session, controls) {
|
||
const value = event.target.value;
|
||
setThread(sessionId, { draft: value });
|
||
saveChatDraft(sessionId, value);
|
||
growComposerTextarea(event.target);
|
||
refreshComposerControls(sessionId, session, controls);
|
||
}
|
||
|
||
/**
|
||
* The composer's key handling. While the offer list is showing, Up/Down move the
|
||
* highlight and Enter runs the highlighted command (mirrors ChatComposer's
|
||
* preview handler). Enter otherwise submits — which is inert while a turn is
|
||
* running unless the palette or a slash draft is present (see composerSubmit);
|
||
* Shift+Enter is left to insert a newline.
|
||
*/
|
||
function onComposerKeydown(event, sessionId, session, controls) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const suggestions = chatCommandSuggestions(thread.draft);
|
||
if (suggestions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
|
||
event.preventDefault();
|
||
const step = event.key === "ArrowDown" ? 1 : -1;
|
||
controls.selected = (controls.selected + step + suggestions.length) % suggestions.length;
|
||
refreshComposerControls(sessionId, session, controls);
|
||
return;
|
||
}
|
||
if (event.key === "Enter" && !event.shiftKey) {
|
||
event.preventDefault();
|
||
submitChatComposer(sessionId, session, controls);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Grow the composer's textarea between one and six rows to fit its content. The
|
||
* element is `box-sizing: border-box` with vertical padding, so the cap and the
|
||
* measured height both include the padding and the border: a six-row field is
|
||
* six full text lines, not five-and-a-bit, and the first row is not clipped.
|
||
*/
|
||
function growComposerTextarea(el) {
|
||
if (!el) return;
|
||
const style = getComputedStyle(el);
|
||
const line = parseFloat(style.lineHeight) || 20;
|
||
const border = el.offsetHeight - el.clientHeight;
|
||
const padding = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.paddingBottom) || 0);
|
||
const maxRows = 6;
|
||
const max = line * maxRows + padding + border;
|
||
el.style.height = "auto";
|
||
const wanted = el.scrollHeight + border;
|
||
el.style.height = `${Math.min(wanted, max)}px`;
|
||
el.style.overflowY = wanted > max ? "auto" : "hidden";
|
||
}
|
||
|
||
/**
|
||
* Refresh the composer's derived parts (the offer list, the send/stop control)
|
||
* after a keystroke, without rebuilding the textarea. The highlighted row moves
|
||
* only through the palette itself, so it is preserved here.
|
||
*/
|
||
function refreshComposerControls(sessionId, session, controls) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || !controls) return;
|
||
const suggestions = chatCommandSuggestions(thread.draft);
|
||
if (controls.selected >= suggestions.length) controls.selected = 0;
|
||
fillCommandPalette(controls.palette, suggestions, controls.selected, (index) => {
|
||
const command = suggestions[index];
|
||
if (command) runChatCommand(sessionId, session, `/${command.name}`);
|
||
});
|
||
fillComposerPrimary(controls.primary, thread, {
|
||
onSend: () => submitChatComposer(sessionId, session, controls),
|
||
onStop: () => stopChatTurn(sessionId),
|
||
});
|
||
}
|
||
|
||
/** Run the composer's submit (Enter): a command runs, else the draft sends. */
|
||
function submitChatComposer(sessionId, session, controls) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const action = composerSubmit(thread, controls?.selected ?? 0);
|
||
if (action.kind === "command") {
|
||
runChatCommand(sessionId, session, action.text);
|
||
} else if (action.kind === "send") {
|
||
sendChatPrompt(sessionId, session);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Run one slash command against a conversation (C9). The draft is always consumed
|
||
* here — a slash draft is never handed to the prompt path — so only an explicit
|
||
* "Send as message" from an unknown-command offer reaches the agent. Every
|
||
* outcome is a local transcript line.
|
||
*/
|
||
function runChatCommand(sessionId, session, text) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
setThread(sessionId, { draft: "" });
|
||
saveChatDraft(sessionId, "");
|
||
const view = { ...thread, draft: "", directory: session?.directory ?? "", running: thread.running === true };
|
||
const effect = chatCommandEffect(parseChatInput(text), view);
|
||
if (effect == null) return;
|
||
applyChatCommandEffect(sessionId, session, effect);
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Perform one command effect. `/new` creates a session in the current directory
|
||
* and opens it (the create request is C2's; until C2 lands the browser sends
|
||
* `chat_create` directly); `/close` reuses the C3 confirm; `/rename` writes to
|
||
* C13's durable device-local store; `/stop` interrupts; `/help` shows the
|
||
* command list.
|
||
*/
|
||
function applyChatCommandEffect(sessionId, session, effect) {
|
||
switch (effect.kind) {
|
||
case "start-session":
|
||
startChatSession(effect.directory);
|
||
break;
|
||
case "finish-session":
|
||
if (session) openChatClose(session);
|
||
break;
|
||
case "rename-session":
|
||
renameChatSessionLocally(sessionId, effect.title);
|
||
break;
|
||
case "stop-turn":
|
||
stopChatTurn(sessionId);
|
||
break;
|
||
case "show-help":
|
||
addChatNotice(sessionId, chatCommandHelp());
|
||
break;
|
||
case "report":
|
||
addChatNotice(sessionId, effect.text, { failed: true, offer: effect.offer ?? null });
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
|
||
/** `/new`: create a session titled "New chat" in [directory] and open it. */
|
||
async function startChatSession(directory) {
|
||
const from = state.chatActiveId;
|
||
try {
|
||
// An automated check (the UI smoke) can mark its throwaway chat ephemeral, so
|
||
// creating one for verification never adds a stray "New chat" to the
|
||
// operator's list. Set only by test tooling; a normal page leaves it unset.
|
||
const ephemeral = globalThis.__pipelinesEphemeralChat === true;
|
||
const created = await repo.chatCreate("New chat", directory, undefined, { ephemeral });
|
||
if (ephemeral) {
|
||
state.chatEphemeralIds = new Set(state.chatEphemeralIds).add(created.id);
|
||
writeEphemeralChatIds(state.chatEphemeralIds);
|
||
}
|
||
// The list is the server's; insert the created session so the row is present
|
||
// before the conversation opens, then refresh from the server.
|
||
state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)];
|
||
state.chatThreads.set(created.id, {
|
||
draft: "",
|
||
attachments: [],
|
||
notices: [],
|
||
queued: false,
|
||
running: false,
|
||
messages: [],
|
||
nextCursor: "",
|
||
hasMore: false,
|
||
loaded: false,
|
||
loading: true,
|
||
error: "",
|
||
});
|
||
const title = String(created.title ?? "").trim() || "New chat";
|
||
addChatNotice(created.id, `Started a new session “${title}” in ${directory}.`);
|
||
await openChatSession(created.id);
|
||
// An ephemeral (verification) create is intentionally absent from the server's
|
||
// list, so a refresh here would replace the just-opened conversation and drop
|
||
// its local notice. The row is already spliced above and is kept by
|
||
// loadChatSessions via chatEphemeralIds, so a listed create still refreshes.
|
||
if (!ephemeral) await loadChatSessions();
|
||
} catch (error) {
|
||
if (from) addChatNotice(from, `Couldn't start a new session in ${directory}: ${describeError(error)}`, { failed: true });
|
||
state.actionError = describeError(error);
|
||
renderContent();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* `/rename`: rename the session on this device only, through the same durable
|
||
* store the row's Rename chat dialog uses (C13). The local title wins over the
|
||
* server's on every later refresh; nothing is sent to the server.
|
||
*/
|
||
function renameChatSessionLocally(sessionId, title) {
|
||
const trimmed = String(title ?? "").trim();
|
||
if (trimmed === "") return;
|
||
applyLocalChatRename(sessionId, trimmed);
|
||
addChatNotice(sessionId, `Renamed this session to “${trimmed}” on this device only; the server's title is unchanged.`);
|
||
}
|
||
|
||
/** The composer's Stop control: interrupt the session's running turn. */
|
||
async function stopChatTurn(sessionId) {
|
||
try {
|
||
await repo.chatInterrupt(sessionId);
|
||
addChatNotice(sessionId, "Stopping the running turn…");
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Send the composer's draft with its attachments (mirrors
|
||
* `AppViewModel.sendChatPrompt`): the draft is trimmed, the compose state is
|
||
* cleared at once, and a rejected prompt restores the draft and the attachments
|
||
* with the server's own message.
|
||
*/
|
||
async function sendChatPrompt(sessionId, session) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || !composerCanSend(thread)) return;
|
||
const text = String(thread.draft).trim();
|
||
if (text === "") return;
|
||
const attachments = thread.attachments ?? [];
|
||
releaseAttachments(attachments);
|
||
setThread(sessionId, { draft: "", attachments: [] });
|
||
saveChatDraft(sessionId, "");
|
||
renderContent();
|
||
await postChatPrompt(sessionId, text, attachments);
|
||
}
|
||
|
||
/**
|
||
* One prompt, from the composer or an unknown-command offer. Flags the chat
|
||
* running, posts it, and takes the attachments back out flagged with the
|
||
* server's reason if it is rejected. The live transcript item (C5) owns the
|
||
* optimistic bubble; this only drives the composer and its request.
|
||
*/
|
||
async function postChatPrompt(sessionId, text, attachments) {
|
||
const body = String(text).trim();
|
||
if (body === "") return;
|
||
setThread(sessionId, { running: true });
|
||
renderContent();
|
||
try {
|
||
const queued = await repo.chatPrompt(sessionId, body, attachmentFiles(attachments));
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
// Prompting a closed session reopens it on the server; clear the local mark
|
||
// too so the list agrees without a re-fetch.
|
||
applyChatSessionUpdate(sessionId, null, false);
|
||
setThread(sessionId, { queued, running: true });
|
||
renderContent();
|
||
} catch (error) {
|
||
const message = describeError(error);
|
||
const restored = (attachments ?? []).map((attachment) => {
|
||
releaseAttachment(attachment);
|
||
return { ...attachment, thumbUrl: null, error: message };
|
||
});
|
||
setThread(sessionId, {
|
||
running: false,
|
||
queued: false,
|
||
error: message,
|
||
draft: body,
|
||
attachments: restored,
|
||
});
|
||
saveChatDraft(sessionId, body);
|
||
state.actionError = message;
|
||
renderContent();
|
||
}
|
||
}
|
||
|
||
/** Send an unknown-command offer's draft through the ordinary prompt path. */
|
||
function sendChatCommandOffer(sessionId, noticeId) {
|
||
const offer = takeChatNoticeOffer(sessionId, noticeId);
|
||
if (offer == null) return;
|
||
renderContent();
|
||
postChatPrompt(sessionId, offer, []);
|
||
}
|
||
|
||
/**
|
||
* Resolve the files the operator picked into composer attachments. Only the
|
||
* metadata is read here (nothing is transmitted until the message is sent): the
|
||
* browser has no `content://` reference, so the file's own name is carried as the
|
||
* best-effort reference string. A file over the limit is returned with its error
|
||
* set rather than dropped.
|
||
*/
|
||
function onChatFilesPicked(sessionId, session, fileList) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const picked = [];
|
||
for (const file of fileList ?? []) {
|
||
chatAttachmentSeq += 1;
|
||
const name = String(file?.name ?? "");
|
||
const mime = String(file?.type ?? "");
|
||
const size = Number(file?.size) || 0;
|
||
picked.push({
|
||
id: `att-${chatAttachmentSeq}`,
|
||
name,
|
||
uri: name,
|
||
mime,
|
||
size,
|
||
error: attachmentError(name, size, true),
|
||
thumbUrl: mime.startsWith("image/") ? createThumbUrl(file) : null,
|
||
file,
|
||
});
|
||
}
|
||
if (picked.length === 0) return;
|
||
setThread(sessionId, { attachments: [...(thread.attachments ?? []), ...picked] });
|
||
renderContent();
|
||
}
|
||
|
||
/** An object URL for a local image preview, or null when the browser refuses one. */
|
||
function createThumbUrl(file) {
|
||
try {
|
||
return URL.createObjectURL(file);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** Remove one attachment from the next message and release its preview URL. */
|
||
function removeChatAttachment(sessionId, attachmentId) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const attachment = (thread.attachments ?? []).find((entry) => entry.id === attachmentId);
|
||
releaseAttachment(attachment);
|
||
setThread(sessionId, {
|
||
attachments: (thread.attachments ?? []).filter((entry) => entry.id !== attachmentId),
|
||
});
|
||
renderContent();
|
||
}
|
||
|
||
function renderChatList() {
|
||
// The open menu must not be clipped by the list's rounded-corner overflow; the
|
||
// class is present only while a menu is open, so the normal list stays clipped.
|
||
const list = h("div", { class: `list chat-list${state.chatMenu ? " menu-open" : ""}` });
|
||
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);
|
||
},
|
||
}),
|
||
// C2: the create path stays one tap away while the list is narrowed, the same
|
||
// trailing action the app keeps beside its search control.
|
||
h("button", {
|
||
class: "ghost chat-new",
|
||
type: "button",
|
||
text: CHAT_NEW_ACTION,
|
||
onclick: startNewChat,
|
||
}),
|
||
);
|
||
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 visible = applyChatOverrides(state.chatSessions, state.chatOverrides);
|
||
const filtered = filterSessions(visible, 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) {
|
||
const empty = chatEmpty(CHAT_EMPTY);
|
||
empty.append(
|
||
h("button", {
|
||
class: "ghost chat-new",
|
||
type: "button",
|
||
text: CHAT_NEW_ACTION,
|
||
onclick: startNewChat,
|
||
}),
|
||
);
|
||
rows.append(empty);
|
||
return;
|
||
}
|
||
|
||
const active = filtered.filter((session) => !session.closed);
|
||
const closed = filtered.filter((session) => session.closed);
|
||
// Titles are often repeated ("New chat"); compute the duplicates once so the
|
||
// per-row actions name can include the session id only when it is needed.
|
||
const duplicateTitles = duplicateChatTitles(filtered);
|
||
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, duplicateTitles));
|
||
}
|
||
} else {
|
||
for (const session of active) rows.append(renderChatRow(session, duplicateTitles));
|
||
}
|
||
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, duplicateTitles));
|
||
}
|
||
if (state.chatError) {
|
||
rows.append(h("div", { class: "chat-error muted", text: state.chatError }));
|
||
}
|
||
}
|
||
|
||
/** The titles shared by more than one rendered session, for unique action names. */
|
||
function duplicateChatTitles(sessions) {
|
||
const counts = new Map();
|
||
for (const session of sessions) {
|
||
const title = sessionTitle(session);
|
||
counts.set(title, (counts.get(title) ?? 0) + 1);
|
||
}
|
||
return new Set(
|
||
[...counts.entries()].filter(([, count]) => count > 1).map(([title]) => title),
|
||
);
|
||
}
|
||
|
||
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, duplicateTitles = new Set()) {
|
||
const open = state.chatActiveId === session.id;
|
||
const thread = state.chatThreads.get(session.id) ?? null;
|
||
const unseen =
|
||
!session.closed &&
|
||
isChatSessionUnseen(session, {
|
||
activeId: state.chatActiveId,
|
||
seen: state.chatSeen,
|
||
opened: state.chatThreads.has(session.id),
|
||
});
|
||
const activity = sessionActivity(thread?.running === true, unseen);
|
||
const badge = sessionActivityBadge(activity, open);
|
||
// The row is a plain container (M6): the session title/meta area is the native
|
||
// button and the Chat actions control is its sibling, not a child.
|
||
const row = h("div", {
|
||
class: `row chat-row${open ? " selected" : ""}`,
|
||
"data-session": session.id,
|
||
});
|
||
// Keep background and programmatic clicks opening the session, but never
|
||
// double-fire when a real control (session button or actions) was clicked.
|
||
row.addEventListener("click", (event) => {
|
||
const target = event.target;
|
||
if (target instanceof Element && target.closest("button, a")) return;
|
||
openChatSession(session.id);
|
||
});
|
||
const sessionButton = h("button", {
|
||
class: "chat-session-button",
|
||
type: "button",
|
||
onclick: (event) => {
|
||
event.stopPropagation();
|
||
openChatSession(session.id);
|
||
},
|
||
});
|
||
const head = h("span", { 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 }),
|
||
),
|
||
);
|
||
}
|
||
sessionButton.append(head);
|
||
sessionButton.append(
|
||
h("span", {
|
||
class: "row-meta chat-row-meta",
|
||
text: sessionMeta(session, sessionWorkLabel(session.busy === true, thread)),
|
||
}),
|
||
);
|
||
row.append(sessionButton, renderChatActionsMenu(session, duplicateTitles));
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* The create pane (C2): the app's NewChatPane. A back control leaves without
|
||
* creating, then the directory error / loading / picker states in the app's own
|
||
* order, the model note and the footer naming the value that will be sent. Every
|
||
* server string is set with textContent.
|
||
*/
|
||
function renderChatCreate() {
|
||
const create = state.chatCreate;
|
||
const pane = h("div", { class: "detail chat-detail chat-create" });
|
||
|
||
const bar = h("div", { class: "chat-bar chat-create-bar" });
|
||
bar.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "ghost chat-create-back",
|
||
type: "button",
|
||
"aria-label": CHAT_CREATE_BACK_LABEL,
|
||
title: CHAT_CREATE_BACK_LABEL,
|
||
onclick: cancelNewChat,
|
||
},
|
||
h("span", { class: "chat-create-back-glyph", "aria-hidden": "true", text: "←" }),
|
||
),
|
||
h("h2", { class: "chat-bar-title chat-create-title", text: CHAT_CREATE_TITLE }),
|
||
);
|
||
pane.append(bar);
|
||
|
||
if (state.chatDirectoriesError && !state.chatDirectoriesLoaded) {
|
||
const empty = chatEmpty(state.chatDirectoriesError);
|
||
empty.classList.add("chat-create-directories-error");
|
||
empty.append(
|
||
h("button", {
|
||
class: "ghost chat-create-retry",
|
||
type: "button",
|
||
text: "Retry",
|
||
onclick: () => loadChatDirectories(true),
|
||
}),
|
||
);
|
||
pane.append(empty);
|
||
} else if (!state.chatDirectoriesLoaded) {
|
||
pane.append(h("div", { class: "chat-create-loading muted", text: CHAT_CREATE_LOADING }));
|
||
} else {
|
||
pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT }));
|
||
|
||
const choices = directoryChoices(state.chatDirectories);
|
||
const selected =
|
||
choices.find((choice) => choice.createDirectory === create.directory) ??
|
||
defaultDirectoryChoice(choices);
|
||
const list = h("div", {
|
||
class: "chat-create-choices",
|
||
role: "listbox",
|
||
"aria-label": CHAT_CREATE_PROMPT,
|
||
});
|
||
for (const choice of choices) {
|
||
const active = choice.createDirectory === selected?.createDirectory;
|
||
const row = h("button", {
|
||
class: `row chat-create-choice${active ? " selected" : ""}`,
|
||
type: "button",
|
||
role: "option",
|
||
"aria-selected": active ? "true" : "false",
|
||
"data-directory": choice.createDirectory,
|
||
onclick: () => selectChatDirectory(choice.createDirectory),
|
||
});
|
||
row.append(h("span", { class: "row-title chat-create-choice-label", text: choice.label }));
|
||
if (choice.secondary) {
|
||
row.append(h("span", { class: "row-meta chat-create-choice-path", text: choice.secondary }));
|
||
}
|
||
list.append(row);
|
||
}
|
||
pane.append(list);
|
||
|
||
// A refresh that failed after a successful first load keeps the choices and
|
||
// says why the list may be stale (the app's own bodySmall error line).
|
||
if (state.chatDirectoriesError) {
|
||
pane.append(h("div", { class: "chat-create-directories-error", text: state.chatDirectoriesError }));
|
||
}
|
||
if (create.error) {
|
||
pane.append(h("div", { class: "chat-create-error", text: create.error }));
|
||
}
|
||
pane.append(h("p", { class: "chat-create-model-note muted", text: CHAT_CREATE_MODEL_NOTE }));
|
||
|
||
const directory = selected?.createDirectory ?? create.directory;
|
||
const footer = h("div", { class: "chat-create-footer" });
|
||
footer.append(h("span", { class: "chat-create-start", text: chatStartInLabel(directory) }));
|
||
footer.append(
|
||
h("button", {
|
||
class: "ghost chat-create-cancel",
|
||
type: "button",
|
||
text: CHAT_CREATE_CANCEL,
|
||
disabled: create.creating,
|
||
onclick: cancelNewChat,
|
||
}),
|
||
);
|
||
const confirm = h("button", {
|
||
class: "chat-create-confirm",
|
||
type: "button",
|
||
"aria-label": CHAT_CREATE_CONFIRM,
|
||
disabled: create.creating,
|
||
onclick: createNewChat,
|
||
});
|
||
if (create.creating) {
|
||
confirm.append(h("span", { class: "spinner chat-create-spinner", "aria-hidden": "true" }));
|
||
} else {
|
||
confirm.append(document.createTextNode(CHAT_CREATE_CONFIRM));
|
||
}
|
||
footer.append(confirm);
|
||
pane.append(footer);
|
||
}
|
||
|
||
appendChatDialogs(pane);
|
||
return pane;
|
||
}
|
||
|
||
/**
|
||
* One row's Chat actions menu, with Android's items in its order: Rename…, then
|
||
* Close chat… (open) or Reopen (closed), then Hide on this device. Closing is the
|
||
* shared, server-side finish; hiding only affects this device and says so.
|
||
*/
|
||
function renderChatActionsMenu(session, duplicateTitles = new Set()) {
|
||
const wrap = h("div", { class: "chat-row-actions chat-menu-wrap" });
|
||
const expanded = state.chatMenu === session.id;
|
||
const title = sessionTitle(session);
|
||
const actionLabel = duplicateTitles.has(title)
|
||
? `${CHAT_ACTIONS_LABEL} for ${title} (${session.id})`
|
||
: `${CHAT_ACTIONS_LABEL} for ${title}`;
|
||
wrap.append(
|
||
h("button", {
|
||
class: "ghost chat-menu-button",
|
||
type: "button",
|
||
text: "⋯",
|
||
"aria-label": actionLabel,
|
||
"aria-haspopup": "menu",
|
||
"aria-expanded": expanded ? "true" : "false",
|
||
title: actionLabel,
|
||
onclick: (event) => {
|
||
event.stopPropagation();
|
||
openChatMenu(session.id);
|
||
},
|
||
}),
|
||
);
|
||
if (expanded) {
|
||
const menu = h("div", { class: "chat-menu-panel", role: "menu", "aria-label": CHAT_ACTIONS_LABEL });
|
||
menu.addEventListener("click", (event) => event.stopPropagation());
|
||
menu.append(
|
||
h("button", {
|
||
class: "ghost chat-menu-item chat-menu-rename",
|
||
type: "button",
|
||
role: "menuitem",
|
||
text: CHAT_RENAME_ACTION,
|
||
onclick: () => openChatRename(session),
|
||
}),
|
||
);
|
||
if (session.closed) {
|
||
menu.append(
|
||
h("button", {
|
||
class: "ghost chat-menu-item chat-menu-reopen",
|
||
type: "button",
|
||
role: "menuitem",
|
||
text: REOPEN_ACTION,
|
||
disabled: state.chatBusy,
|
||
onclick: () => reopenChatSession(session.id),
|
||
}),
|
||
);
|
||
} else {
|
||
menu.append(
|
||
h("button", {
|
||
class: "ghost chat-menu-item chat-menu-close",
|
||
type: "button",
|
||
role: "menuitem",
|
||
text: CLOSE_CHAT_ACTION,
|
||
disabled: state.chatBusy,
|
||
onclick: () => openChatClose(session),
|
||
}),
|
||
);
|
||
}
|
||
menu.append(
|
||
h("button", {
|
||
class: "ghost chat-menu-item chat-menu-hide",
|
||
type: "button",
|
||
role: "menuitem",
|
||
text: CHAT_HIDE_ACTION,
|
||
onclick: () => hideChatLocally(session.id),
|
||
}),
|
||
);
|
||
wrap.append(menu);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
/** 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 effective = effectiveChatSession(session);
|
||
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
|
||
const title = effective ? sessionTitle(effective) : state.chatActiveId.slice(0, 18);
|
||
// The pending approval card (C10), derived from the stored frame plus the local
|
||
// answer. While it is actionable the top bar offers a jump control and the
|
||
// running indicator stands down (a turn blocked on a decision is not generating).
|
||
const approval = approvalCard(thread?.permission, thread?.permissionAnswer);
|
||
const awaiting = approval?.actionable === true;
|
||
|
||
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),
|
||
}),
|
||
);
|
||
}
|
||
// The approval jump control appears only while a request is actionable, and
|
||
// brings its card (the transcript's last item) into view — the one scroll path,
|
||
// so a pending request is reached the same way new content is.
|
||
if (awaiting) bar.append(approvalJumpButton());
|
||
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),
|
||
}),
|
||
);
|
||
// The live-stream badge (C5): live while this session is subscribed, the same
|
||
// words as the run badge (`live` / `reconnecting` / `not live`).
|
||
context.append(
|
||
renderLiveBadge({
|
||
...chatStreamState(state.connection.kind, state.chatSubscriptions.has(state.chatActiveId)),
|
||
title: "Live chat stream",
|
||
}),
|
||
);
|
||
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);
|
||
|
||
// The background-tasks bar (C11) sits above the transcript, outside the
|
||
// scroller so the C14 scroll positions are untouched. It is present only while
|
||
// a shell is still running and disappears with the last exit.
|
||
const backgroundTasks = renderBackgroundTasks(thread);
|
||
if (backgroundTasks) pane.append(backgroundTasks);
|
||
|
||
const notices = thread?.notices ?? [];
|
||
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 ?? []);
|
||
// The running indicator stands down while an approval is pending (C10): a turn
|
||
// blocked on a decision is not generating, so neither the spinner nor its clock
|
||
// shows. The composer's Stop control stays governed by thread.running.
|
||
const running = thread?.running === true && !awaiting;
|
||
if (rows.length === 0 && notices.length === 0 && !running && !approval) {
|
||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
|
||
} else {
|
||
pane.append(
|
||
renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now(), approval }),
|
||
);
|
||
}
|
||
if (thread?.error && thread?.loaded) {
|
||
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
|
||
}
|
||
}
|
||
|
||
// The composer sits at the foot of the conversation, always available while a
|
||
// chat is open (the transcript may still be loading).
|
||
pane.append(renderChatComposer(thread, session, state.chatActiveId));
|
||
|
||
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.chatRename) pane.append(renderChatRenameDialog(state.chatRename));
|
||
if (state.chatSnackbar) pane.append(renderChatSnackbar());
|
||
if (state.actionError) pane.append(renderActionFailedDialog());
|
||
}
|
||
|
||
/**
|
||
* The one hide report (C13): the exact Android message and an `Undo` action. It
|
||
* is a fixed overlay (so a re-render or the transcript's height never moves it)
|
||
* and it is replaced, never queued, by a newer hide.
|
||
*/
|
||
function renderChatSnackbar() {
|
||
const bar = h("div", { class: "chat-snackbar", role: "status" });
|
||
bar.append(h("span", { class: "chat-snackbar-message", text: CHAT_REMOVED_MESSAGE }));
|
||
bar.append(
|
||
h("button", {
|
||
class: "ghost chat-snackbar-undo",
|
||
type: "button",
|
||
text: CHAT_UNDO_ACTION,
|
||
onclick: () => undoHideChat(),
|
||
}),
|
||
);
|
||
return bar;
|
||
}
|
||
|
||
/**
|
||
* The Rename chat dialog (C13): a locally-kept name, with the helper that says so
|
||
* plainly. Save is disabled while the trimmed value is blank; typing toggles that
|
||
* state directly, so the transcript's scroll is never disturbed by a re-render.
|
||
* Nothing is sent to the server — there is no chat rename on the wire.
|
||
*/
|
||
function renderChatRenameDialog(session) {
|
||
const effective = effectiveChatSession(session) ?? session;
|
||
const overlay = h("div", {
|
||
class: "confirm-dialog confirm-chat-rename",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": CHAT_RENAME_TITLE,
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) dismissChatRename();
|
||
});
|
||
const panel = h("div", { class: "confirm-panel" });
|
||
panel.append(h("h2", { class: "confirm-title", text: CHAT_RENAME_TITLE }));
|
||
const field = h("div", { class: "chat-rename-field" });
|
||
field.append(h("label", { class: "chat-rename-label", for: "chatRenameInput", text: CHAT_RENAME_FIELD_LABEL }));
|
||
const input = h("input", {
|
||
id: "chatRenameInput",
|
||
class: "rename-input chat-rename-input",
|
||
type: "text",
|
||
value: sessionTitle(effective),
|
||
spellcheck: "false",
|
||
autocomplete: "off",
|
||
});
|
||
field.append(input);
|
||
panel.append(field);
|
||
panel.append(h("p", { class: "chat-rename-helper", text: CHAT_RENAME_HELPER }));
|
||
const actions = h("div", { class: "confirm-actions" });
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost confirm-dismiss chat-rename-cancel",
|
||
type: "button",
|
||
text: CHAT_RENAME_DISMISS,
|
||
onclick: dismissChatRename,
|
||
}),
|
||
);
|
||
const save = h("button", {
|
||
class: "confirm-accept chat-rename-save",
|
||
type: "button",
|
||
text: CHAT_RENAME_SAVE,
|
||
disabled: input.value.trim() === "",
|
||
onclick: () => acceptChatRename(session, input.value),
|
||
});
|
||
// Toggle Save in place on input: no renderContent, so the transcript's scroll
|
||
// position (C14) is untouched while the operator types.
|
||
input.addEventListener("input", () => {
|
||
save.disabled = input.value.trim() === "";
|
||
});
|
||
actions.append(save);
|
||
panel.append(actions);
|
||
overlay.append(panel);
|
||
return overlay;
|
||
}
|
||
|
||
/**
|
||
* The background-tasks bar (C11): the running shells this conversation still
|
||
* owns. It returns null (renders nothing) unless at least one shell is running,
|
||
* so it disappears the moment the last task exits. Heading `Background tasks` +
|
||
* `{n} running`; the list shows at most BACKGROUND_TASK_VISIBLE_ROWS rows and
|
||
* scrolls beyond; a selected row reveals its bounded, read-only output pane.
|
||
* Every server string is set with textContent (never innerHTML).
|
||
*/
|
||
function renderBackgroundTasks(thread) {
|
||
const running = runningBackgroundShells(thread?.shells ?? []);
|
||
if (running.length === 0) return null;
|
||
const wrap = h("section", { class: "chat-bg-tasks", id: "chatBackgroundTasks" });
|
||
const head = h("div", { class: "chat-bg-tasks-head" });
|
||
head.append(h("span", { class: "chat-bg-tasks-title", text: BACKGROUND_TASKS_TITLE }));
|
||
head.append(
|
||
h("span", { class: "chat-bg-tasks-count muted", text: backgroundTasksRunningLabel(running.length) }),
|
||
);
|
||
wrap.append(head);
|
||
const list = h("div", { class: "chat-bg-tasks-list" });
|
||
const selectedId = thread?.selectedShellId ?? null;
|
||
running.forEach((shell) => list.append(renderBackgroundTaskRow(shell, shell.id === selectedId)));
|
||
wrap.append(list);
|
||
const selected = running.find((shell) => shell.id === selectedId) ?? null;
|
||
if (selected) wrap.append(renderBackgroundTaskDetail(thread, selected));
|
||
return wrap;
|
||
}
|
||
|
||
/** One running shell task; tapping it toggles its detail pane. */
|
||
function renderBackgroundTaskRow(shell, selected) {
|
||
const row = h("button", {
|
||
class: `chat-bg-task${selected ? " selected" : ""}`,
|
||
type: "button",
|
||
"data-shell": shell.id,
|
||
"aria-pressed": selected ? "true" : "false",
|
||
onclick: () => selectChatShell(shell.id),
|
||
});
|
||
// A CSS play glyph, decorative only (the row's own text names the task).
|
||
row.append(h("span", { class: "chat-bg-task-glyph", "aria-hidden": "true" }));
|
||
row.append(h("span", { class: "chat-bg-task-status", text: SHELL_ROW_LABEL }));
|
||
row.append(
|
||
h("span", {
|
||
class: "chat-bg-task-command",
|
||
text: shellCommandSummary(shell.command),
|
||
title: String(shell.command ?? ""),
|
||
}),
|
||
);
|
||
if (selected) row.append(h("span", { class: "chat-bg-task-details muted", text: SHELL_DETAILS_LABEL }));
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* The selected task's read-only detail: its command, its identity in monospace
|
||
* and `Status: running`, then the output area — the exact label order and wording
|
||
* of ChatTranscript.BackgroundProcessDetail. Reload is always a bounded reread
|
||
* from the page's start (`Refresh`; `Retry` after a failure).
|
||
*/
|
||
function renderBackgroundTaskDetail(thread, shell) {
|
||
const labels = SHELL_OUTPUT_LABELS;
|
||
const pane = h("div", { class: "chat-bg-task-detail" });
|
||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.COMMAND }));
|
||
const command = String(shell.command ?? "").trim();
|
||
pane.append(
|
||
h("div", {
|
||
class: "chat-bg-task-command-full",
|
||
text: command === "" ? labels.UNAVAILABLE : shell.command,
|
||
}),
|
||
);
|
||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.TASK_IDENTITY }));
|
||
pane.append(h("div", { class: "chat-bg-task-id monospace", text: String(shell.id ?? "") }));
|
||
pane.append(h("div", { class: "chat-bg-task-status-line", text: labels.STATUS_RUNNING }));
|
||
|
||
const output = thread?.shellOutput ?? null;
|
||
switch (shellOutputState(output)) {
|
||
case SHELL_OUTPUT_LOADING:
|
||
pane.append(h("span", { class: "spinner chat-bg-task-spinner", "aria-hidden": "true" }));
|
||
break;
|
||
case SHELL_OUTPUT_ERROR: {
|
||
const row = h("div", { class: "chat-bg-task-error-row" });
|
||
row.append(h("span", { class: "chat-bg-task-error", text: output.error }));
|
||
row.append(
|
||
h("button", {
|
||
class: "ghost chat-bg-task-retry",
|
||
type: "button",
|
||
text: labels.RETRY,
|
||
onclick: () => refreshChatShellOutput(shell.id),
|
||
}),
|
||
);
|
||
pane.append(row);
|
||
break;
|
||
}
|
||
case SHELL_OUTPUT_UNAVAILABLE:
|
||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_UNAVAILABLE }));
|
||
break;
|
||
case SHELL_OUTPUT_EMPTY:
|
||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.NO_OUTPUT }));
|
||
break;
|
||
case SHELL_OUTPUT_READY: {
|
||
const page = output.page;
|
||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.OUTPUT }));
|
||
// Untrusted shell text: set as textContent, never parsed as markup.
|
||
pane.append(h("pre", { class: "chat-bg-task-output", text: String(page.output ?? "") }));
|
||
if (page.truncated) {
|
||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_BOUNDED }));
|
||
}
|
||
pane.append(
|
||
h("button", {
|
||
class: "ghost chat-bg-task-refresh",
|
||
type: "button",
|
||
text: labels.REFRESH,
|
||
onclick: () => refreshChatShellOutput(shell.id),
|
||
}),
|
||
);
|
||
break;
|
||
}
|
||
default:
|
||
break;
|
||
}
|
||
return pane;
|
||
}
|
||
|
||
/**
|
||
* 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,
|
||
{ notices = [], running = false, now = Date.now(), approval = null } = {},
|
||
) {
|
||
const wrap = h("div", { class: "chat-transcript-wrap" });
|
||
const transcript = h("div", {
|
||
class: "chat-transcript",
|
||
id: "chatTranscript",
|
||
"data-session": sessionId,
|
||
});
|
||
const thread = state.chatThreads.get(sessionId) ?? null;
|
||
let lastAgent = -1;
|
||
rows.forEach((row, index) => {
|
||
if (row.kind === "agent") lastAgent = index;
|
||
});
|
||
rows.forEach((row, index) => {
|
||
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
|
||
else {
|
||
const streaming = running && index === lastAgent;
|
||
const elapsed = (part) => threadToolElapsedMillis(thread, part, now);
|
||
transcript.append(renderChatAgentTurn(row.turn, streaming, elapsed));
|
||
}
|
||
});
|
||
// The running indicator sits under the transcript, after the last agent turn:
|
||
// a spinner, the phase headline, the turn's elapsed, then one line per running
|
||
// tool (a call over 60 s is tinted and marked `· long`).
|
||
if (running && thread) transcript.append(renderChatRunningIndicator(thread, now));
|
||
// The conversation's local command lines sit after the turns, full width and
|
||
// deliberately unlike a message bubble (see ChatCommandNoticeItem).
|
||
for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice));
|
||
// The approval card is the transcript's last item (C10) — after the notices and
|
||
// after the running indicator when it is shown — so the top bar's jump control
|
||
// and a fresh card both land at the end.
|
||
if (approval) transcript.append(renderChatApproval(sessionId, approval));
|
||
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;
|
||
}
|
||
|
||
/** The top bar's approval jump control (C10), naming the pending request. */
|
||
function approvalJumpButton() {
|
||
return h("button", {
|
||
class: "ghost chat-approval-jump",
|
||
type: "button",
|
||
text: WAITING_FOR_APPROVAL_LABEL,
|
||
onclick: () => {
|
||
// The card is the transcript's last item, so the transcript's own end is the
|
||
// card; the one scroll path shared with jump-to-latest.
|
||
const el = document.getElementById("chatTranscript");
|
||
if (!el) return;
|
||
state.chatFollowing = true;
|
||
el.scrollTop = el.scrollHeight;
|
||
updateChatJump(el);
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* One approval request as a card (C10), the browser's port of
|
||
* `ui/chat/ChatApprovalCard.kt`: a shield and the headline, the status line, the
|
||
* request's resources newline-joined in monospace (blank entries dropped, at most
|
||
* six lines), the amber `RISK REVIEW` panel only while the app shows it, and the
|
||
* once/always/reject controls only while the request is actionable. Every server
|
||
* string is set with textContent and every node is built by hand.
|
||
*/
|
||
function renderChatApproval(sessionId, card) {
|
||
const node = h("div", {
|
||
class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`,
|
||
id: "chatApproval",
|
||
"data-request-id": card.requestId,
|
||
});
|
||
const head = h("div", { class: "chat-approval-head" });
|
||
head.append(shieldIcon("chat-approval-shield"));
|
||
const titles = h("div", { class: "chat-approval-titles" });
|
||
titles.append(h("div", { class: "chat-approval-headline", text: card.headline }));
|
||
titles.append(h("div", { class: "chat-approval-status muted", text: card.statusLine }));
|
||
head.append(titles);
|
||
node.append(head);
|
||
if (card.resourceText !== "") {
|
||
// The padded frame around a padding-free clamp block: clamping the padded
|
||
// element itself lets the seventh line paint into its bottom padding.
|
||
const box = h("div", { class: "chat-approval-resources" });
|
||
box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText }));
|
||
node.append(box);
|
||
}
|
||
if (card.showRisk && card.risk.trim() !== "") {
|
||
const risk = h("div", { class: "chat-approval-risk" });
|
||
const riskHead = h("div", { class: "chat-approval-risk-head" });
|
||
riskHead.append(shieldIcon("chat-approval-risk-shield"));
|
||
riskHead.append(h("span", { class: "chat-approval-risk-label", text: RISK_REVIEW_LABEL }));
|
||
risk.append(riskHead);
|
||
risk.append(h("div", { class: "chat-approval-risk-text", text: card.risk }));
|
||
node.append(risk);
|
||
}
|
||
if (card.actionable) {
|
||
const controls = h("div", { class: "chat-approval-controls" });
|
||
controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary"));
|
||
controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
|
||
controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId));
|
||
node.append(controls);
|
||
}
|
||
return node;
|
||
}
|
||
|
||
/**
|
||
* The app's amber outlined Shield (`Icons.Outlined.Shield`): an inline SVG stroked
|
||
* with `currentColor` so the palette's warn hue actually tints it, unlike the
|
||
* colour emoji it replaces. Decorative — the headline carries the meaning.
|
||
*/
|
||
function shieldIcon(className) {
|
||
const NS = "http://www.w3.org/2000/svg";
|
||
const svg = document.createElementNS(NS, "svg");
|
||
svg.setAttribute("class", className);
|
||
svg.setAttribute("viewBox", "0 0 24 24");
|
||
svg.setAttribute("aria-hidden", "true");
|
||
svg.setAttribute("focusable", "false");
|
||
const path = document.createElementNS(NS, "path");
|
||
path.setAttribute("d", "M12 3 5 6v5.5c0 4.2 2.8 8.1 7 9.5 4.2-1.4 7-5.3 7-9.5V6l-7-3z");
|
||
path.setAttribute("fill", "none");
|
||
path.setAttribute("stroke", "currentColor");
|
||
path.setAttribute("stroke-width", "1.8");
|
||
path.setAttribute("stroke-linejoin", "round");
|
||
svg.append(path);
|
||
return svg;
|
||
}
|
||
|
||
function approvalControl(label, decision, sessionId, requestId, extraClass = "") {
|
||
return h("button", {
|
||
class: `chat-approval-control${extraClass ? ` ${extraClass}` : ""}`,
|
||
type: "button",
|
||
text: label,
|
||
onclick: () => answerPermission(sessionId, requestId, decision),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
|
||
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
|
||
* with its own elapsed. A call that has passed [TOOL_LONG_RUNNING_MILLIS] is
|
||
* tinted and marked `· long` — the same threshold the tool chip uses.
|
||
*/
|
||
function renderChatRunningIndicator(thread, now) {
|
||
const wrap = h("div", { class: "chat-running", id: "chatRunning" });
|
||
const head = h("div", { class: "chat-running-head" });
|
||
head.append(h("span", { class: "spinner chat-running-spinner", "aria-hidden": "true" }));
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-running-label",
|
||
text: turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING),
|
||
}),
|
||
);
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-running-elapsed",
|
||
text: `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`,
|
||
}),
|
||
);
|
||
wrap.append(head);
|
||
for (const part of threadRunningTools(thread.messages)) {
|
||
wrap.append(renderChatRunningTool(thread, part, now));
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
function renderChatRunningTool(thread, part, now) {
|
||
const line = h("div", { class: "chat-running-tool", "data-part-id": String(part?.id ?? "") });
|
||
const name = toolLabel(part);
|
||
const detail = toolDetail(part);
|
||
line.append(h("span", { class: "chat-running-tool-text", text: detail == null ? name : `${name} ${detail}` }));
|
||
line.append(
|
||
h("span", {
|
||
class: "chat-running-tool-elapsed muted",
|
||
text: formatToolDuration(threadToolElapsedMillis(thread, part, now)),
|
||
}),
|
||
);
|
||
if (toolLongRunning(threadToolElapsedMillis(thread, part, now))) {
|
||
line.classList.add("chat-running-tool-long");
|
||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
}
|
||
return line;
|
||
}
|
||
|
||
/** 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, streaming = false, elapsedMillis = () => 0) {
|
||
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, streaming));
|
||
if (turn.tools.length > 0) {
|
||
const tools = renderChatToolCalls(turn, { streaming, elapsedMillis });
|
||
if (tools) bubble.append(tools);
|
||
}
|
||
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). The label is
|
||
* the app's own (see `reasoningLabel`) with the turn's server-reported duration
|
||
* appended when it has one; a settled history turn reads `Reasoning` (or
|
||
* `Reasoning · N steps`), a live one `Thinking…`/`Thinking · N steps`. Live
|
||
* elapsed time is C5's; this renders the parts' own timing.
|
||
*/
|
||
function renderChatReasoning(turn, streaming = false) {
|
||
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",
|
||
role: "img",
|
||
"aria-label": expanded ? "Hide reasoning" : "Show reasoning",
|
||
text: expanded ? "\u25be" : "\u25b8",
|
||
}),
|
||
);
|
||
const label = reasoningLabel(turn.reasoningSteps.length, streaming);
|
||
const elapsedMillis = turnElapsedMillis(turn.parts);
|
||
const duration = elapsedMillis == null ? null : formatDuration(Math.trunc(elapsedMillis / 1000));
|
||
toggle.append(
|
||
h("span", {
|
||
class: "chat-reasoning-label",
|
||
text: duration == null ? label : `${label} · ${duration}`,
|
||
}),
|
||
);
|
||
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));
|
||
const icon = toggle.querySelector(".chat-reasoning-icon");
|
||
icon.textContent = next ? "\u25be" : "\u25b8";
|
||
icon.setAttribute("aria-label", next ? "Hide reasoning" : "Show reasoning");
|
||
if (next) state.chatReasoning.add(turn.key);
|
||
else state.chatReasoning.delete(turn.key);
|
||
});
|
||
block.append(toggle, body);
|
||
return block;
|
||
}
|
||
|
||
/**
|
||
* One turn's tool calls behind a single summary chip (C6), the browser's port of
|
||
* `ui/chat/ChatToolCalls.kt`: `N tools called`, a spinner while any call is in
|
||
* flight, a `· long` mark (error tint) once a running call has passed
|
||
* [TOOL_LONG_RUNNING_MILLIS], error styling once a call failed, and a chevron
|
||
* naming the panel it opens. The panel is a fixed overlay anchored below the chip
|
||
* (flipped above when there is no room), with a header count, a close control, an
|
||
* internally scrolling list, and per-row expand state; because it never joins the
|
||
* transcript's flow, opening or closing it cannot re-flow the conversation nor
|
||
* move its scroll position (C14).
|
||
*
|
||
* [streaming] is whether the turn is still live, and [elapsedMillis] the live age
|
||
* of a running call (the conversation supplies it from its own clock, so the
|
||
* `long` mark is derived from real time, never guessed). A settled history turn
|
||
* passes neither, so a stored `running` status cannot spin or wear the mark.
|
||
*/
|
||
function renderChatToolCalls(turn, { streaming = false, elapsedMillis = () => 0 } = {}) {
|
||
const parts = turn.tools;
|
||
if (parts.length === 0) return null;
|
||
const count = toolCallCount(turn.parts);
|
||
const running = streaming && toolsRunning(turn.parts);
|
||
const failed = parts.some((part) => toolFailed(part.state));
|
||
const long = running && parts.some((part) => toolRunning(part) && toolLongRunning(elapsedMillis(part)));
|
||
const turnKey = turn.key;
|
||
|
||
const wrap = h("div", { class: "chat-tools" });
|
||
const open = state.chatToolPanels.has(turnKey);
|
||
const chip = h("button", {
|
||
class: `chip chat-tool-chip${failed ? " chat-tool-chip-failed" : ""}`,
|
||
type: "button",
|
||
"aria-label": toolCallsAnnouncement(count),
|
||
"aria-expanded": String(open),
|
||
});
|
||
if (running) {
|
||
chip.append(h("span", { class: "spinner chat-tool-spinner", "aria-hidden": "true" }));
|
||
} else {
|
||
chip.append(
|
||
h("span", {
|
||
class: `chat-tool-icon${failed ? " chat-tool-icon-failed" : ""}`,
|
||
"aria-hidden": "true",
|
||
text: failed ? "\u26a0" : "\u29c9",
|
||
}),
|
||
);
|
||
}
|
||
chip.append(h("span", { class: "chat-tool-label", text: toolCallsLabel(count) }));
|
||
if (long) chip.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
const chevron = h("span", {
|
||
class: "chat-tool-chevron",
|
||
role: "img",
|
||
"aria-label": open ? "Hide tool calls" : "Show tool calls",
|
||
text: open ? "\u25b4" : "\u25be",
|
||
});
|
||
chip.append(chevron);
|
||
wrap.append(chip);
|
||
|
||
const panel = h("div", { class: "chat-tool-panel", role: "dialog", "aria-label": toolCallsLabel(count) });
|
||
panel.hidden = !open;
|
||
const head = h("div", { class: "chat-tool-panel-head" });
|
||
head.append(h("span", { class: "chat-tool-panel-count", text: toolCallsLabel(count) }));
|
||
const close = h("button", {
|
||
class: "ghost chat-tool-close",
|
||
type: "button",
|
||
"aria-label": "Close tool calls",
|
||
title: "Close tool calls",
|
||
text: "\u00d7",
|
||
});
|
||
head.append(close);
|
||
panel.append(head);
|
||
const list = h("div", { class: "chat-tool-list" });
|
||
for (const part of parts) {
|
||
const id = String(part?.id ?? "");
|
||
const holder = h("div", { class: "chat-tool-row-holder" });
|
||
const build = () =>
|
||
renderToolCallRow(part, {
|
||
expanded: state.chatToolRows.has(id),
|
||
onToggle: () => {
|
||
if (state.chatToolRows.has(id)) state.chatToolRows.delete(id);
|
||
else state.chatToolRows.add(id);
|
||
holder.replaceChild(build(), holder.firstChild);
|
||
},
|
||
});
|
||
holder.append(build());
|
||
list.append(holder);
|
||
}
|
||
panel.append(list);
|
||
wrap.append(panel);
|
||
|
||
const setOpen = (next) => {
|
||
if (next) state.chatToolPanels.add(turnKey);
|
||
else state.chatToolPanels.delete(turnKey);
|
||
panel.hidden = !next;
|
||
chip.setAttribute("aria-expanded", String(next));
|
||
chevron.setAttribute("aria-label", next ? "Hide tool calls" : "Show tool calls");
|
||
chevron.textContent = next ? "\u25b4" : "\u25be";
|
||
if (next) positionChatToolPanel(panel, chip);
|
||
};
|
||
chip.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
setOpen(panel.hidden);
|
||
});
|
||
close.addEventListener("click", () => setOpen(false));
|
||
if (open) {
|
||
// The panel is built before its turn is attached to the document, so its
|
||
// rect is not measurable yet; place it on the next frame, when it is.
|
||
const place = () => positionChatToolPanel(panel, chip);
|
||
if (typeof requestAnimationFrame === "function") requestAnimationFrame(place);
|
||
else setTimeout(place, 0);
|
||
}
|
||
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* Places the tool panel below its chip, or above it when there is no room, keeping
|
||
* it inside the viewport margins — the browser's port of
|
||
* `ToolPanelPositionProvider`. Resolved in px from the live rects, so it is
|
||
* independent of any layout guess.
|
||
*/
|
||
function positionChatToolPanel(panel, chip) {
|
||
const gap = 4;
|
||
const margin = 8;
|
||
const chipRect = chip.getBoundingClientRect();
|
||
const rect = panel.getBoundingClientRect();
|
||
let top = chipRect.bottom + gap;
|
||
if (top + rect.height > window.innerHeight - margin) top = chipRect.top - rect.height - gap;
|
||
top = Math.max(margin, Math.min(top, window.innerHeight - rect.height - margin));
|
||
const left = Math.max(margin, Math.min(chipRect.left, window.innerWidth - rect.width - margin));
|
||
panel.style.top = `${Math.round(top)}px`;
|
||
panel.style.left = `${Math.round(left)}px`;
|
||
}
|
||
|
||
/**
|
||
* One call inside the panel: a header naming the call, its `+N -M` stat for an
|
||
* edit and its duration, and — expanded in place — the pretty-printed INPUT, the
|
||
* synthesised edit diff, then the ERROR block for a failed call or the OUTPUT for
|
||
* a settled one. Rows expand and collapse independently. Exported so the smoke can
|
||
* render a representative row through this same builder.
|
||
*/
|
||
function renderToolCallRow(part, { expanded = false, onToggle = null } = {}) {
|
||
const row = toolCallRow(part);
|
||
const node = h("div", { class: `chat-tool-row${row.error != null ? " chat-tool-row-failed" : ""}` });
|
||
const head = h("button", {
|
||
class: "chat-tool-row-head",
|
||
type: "button",
|
||
"aria-expanded": String(expanded),
|
||
});
|
||
head.append(
|
||
h("span", {
|
||
class: `chat-tool-icon${row.error != null ? " chat-tool-icon-failed" : ""}`,
|
||
role: "img",
|
||
"aria-label": row.error != null ? "Failed tool call" : "",
|
||
"aria-hidden": row.error != null ? null : "true",
|
||
text: row.error != null ? "\u26a0" : row.diff != null ? "\u270e" : "\u29c9",
|
||
}),
|
||
);
|
||
const titles = h("span", { class: "chat-tool-row-titles" });
|
||
titles.append(h("span", { class: "chat-tool-name", text: row.name }));
|
||
if (row.detail != null) titles.append(h("span", { class: "chat-tool-detail", text: row.detail }));
|
||
head.append(titles);
|
||
if (row.diff != null) {
|
||
head.append(h("span", { class: "chat-tool-stat", text: changeStat(row.diff.added, row.diff.removed) }));
|
||
}
|
||
if (row.duration != null) head.append(h("span", { class: "chat-tool-duration", text: row.duration }));
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-tool-row-chevron",
|
||
role: "img",
|
||
"aria-label": expanded ? `Collapse ${row.name}` : `Expand ${row.name}`,
|
||
text: expanded ? "\u25b4" : "\u25be",
|
||
}),
|
||
);
|
||
node.append(head);
|
||
if (expanded) {
|
||
const body = h("div", { class: "chat-tool-body" });
|
||
const input = toolSection("INPUT", row.input);
|
||
if (input) body.append(input);
|
||
if (row.diff != null) body.append(renderToolDiff(row.diff));
|
||
if (row.error != null) {
|
||
const error = toolSection("ERROR", row.error);
|
||
if (error) body.append(error);
|
||
} else {
|
||
const output = toolSection("OUTPUT", row.output);
|
||
if (output) body.append(output);
|
||
}
|
||
node.append(body);
|
||
}
|
||
if (typeof onToggle === "function") {
|
||
head.addEventListener("click", () => onToggle());
|
||
}
|
||
return node;
|
||
}
|
||
|
||
/** One monospace section card (INPUT/OUTPUT/ERROR); blank content renders none. */
|
||
function toolSection(label, text) {
|
||
if (text == null || String(text).trim() === "") return null;
|
||
const section = h("div", { class: "chat-tool-section" });
|
||
section.append(h("div", { class: "chat-tool-section-label", text: label }));
|
||
section.append(h("pre", { class: "chat-tool-section-body", text }));
|
||
return section;
|
||
}
|
||
|
||
/**
|
||
* The unified diff body of an edit call: line-by-line monospace with `+`/`-`
|
||
* gutter symbols and the app's success/failure hues, the shared line language of
|
||
* the run Changes viewer. A diff longer than the rendered cap is summarised with
|
||
* an omitted note. Exported so the smoke can render a representative sample.
|
||
*/
|
||
function renderToolDiff(diff) {
|
||
const card = h("div", { class: "chat-tool-diff" });
|
||
if (diff.omitted > 0) {
|
||
card.append(
|
||
h("div", {
|
||
class: "chat-tool-diff-note",
|
||
text: `\u2026 ${diff.omitted} more changed ${diff.omitted === 1 ? "line" : "lines"} not shown`,
|
||
}),
|
||
);
|
||
}
|
||
for (const line of diff.lines) {
|
||
card.append(
|
||
h("div", {
|
||
class: `chat-tool-diff-line ${diffLineClass(line.kind)}`,
|
||
text: `${diffLineSymbol(line.kind)} ${line.text}`,
|
||
}),
|
||
);
|
||
}
|
||
return card;
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
*/
|
||
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 ?? ""));
|
||
});
|
||
}
|
||
|
||
/** One local command line in the transcript (see ChatCommandNoticeItem). */
|
||
function renderChatCommandNotice(sessionId, notice) {
|
||
const failed = notice?.failed === true;
|
||
const row = h("div", {
|
||
class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`,
|
||
role: "note",
|
||
"data-notice-id": notice?.id ?? "",
|
||
});
|
||
const head = h("div", { class: "chat-command-notice-head" });
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-command-notice-glyph",
|
||
"aria-hidden": "true",
|
||
// The app draws `Icons.Default.Terminal` for both states and only changes
|
||
// the tint, so both notices share the one terminal glyph.
|
||
text: CHAT_COMMAND_GLYPH,
|
||
}),
|
||
);
|
||
head.append(
|
||
h("span", { class: "chat-command-notice-label", text: chatNoticeLabel(failed) }),
|
||
);
|
||
row.append(head);
|
||
row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" }));
|
||
if (notice?.offer != null) {
|
||
const actions = h("div", { class: "chat-command-notice-actions" });
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost chat-command-send-as-message",
|
||
type: "button",
|
||
text: "Send as message",
|
||
onclick: () => sendChatCommandOffer(sessionId, notice.id),
|
||
}),
|
||
);
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost chat-command-cancel",
|
||
type: "button",
|
||
text: "Cancel",
|
||
onclick: () => dismissChatNotice(sessionId, notice.id),
|
||
}),
|
||
);
|
||
row.append(actions);
|
||
} else {
|
||
// Android only offers the Send/Cancel pair on an offer-bearing notice, so a
|
||
// `/help` or `/new` line cannot be dismissed there. The browser item requires
|
||
// each notice to be individually dismissible; the wording and the offer pair
|
||
// still match the app verbatim, and this extra control is stated in PARITY.
|
||
const actions = h("div", { class: "chat-command-notice-actions" });
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost chat-command-dismiss",
|
||
type: "button",
|
||
text: "Dismiss",
|
||
"aria-label": CHAT_COMMAND_DISMISS_LABEL,
|
||
onclick: () => dismissChatNotice(sessionId, notice.id),
|
||
}),
|
||
);
|
||
row.append(actions);
|
||
}
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* The composer at the foot of an open conversation: the queued notice, the
|
||
* attachment chips, the slash-command offer list, the attach control, the growing
|
||
* multiline field and the single send/stop control. All state is derived from the
|
||
* thread and its session; every server/model string is set with textContent.
|
||
*/
|
||
function renderChatComposer(thread, session, sessionId) {
|
||
const composer = h("div", { class: "chat-composer", id: "chatComposer" });
|
||
if (!thread) return composer;
|
||
const controls = { selected: 0, palette: null, primary: null };
|
||
|
||
if (thread.queued) {
|
||
composer.append(h("div", { class: "chat-queued", id: "chatQueued", text: CHAT_QUEUED_NOTICE }));
|
||
}
|
||
|
||
const strip = renderChatAttachmentStrip(sessionId, thread);
|
||
if (strip) composer.append(strip);
|
||
|
||
const palette = h("div", {
|
||
class: "chat-command-palette",
|
||
id: "chatPalette",
|
||
role: "listbox",
|
||
"aria-label": "Command suggestions",
|
||
hidden: true,
|
||
});
|
||
controls.palette = palette;
|
||
composer.append(palette);
|
||
|
||
const row = h("div", { class: "chat-composer-row" });
|
||
const fileInput = h("input", {
|
||
id: "chatFileInput",
|
||
class: "chat-file-input",
|
||
type: "file",
|
||
multiple: true,
|
||
tabindex: "-1",
|
||
"aria-hidden": "true",
|
||
onchange: (event) => {
|
||
onChatFilesPicked(sessionId, session, event.target.files);
|
||
event.target.value = "";
|
||
},
|
||
});
|
||
row.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "ghost chat-attach",
|
||
id: "chatAttach",
|
||
type: "button",
|
||
"aria-label": CHAT_ATTACH_LABEL,
|
||
title: CHAT_ATTACH_LABEL,
|
||
onclick: () => fileInput.click(),
|
||
},
|
||
"\u{1F4CE}",
|
||
),
|
||
);
|
||
row.append(fileInput);
|
||
|
||
const input = h("textarea", {
|
||
id: "chatInput",
|
||
class: "chat-composer-input",
|
||
rows: "1",
|
||
placeholder: CHAT_COMPOSER_PLACEHOLDER,
|
||
"aria-label": CHAT_COMPOSER_PLACEHOLDER,
|
||
spellcheck: "false",
|
||
});
|
||
input.value = thread.draft ?? "";
|
||
input.addEventListener("input", (event) => onComposerInput(event, sessionId, session, controls));
|
||
input.addEventListener("keydown", (event) => onComposerKeydown(event, sessionId, session, controls));
|
||
row.append(input);
|
||
|
||
const primary = h("span", { class: "chat-composer-primary" });
|
||
controls.primary = primary;
|
||
row.append(primary);
|
||
composer.append(row);
|
||
|
||
const suggestions = chatCommandSuggestions(thread.draft);
|
||
fillCommandPalette(palette, suggestions, controls.selected, (index) => {
|
||
const command = suggestions[index];
|
||
if (command) runChatCommand(sessionId, session, `/${command.name}`);
|
||
});
|
||
fillComposerPrimary(primary, thread, {
|
||
onSend: () => submitChatComposer(sessionId, session, controls),
|
||
onStop: () => stopChatTurn(sessionId),
|
||
});
|
||
|
||
if (typeof requestAnimationFrame === "function") {
|
||
requestAnimationFrame(() => growComposerTextarea(input));
|
||
}
|
||
return composer;
|
||
}
|
||
|
||
/** The offer list above the composer: `/name` and the summary per row. */
|
||
function fillCommandPalette(palette, suggestions, selected, onPick) {
|
||
if (!palette) return;
|
||
palette.replaceChildren();
|
||
if (!suggestions || suggestions.length === 0) {
|
||
palette.hidden = true;
|
||
return;
|
||
}
|
||
palette.hidden = false;
|
||
suggestions.forEach((command, index) => {
|
||
palette.append(
|
||
h(
|
||
"div",
|
||
{
|
||
class: `chat-command-row${index === selected ? " selected" : ""}`,
|
||
role: "option",
|
||
"aria-selected": index === selected ? "true" : "false",
|
||
tabindex: "-1",
|
||
onclick: () => onPick(index),
|
||
},
|
||
h("span", { class: "chat-command-name", text: `/${command.name}` }),
|
||
h("span", { class: "chat-command-summary", text: command.summary }),
|
||
),
|
||
);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* The composer's single primary control: Stop while a turn is in flight (error
|
||
* tint), else Send, disabled unless the draft is sendable (or a slash draft).
|
||
* Stop routes to [onStop] (`chat_interrupt`), never to the submit path — the
|
||
* control must interrupt the running turn, as Android's `onStop` does.
|
||
*/
|
||
function fillComposerPrimary(primary, thread, { onSend, onStop } = {}) {
|
||
if (!primary) return;
|
||
primary.replaceChildren();
|
||
if (composerAction(thread) === COMPOSER_STOP) {
|
||
primary.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "chat-stop",
|
||
id: "chatStop",
|
||
type: "button",
|
||
"aria-label": CHAT_STOP_LABEL,
|
||
title: CHAT_STOP_LABEL,
|
||
onclick: onStop,
|
||
},
|
||
"■",
|
||
),
|
||
);
|
||
return;
|
||
}
|
||
primary.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "chat-send",
|
||
id: "chatSend",
|
||
type: "button",
|
||
"aria-label": CHAT_SEND_LABEL,
|
||
title: CHAT_SEND_LABEL,
|
||
disabled: !composerSendEnabled(thread),
|
||
onclick: onSend,
|
||
},
|
||
"➤",
|
||
),
|
||
);
|
||
}
|
||
|
||
/** The removable chips for the files attached to the next message. */
|
||
function renderChatAttachmentStrip(sessionId, thread) {
|
||
const attachments = thread?.attachments ?? [];
|
||
if (attachments.length === 0) return null;
|
||
const strip = h("div", { class: "chat-attachment-strip", id: "chatAttachments" });
|
||
for (const attachment of attachments) {
|
||
strip.append(renderChatAttachmentChip(sessionId, attachment));
|
||
}
|
||
return strip;
|
||
}
|
||
|
||
/** One attachment chip: its preview, its name, its size or error, and remove. */
|
||
function renderChatAttachmentChip(sessionId, attachment) {
|
||
const failed = attachment?.error != null;
|
||
const display = attachmentDisplayName(attachment?.name, attachment?.uri);
|
||
const chip = h("div", {
|
||
class: `chat-attachment-chip${failed ? " chat-attachment-chip-failed" : ""}`,
|
||
});
|
||
chip.append(renderAttachmentThumb(attachment, display));
|
||
const body = h("div", { class: "chat-attachment-body" });
|
||
body.append(h("span", { class: "chat-attachment-name", text: display }));
|
||
if (failed) {
|
||
body.append(h("span", { class: "chat-attachment-meta chat-attachment-error", text: attachment.error }));
|
||
} else if (Number(attachment?.size) > 0) {
|
||
body.append(h("span", { class: "chat-attachment-meta", text: humanBytes(attachment.size) }));
|
||
}
|
||
chip.append(body);
|
||
chip.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "ghost chat-attachment-remove",
|
||
type: "button",
|
||
"aria-label": `Remove ${display}`,
|
||
title: `Remove ${display}`,
|
||
onclick: () => removeChatAttachment(sessionId, attachment.id),
|
||
},
|
||
"✕",
|
||
),
|
||
);
|
||
return chip;
|
||
}
|
||
|
||
/** The chip's square preview: the decoded thumbnail for an image, else a glyph. */
|
||
function renderAttachmentThumb(attachment, display) {
|
||
if (attachment?.thumbUrl) {
|
||
return h("img", {
|
||
class: "chat-attachment-thumb",
|
||
src: attachment.thumbUrl,
|
||
alt: display,
|
||
"aria-hidden": "true",
|
||
});
|
||
}
|
||
const image = String(attachment?.mime ?? "").startsWith("image/");
|
||
return h("span", {
|
||
class: "chat-attachment-glyph",
|
||
"aria-hidden": "true",
|
||
text: image ? "🖼" : "📄",
|
||
});
|
||
}
|
||
|
||
/** 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,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* (Re)start the chat indicator's clock: it ticks once a second only while the
|
||
* open conversation has a turn in flight, updating the phase, the elapsed and the
|
||
* per-tool `· long` marks in place (never a full re-render).
|
||
*/
|
||
function refreshChatClock() {
|
||
stopChatClock();
|
||
chatNow = Date.now();
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true;
|
||
if (state.view === "chat" && thread?.running && !awaiting) {
|
||
chatClock = setInterval(() => {
|
||
chatNow = Date.now();
|
||
updateChatIndicator(chatNow);
|
||
}, 1000);
|
||
}
|
||
}
|
||
|
||
function stopChatClock() {
|
||
if (chatClock) {
|
||
clearInterval(chatClock);
|
||
chatClock = null;
|
||
}
|
||
}
|
||
|
||
/** Refresh the running indicator in place from the thread's own state at [now]. */
|
||
function updateChatIndicator(now) {
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
const el = document.getElementById("chatRunning");
|
||
if (!thread?.running || !el) return;
|
||
const label = el.querySelector(".chat-running-label");
|
||
if (label) label.textContent = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING);
|
||
const elapsed = el.querySelector(".chat-running-elapsed");
|
||
if (elapsed) elapsed.textContent = `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`;
|
||
for (const part of threadRunningTools(thread.messages)) {
|
||
const line = el.querySelector(`.chat-running-tool[data-part-id="${String(part?.id ?? "")}"]`);
|
||
if (!line) continue;
|
||
const age = threadToolElapsedMillis(thread, part, now);
|
||
const toolElapsed = line.querySelector(".chat-running-tool-elapsed");
|
||
if (toolElapsed) toolElapsed.textContent = formatToolDuration(age);
|
||
const mark = line.querySelector(".chat-tool-long");
|
||
if (toolLongRunning(age) && !mark) {
|
||
line.classList.add("chat-running-tool-long");
|
||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
}
|
||
}
|
||
}
|
||
|
||
return {
|
||
renderChatList,
|
||
renderChatCreate,
|
||
renderChatConversation,
|
||
afterChatRender,
|
||
updateChatIndicator,
|
||
refreshChatClock,
|
||
stopChatClock,
|
||
captureChatPosition,
|
||
loadChatSessions,
|
||
loadChatDirectories,
|
||
startNewChat,
|
||
openChatSession,
|
||
subscribeChatSession,
|
||
clearChatSubscriptions,
|
||
settleChatThreads,
|
||
resyncOpenChat,
|
||
onChatEvent,
|
||
onChatPermission,
|
||
onChatFrame,
|
||
renderToolCallRow,
|
||
renderToolDiff,
|
||
renderMarkdown,
|
||
dismissChatClose,
|
||
dismissChatRename,
|
||
};
|
||
}
|