4446 lines
168 KiB
JavaScript
4446 lines
168 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 { backChevronIcon, h, artifactBrowserLinkProps } from "../dom.js";
|
||
import { isLocalArtifactLink } from "../artifactNavigation.js";
|
||
import { formFieldVisible, formFieldValue, formAnswerError, visibleFormAnswers, safeFormURL } from "../chatForms.js";
|
||
import { readChatStars, writeChatStars } from "../chatStars.js";
|
||
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../chatModels.js";
|
||
import { chatUsageMetrics } from "../chatUsage.js";
|
||
import { describeError } from "../format.js";
|
||
import { SHELL_OUTPUT_LIMIT, nativeChatMessageId, newChatOperationId } from "../repository.js";
|
||
import { codeBlockLabel, parseInline, parseMarkdown } from "../markdown.js";
|
||
import { highlight } from "../highlight.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,
|
||
DEFAULT_CHAT_INSTRUCTIONS,
|
||
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,
|
||
applyChatForm,
|
||
chatApprovalCards,
|
||
chatPendingForms,
|
||
abbreviateHome,
|
||
appendChatNotice,
|
||
approvalCard,
|
||
attachmentDisplayName,
|
||
attachmentError,
|
||
backgroundTasksRunningLabel,
|
||
chatBottomDistancePx,
|
||
chatCommandEffect,
|
||
chatCommandHelp,
|
||
chatCommandSuggestions,
|
||
chatCreateFailed,
|
||
chatCreateSucceeded,
|
||
chatFirstScroll,
|
||
chatFollowsAt,
|
||
chatNoMatchMessage,
|
||
chatNoticeLabel,
|
||
chatOpensAtNewest,
|
||
chatShowJumpToLatest,
|
||
chatStartInLabel,
|
||
closeChatConfirmation,
|
||
composerAction,
|
||
composerCanSend,
|
||
composerSendEnabled,
|
||
composerSubmit,
|
||
decodeChatOverrides,
|
||
decodeChatSeen,
|
||
defaultDirectoryChoice,
|
||
directoryChoices,
|
||
directoryLabel,
|
||
dismissChatNotice as dismissChatNoticeModel,
|
||
emptyChatOverrides,
|
||
emptyChatSeen,
|
||
encodeChatOverrides,
|
||
encodeChatSeen,
|
||
filterChatModels,
|
||
filterSessions,
|
||
groupSessionsByDirectory,
|
||
hideChatOverride,
|
||
historyResync,
|
||
homeDirectoryFor,
|
||
isChatSessionUnseen,
|
||
makeChatNotice,
|
||
markChatUnseen,
|
||
mergeHistoryPage,
|
||
mergeShellFrame,
|
||
newChatCreateState,
|
||
newChatThread,
|
||
parseChatInput,
|
||
queuedAfterFrame,
|
||
readChatSeen,
|
||
reasoningLabel,
|
||
relativeSessionTime,
|
||
renameChatOverride,
|
||
restoreChatOverride,
|
||
resumedThread,
|
||
runningAfterFrame,
|
||
runningBackgroundShells,
|
||
runningToolElapsedMillis,
|
||
seedChatSeen,
|
||
sessionActivity,
|
||
sessionActivityBadge,
|
||
selectChatBackend as selectChatBackendModel,
|
||
selectChatDirectory as selectChatDirectoryModel,
|
||
sessionTitle,
|
||
sessionWorkLabel,
|
||
settledThread,
|
||
shellCommandSummary,
|
||
shellOutputState,
|
||
shellsLoaded,
|
||
takeChatNoticeOffer as takeChatNoticeOfferModel,
|
||
threadElapsedMillis,
|
||
threadPhase,
|
||
threadToolElapsedMillis,
|
||
TURN_PHASE_WAITING,
|
||
TURN_PHASE_COMPACTING,
|
||
toolCallCount,
|
||
toolCallRow,
|
||
toolCallsAnnouncement,
|
||
toolCallsLabel,
|
||
toolDetail,
|
||
toolFailureCount,
|
||
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, modal } = rt;
|
||
let chatClock = null;
|
||
let chatNow = Date.now();
|
||
const renderContent = (...args) => rt.renderContent(...args);
|
||
const focusDetailHeading = (...args) => rt.focusDetailHeading(...args);
|
||
const closeDetail = (...args) => rt.closeDetail?.(...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.
|
||
*/
|
||
let pendingComposerFocus = null;
|
||
|
||
/**
|
||
* Remember the composer's focus and selection before a re-render replaces the
|
||
* textarea. Live frames arrive continuously, so without this every tool/text
|
||
* frame would steal focus and the operator could not type a queued message.
|
||
*/
|
||
function captureChatFocus() {
|
||
const input = document.activeElement;
|
||
const question = input?.matches?.(".chat-question-input") ? input.closest(".chat-question") : null;
|
||
if (!input || (input !== document.getElementById("chatInput") && !question)) {
|
||
pendingComposerFocus = null;
|
||
return;
|
||
}
|
||
pendingComposerFocus = {
|
||
sessionId: state.chatActiveId ?? "",
|
||
formId: question?.dataset.formId ?? "",
|
||
fieldKey: input.dataset.fieldKey ?? "",
|
||
start: input.selectionStart,
|
||
end: input.selectionEnd,
|
||
direction: input.selectionDirection,
|
||
};
|
||
}
|
||
|
||
/** Put the caret back after the transcript is rebuilt, without scrolling. */
|
||
function restoreChatFocus() {
|
||
const pending = pendingComposerFocus;
|
||
pendingComposerFocus = null;
|
||
if (!pending) return;
|
||
if (state.chatActiveId !== pending.sessionId) return;
|
||
const input = pending.formId
|
||
? document.querySelector(`[data-form-id="${CSS.escape(pending.formId)}"] [data-field-key="${CSS.escape(pending.fieldKey)}"]`)
|
||
: document.getElementById("chatInput");
|
||
if (!input) return;
|
||
input.focus({ preventScroll: true });
|
||
try {
|
||
input.setSelectionRange(pending.start, pending.end, pending.direction);
|
||
} catch {
|
||
// A non-text input or an unsupported selection range is harmless.
|
||
}
|
||
}
|
||
|
||
function captureChatPosition() {
|
||
captureChatFocus();
|
||
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 installed chat harnesses, loaded when the create pane opens. */
|
||
async function loadChatBackends() {
|
||
try {
|
||
const backends = await repo.chatBackends();
|
||
if (Array.isArray(backends) && backends.length) state.chatBackends = backends;
|
||
} catch {
|
||
// Keep the OpenCode default; create reports an unavailable backend clearly.
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
function selectChatBackend(value) {
|
||
state.chatCreate = selectChatBackendModel(state.chatCreate, value);
|
||
renderContent();
|
||
}
|
||
|
||
/** 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();
|
||
// One-time migration from the old local-only stars: upload this device's
|
||
// saved set, then let the server's shared set be authoritative everywhere.
|
||
const localStars = readChatStars();
|
||
if (localStars.size) {
|
||
for (const id of localStars) {
|
||
const session = listed.find((entry) => entry.id === id);
|
||
if (!session || session.starred) continue;
|
||
try {
|
||
const updated = await repo.starChat(id, true);
|
||
if (updated) Object.assign(session, updated);
|
||
} catch {
|
||
// Keep going: a missing session or a transient failure must not block
|
||
// the rest of the list.
|
||
}
|
||
}
|
||
writeChatStars(new Set());
|
||
}
|
||
// One-time migration from device-local chat titles. The server now owns the
|
||
// shared title; upload any saved local title, then drop it so other devices
|
||
// cannot be outvoted by a stale override.
|
||
const localTitles = { ...(state.chatOverrides?.titles ?? {}) };
|
||
let titlesChanged = false;
|
||
for (const [id, title] of Object.entries(localTitles)) {
|
||
const session = listed.find((entry) => entry.id === id);
|
||
if (!session) continue;
|
||
if (String(session.title ?? "").trim() === title) {
|
||
delete localTitles[id];
|
||
titlesChanged = true;
|
||
continue;
|
||
}
|
||
try {
|
||
const updated = await repo.renameChat(id, title);
|
||
if (updated) Object.assign(session, updated);
|
||
delete localTitles[id];
|
||
titlesChanged = true;
|
||
} catch {
|
||
// Keep the local title and retry on a later list load.
|
||
}
|
||
}
|
||
if (titlesChanged) {
|
||
state.chatOverrides = { ...state.chatOverrides, titles: localTitles };
|
||
saveChatOverrides();
|
||
}
|
||
// 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];
|
||
syncChatStarsFromSessions();
|
||
state.chatLoaded = true;
|
||
rt.touchView?.("chat");
|
||
// 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();
|
||
focusDetailHeading();
|
||
loadChatDirectories();
|
||
loadChatBackends();
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
*/
|
||
function reportInstructionStatus(created) {
|
||
const status = created?.instruction_status;
|
||
if (status === "applied") addChatNotice(created.id, "Session instructions applied.");
|
||
else if (status === "unsupported" || status === "failed") {
|
||
addChatNotice(created.id, `Session instructions ${status}: ${created.instruction_error || "this harness does not support preloaded instructions"}.`);
|
||
}
|
||
}
|
||
|
||
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, {
|
||
backend: create.backend,
|
||
instructions: create.instructions,
|
||
});
|
||
state.chatCreate = null;
|
||
state.chatSessions = chatCreateSucceeded(state.chatSessions, created);
|
||
await openChatSession(created.id);
|
||
reportInstructionStatus(created);
|
||
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, { updateRoute = true } = {}) {
|
||
if (updateRoute) rt.pushRoute({ kind: "chatSession", id });
|
||
state.view = "chat";
|
||
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.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();
|
||
focusDetailHeading();
|
||
// 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);
|
||
// The history load repaints the pane; keep the row activation's focus contract
|
||
// true after it lands, not only for the loading paint.
|
||
focusDetailHeading();
|
||
}
|
||
|
||
/** 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.
|
||
*/
|
||
let chatRenderScheduled = false;
|
||
let chatRenderMode = null;
|
||
|
||
/**
|
||
* Coalesce a burst of pushed frames into one paint. A turn can emit many text
|
||
* and tool frames in the same animation frame; rebuilding the whole page for
|
||
* each one made the text flicker and replaced the composer, which on a phone
|
||
* drops the virtual keyboard. Transcript-only paints replace just the message
|
||
* scroller and leave the composer DOM untouched.
|
||
*/
|
||
function scheduleChatRender(mode = "full") {
|
||
// A background chat must never repaint the screen the operator is using.
|
||
// Folding its frames into state is enough; the chat list/detail paint when the
|
||
// operator returns to Chat.
|
||
if (state.view !== "chat") return;
|
||
if (mode === "full" || chatRenderMode == null) chatRenderMode = mode === "full" ? "full" : chatRenderMode ?? "transcript";
|
||
if (chatRenderScheduled) return;
|
||
chatRenderScheduled = true;
|
||
const paint = () => {
|
||
chatRenderScheduled = false;
|
||
const chosen = chatRenderMode;
|
||
chatRenderMode = null;
|
||
if (state.view !== "chat") return;
|
||
if (chosen === "transcript" && refreshChatTranscript(state.chatActiveId)) return;
|
||
renderContent();
|
||
};
|
||
if (typeof requestAnimationFrame === "function") requestAnimationFrame(paint);
|
||
else setTimeout(paint, 0);
|
||
}
|
||
|
||
/**
|
||
* Repaint only the transcript scroller for a live frame. The composer, its
|
||
* focused textarea, the chat bar and the background-task bar are left mounted,
|
||
* so a phone keeps its keyboard open while an answer streams. Returns false
|
||
* when the page is not in a shape this can update safely; the caller then does
|
||
* a full render.
|
||
*/
|
||
function refreshChatTranscript(sessionId) {
|
||
if (!sessionId || state.chatActiveId !== sessionId || state.view !== "chat") return false;
|
||
const oldWrap = document.querySelector(".chat-transcript-wrap");
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!oldWrap || !thread) return false;
|
||
const rows = transcriptRows(thread.messages ?? []);
|
||
const notices = thread.notices ?? [];
|
||
const approval = approvalCard(thread.permission, thread.permissionAnswer);
|
||
const form =
|
||
thread.form && thread.form.resolved !== true && thread.form.cancelled !== true
|
||
? thread.form
|
||
: null;
|
||
if (rows.length === 0 && notices.length === 0 && !thread.running && !approval && !form) {
|
||
return false;
|
||
}
|
||
const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0;
|
||
const running = thread.running === true && !awaiting;
|
||
const bar = document.querySelector(".chat-bar");
|
||
const jump = bar?.querySelector(".chat-approval-jump");
|
||
const jumpLabel=chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question";
|
||
if (awaiting && bar && !jump) bar.insertBefore(approvalJumpButton(jumpLabel), bar.querySelector("#chatUsageInfo"));
|
||
else if (awaiting && jump) jump.textContent=jumpLabel;
|
||
else if (!awaiting) jump?.remove();
|
||
captureChatPosition();
|
||
// The background-tasks bar sits outside the transcript but is driven by the
|
||
// same shell frames. Patch it in place instead of full-rendering the pane (and
|
||
// closing the phone keyboard) when a background command starts or exits.
|
||
const oldTasks = document.getElementById("chatBackgroundTasks");
|
||
const nextTasks = renderBackgroundTasks(thread);
|
||
if (nextTasks) {
|
||
if (oldTasks) oldTasks.replaceWith(nextTasks);
|
||
else oldWrap.before(nextTasks);
|
||
} else if (oldTasks) {
|
||
oldTasks.remove();
|
||
}
|
||
const next = renderChatTranscript(sessionId, rows, {
|
||
notices,
|
||
running,
|
||
now: Date.now(),
|
||
approval,
|
||
form,
|
||
});
|
||
oldWrap.replaceWith(next);
|
||
afterChatRender();
|
||
refreshChatClock();
|
||
return true;
|
||
}
|
||
|
||
function onChatEvent(frame) {
|
||
const sessionId = String(frame?.session_id ?? "").trim();
|
||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||
if (frame.kind === "resync") {
|
||
markBackgroundChatUnseen(sessionId);
|
||
scheduleHistorySync(sessionId, "", {force:true});
|
||
return;
|
||
}
|
||
if (frame.kind === "usage") {
|
||
const current = state.chatThreads.get(sessionId);
|
||
const next = applyChatEvent(current, frame);
|
||
state.chatThreads.set(sessionId, next);
|
||
if (state.view === "chat" && sessionId === state.chatActiveId) refreshChatUsageMetrics(sessionId, next);
|
||
return;
|
||
}
|
||
markBackgroundChatUnseen(sessionId);
|
||
const thread = state.chatThreads.get(sessionId);
|
||
const messageId = String(frame?.message_id ?? "");
|
||
// The user turn of a prompt sent from another client (the OpenCode UI, not this
|
||
// page) never reaches the broker, so no `user` frame exists for it: only the
|
||
// assistant's frames arrive. When the first frame of an unknown turn arrives,
|
||
// read the newest history once so the user message (and anything else the page
|
||
// missed) appears without a manual refresh.
|
||
const knownTurn = messageId !== "" && (thread.messages ?? []).some((m) => m?.id === messageId);
|
||
const wasRunning = thread.running === true;
|
||
const wasQueued = thread.queued === true;
|
||
const next = applyChatEvent(thread, frame, Date.now());
|
||
state.chatThreads.set(sessionId, next);
|
||
refreshChatRowActivity(sessionId, next);
|
||
if (state.view === "chat" && sessionId === state.chatActiveId) {
|
||
// The composer's Stop lives outside the transcript. A step frame changes
|
||
// running here, so update the mounted primary control now; the transcript-only
|
||
// repaint below leaves the composer in place.
|
||
if (next.running !== wasRunning || next.queued !== wasQueued) {
|
||
refreshChatComposerState(sessionId);
|
||
}
|
||
scheduleChatRender("transcript");
|
||
}
|
||
if (!knownTurn) scheduleHistorySync(sessionId, messageId);
|
||
}
|
||
|
||
/** At most one history read per unseen turn, and only for the open conversation. */
|
||
const historySyncTimers = new Map();
|
||
const historySyncedFor = new Map();
|
||
function scheduleHistorySync(sessionId, messageId, {force=false} = {}) {
|
||
if ((!messageId && !force) || state.view !== "chat" || sessionId !== state.chatActiveId) return;
|
||
if (!force && historySyncedFor.get(sessionId) === messageId) return;
|
||
if (!force) historySyncedFor.set(sessionId, messageId);
|
||
if (historySyncTimers.has(sessionId)) return;
|
||
const timer = setTimeout(() => {
|
||
historySyncTimers.delete(sessionId);
|
||
loadChatHistory(sessionId).catch(() => {});
|
||
}, 250);
|
||
historySyncTimers.set(sessionId, timer);
|
||
}
|
||
|
||
/**
|
||
* 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);
|
||
markBackgroundChatUnseen(sessionId);
|
||
if (state.view === "chat" && sessionId === state.chatActiveId) scheduleChatRender("transcript");
|
||
}
|
||
|
||
/**
|
||
* 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?.permissions ?? [thread?.permission]).find((entry) => entry?.request_id === requestId);
|
||
if (!thread || !permission) return;
|
||
setThread(sessionId, { permissionAnswers: { ...thread.permissionAnswers, [requestId]: 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 || !(current.permissions ?? [current.permission]).some((entry) => entry?.request_id === requestId)) return;
|
||
const reason = describeError(error);
|
||
setThread(sessionId, { permissionAnswers: { ...current.permissionAnswers, [requestId]: "" }, error: reason, permissionError: reason });
|
||
renderContent();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Answer the agent's pending question. The answer map is keyed by the form
|
||
* field's own key and mirrors OpenCode's form.reply body; the resolved form
|
||
* arrives on the stream and clears the card for every watching client.
|
||
*/
|
||
async function answerChatQuestion(sessionId, form, answers, action = "") {
|
||
if (!form?.id) return;
|
||
try {
|
||
await repo.answerChatForm(sessionId, form.id, answers, action);
|
||
const current = state.chatThreads.get(sessionId);
|
||
if (current) state.chatThreads.set(sessionId, applyChatForm(current, { ...form, resolved: true }));
|
||
renderContent();
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
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;
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
state.chatThreads.set(id, resumedThread(previous));
|
||
await subscribeChatSession(id);
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
state.chatThreads.set(id, historyResync(state.chatThreads.get(id), page, { preserveActivity: true }));
|
||
} catch {
|
||
// Keep fresh replayed activity if any; otherwise the settled reset stands.
|
||
}
|
||
await loadChatShells(id);
|
||
renderContent();
|
||
}
|
||
|
||
/** Load (or reload) a session's newest history page and merge it in. */
|
||
const historyReadGenerations = new Map();
|
||
async function loadChatHistory(id) {
|
||
const generation=(historyReadGenerations.get(id) ?? 0)+1;
|
||
historyReadGenerations.set(id,generation);
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
if (historyReadGenerations.get(id)!==generation) return;
|
||
// 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).
|
||
// Live approvals/questions can arrive before this HTTP read finishes. Merge
|
||
// over the current thread, never the pre-request snapshot that would erase
|
||
// the just-delivered interaction (and any draft typed during the read).
|
||
setThread(id, mergeHistoryPage(state.chatThreads.get(id) ?? previous, page, { older: false }));
|
||
} catch (error) {
|
||
if (historyReadGenerations.get(id)!==generation) return;
|
||
setThread(id, { loading: false, loaded: true, error: describeError(error) });
|
||
}
|
||
// A streaming turn triggers this resync after its first unseen message. Keep
|
||
// the composer mounted when the transcript already exists; replacing the whole
|
||
// page here closed the phone keyboard mid-turn.
|
||
if (!refreshChatTranscript(id)) 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) });
|
||
}
|
||
if (!refreshChatTranscript(id)) 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 syncChatStarsFromSessions(sessions = state.chatSessions) {
|
||
state.chatStars = new Set(
|
||
(sessions ?? []).filter((session) => session.starred === true).map((session) => session.id),
|
||
);
|
||
}
|
||
|
||
function applyChatSessionUpdate(id, updated, closed) {
|
||
state.chatSessions = state.chatSessions.map((session) =>
|
||
session.id === id ? { ...session, ...(updated ?? {}), closed } : session,
|
||
);
|
||
syncChatStarsFromSessions();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 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) {
|
||
const scrollTop = document.getElementById("chatRows")?.scrollTop ?? 0;
|
||
state.chatMenu = state.chatMenu === sessionId ? null : sessionId;
|
||
renderContent();
|
||
const rows = document.getElementById("chatRows");
|
||
if (rows) rows.scrollTop = scrollTop;
|
||
if (state.chatMenu) {
|
||
// 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({ preventScroll: true });
|
||
}
|
||
}
|
||
|
||
/** Open the Rename chat dialog for [session] (its current effective title). */
|
||
function openChatRename(session) {
|
||
state.chatMenu = null;
|
||
state.chatRename = session;
|
||
renderContent();
|
||
}
|
||
|
||
function dismissChatRename() {
|
||
state.chatRename = null;
|
||
renderContent();
|
||
}
|
||
|
||
/** Drop this device's old local title now that the server carries it. */
|
||
function clearLocalChatTitle(sessionId) {
|
||
const id = String(sessionId ?? "");
|
||
const titles = { ...(state.chatOverrides?.titles ?? {}) };
|
||
if (!(id in titles)) return;
|
||
delete titles[id];
|
||
state.chatOverrides = { ...state.chatOverrides, titles };
|
||
saveChatOverrides();
|
||
}
|
||
|
||
/**
|
||
* The dialog's Save: trim, write the shared title through `chat_rename`, close
|
||
* the dialog and re-render. The server's registry title is authoritative; a
|
||
* failure leaves the dialog open and surfaces the server's reason. A blank title
|
||
* is ignored (Save is already disabled while trimmed-blank).
|
||
*/
|
||
async function acceptChatRename(session, title) {
|
||
if (state.chatBusy) return;
|
||
const trimmed = String(title ?? "").trim();
|
||
if (trimmed === "") return;
|
||
state.chatBusy = true;
|
||
try {
|
||
const updated = await repo.renameChat(session.id, trimmed);
|
||
if (updated) {
|
||
applyChatSessionUpdate(session.id, updated, updated.closed === true);
|
||
clearLocalChatTitle(session.id);
|
||
setThread(session.id, { title: updated.title ?? trimmed });
|
||
}
|
||
state.chatRename = null;
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
}
|
||
state.chatBusy = false;
|
||
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.
|
||
*/
|
||
/**
|
||
* Update the composer's primary control and queued notice in place when only
|
||
* the running/queued flags changed. The textarea and its listeners stay mounted,
|
||
* so a phone keeps the keyboard open across the start and end of a turn.
|
||
*/
|
||
function refreshChatComposerState(sessionId) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread || state.chatActiveId !== sessionId) return;
|
||
const primary = document.querySelector("#chatComposer .chat-composer-primary");
|
||
if (primary) {
|
||
const session = state.chatSessions.find((row) => row.id === sessionId) ?? null;
|
||
fillComposerPrimary(primary, thread, {
|
||
onSend: () => submitChatComposer(sessionId, session, { selected: 0 }),
|
||
onStop: () => stopChatTurn(sessionId),
|
||
});
|
||
}
|
||
const composer = document.getElementById("chatComposer");
|
||
if (!composer) return;
|
||
const existing = document.getElementById("chatQueued");
|
||
if (thread.queued && !existing) {
|
||
composer.prepend(h("div", { class: "chat-queued", id: "chatQueued", text: CHAT_QUEUED_NOTICE }));
|
||
} else if (!thread.queued && existing) {
|
||
existing.remove();
|
||
}
|
||
}
|
||
|
||
function onChatFrame(message) {
|
||
const frame = message?.chat_event;
|
||
if (!frame || !frame.session_id) return;
|
||
// onChatEvent already folded this session activity with native identity
|
||
// checks and refreshed the composer. Do not reapply an ignored stale start.
|
||
if (frame.kind === "compaction" || frame.kind === "usage") return;
|
||
rt.touchView?.("chat");
|
||
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 (state.view === "chat" && sessionId === state.chatActiveId) {
|
||
refreshChatComposerState(sessionId);
|
||
scheduleChatRender("transcript");
|
||
}
|
||
}
|
||
|
||
/** 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. Enter inserts a newline (so a phone keyboard can
|
||
* compose multi-line text); Ctrl/Cmd+Enter sends. A slash draft still runs on
|
||
* Enter, matching the command palette. Up/Down move the highlighted command.
|
||
*/
|
||
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") return;
|
||
const slash = String(thread.draft ?? "").trimStart().startsWith("/");
|
||
if (slash || event.metaKey || event.ctrlKey) {
|
||
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,
|
||
instructions: DEFAULT_CHAT_INSTRUCTIONS,
|
||
});
|
||
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}.`);
|
||
reportInstructionStatus(created);
|
||
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 ?? [];
|
||
const operationId = newChatOperationId();
|
||
const messageId = nativeChatMessageId(operationId);
|
||
// Show the operator's own turn at once, with the id OpenCode will persist.
|
||
// Waiting for the first assistant frame made the running placeholder appear
|
||
// before the message the operator just sent.
|
||
const fileParts = attachments
|
||
.filter((attachment) => attachment?.error == null)
|
||
.map((attachment) => ({
|
||
type: "file",
|
||
name: String(attachment.name ?? ""),
|
||
uri: String(attachment.uri ?? attachment.name ?? ""),
|
||
mime: String(attachment.mime ?? ""),
|
||
}));
|
||
const optimistic = {
|
||
id: messageId || `local-${operationId}`,
|
||
session_id: sessionId,
|
||
role: "user",
|
||
operation_id: operationId,
|
||
parts: [{ type: "text", text }, ...fileParts],
|
||
};
|
||
// Sending is an explicit request to see the new turn, even if the operator
|
||
// had scrolled up to read earlier history. Later manual scrolling still wins.
|
||
state.chatFollowing = true;
|
||
state.chatAnchor = null;
|
||
state.chatPending = null;
|
||
setThread(sessionId, {
|
||
draft: "",
|
||
attachments: [],
|
||
running: true,
|
||
messages: [...(thread.messages ?? []), optimistic],
|
||
});
|
||
saveChatDraft(sessionId, "");
|
||
renderContent();
|
||
await postChatPrompt(sessionId, text, attachments, {
|
||
operationId,
|
||
optimisticId: optimistic.id,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 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, { operationId, optimisticId } = {}) {
|
||
const body = String(text).trim();
|
||
if (body === "") return;
|
||
setThread(sessionId, { running: true });
|
||
renderContent();
|
||
try {
|
||
const payloads = await chatAttachmentPayloads(attachments);
|
||
// The optimistic message and the wire copy are built; the File objects and
|
||
// their preview URLs are no longer needed.
|
||
releaseAttachments(attachments);
|
||
const queued = await repo.chatPrompt(sessionId, body, [], operationId, payloads);
|
||
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 };
|
||
});
|
||
const current = state.chatThreads.get(sessionId);
|
||
setThread(sessionId, {
|
||
running: false,
|
||
queued: false,
|
||
error: message,
|
||
draft: body,
|
||
attachments: restored,
|
||
messages: optimisticId
|
||
? (current?.messages ?? []).filter((entry) => entry.id !== optimisticId)
|
||
: current?.messages,
|
||
});
|
||
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, []);
|
||
}
|
||
|
||
// The websocket frame that carries a prompt is bounded at 2 MiB, and base64
|
||
// expands bytes by a third. This keeps ordinary screenshots and text files
|
||
// usable without risking a frame the server refuses. The server enforces the
|
||
// same budget again.
|
||
const MAX_CHAT_ATTACHMENT_BYTES = 1 << 20;
|
||
|
||
/** Encode an ArrayBuffer as standard base64 without a huge spread call. */
|
||
function base64FromBuffer(buffer) {
|
||
const bytes = new Uint8Array(buffer);
|
||
let binary = "";
|
||
const chunk = 0x8000;
|
||
for (let offset = 0; offset < bytes.length; offset += chunk) {
|
||
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunk));
|
||
}
|
||
return btoa(binary);
|
||
}
|
||
|
||
/** Read the pending files into the wire attachment shape, or explain why not. */
|
||
async function chatAttachmentPayloads(attachments) {
|
||
const valid = (attachments ?? []).filter((attachment) => attachment?.error == null);
|
||
if (valid.length === 0) return [];
|
||
if (valid.length > 8) throw new Error("At most 8 attachments are allowed.");
|
||
let total = 0;
|
||
const payloads = [];
|
||
for (const attachment of valid) {
|
||
if (!attachment?.file || typeof attachment.file.arrayBuffer !== "function") {
|
||
throw new Error(`"${attachmentDisplayName(attachment?.name, attachment?.uri)}" could not be read.`);
|
||
}
|
||
const buffer = await attachment.file.arrayBuffer();
|
||
total += buffer.byteLength;
|
||
if (total > MAX_CHAT_ATTACHMENT_BYTES) {
|
||
throw new Error("Attachments are too large for web chat (1 MiB total).");
|
||
}
|
||
payloads.push({
|
||
name: String(attachment.name ?? "").trim() || "attachment",
|
||
mime: String(attachment.mime ?? "").trim() || "application/octet-stream",
|
||
data: base64FromBuffer(buffer),
|
||
});
|
||
}
|
||
return payloads;
|
||
}
|
||
|
||
/**
|
||
* Resolve the files the operator picked or pasted into composer attachments.
|
||
* Only the metadata is read here (nothing is transmitted until the message is
|
||
* sent); a file over the limit is returned with its error set rather than
|
||
* dropped.
|
||
*/
|
||
function pastedAttachmentName(mime, sequence) {
|
||
const subtype = String(mime ?? "").split("/").pop()?.toLowerCase() ?? "";
|
||
const extension = subtype === "jpeg" ? "jpg" : subtype.replace(/[^a-z0-9]/g, "") || "bin";
|
||
return `pasted-${sequence}.${extension}`;
|
||
}
|
||
|
||
/** Attach files pasted into the composer (an image or copied file). */
|
||
function onComposerPaste(event, sessionId, session) {
|
||
const data = event.clipboardData;
|
||
if (!data) return;
|
||
const files = [];
|
||
for (const item of data.items ?? []) {
|
||
if (item?.kind !== "file") continue;
|
||
const file = item.getAsFile?.();
|
||
if (file) files.push(file);
|
||
}
|
||
if (files.length === 0) return;
|
||
// A pasted image has no editable text; keep the composer's own text untouched
|
||
// and attach the clipboard file as the next message's attachment.
|
||
event.preventDefault();
|
||
onChatFilesPicked(sessionId, session, files);
|
||
}
|
||
|
||
function onChatFilesPicked(sessionId, session, fileList) {
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (!thread) return;
|
||
const picked = [];
|
||
for (const file of fileList ?? []) {
|
||
chatAttachmentSeq += 1;
|
||
const mime = String(file?.type ?? "");
|
||
const name = String(file?.name ?? "").trim() || pastedAttachmentName(mime, chatAttachmentSeq);
|
||
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();
|
||
}
|
||
|
||
/** The one New chat control: a real primary action, not a quiet text link. */
|
||
function chatNewButton() {
|
||
return h(
|
||
"button",
|
||
{
|
||
class: "chat-new",
|
||
type: "button",
|
||
title: CHAT_NEW_ACTION,
|
||
"aria-label": CHAT_NEW_ACTION,
|
||
onclick: startNewChat,
|
||
},
|
||
h("span", { class: "chat-new-glyph", "aria-hidden": "true", text: "+" }),
|
||
h("span", { class: "chat-new-label", text: CHAT_NEW_ACTION }),
|
||
);
|
||
}
|
||
|
||
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.
|
||
chatNewButton(),
|
||
);
|
||
list.append(toolbar);
|
||
const rows = h("div", { id: "chatRows", class: "chat-rows list-scroll" });
|
||
fillChatRows(rows);
|
||
list.append(rows);
|
||
return list;
|
||
}
|
||
|
||
/** The home prefix used to shorten directory labels to `~`, when knowable. */
|
||
function chatHomePrefix() {
|
||
const reported = String(state.chatDirectories?.[0] ?? "").trim();
|
||
if (reported !== "") return reported;
|
||
return homeDirectoryFor([
|
||
...(state.chatDirectories ?? []),
|
||
...(state.chatSessions ?? []).map((session) => session?.directory),
|
||
]);
|
||
}
|
||
|
||
/** 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(chatNewButton());
|
||
rows.append(empty);
|
||
return;
|
||
}
|
||
|
||
const home = chatHomePrefix();
|
||
const starred = filtered.filter(
|
||
(session) => !session.closed && state.chatStars?.has?.(session.id) === true,
|
||
);
|
||
const active = filtered.filter(
|
||
(session) => !session.closed && state.chatStars?.has?.(session.id) !== true,
|
||
);
|
||
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);
|
||
if (starred.length > 0) {
|
||
rows.append(
|
||
h(
|
||
"div",
|
||
{ class: "chat-group-header chat-group-starred" },
|
||
h("span", { class: "chat-group-title", text: "Starred" }),
|
||
),
|
||
);
|
||
for (const session of starred) rows.append(renderChatRow(session, duplicateTitles, home));
|
||
}
|
||
const groups = groupSessionsByDirectory(active);
|
||
if (groups.length > 1) {
|
||
for (const group of groups) {
|
||
const fullLabel = directoryLabel(group.directory);
|
||
const label = abbreviateHome(fullLabel, home);
|
||
const key = String(group.directory ?? "");
|
||
const collapsed = state.chatCollapsedDirs?.has?.(key) === true;
|
||
const toggle = h("button", {
|
||
class: "chat-group-header chat-group-toggle chat-group-directory",
|
||
type: "button",
|
||
title: fullLabel,
|
||
"aria-expanded": collapsed ? "false" : "true",
|
||
"aria-label": `${collapsed ? "Expand" : "Collapse"} ${label}`,
|
||
onclick: () => {
|
||
if (!state.chatCollapsedDirs) state.chatCollapsedDirs = new Set();
|
||
if (collapsed) state.chatCollapsedDirs.delete(key);
|
||
else state.chatCollapsedDirs.add(key);
|
||
renderContent();
|
||
},
|
||
});
|
||
toggle.append(h("span", { class: "chat-group-title", text: label }));
|
||
toggle.append(h("span", { class: "chevron", text: collapsed ? "\u25b8" : "\u25be" }));
|
||
rows.append(toggle);
|
||
if (!collapsed) {
|
||
for (const session of group.sessions) rows.append(renderChatRow(session, duplicateTitles, home));
|
||
}
|
||
}
|
||
} else {
|
||
for (const session of active) rows.append(renderChatRow(session, duplicateTitles, home));
|
||
}
|
||
if (closed.length > 0) {
|
||
const open = state.chatClosedOpen === true;
|
||
const toggle = h("button", {
|
||
class: "chat-group-toggle",
|
||
type: "button",
|
||
"aria-expanded": open ? "true" : "false",
|
||
"aria-label": `${open ? "Collapse" : "Expand"} ${CLOSED_SECTION_LABEL.toLowerCase()} chats`,
|
||
});
|
||
toggle.append(
|
||
h("span", { class: "chat-group-label", text: CLOSED_SECTION_LABEL }),
|
||
h("span", { class: "chevron", text: open ? "\u25be" : "\u25b8" }),
|
||
);
|
||
toggle.addEventListener("click", () => {
|
||
state.chatClosedOpen = !open;
|
||
renderContent();
|
||
});
|
||
rows.append(toggle);
|
||
if (open) {
|
||
for (const session of closed) rows.append(renderChatRow(session, duplicateTitles, home));
|
||
}
|
||
}
|
||
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 }));
|
||
}
|
||
|
||
/** Toggle one session's shared star on the server, then repaint its group. */
|
||
async function toggleChatStar(id) {
|
||
const wasStarred = state.chatStars?.has?.(id) === true;
|
||
state.chatSessions = state.chatSessions.map((session) =>
|
||
session.id === id ? { ...session, starred: !wasStarred } : session,
|
||
);
|
||
syncChatStarsFromSessions();
|
||
renderContent();
|
||
try {
|
||
const updated = await repo.starChat(id, !wasStarred);
|
||
if (updated) applyChatSessionUpdate(id, updated, updated.closed === true);
|
||
} catch (error) {
|
||
state.chatSessions = state.chatSessions.map((session) =>
|
||
session.id === id ? { ...session, starred: wasStarred } : session,
|
||
);
|
||
syncChatStarsFromSessions();
|
||
state.actionError = describeError(error);
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* 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(), home = "") {
|
||
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);
|
||
// `Idle` and `Open` said nothing about a chat; the row's recency does. Keep a
|
||
// badge only when the session is genuinely doing something or has news.
|
||
const badge = activity === "idle" ? "" : sessionActivityBadge(activity, open);
|
||
const updated = relativeSessionTime(session.updated_at);
|
||
// 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" : ""}${state.chatMenu === session.id ? " menu-open" : ""}`,
|
||
"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(chatBackendLogo(session.backend, activity));
|
||
head.append(h("span", { class: "row-title chat-row-title", text: sessionTitle(session) }));
|
||
// Only the status word, coloured, with no dot and no operator chip. A closed
|
||
// session says so here instead of carrying a second chip.
|
||
const statusWord = session.closed ? "Closed" : activity === "streaming" ? "" : badge;
|
||
const statusClass = session.closed ? "chat-activity-closed" : `chat-activity-${activity}`;
|
||
if (statusWord) {
|
||
head.append(h("span", { class: `chat-activity ${statusClass}`, text: statusWord }));
|
||
}
|
||
sessionButton.append(head);
|
||
const meta = [updated, abbreviateHome(String(session.directory ?? "").trim(), home)]
|
||
.filter(Boolean)
|
||
.join(" \u00b7 ");
|
||
if (meta !== "") {
|
||
sessionButton.append(h("span", { class: "row-meta chat-row-meta", text: meta }));
|
||
}
|
||
const model = String(session.model ?? "").trim();
|
||
if (model !== "") {
|
||
sessionButton.append(h("span", { class: "row-meta chat-row-model muted", text: model }));
|
||
}
|
||
row.append(sessionButton, renderChatActionsMenu(session, duplicateTitles));
|
||
return row;
|
||
}
|
||
|
||
/** Keep the harness mark current without repainting the list or its rows. */
|
||
function refreshChatRowActivity(sessionId, thread) {
|
||
const row = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"]`);
|
||
const icon = row?.querySelector(".chat-backend-logo");
|
||
if (!icon) return;
|
||
const session = state.chatSessions.find((entry) => entry.id === sessionId);
|
||
const unseen = session && isChatSessionUnseen(session, { activeId: state.chatActiveId, seen: state.chatSeen, opened: true });
|
||
const activity = sessionActivity(thread?.running === true, unseen);
|
||
icon.dataset.activity = activity;
|
||
const label = chatBackendLabel(session?.backend || "opencode");
|
||
icon.setAttribute("aria-label", activity === "streaming" ? `${label} · Running` : label);
|
||
icon.title = activity === "streaming" ? `${label} · Running` : label;
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
*/
|
||
/** One agent's mark immediately before its chat title. */
|
||
function chatBackendLogo(backend, activity = "idle") {
|
||
const value = String(backend ?? "").trim().toLowerCase() || "opencode";
|
||
const label = chatBackendLabel(value);
|
||
const wrap = h("span", {
|
||
class: `chat-backend-logo chat-backend-${value}`,
|
||
title: label,
|
||
"aria-label": activity === "streaming" ? `${label} · Running` : label,
|
||
"data-activity": activity,
|
||
});
|
||
const NS = "http://www.w3.org/2000/svg";
|
||
const svg = document.createElementNS(NS, "svg");
|
||
svg.setAttribute("viewBox", "0 0 24 24");
|
||
svg.setAttribute("aria-hidden", "true");
|
||
svg.setAttribute("focusable", "false");
|
||
const add = (tag, attrs) => {
|
||
const node = document.createElementNS(NS, tag);
|
||
for (const [key, attr] of Object.entries(attrs)) node.setAttribute(key, attr);
|
||
svg.append(node);
|
||
return node;
|
||
};
|
||
const stroke = { fill: "none", stroke: "currentColor", "stroke-width": "1.8", "stroke-linecap": "round", "stroke-linejoin": "round" };
|
||
if (value === "opencode") {
|
||
add("rect", { x: "3.5", y: "4.5", width: "17", height: "15", rx: "3", ...stroke });
|
||
add("path", { d: "M7.5 9.5 10.5 12l-3 2.5", ...stroke });
|
||
add("path", { d: "M13 15h3.5", ...stroke });
|
||
} else if (value === "codex") {
|
||
add("path", { d: "M12 3.2 19.5 7.4v9.2L12 20.8l-7.5-4.2V7.4z", ...stroke });
|
||
add("path", { d: "m8.5 12 2.3 2.3 4.7-4.7", ...stroke });
|
||
} else if (value === "claude") {
|
||
add("path", { d: "M12 3v18M4.2 7.5l15.6 9M4.2 16.5l15.6-9", ...stroke });
|
||
add("circle", { cx: "12", cy: "12", r: "2.2", ...stroke });
|
||
} else if (value === "pi") {
|
||
add("path", { d: "M5.5 7.5h13M8.5 7.5v9M15.5 7.5v9", ...stroke });
|
||
} else {
|
||
add("circle", { cx: "12", cy: "12", r: "7", ...stroke });
|
||
add("circle", { cx: "12", cy: "12", r: "2", fill: "currentColor" });
|
||
}
|
||
wrap.append(svg);
|
||
return wrap;
|
||
}
|
||
|
||
function chatBackendLabel(backend) {
|
||
switch (backend) {
|
||
case "codex": return "Codex";
|
||
case "claude": return "Claude";
|
||
case "pi": return "Pi";
|
||
case "opencode": return "OpenCode";
|
||
default: return String(backend ?? "");
|
||
}
|
||
}
|
||
|
||
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 back-button chat-create-back",
|
||
type: "button",
|
||
"aria-label": CHAT_CREATE_BACK_LABEL,
|
||
title: CHAT_CREATE_BACK_LABEL,
|
||
onclick: cancelNewChat,
|
||
},
|
||
backChevronIcon(),
|
||
),
|
||
// The create pane is a chat detail too: its title is the route's h1.
|
||
h("h1", {
|
||
class: "chat-bar-title chat-create-title",
|
||
id: "detailTitle",
|
||
tabindex: "-1",
|
||
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 }));
|
||
|
||
if ((state.chatBackends ?? []).length > 1) {
|
||
const harness = h("div", { class: "chat-create-backends", role: "group", "aria-label": "Chat harness" });
|
||
for (const backend of state.chatBackends) {
|
||
const active = (create.backend ?? "opencode") === backend;
|
||
harness.append(
|
||
h("button", {
|
||
class: `ghost chat-create-backend${active ? " selected" : ""}`,
|
||
type: "button",
|
||
"aria-pressed": active ? "true" : "false",
|
||
text: chatBackendLabel(backend),
|
||
onclick: () => selectChatBackend(backend),
|
||
}),
|
||
);
|
||
}
|
||
pane.append(harness);
|
||
}
|
||
|
||
const instructions = h("div", { class: "chat-create-instructions" });
|
||
instructions.append(
|
||
h("label", {
|
||
class: "chat-create-instructions-label",
|
||
for: "chatCreateInstructions",
|
||
text: "How should it act?",
|
||
}),
|
||
);
|
||
const instructionField = h(
|
||
"textarea",
|
||
{
|
||
id: "chatCreateInstructions",
|
||
class: "chat-create-instructions-input",
|
||
rows: "4",
|
||
spellcheck: "false",
|
||
oninput: (event) => {
|
||
if (!state.chatCreate) return;
|
||
state.chatCreate = { ...state.chatCreate, instructions: event.target.value };
|
||
},
|
||
},
|
||
create.instructions ?? DEFAULT_CHAT_INSTRUCTIONS,
|
||
);
|
||
instructions.append(instructionField);
|
||
instructions.append(
|
||
h("p", {
|
||
class: "chat-create-instructions-helper muted",
|
||
text: "Preloaded as this chat's session instructions. The agent still reads the repository's AGENTS.md and skills.",
|
||
}),
|
||
);
|
||
pane.append(instructions);
|
||
|
||
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 starred = state.chatStars?.has?.(session.id) === true;
|
||
const star = h("button", {
|
||
class: `ghost chat-star${starred ? " starred" : ""}`,
|
||
type: "button",
|
||
text: starred ? "\u2605" : "\u2606",
|
||
"aria-pressed": starred ? "true" : "false",
|
||
"aria-label": starred ? "Unstar chat" : "Star chat",
|
||
title: starred ? "Unstar chat" : "Star chat",
|
||
});
|
||
star.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
toggleChatStar(session.id);
|
||
});
|
||
wrap.append(star);
|
||
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);
|
||
// Measure after mounting (and after openChatMenu restores list scroll), but
|
||
// before painting. Re-anchor on every render, not only the initial click.
|
||
queueMicrotask(() => {
|
||
if (!menu.isConnected) return;
|
||
const anchor = wrap.querySelector(".chat-menu-button").getBoundingClientRect();
|
||
const rect = menu.getBoundingClientRect();
|
||
const below = anchor.bottom + 4;
|
||
const top = below + rect.height <= window.innerHeight - 8 ? below : anchor.top - rect.height - 4;
|
||
menu.style.left = `${Math.max(8, Math.min(anchor.right - rect.width, window.innerWidth - rect.width - 8))}px`;
|
||
menu.style.top = `${Math.max(8, Math.min(top, window.innerHeight - rect.height - 8))}px`;
|
||
});
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
/** Reported usage, with explicit unknowns and no inferred token/cost values. */
|
||
function renderChatUsageMetrics(thread, sessionId) {
|
||
const metrics = h("dl", {
|
||
class: "chat-usage-metrics",
|
||
id: "chatUsageMetrics",
|
||
"data-session": sessionId,
|
||
"aria-label": "Chat usage and performance",
|
||
});
|
||
for (const metric of chatUsageMetrics(thread?.usage)) {
|
||
metrics.append(h("div", {
|
||
class: "chat-usage-metric",
|
||
"data-metric": metric.key,
|
||
"data-available": String(metric.available),
|
||
title: metric.title,
|
||
}, h("dt", { text: metric.label }), h("dd", { text: metric.value })));
|
||
}
|
||
return metrics;
|
||
}
|
||
|
||
function refreshChatUsageMetrics(sessionId, thread) {
|
||
const metrics = document.getElementById("chatUsageMetrics");
|
||
if (metrics?.dataset.session === sessionId) metrics.replaceWith(renderChatUsageMetrics(thread, sessionId));
|
||
}
|
||
|
||
let usageInfoSessionId = null;
|
||
function openChatUsageInfo(sessionId, trigger) {
|
||
if (modal.isOpen("chat-usage-info")) {
|
||
modal.close("chat-usage-info");
|
||
return;
|
||
}
|
||
usageInfoSessionId = sessionId;
|
||
trigger.setAttribute("aria-expanded", "true");
|
||
const close = () => modal.close("chat-usage-info");
|
||
const overlay = h("div", {
|
||
class: "chat-usage-info-overlay",
|
||
id: "chatUsageInfoPanel",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": "Chat information",
|
||
});
|
||
const panel = h("div", { class: "chat-usage-info-panel" });
|
||
panel.style.setProperty("--chat-info-top", `${trigger.getBoundingClientRect().bottom + 8}px`);
|
||
panel.append(h("div", { class: "chat-usage-info-heading" },
|
||
h("h2", { text: "Chat information" }),
|
||
h("button", { class: "ghost chat-usage-info-close", type: "button", text: "Close", onclick: close }),
|
||
));
|
||
panel.append(renderChatUsageMetrics(state.chatThreads.get(sessionId), sessionId));
|
||
panel.append(h("p", { class: "muted chat-usage-info-note", text: "Last reported by the harness. Unavailable values are not estimated." }));
|
||
overlay.append(panel);
|
||
overlay.addEventListener("click", (event) => { if (event.target === overlay) close(); });
|
||
modal.open("chat-usage-info", overlay, {
|
||
trigger,
|
||
onClose: close,
|
||
onClosed: () => {
|
||
usageInfoSessionId = null;
|
||
document.getElementById("chatUsageInfo")?.setAttribute("aria-expanded", "false");
|
||
},
|
||
fallbackSelectors: ["#chatUsageInfo", "#chatInput", "#detailTitle"],
|
||
});
|
||
}
|
||
|
||
/** The active conversation: identity, context, transcript and its controls. */
|
||
function renderChatConversation() {
|
||
if (usageInfoSessionId && usageInfoSessionId !== state.chatActiveId) modal.close("chat-usage-info");
|
||
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 chat pane 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 form =
|
||
thread?.form && thread.form.resolved !== true && thread.form.cancelled !== true
|
||
? thread.form
|
||
: null;
|
||
const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0;
|
||
|
||
const bar = h("div", { class: "chat-bar" });
|
||
const lead = h("div", { class: "chat-bar-lead" });
|
||
// A compact back control in the conversation header, matching the create
|
||
// pane's own. The narrow layout is where the list is covered; on wide screens
|
||
// the list is still visible, so CSS hides it there.
|
||
lead.append(
|
||
h(
|
||
"button",
|
||
{
|
||
class: "ghost back-button chat-back",
|
||
type: "button",
|
||
"aria-label": "Back to chats",
|
||
title: "Back to chats",
|
||
onclick: () => closeDetail("chat"),
|
||
},
|
||
backChevronIcon(),
|
||
),
|
||
);
|
||
const titles = h("div", { class: "chat-bar-titles" });
|
||
// The open conversation is the route's one h1; the list heading above becomes
|
||
// its h2 while the detail is open.
|
||
titles.append(h("h1", { class: "chat-bar-title", id: "detailTitle", tabindex: "-1", text: title }));
|
||
lead.append(titles);
|
||
bar.append(lead);
|
||
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(chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question"));
|
||
bar.append(h("button", {
|
||
id: "chatUsageInfo",
|
||
class: "ghost chat-usage-info-button",
|
||
type: "button",
|
||
title: "Chat information",
|
||
"aria-label": "Chat information",
|
||
"aria-haspopup": "dialog",
|
||
"aria-controls": "chatUsageInfoPanel",
|
||
"aria-expanded": String(usageInfoSessionId === state.chatActiveId && modal?.isOpen?.("chat-usage-info") === true),
|
||
onclick: (event) => openChatUsageInfo(state.chatActiveId, event.currentTarget),
|
||
}, h("span", { class: "chat-usage-info-icon", "aria-hidden": "true", text: "i" })));
|
||
pane.append(bar);
|
||
const modelButton = effective ? renderChatModelButton(effective) : null;
|
||
if (modelButton) {
|
||
const context = h("div", { class: "chat-context" });
|
||
context.append(modelButton);
|
||
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 && !form) {
|
||
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, form }),
|
||
);
|
||
}
|
||
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.chatModelPicker) pane.append(renderChatModelDialog(state.chatModelPicker));
|
||
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 chat header's model control: current model, opens the switcher. */
|
||
function renderChatModelButton(session) {
|
||
const backend = String(session?.backend ?? "").trim();
|
||
if (!supportsChatModels(backend)) return null;
|
||
const label = chatModelLabel(session);
|
||
return h(
|
||
"button",
|
||
{
|
||
class: "ghost chat-model-button",
|
||
type: "button",
|
||
title: `Change model (currently ${label})`,
|
||
"aria-label": `Change model, currently ${label}`,
|
||
"aria-haspopup": "dialog",
|
||
onclick: () => openChatModelPicker(session),
|
||
},
|
||
h("span", { class: "chat-model-button-label", text: label }),
|
||
h("span", { class: "chevron", text: "\u25be" }),
|
||
);
|
||
}
|
||
|
||
/** Open the model picker and load the harness's list on first use. */
|
||
function openChatModelPicker(session) {
|
||
state.chatModelPicker = session;
|
||
state.chatModelsError = "";
|
||
state.chatModelsFor = "";
|
||
state.chatModels = [];
|
||
state.chatModelQuery = "";
|
||
state.chatModelsLoading = true;
|
||
renderContent();
|
||
loadChatModels(session.id);
|
||
}
|
||
|
||
function closeChatModelPicker() {
|
||
state.chatModelPicker = null;
|
||
state.chatModelsError = "";
|
||
state.chatModelsLoading = false;
|
||
state.chatModelQuery = "";
|
||
renderContent();
|
||
}
|
||
|
||
async function loadChatModels(sessionId) {
|
||
const backend = state.chatSessions.find((row) => row.id === sessionId)?.backend ?? "opencode";
|
||
if (!supportsChatModels(backend)) {
|
||
state.chatModelsLoading = false;
|
||
state.chatModelsError = `${chatBackendLabel(backend)} does not support changing models from this client.`;
|
||
if (state.chatModelPicker?.id === sessionId) renderContent();
|
||
return;
|
||
}
|
||
try {
|
||
const models = await repo.chatModels(sessionId);
|
||
if (state.chatModelPicker?.id !== sessionId) return;
|
||
state.chatModels = Array.isArray(models) ? models : [];
|
||
state.chatModelsFor = sessionId;
|
||
state.chatModelsError = "";
|
||
} catch (error) {
|
||
if (state.chatModelPicker?.id !== sessionId) return;
|
||
state.chatModelsError = describeError(error);
|
||
}
|
||
state.chatModelsLoading = false;
|
||
if (state.chatModelPicker?.id === sessionId) renderContent();
|
||
}
|
||
|
||
/** Apply one selected model and close the picker. */
|
||
async function selectChatModel(session, model) {
|
||
if (state.chatModelBusy) return;
|
||
state.chatModelBusy = true;
|
||
state.chatModelsError = "";
|
||
renderContent();
|
||
try {
|
||
const selected = await repo.switchChatModel(session.id, model.provider, model.id);
|
||
applyChatSessionModel(session.id, model.provider, model.id, selected.selection);
|
||
state.chatModelPicker = null;
|
||
} catch (error) {
|
||
state.chatModelsError = describeError(error);
|
||
}
|
||
state.chatModelBusy = false;
|
||
renderContent();
|
||
}
|
||
|
||
/** Apply a successful model switch to the list row and the open thread. */
|
||
function applyChatSessionModel(sessionId, provider, model, selection = "") {
|
||
state.chatSessions = (state.chatSessions ?? []).map((row) =>
|
||
row.id === sessionId ? { ...row, model, model_provider: provider, model_selection: selection } : row,
|
||
);
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (thread) setThread(sessionId, { model, modelProvider: provider });
|
||
}
|
||
|
||
/** The model dialog: current model highlighted; providers and names grouped. */
|
||
function renderChatModelDialog(session) {
|
||
const overlay = h("div", {
|
||
class: "confirm-dialog confirm-chat-model",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": "Change model",
|
||
// Preserve typing only once loaded. Keeping a stable loading/error panel
|
||
// would prevent the asynchronous model response from ever replacing it.
|
||
"data-modal-stable": !state.chatModelsLoading && !state.chatModelBusy && !state.chatModelsError ? "true" : null,
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) closeChatModelPicker();
|
||
});
|
||
const panel = h("div", { class: "confirm-panel chat-model-panel" });
|
||
panel.append(h("h2", { class: "confirm-title", text: "Change model" }));
|
||
panel.append(
|
||
h("p", {
|
||
class: "chat-model-helper muted",
|
||
text: chatModelSelectionNote(session.backend),
|
||
}),
|
||
);
|
||
if (state.chatModelsLoading) {
|
||
const loading = h("div", { class: "chat-model-loading muted" });
|
||
loading.append(h("span", { class: "spinner", "aria-hidden": "true" }), h("span", { text: "Loading models\u2026" }));
|
||
panel.append(loading);
|
||
} else if (state.chatModelsError) {
|
||
panel.append(h("p", { class: "chat-model-error", text: state.chatModelsError }));
|
||
} else if ((state.chatModels ?? []).length === 0) {
|
||
panel.append(h("p", { class: "chat-model-empty muted", text: "No models are available for this chat." }));
|
||
} else {
|
||
const search = h("input", {
|
||
id: "chatModelSearch",
|
||
class: "chat-model-search",
|
||
type: "search",
|
||
placeholder: "Search models",
|
||
"aria-label": "Search models",
|
||
"aria-controls": "chatModelList",
|
||
autocomplete: "off",
|
||
spellcheck: "false",
|
||
value: state.chatModelQuery,
|
||
});
|
||
panel.append(search);
|
||
const list = h("div", {
|
||
id: "chatModelList",
|
||
class: "chat-model-list",
|
||
role: "listbox",
|
||
"aria-label": "Available models",
|
||
});
|
||
const noMatch = h("p", { class: "chat-model-empty muted", hidden: true });
|
||
const currentProvider = String(session.model_provider ?? "");
|
||
const currentModel = String(session.model ?? "");
|
||
const renderOptions = (query) => {
|
||
const models = filterChatModels(state.chatModels, query);
|
||
list.replaceChildren();
|
||
for (const model of models) {
|
||
const selected =
|
||
model.id === currentModel && (currentProvider === "" || model.provider === currentProvider);
|
||
const option = h("button", {
|
||
class: `ghost chat-model-option${selected ? " selected" : ""}`,
|
||
type: "button",
|
||
role: "option",
|
||
"aria-selected": selected ? "true" : "false",
|
||
disabled: state.chatModelBusy,
|
||
onclick: () => selectChatModel(session, model),
|
||
});
|
||
option.append(h("span", { class: "chat-model-option-name", text: model.name || model.id }));
|
||
option.append(h("span", { class: "chat-model-option-provider muted", text: model.provider }));
|
||
if (selected) option.append(h("span", { class: "chat-model-check", text: "\u2713" }));
|
||
list.append(option);
|
||
}
|
||
const needle = String(query ?? "").trim();
|
||
noMatch.hidden = models.length > 0;
|
||
noMatch.textContent = needle === "" ? "" : `No models match "${needle}".`;
|
||
};
|
||
search.addEventListener("input", (event) => {
|
||
state.chatModelQuery = event.target.value;
|
||
renderOptions(event.target.value);
|
||
list.scrollTop = 0;
|
||
});
|
||
renderOptions(state.chatModelQuery);
|
||
panel.append(list, noMatch);
|
||
if (typeof requestAnimationFrame === "function") {
|
||
requestAnimationFrame(() => search.focus());
|
||
}
|
||
if (typeof requestAnimationFrame === "function") {
|
||
requestAnimationFrame(() => {
|
||
if (String(state.chatModelQuery ?? "").trim() !== "") return;
|
||
const selected = list.querySelector(".chat-model-option.selected");
|
||
if (!selected) return;
|
||
const top = selected.offsetTop - list.clientHeight / 2 + selected.offsetHeight / 2;
|
||
list.scrollTop = Math.max(0, top);
|
||
});
|
||
}
|
||
}
|
||
const actions = h("div", { class: "confirm-actions" });
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost confirm-dismiss",
|
||
type: "button",
|
||
text: "Cancel",
|
||
onclick: closeChatModelPicker,
|
||
}),
|
||
);
|
||
panel.append(actions);
|
||
overlay.append(panel);
|
||
modal.stage("chat-model", overlay, {
|
||
onClose: closeChatModelPicker,
|
||
fallbackSelectors: ["#chatComposer", "#detailTitle", "#pane-main"],
|
||
});
|
||
return overlay;
|
||
}
|
||
|
||
/**
|
||
* 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,
|
||
"data-modal-stable": "true",
|
||
});
|
||
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);
|
||
modal.stage("chat-rename", overlay, {
|
||
onClose: () => dismissChatRename(),
|
||
triggerSelector: `#chatRows .chat-row[data-session="${CSS.escape(String(session.id))}"] .chat-menu-button`,
|
||
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
|
||
});
|
||
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, form = 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, thread));
|
||
}
|
||
});
|
||
// The live turn's one activity row lives inside the last agent turn. If the
|
||
// turn has not produced an assistant row yet (the operator just sent the
|
||
// prompt), show the same row after their message instead of a second indicator.
|
||
const lastRow = rows[rows.length - 1] ?? null;
|
||
if (running && lastRow?.kind !== "agent") {
|
||
const placeholder = { key: `pending:${sessionId}`, parts: [], reasoning: "", reasoningSteps: [], tools: [] };
|
||
transcript.append(renderChatActivity(placeholder, true, () => 0, thread));
|
||
}
|
||
// 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 pane's jump control
|
||
// and a fresh card both land at the end.
|
||
const approvals = chatApprovalCards(thread);
|
||
const forms = chatPendingForms(thread);
|
||
if (!approvals.length && approval) approvals.push(approval);
|
||
approvals.forEach((card, index) => {
|
||
const node = renderChatApproval(sessionId, card);
|
||
if (index === 0) node.id = "chatApproval";
|
||
transcript.append(node);
|
||
});
|
||
forms.forEach((pending, index) => {
|
||
const node = renderChatQuestion(sessionId, pending);
|
||
if (index === 0) node.id = "chatQuestion";
|
||
transcript.append(node);
|
||
});
|
||
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 chat pane's approval jump control (C10), naming the pending request. */
|
||
function approvalJumpButton(label = WAITING_FOR_APPROVAL_LABEL) {
|
||
return h("button", {
|
||
class: "ghost chat-approval-jump",
|
||
type: "button",
|
||
text: 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-${card.requestId}`,
|
||
"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);
|
||
const full = card.resources.join("\n");
|
||
if (full !== card.resourceText) {
|
||
node.append(h("details", { class: "chat-approval-details" },
|
||
h("summary", { text: "Show full request" }),
|
||
h("pre", { text: full, style: "white-space: pre-wrap; overflow-wrap: anywhere;" })));
|
||
}
|
||
}
|
||
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"));
|
||
const frame = (state.chatThreads.get(sessionId)?.permissions ?? []).find((entry) => entry.request_id === card.requestId);
|
||
controls.append(approvalControl(frame?.always_label || 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 agent's structured question (OpenCode form with kind=question). Each form
|
||
* field is rendered with its options (single-select buttons or multi-select
|
||
* toggles) and, when the field is free-form or allows Other, a text input.
|
||
* Answers stay local until Send answer; the tool call is paused until then.
|
||
*/
|
||
function renderChatQuestion(sessionId, form) {
|
||
const node = h("div", {
|
||
class: "chat-question",
|
||
id: `chatQuestion-${form.id}`,
|
||
"data-form-id": form.id,
|
||
});
|
||
const head = h("div", { class: "chat-question-head" });
|
||
head.append(h("div", { class: "chat-question-title", text: form.title || "Question" }));
|
||
head.append(
|
||
h("div", { class: "chat-question-status muted", text: "The agent is waiting for your answer." }),
|
||
);
|
||
node.append(head);
|
||
|
||
// Keep entered answers across unrelated streaming frames and reconnect paints.
|
||
const thread = state.chatThreads.get(sessionId);
|
||
if (thread && !thread.formAnswers) thread.formAnswers = {};
|
||
const answers = thread ? (thread.formAnswers[form.id] ??= {}) : {};
|
||
const parts = [];
|
||
const fieldNodes = [];
|
||
for (const field of form.fields ?? []) {
|
||
if (answers[field.key] === undefined && field.default !== undefined) answers[field.key] = field.default;
|
||
}
|
||
const paintVisibility = () => {
|
||
for (const { field, part } of fieldNodes) part.hidden = !formFieldVisible(field, answers);
|
||
};
|
||
for (const field of form.fields ?? []) {
|
||
const key = String(field.key ?? "");
|
||
if (key === "") continue;
|
||
const options = Array.isArray(field.options) ? field.options : [];
|
||
const multi = field.type === "multiselect";
|
||
const part = h("div", { class: "chat-question-field" });
|
||
fieldNodes.push({field,part});
|
||
part.append(
|
||
h("div", { class: "chat-question-label", text: field.title || field.description || key }),
|
||
);
|
||
if (field.description && field.description !== field.title) {
|
||
part.append(h("div", { class: "chat-question-desc muted", text: field.description }));
|
||
}
|
||
if (field.type === "external") {
|
||
const url = safeFormURL(field.url);
|
||
part.append(url ? h("a", { href: url, target: "_blank", rel: "noopener noreferrer", text: "Open external form" }) : h("div", {role:"alert",text:"This form has an unsupported external URL."}));
|
||
parts.push(part);
|
||
continue;
|
||
}
|
||
if (field.type === "boolean") {
|
||
const select = h("select", {class:"chat-question-input", "data-field-key":key, "aria-label":field.title || key},
|
||
h("option",{value:"",text:"Choose Yes or No"}),h("option",{value:"true",text:"Yes"}),h("option",{value:"false",text:"No"}));
|
||
select.value = typeof answers[key] === "boolean" ? String(answers[key]) : "";
|
||
select.addEventListener("change",()=>{const value=formFieldValue(field,select.value);if(value===undefined)delete answers[key];else answers[key]=value;paintVisibility();});
|
||
part.append(select);
|
||
parts.push(part);
|
||
continue;
|
||
}
|
||
if (options.length) {
|
||
const rows = h("div", { class: "chat-question-options" });
|
||
const buttons = [];
|
||
const chosen = () => (multi ? (Array.isArray(answers[key]) ? answers[key] : []) : [answers[key]].filter(Boolean));
|
||
const paint = () => {
|
||
const selected = new Set(chosen());
|
||
for (const button of buttons) {
|
||
const on = selected.has(button.dataset.value);
|
||
button.classList.toggle("selected", on);
|
||
button.setAttribute("aria-pressed", on ? "true" : "false");
|
||
}
|
||
};
|
||
for (const option of options) {
|
||
const value = String(option.value ?? option.label ?? "");
|
||
if (value === "") continue;
|
||
const button = h(
|
||
"button",
|
||
{
|
||
class: "chat-question-option",
|
||
type: "button",
|
||
"data-value": value,
|
||
"aria-pressed": "false",
|
||
text: option.label || value,
|
||
},
|
||
option.description
|
||
? h("span", { class: "chat-question-option-desc", text: option.description })
|
||
: null,
|
||
);
|
||
button.addEventListener("click", () => {
|
||
if (multi) {
|
||
const next = new Set(chosen());
|
||
if (next.has(value)) next.delete(value);
|
||
else next.add(value);
|
||
answers[key] = [...next];
|
||
} else {
|
||
answers[key] = value;
|
||
}
|
||
paint();
|
||
paintVisibility();
|
||
});
|
||
buttons.push(button);
|
||
rows.append(button);
|
||
}
|
||
paint();
|
||
part.append(rows);
|
||
}
|
||
if (field.custom === true || options.length === 0) {
|
||
const input = h("input", {
|
||
class: "chat-question-input",
|
||
"data-field-key": key,
|
||
type: field.secret ? "password" : ["number","integer"].includes(field.type) ? "number" : field.format === "email" ? "email" : field.format === "uri" ? "url" : field.format === "date" ? "date" : "text",
|
||
step: field.type === "number" ? "any" : field.type === "integer" ? "1" : null,
|
||
min: typeof field.minimum === "number" ? String(field.minimum) : null,
|
||
max: typeof field.maximum === "number" ? String(field.maximum) : null,
|
||
minlength: field.min_length ?? null,
|
||
maxlength: field.max_length ?? null,
|
||
pattern: field.pattern || null,
|
||
"aria-label": field.title || key,
|
||
placeholder: field.placeholder || (options.length ? "Type another answer" : "Your answer"),
|
||
autocomplete: "off",
|
||
value: ["string","number"].includes(typeof answers[key]) ? String(answers[key]) : "",
|
||
});
|
||
input.addEventListener("input", () => {
|
||
const value = formFieldValue(field,input.value);
|
||
if (value === undefined) delete answers[key];
|
||
else if (multi) {
|
||
const known=new Set(options.map(option=>String(option.value ?? option.label ?? "")));
|
||
answers[key]=[...(Array.isArray(answers[key]) ? answers[key].filter(v=>known.has(v)) : []),...String(value).split(",").map(v=>v.trim()).filter(Boolean)];
|
||
} else answers[key] = value;
|
||
paintVisibility();
|
||
});
|
||
part.append(input);
|
||
}
|
||
parts.push(part);
|
||
}
|
||
node.append(...parts);
|
||
paintVisibility();
|
||
|
||
const error = h("div", { class: "chat-question-error", role: "alert", hidden: true });
|
||
node.append(error);
|
||
const controls = h("div", { class: "chat-question-controls" });
|
||
const submit = h("button", {
|
||
class: "primary chat-question-submit",
|
||
type: "button",
|
||
text: (form.fields ?? []).every(field=>field.type === "external") ? "Confirm completion" : "Send answer",
|
||
});
|
||
let sent = false;
|
||
submit.addEventListener("click", () => {
|
||
if (sent) return;
|
||
const invalidInput=[...node.querySelectorAll('input')].find(input=>!input.closest('.chat-question-field').hidden && !input.checkValidity());
|
||
const reason=formAnswerError(form.fields,answers);
|
||
if (reason || invalidInput) {
|
||
error.hidden = false;
|
||
error.textContent = reason || invalidInput.validationMessage;
|
||
return;
|
||
}
|
||
sent = true;
|
||
submit.disabled = true;
|
||
submit.textContent = "Sending…";
|
||
answerChatQuestion(sessionId, form, visibleFormAnswers(form.fields,answers), form.actions?.includes("accept") ? "accept" : "");
|
||
});
|
||
controls.append(submit);
|
||
for (const action of ["decline","cancel"]) {
|
||
if (!form.actions?.includes(action)) continue;
|
||
controls.append(h("button",{class:"ghost",type:"button",text:action === "cancel" ? "Cancel question" : "Decline",onclick:()=>answerChatQuestion(sessionId,form,{},action)}));
|
||
}
|
||
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),
|
||
});
|
||
}
|
||
|
||
/** 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 parts = message?.parts ?? [];
|
||
const text = 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 }));
|
||
const files = parts.filter(
|
||
(part) => part?.type === "file" && (String(part?.name ?? "").trim() !== "" || String(part?.uri ?? "").trim() !== ""),
|
||
);
|
||
if (files.length > 0) {
|
||
const strip = h("div", { class: "chat-user-files" });
|
||
for (const part of files) {
|
||
const name = attachmentDisplayName(part?.name, part?.uri);
|
||
const file = h("span", { class: "chat-user-file", title: name });
|
||
file.append(h("span", { class: "chat-user-file-glyph", "aria-hidden": "true", text: "\u{1F4CE}" }));
|
||
file.append(h("span", { class: "chat-user-file-name", text: name }));
|
||
strip.append(file);
|
||
}
|
||
bubble.append(strip);
|
||
}
|
||
turn.append(bubble);
|
||
return turn;
|
||
}
|
||
|
||
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
|
||
function renderChatAgentTurn(turn, streaming = false, elapsedMillis = () => 0, thread = null) {
|
||
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
|
||
const bubble = h("div", { class: "chat-bubble agent-bubble" });
|
||
// One activity line carries the whole live turn: the spinner, the reasoning
|
||
// toggle, the tool-call summary and the elapsed time. The old separate
|
||
// reasoning, tool and bottom "thinking" rows made the transcript jump as each
|
||
// phase came and went.
|
||
const activity = renderChatActivity(turn, streaming, elapsedMillis, thread);
|
||
if (activity) wrap.append(activity);
|
||
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
|
||
if (bubble.childElementCount > 0) wrap.append(bubble);
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* One stable activity row for a turn: spinner, reasoning toggle, tool-call
|
||
* summary and the elapsed time. The reasoning body (when expanded) and the tool
|
||
* panel hang off this row, so the three old live lines never appear and vanish
|
||
* independently while a turn moves from thinking to tools and back.
|
||
*/
|
||
function renderChatActivity(turn, streaming = false, elapsedMillis = () => 0, thread = null) {
|
||
const steps = turn.reasoningSteps ?? [];
|
||
const parts = turn.tools ?? [];
|
||
if (!streaming && steps.length === 0 && parts.length === 0) return null;
|
||
const wrap = h("div", {
|
||
class: `chat-reasoning chat-activity${streaming ? " chat-reasoning-live" : ""}`,
|
||
});
|
||
const head = h("div", { class: "chat-activity-head" });
|
||
const compacting = streaming && threadPhase(thread, Date.now()) === TURN_PHASE_COMPACTING;
|
||
if (compacting) head.classList.add("chat-activity-compacting");
|
||
if (streaming) {
|
||
const spinner = h("span", {
|
||
class: "spinner chat-activity-spinner",
|
||
"aria-hidden": "true",
|
||
});
|
||
// Keep the rotation continuous across transcript repaints.
|
||
spinner.style.animationDelay = `-${(performance.now() % 800) / 1000}s`;
|
||
head.append(spinner);
|
||
}
|
||
if (compacting) {
|
||
head.append(h("span", {
|
||
class: "chat-activity-phase chat-compaction-status",
|
||
role: "status",
|
||
"aria-live": "polite",
|
||
text: turnPhaseLabel(TURN_PHASE_COMPACTING),
|
||
}));
|
||
if (steps.length || parts.length) head.append(h("span", { class: "chat-compaction-break", "aria-hidden": "true" }));
|
||
}
|
||
if (steps.length > 0) {
|
||
head.append(renderChatReasoningToggle(turn, streaming && !compacting, steps));
|
||
} else if (streaming && !compacting) {
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-activity-phase",
|
||
text: turnPhaseLabel(threadPhase(thread, Date.now()) ?? TURN_PHASE_WAITING),
|
||
}),
|
||
);
|
||
}
|
||
if (parts.length > 0) {
|
||
if (steps.length > 0 || (streaming && !compacting)) head.append(h("span", { class: "chat-activity-sep", text: "\u00b7" }));
|
||
head.append(renderChatToolChip(turn, { streaming, elapsedMillis }));
|
||
}
|
||
const elapsed = streaming
|
||
? threadElapsedMillis(thread, Date.now())
|
||
: turnElapsedMillis(turn.parts);
|
||
if (elapsed != null) {
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-activity-elapsed",
|
||
text: `\u00b7 ${formatDuration(Math.trunc(elapsed / 1000))}`,
|
||
}),
|
||
);
|
||
}
|
||
wrap.append(head);
|
||
return wrap;
|
||
}
|
||
|
||
/** The reasoning half of the activity row: a quiet, expandable label. */
|
||
function renderChatReasoningToggle(turn, streaming, steps) {
|
||
const toggle = h("button", {
|
||
class: "chat-reasoning-toggle",
|
||
type: "button",
|
||
"aria-haspopup": "dialog",
|
||
"aria-label": "Open reasoning",
|
||
title: "Open reasoning",
|
||
});
|
||
toggle.append(
|
||
h("span", {
|
||
class: "chat-reasoning-icon",
|
||
role: "img",
|
||
"aria-label": "Open reasoning",
|
||
text: "\u25b8",
|
||
}),
|
||
);
|
||
toggle.append(
|
||
h("span", {
|
||
class: "chat-reasoning-label",
|
||
"data-live-steps": streaming ? String(steps.length) : null,
|
||
text: reasoningLabel(steps.length, streaming),
|
||
}),
|
||
);
|
||
toggle.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
openChatReasoning(turn, steps);
|
||
});
|
||
return toggle;
|
||
}
|
||
|
||
/** The reasoning overlay, shaped like the tool-call popup. */
|
||
function openChatReasoning(turn, steps) {
|
||
const close = () => modal.close("chat-reasoning");
|
||
const overlay = h("div", {
|
||
class: "chat-tools-viewer chat-reasoning-viewer",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": "Reasoning",
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) close();
|
||
});
|
||
const panel = h("div", { class: "chat-tools-modal-panel chat-reasoning-modal-panel" });
|
||
panel.append(
|
||
h(
|
||
"div",
|
||
{ class: "chat-tool-panel-head" },
|
||
h("span", { class: "chat-tool-panel-count", text: reasoningLabel(steps.length, false) }),
|
||
h("button", {
|
||
class: "ghost chat-tool-close",
|
||
type: "button",
|
||
"aria-label": "Close reasoning",
|
||
title: "Close reasoning",
|
||
text: "\u00d7",
|
||
onclick: close,
|
||
}),
|
||
),
|
||
h("div", { class: "chat-reasoning-modal-body", text: turn.reasoning }),
|
||
);
|
||
overlay.append(panel);
|
||
modal.open("chat-reasoning", overlay, {
|
||
history: false,
|
||
onClose: close,
|
||
trigger: document.activeElement,
|
||
fallbackSelectors: ["#chatTranscript", "#detailTitle", "#pane-main"],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* One turn's tool calls behind a single summary chip: `N tools`, the
|
||
* current call while one is in flight, a `· long` mark and the panel chevron.
|
||
* The line's single spinner lives in the activity row, not here.
|
||
*/
|
||
function renderChatToolChip(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 errors = toolFailureCount(turn.parts);
|
||
const errorLabel = errors === 1 ? "1 error" : `${errors} errors`;
|
||
const long = running && parts.some((part) => toolRunning(part) && toolLongRunning(elapsedMillis(part)));
|
||
const chip = h("button", {
|
||
class: "chat-tool-chip",
|
||
type: "button",
|
||
"aria-label": `${toolCallsAnnouncement(count)}${errors ? `, ${errorLabel}` : ""}`,
|
||
"aria-expanded": "false",
|
||
"aria-haspopup": "dialog",
|
||
});
|
||
const currentTool = running ? parts.filter((part) => toolRunning(part)).at(-1) ?? null : null;
|
||
chip.append(
|
||
h("span", {
|
||
class: "chat-tool-icon",
|
||
"aria-hidden": "true",
|
||
text: "\u29c9",
|
||
}),
|
||
);
|
||
chip.append(h("span", { class: "chat-tool-label", text: toolCallsLabel(count) }));
|
||
if (errors) chip.append(h("span", { class: "chat-tool-error-count", text: `· ${errorLabel}` }));
|
||
if (currentTool) {
|
||
const detail = toolDetail(currentTool);
|
||
const name = toolLabel(currentTool);
|
||
chip.append(
|
||
h("span", {
|
||
class: "chat-tool-current",
|
||
text: detail == null ? name : `${name} ${detail}`,
|
||
}),
|
||
);
|
||
}
|
||
if (long) chip.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
chip.append(
|
||
h("span", {
|
||
class: "chat-tool-chevron",
|
||
role: "img",
|
||
"aria-label": "Open tool calls",
|
||
text: "\u25b8",
|
||
}),
|
||
);
|
||
chip.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
openChatToolCalls(turn, parts, count);
|
||
});
|
||
return chip;
|
||
}
|
||
|
||
/** The tool list body, shared by the modal: one expandable row per call. */
|
||
function renderChatToolPanelBody(turn, parts, count) {
|
||
const panel = h("div", { class: "chat-tool-panel" });
|
||
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);
|
||
return panel;
|
||
}
|
||
|
||
/** Open one turn's tool calls in a modal, not an inline popover. */
|
||
function openChatToolCalls(turn, parts, count) {
|
||
const close = () => modal.close("chat-tools");
|
||
const overlay = h("div", {
|
||
class: "chat-tools-viewer",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": toolCallsLabel(count),
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) close();
|
||
});
|
||
const panel = h("div", { class: "chat-tools-modal-panel" });
|
||
panel.append(
|
||
h(
|
||
"div",
|
||
{ class: "chat-tool-panel-head" },
|
||
h("span", { class: "chat-tool-panel-count", text: toolCallsLabel(count) }),
|
||
h("button", {
|
||
class: "ghost chat-tool-close",
|
||
type: "button",
|
||
"aria-label": "Close tool calls",
|
||
title: "Close tool calls",
|
||
text: "\u00d7",
|
||
onclick: close,
|
||
}),
|
||
),
|
||
renderChatToolPanelBody(turn, parts, count),
|
||
);
|
||
overlay.append(panel);
|
||
modal.open("chat-tools", overlay, {
|
||
history: false,
|
||
onClose: close,
|
||
trigger: document.activeElement,
|
||
fallbackSelectors: ["#chatTranscript", "#detailTitle", "#pane-main"],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 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) }));
|
||
const pre = h("pre", { class: "md-pre" });
|
||
const body = h("code");
|
||
for (const token of highlight(block.code, block.language)) {
|
||
if (token.kind === "plain") body.append(document.createTextNode(token.text));
|
||
else body.append(h("span", { class: `tok-${token.kind}`, text: token.text }));
|
||
}
|
||
pre.append(body);
|
||
code.append(pre);
|
||
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);
|
||
// A markdown table must never widen the message bubble. Scroll it sideways
|
||
// inside its own frame on a phone instead of pushing the transcript past its
|
||
// right edge.
|
||
return h("div", { class: "md-table-wrap" }, 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) or validated same-origin artifact 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.
|
||
const artifact = isLocalArtifactLink(span.url, globalThis.location?.href);
|
||
const linkProps = artifact ? artifactBrowserLinkProps(span.url)
|
||
: /^https?:\/\//i.test(span.url) ? { href: span.url, rel: "noreferrer noopener", target: "_blank" } : null;
|
||
if (linkProps) {
|
||
return h(
|
||
"a",
|
||
{ class: "md-link", ...linkProps },
|
||
...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",
|
||
// Keep the empty single-line field aligned with its controls on phones.
|
||
// The full command hint remains the accessible name below.
|
||
placeholder: "Message the agent…",
|
||
"aria-label": CHAT_COMPOSER_PLACEHOLDER,
|
||
title: "Enter adds a new line · Ctrl/Cmd+Enter sends",
|
||
spellcheck: "false",
|
||
});
|
||
input.value = thread.draft ?? "";
|
||
input.addEventListener("input", (event) => onComposerInput(event, sessionId, session, controls));
|
||
input.addEventListener("keydown", (event) => onComposerKeydown(event, sessionId, session, controls));
|
||
input.addEventListener("paste", (event) => onComposerPaste(event, sessionId, session));
|
||
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();
|
||
// Send is always available; while a turn runs, Stop sits beside it and a send
|
||
// is queued behind the current turn instead of making the operator wait.
|
||
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,
|
||
},
|
||
"➤",
|
||
),
|
||
);
|
||
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,
|
||
},
|
||
"■",
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/** 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,
|
||
"data-modal-stable": "true",
|
||
});
|
||
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);
|
||
modal.stage("chat-close", overlay, {
|
||
onClose: () => dismissChatClose(),
|
||
triggerSelector: `#chatRows .chat-row[data-session="${CSS.escape(String(session.id))}"] .chat-menu-button`,
|
||
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
|
||
});
|
||
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 = () => {
|
||
// A touch/pointer scroll is the operator's own intent, exactly like a wheel.
|
||
// Without this, a phone scroll up never cleared `chatFollowing`, so the next
|
||
// streamed frame snapped the transcript back to the bottom.
|
||
state.chatUserIntent = true;
|
||
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);
|
||
restoreChatFocus();
|
||
}
|
||
|
||
/** 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() {
|
||
chatNow = Date.now();
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0;
|
||
if (state.view !== "chat" || !thread?.running || awaiting) {
|
||
stopChatClock();
|
||
return;
|
||
}
|
||
// Keep the one ticker. A streaming turn re-renders on every delta, and a clock
|
||
// restarted on each render would be cleared before its first second elapsed, so
|
||
// the indicator's elapsed time sat at 0s for the whole turn.
|
||
if (chatClock) return;
|
||
chatClock = setInterval(() => {
|
||
chatNow = Date.now();
|
||
updateChatIndicator(chatNow);
|
||
}, 1000);
|
||
}
|
||
|
||
function stopChatClock() {
|
||
if (chatClock) {
|
||
clearInterval(chatClock);
|
||
chatClock = null;
|
||
}
|
||
}
|
||
|
||
/** Refresh the activity row in place from the thread's own state at [now]. */
|
||
function updateChatIndicator(now) {
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
if (!thread?.running) return;
|
||
// The live turn is the last activity row, not the first one in a long
|
||
// transcript.
|
||
const elapsed = [...document.querySelectorAll("#chatTranscript .chat-activity-elapsed")].at(-1);
|
||
if (elapsed) {
|
||
elapsed.textContent = `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`;
|
||
}
|
||
const phase = [...document.querySelectorAll("#chatTranscript .chat-activity-phase")].at(-1);
|
||
if (phase) {
|
||
const label = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING);
|
||
if (phase.textContent !== label) phase.textContent = label;
|
||
}
|
||
}
|
||
|
||
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,
|
||
};
|
||
}
|