// Pure, DOM-free logic for the browser client's chat surface (C1/C3/C4/C7/C14). // Ported from the Android client so the browser shows exactly the same words and // makes exactly the same decisions: // ui/chat/ChatFormat.kt sessionTitle, sessionTagLabel, sessionWorkLabel, // sessionMeta, sessionActivity, sessionStatusLabel, // chatHeaderMeta, transcriptRows, ChatTurn, // partRendering, closeChatConfirmation, // reasoningLabel, turnElapsedMillis, toolRunning, // toolFailed, toolCallCount, toolsRunning, // toolCallsAnnouncement, toolDetail, prettyToolInput, // toolOutputText, toolErrorText, toolDurationMillis, // runningToolElapsedMillis, formatToolDuration, // toolEditDiff, lineDiff, toolCallRow // ui/chat/ChatToolCalls.kt toolCallsLabel, toolCallsAnnouncement, toolDetail, // toolCallRow, TOOL_LONG_RUNNING_MILLIS/ // toolLongRunning (the chip and its panel) // ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions, // groupChatSessionsByDirectory // ui/chat/ChatDirectories.kt HOME_DIRECTORY, directoryChoices, // defaultDirectoryChoice (the create picker) // ui/chat/ChatCreatePane.kt the create flow's wording, NewChatActions footer // and the create state transitions // ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt, // chatShowJumpToLatest, chatOpensAtNewest, // chatFirstScroll // ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an // older page, replace nextCursor/hasMore) and the // local command notices (append, dismiss one, // take an offer; ChatCommandNotice) // ui/chat/ChatCommandUi.kt the Command / Command failed labels and the // terminal glyph of one local notice line // ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled, // the submit routing (command vs prompt) // ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions, // chatCommandForEnter, chatCommandHelp, // chatCommandEffect // ui/chat/ChatFormat.kt attachmentError, attachmentFiles, // MAX_ATTACHMENT_BYTES, attachmentDisplayName // ui/chat/ChatAttachments.kt the attachment display name/error rules // ui/chat/ChatOverrides.kt ChatSessionOverrides: local titles + hidden ids, // applied over every server list refresh // ui/chat/ChatSeen.kt ChatSeenState: the seen watermark and explicit // unseen marks behind the row's "New" badge // // Nothing here touches the DOM or imports the app: every wording and decision is // unit-tested without a browser. The caller sets each server string with // textContent, never innerHTML. // The one diff-line vocabulary, shared with the run summary's Changes viewer // (ui/chat/ChatDiffCard.kt diffLineSymbol/diffLineColor) so an edit call's // synthesised diff and the Changes viewer can never disagree about what a line // kind is called or coloured. import { ChangeLineKind } from "./changes.js"; import { humanBytes } from "./artifacts.js"; /** ChatMessage.Role values (internal/protocol/chat.go). */ export const ROLE_USER = "user"; export const ROLE_ASSISTANT = "assistant"; /** ChatPart.Type values. */ export const PART_TEXT = "text"; export const PART_REASONING = "reasoning"; export const PART_TOOL = "tool"; /** ChatSession.Tag values, and the one display label derived from them. */ export const TAG_OPERATOR = "operator"; export const OPERATOR_TAG_LABEL = "Operator"; /** The row chip and the section heading for a chat the operator finished with. */ export const CLOSED_CHIP_LABEL = "Closed"; export const CLOSED_SECTION_LABEL = "Closed"; /** The section heading for sessions the server reported without a directory. */ export const NO_DIRECTORY_LABEL = "No directory"; /** The fallback title, when a session has neither a title nor an id. */ export const UNTITLED_TITLE = "Untitled chat"; /** How long a session id is truncated to when a session has no title. */ export const SESSION_ID_TITLE_LENGTH = 18; /** The pixels within which the transcript still counts as at the bottom. */ export const CHAT_FOLLOW_THRESHOLD_PX = 32; /** The settled label of a single-step turn's reasoning block. */ export const REASONING_LABEL = "Reasoning"; /** The in-flight label of a single-step turn's reasoning block. */ export const REASONING_STREAMING_LABEL = "Thinking…"; /** * The collapsed thinking line's label. A turn that reasoned several times reads * as its step count — `Thinking · N steps` while in flight, `Reasoning · N steps` * once settled — so the operator can tell before opening it how much thinking * there is; a turn that reasoned once keeps the plain one-block wording, because * a count of one is never shown. */ export function reasoningLabel(count, streaming = false) { if (count > 1 && streaming) return `Thinking · ${count} steps`; if (count > 1) return `${REASONING_LABEL} · ${count} steps`; if (streaming) return REASONING_STREAMING_LABEL; return REASONING_LABEL; } // --------------------------------------------------------------------------- // Wording (ChatListPane.kt / ChatConversationPane.kt / ChatFormat.kt), verbatim // --------------------------------------------------------------------------- export const CHAT_TAB_TITLE = "Chat"; export const CHAT_LOADING = "Loading chats…"; export const CHAT_EMPTY = "No chat sessions on this server yet."; export const CHAT_NEW_ACTION = "New chat"; export const CHAT_NO_MATCH_ACTION = "Clear search"; export const CHAT_SEARCH_LABEL = "Search chats"; export const CLOSE_CHAT_ACTION = "Close chat…"; export const CLOSE_CHAT_TITLE = "Close chat?"; export const CLOSE_CHAT_CONFIRM = "Close chat"; export const CLOSE_CHAT_DISMISS = "Cancel"; export const REOPEN_ACTION = "Reopen"; export const CONVERSATION_LOADING = "Loading conversation…"; export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something below."; export const LOAD_OLDER_ACTION = "Load older messages"; export const SELECT_CHAT_HINT = "Select a chat to open it."; // The create flow (C2, ChatCreatePane.kt), verbatim. The home choice's row is // `Home (~)` while chat_create sends the `~` the server documents; the footer // names the value that will be sent (see chatStartInLabel). export const HOME_DIRECTORY = "~"; export const HOME_LABEL = `Home (${HOME_DIRECTORY})`; export const CHAT_CREATE_TITLE = "Start a chat"; export const CHAT_CREATE_BACK_LABEL = "Cancel new chat"; export const CHAT_CREATE_LOADING = "Loading directories…"; export const CHAT_CREATE_PROMPT = "Where should this chat live?"; export const CHAT_CREATE_MODEL_NOTE = "This server has no request for choosing a chat's model, so a new chat uses the server's default."; export const CHAT_CREATE_CONFIRM = "New chat"; export const CHAT_CREATE_CANCEL = "Cancel"; /** The create footer's line: `Start in {directory}` with the value that is sent. */ export function chatStartInLabel(directory) { return `Start in ${str(directory)}`; } /** The listing's narrowed-to-nothing message: `No chats match "{query}".` */ export function chatNoMatchMessage(query) { return `No chats match "${str(query).trim()}".`; } /** A blank-safe string read of a wire value. */ function str(value) { return value == null ? "" : String(value); } function isBlank(value) { return str(value).trim() === ""; } // --------------------------------------------------------------------------- // Session identity (ChatFormat.kt) // --------------------------------------------------------------------------- /** * A session's short title: the server title, or a truncated id when untitled, so * a row never renders as a blank line. */ export function sessionTitle(session) { const title = str(session?.title); if (!isBlank(title)) return title; const short = str(session?.id).slice(0, SESSION_ID_TITLE_LENGTH); if (!isBlank(short)) return short; return UNTITLED_TITLE; } /** * The kind chip label for a session's own tag: an `operator` tag reads * `Operator`, any other tag is shown verbatim (a kind this client does not know * is never silently dropped) and a blank tag shows no chip. */ export function sessionTagLabel(tag) { const value = str(tag); if (isBlank(value)) return null; return value === TAG_OPERATOR ? OPERATOR_TAG_LABEL : value; } /** The chip label for a session, from its own tag (see [sessionTagLabel]). */ export function sessionChipLabel(session) { return sessionTagLabel(session?.tag); } /** The chip label for a tool call: its name, or `tool` when unnamed. */ export function toolLabel(part) { const name = str(part?.name); return isBlank(name) ? "tool" : name; } /** * A turn's one summary chip: `N tools called`, and `1 tool called` for a single * call — a count of one is never pluralised. */ export function toolCallsLabel(count) { return count === 1 ? "1 tool called" : `${count} tools called`; } /** * The tool lifecycle statuses (internal/protocol/chat.go ChatToolState.Status) * that mean a call is still in flight: `streaming` and `running`. `completed` * and `error` are settled, and a missing status is settled too. */ function toolStatusRunning(status) { const value = str(status); return value === "streaming" || value === "running"; } /** True while [part] is a tool call the stream still reports as running. */ export function toolRunning(part) { return part?.type === PART_TOOL && toolStatusRunning(part?.state?.status); } /** The tool calls of [parts] that are still in flight, in transcript order. */ export function runningTools(parts) { return (parts ?? []).filter((part) => toolRunning(part)); } /** True when a tool call ended in an error state. */ export function toolFailed(state) { return str(state?.status) === "error"; } /** How many tool calls [parts] holds, counted by kind rather than by length. */ export function toolCallCount(parts) { return (parts ?? []).filter((part) => part?.type === PART_TOOL).length; } /** True while any tool call in [parts] is still in flight. */ export function toolsRunning(parts) { return (parts ?? []).some((part) => toolRunning(part)); } /** * What the summary chip announces to a screen reader, since the individual calls * only exist inside the panel: the count, plus how to reach the detail. Singular * and plural follow [toolCallsLabel] so the two never disagree. */ export function toolCallsAnnouncement(count) { return count === 1 ? "1 tool call, expand for details" : `${count} tool calls, expand for details`; } /** * A tool call running longer than this reads as unusually long and is marked, so * a genuinely stuck call is visible without a fabricated ETA. One minute. */ export const TOOL_LONG_RUNNING_MILLIS = 60000; /** Whether a running call has been going long enough to be marked unusual. */ export function toolLongRunning(elapsedMillis) { return elapsedMillis >= TOOL_LONG_RUNNING_MILLIS; } /** Wall-clock duration of a tool call, or null while it has no completion time. */ export function toolDurationMillis(part) { const time = part?.time; if (time == null) return null; const start = Number(time.ran) > 0 ? Number(time.ran) : Number(time.created); const completed = Number(time.completed); if (!(start > 0) || !(completed > 0) || completed < start) return null; return completed - start; } /** * How long a running [part] has been going at [nowMillis]. The protocol's own * timing wins whenever the part carries it (a running call from stored history * has `time.ran`, the moment it started); otherwise the elapsed is measured * locally from [startedAt] — the wall clock at which this client first saw the * part running. Zero when neither is usable, so a caller never shows a time it * cannot stand behind. */ export function runningToolElapsedMillis(part, startedAt, nowMillis) { const time = part?.time; const protocolStart = time == null ? 0 : Number(time.ran) > 0 ? Number(time.ran) : Number(time.created); const start = protocolStart > 0 ? protocolStart : startedAt; return start >= 1 && start < nowMillis ? nowMillis - start : 0; } /** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */ export function formatToolDuration(millis) { const value = Number(millis) || 0; if (value < 1000) return `${value}ms`; if (value < 60000) return `${(value / 1000).toFixed(1)}s`; return `${Math.floor(value / 60000)}m ${Math.floor((value % 60000) / 1000)}s`; } /** * The input keys, in preference order, that carry a human-facing command or a * short description of what a tool call is doing. OpenCode's tools put the * substance in different places (`command` for a shell, `description` for a task, * a path or pattern for the file/search tools), so the first one present is shown * rather than the raw arguments. */ export const TOOL_DETAIL_KEYS = [ "description", "command", "filePath", "file_path", "path", "pattern", "query", "url", ]; /** How much of a command/description is shown before it is elided. */ export const TOOL_DETAIL_MAX_LENGTH = 72; /** * A one-line command or short description for [part], taken from the input the * part actually carries: the first of [TOOL_DETAIL_KEYS] present, collapsed to a * single line and elided past [TOOL_DETAIL_MAX_LENGTH]. Null when the input * carries no such key (a partial-JSON string while the call is still streaming, * or a tool that reports none), so a caller shows the name alone rather than a * fabricated summary. */ export function toolDetail(part) { const input = part?.state?.input; if (input == null || typeof input !== "object" || Array.isArray(input)) return null; for (const key of TOOL_DETAIL_KEYS) { const value = input[key]; if (typeof value !== "string") continue; const text = value.trim().replace(/\s+/g, " "); if (text === "") continue; return text.length <= TOOL_DETAIL_MAX_LENGTH ? text : text.slice(0, TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"; } return null; } /** * The one-line command a background process is running, collapsed to a single * line and elided past [TOOL_DETAIL_MAX_LENGTH] like a tool call's detail, so a * long command line cannot flood the bar. A shell that reported no command reads * as a generic `background process` rather than a blank line (ChatFormat.kt * shellCommandSummary, which shares the tool-detail regex and bound). */ export function shellCommandSummary(command) { const text = str(command).trim().replace(/\s+/g, " "); if (text === "") return "background process"; return text.length <= TOOL_DETAIL_MAX_LENGTH ? text : text.slice(0, TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"; } /** * The INPUT section of a tool call: pretty-printed JSON once the arguments are an * object/array, the raw partial-JSON string while still streaming, or empty when * there is nothing. */ export function prettyToolInput(input) { if (input == null) return ""; if (typeof input === "string") return input; if (typeof input === "object") return JSON.stringify(input, null, 2); return String(input); } /** * The OUTPUT section of a tool call: the concatenated textual content, the * literal `(no output)` when it settled with nothing, and an empty string while * the call is still in flight. */ export function toolOutputText(state) { if (state == null) return ""; const text = (state.content ?? []) .filter((item) => item?.type === "text" && !isBlank(item.text)) .map((item) => str(item.text)) .join("\n"); if (!isBlank(text)) return text; if (toolStatusRunning(state.status)) return ""; return "(no output)"; } /** * The ERROR section of a failed tool call. The server's error message takes * precedence over any partial output the call had already produced, falling back * to the output text so the block is never blank when the failure carries no * message. */ export function toolErrorText(state) { const message = state?.error?.message; return !isBlank(message) ? str(message) : toolOutputText(state); } /** How many diff lines are rendered before the remainder is summarised. */ export const MAX_RENDERED_DIFF_LINES = 200; /** The larger algorithm guard that bounds the quadratic LCS table. */ export const MAX_DIFF_LINES = 400; /** * A minimal line diff (LCS) so only the changed lines are marked, not the whole * block. A pathologically large edit falls back to a plain remove-then-add block * to bound the quadratic table. Each line carries a [ChangeLineKind]. */ export function lineDiff(oldLines, newLines) { const old = oldLines ?? []; const next = newLines ?? []; if (old.length > MAX_DIFF_LINES || next.length > MAX_DIFF_LINES) { return [ ...old.map((text) => ({ kind: ChangeLineKind.Remove, text })), ...next.map((text) => ({ kind: ChangeLineKind.Add, text })), ]; } const m = old.length; const n = next.length; const lcs = Array.from({ length: m + 1 }, () => new Int32Array(n + 1)); for (let i = m - 1; i >= 0; i -= 1) { for (let j = n - 1; j >= 0; j -= 1) { lcs[i][j] = old[i] === next[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); } } const result = []; let i = 0; let j = 0; while (i < m && j < n) { if (old[i] === next[j]) { result.push({ kind: ChangeLineKind.Context, text: old[i] }); i += 1; j += 1; } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { result.push({ kind: ChangeLineKind.Remove, text: old[i] }); i += 1; } else { result.push({ kind: ChangeLineKind.Add, text: next[j] }); j += 1; } } while (i < m) { result.push({ kind: ChangeLineKind.Remove, text: old[i] }); i += 1; } while (j < n) { result.push({ kind: ChangeLineKind.Add, text: next[j] }); j += 1; } return result; } /** * Derives a unified diff for an `edit`-family tool call from its * `oldString`/`newString` arguments. A diff longer than * [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are kept, with * `omitted` carrying the rest — so a very large edit cannot flood the transcript. * Returns null for any other tool, so a non-edit call keeps only INPUT/OUTPUT. */ export function toolEditDiff(input) { if (input == null || typeof input !== "object" || Array.isArray(input)) return null; const old = stringField(input, ["oldString", "old_string"]); const next = stringField(input, ["newString", "new_string"]); if (old == null || next == null) return null; if (old === "" && next === "") return null; const lines = lineDiff(old.split("\n"), next.split("\n")); return { file: stringField(input, ["filePath", "file_path", "file"]) ?? "", added: lines.filter((line) => line.kind === ChangeLineKind.Add).length, removed: lines.filter((line) => line.kind === ChangeLineKind.Remove).length, lines: lines.slice(0, MAX_RENDERED_DIFF_LINES), omitted: Math.max(0, lines.length - MAX_RENDERED_DIFF_LINES), }; } /** The first present string value among [keys], or null. */ function stringField(object, keys) { for (const key of keys) { const value = object[key]; if (typeof value === "string") return value; } return null; } /** * Everything one row of the tool panel shows for a single call, derived once so * the row, the summary chip and their unit test agree: the call's real name (the * name the earlier frames taught it, only falling back to `tool` when none was * ever seen), its one-line detail, its duration, the pretty-printed INPUT, the * OUTPUT, the ERROR text for a failed call and the synthesised edit diff. * `error` is null for a call that did not fail, and `diff` is null for every * non-edit call, so the row shows only the sections that have content. */ export function toolCallRow(part) { const state = part?.state; const duration = toolDurationMillis(part); return { name: toolLabel(part), detail: toolDetail(part), duration: duration == null ? null : formatToolDuration(duration), input: prettyToolInput(state?.input), output: toolOutputText(state), error: toolFailed(state) ? toolErrorText(state) : null, diff: toolEditDiff(state?.input), }; } /** * The status a session row reports while a turn is in flight: it names the tool * call it is parked on (or how many, when several run at once), so a working chat * says what it is doing rather than just `Running`; a chat only generating text * still reads as plain `Running`. A chat with nothing running falls back to the * ordinary busy/idle label. */ export function sessionWorkLabel(busy, thread) { if (thread?.running) return runningSessionLabel(thread.runningTools ?? []); if (busy) return "Busy · read-only"; return "Idle"; } function runningSessionLabel(tools) { if (tools.length === 0) return "Running"; if (tools.length === 1) return `Running ${toolLabel(tools[0])}`; return `Running ${tools.length} tools`; } /** The one-line meta under a session row's title: work label · directory · model. */ export function sessionMeta(session, workLabel) { const parts = []; if (!isBlank(workLabel)) parts.push(str(workLabel)); if (!isBlank(session?.directory)) parts.push(str(session.directory)); if (!isBlank(session?.model)) parts.push(str(session.model)); return parts.join(" · "); } /** * The one-line meta under a conversation's own title: the model the server * reports is answering, the session's kind tag and its directory. Every part is a * value the server reported; a blank part is omitted. */ export function chatHeaderMeta(thread) { const parts = []; if (!isBlank(thread?.model)) parts.push(str(thread.model)); const tag = sessionTagLabel(thread?.tag); if (tag != null) parts.push(tag); if (!isBlank(thread?.directory)) parts.push(str(thread.directory)); return parts.join(" · "); } /** * The activity a session row signals beyond its open/tag/directory state: * `streaming` (a turn producing a reply now), `new` (finished since last read), * or `idle`. */ export function sessionActivity(running, unseen) { if (running) return "streaming"; if (unseen) return "new"; return "idle"; } /** * The activity badge word, or null when the row shows none. An idle session * shows `Open` only while its conversation is open; a streaming or unseen one * always shows its word. */ export function sessionActivityBadge(activity, open) { if (activity === "streaming") return "Streaming"; if (activity === "new") return "New"; if (activity === "idle" && open) return "Open"; return "Idle"; } /** * The status a conversation header shows: a closed session reads `Closed` first, * otherwise `Running` while this client has a turn in flight, else `Idle`. */ export function sessionStatusLabel(runningLocally, closed = false) { if (closed) return "Closed"; if (runningLocally) return "Running"; return "Idle"; } /** * The close confirmation's body: it says exactly what closing does — stops a * running turn, marks the chat closed on every device — and what it does not do: * nothing is deleted, the chat and its history are kept and can be reopened. * Kept pure so the confirmation wording and its unit test share one string. */ export function closeChatConfirmation(title) { return ( `Closes "${title}" and marks it closed on every device. ` + "A turn that is running is stopped first. " + "Nothing is deleted — the chat and its history are kept, " + "and you can reopen it from the list." ); } // --------------------------------------------------------------------------- // Local overrides and seen state (ChatOverrides.kt / ChatSeen.kt) // --------------------------------------------------------------------------- /** The row menu and the rename dialog, verbatim from ChatListPane.kt. */ export const CHAT_RENAME_ACTION = "Rename…"; export const CHAT_HIDE_ACTION = "Hide on this device"; export const CHAT_ACTIONS_LABEL = "Chat actions"; export const CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server."; export const CHAT_UNDO_ACTION = "Undo"; export const CHAT_RENAME_TITLE = "Rename chat"; export const CHAT_RENAME_FIELD_LABEL = "Name"; export const CHAT_RENAME_HELPER = "The server has no rename for a chat, so this name is kept on this device."; export const CHAT_RENAME_SAVE = "Save"; export const CHAT_RENAME_DISMISS = "Cancel"; /** The empty override model: no local titles, nothing hidden. */ export function emptyChatOverrides() { return { titles: {}, hidden: [] }; } /** The empty seen model: no watermarks, no explicit unseen marks. */ export function emptyChatSeen() { return { seenAt: {}, unseen: [] }; } /** A positive finite epoch-millisecond value, else 0 (never NaN). */ function millis(value) { const number = Number(value); return Number.isFinite(number) && number > 0 ? number : 0; } /** * Decode a stored overrides value. Blank text, `null`, corrupt JSON, an array and * wrong-typed fields all fall back to the empty model; nothing here throws, so a * bad preference can never break the list. */ export function decodeChatOverrides(stored) { const empty = emptyChatOverrides(); if (stored == null || stored === "") return empty; let parsed = stored; if (typeof stored === "string") { if (stored.trim() === "") return empty; try { parsed = JSON.parse(stored); } catch { return empty; } } if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty; const titles = {}; const rawTitles = parsed.titles; if (rawTitles != null) { if (typeof rawTitles !== "object" || Array.isArray(rawTitles)) return empty; for (const [id, title] of Object.entries(rawTitles)) { if (isBlank(id) || typeof title !== "string" || isBlank(title)) continue; titles[id] = title.trim(); } } const hidden = []; const rawHidden = parsed.hidden; if (rawHidden != null) { if (!Array.isArray(rawHidden)) return empty; for (const id of rawHidden) { if (typeof id !== "string" || isBlank(id) || hidden.includes(id)) continue; hidden.push(id); } } return { titles, hidden }; } /** The one-line JSON an overrides value is stored as. */ export function encodeChatOverrides(overrides) { return JSON.stringify({ titles: { ...(overrides?.titles ?? {}) }, hidden: [...(overrides?.hidden ?? [])], }); } /** * Decode a stored seen value with the same tolerance as the overrides: blank, * corrupt or wrong-typed input is nothing seen, never an exception. Unseen ids * are de-duplicated. */ export function decodeChatSeen(stored) { const empty = emptyChatSeen(); if (stored == null || stored === "") return empty; let parsed = stored; if (typeof stored === "string") { if (stored.trim() === "") return empty; try { parsed = JSON.parse(stored); } catch { return empty; } } if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty; const seenAt = {}; const rawSeenAt = parsed.seenAt; if (rawSeenAt != null) { if (typeof rawSeenAt !== "object" || Array.isArray(rawSeenAt)) return empty; for (const [id, value] of Object.entries(rawSeenAt)) { const at = millis(value); if (isBlank(id) || at <= 0) continue; seenAt[id] = at; } } const unseen = []; const rawUnseen = parsed.unseen; if (rawUnseen != null) { if (!Array.isArray(rawUnseen)) return empty; for (const id of rawUnseen) { if (typeof id !== "string" || isBlank(id) || unseen.includes(id)) continue; unseen.push(id); } } return { seenAt, unseen }; } /** The one-line JSON a seen value is stored as. */ export function encodeChatSeen(seen) { return JSON.stringify({ seenAt: { ...(seen?.seenAt ?? {}) }, unseen: [...(seen?.unseen ?? [])], }); } /** * Record a local rename. A blank id or a title that is blank after trimming * changes nothing; a recorded title is trimmed, and it wins over the server's * own on every later refresh. */ export function renameChatOverride(overrides, id, title) { const current = overrides ?? emptyChatOverrides(); const trimmed = str(title).trim(); const key = str(id); if (isBlank(key) || trimmed === "") return current; if (current.titles?.[key] === trimmed) return current; return { ...current, titles: { ...(current.titles ?? {}), [key]: trimmed } }; } /** * Hide a session on this device. A blank id or an already-hidden id changes * nothing, and an id is never appended twice. */ export function hideChatOverride(overrides, id) { const current = overrides ?? emptyChatOverrides(); const key = str(id); const hidden = current.hidden ?? []; if (isBlank(key) || hidden.includes(key)) return current; return { ...current, hidden: [...hidden, key] }; } /** Restore a hidden session, undoing [hideChatOverride]. */ export function restoreChatOverride(overrides, id) { const current = overrides ?? emptyChatOverrides(); const key = str(id); const hidden = current.hidden ?? []; if (!hidden.includes(key)) return current; return { ...current, hidden: hidden.filter((entry) => entry !== key) }; } /** * The server's sessions with this device's overrides applied: hidden ids are * removed (the set is built once, so each row is O(1)) and a local title replaces * the server's. A blank/absent server title still falls through to * `sessionTitle` at render time. */ export function applyChatOverrides(sessions, overrides) { const list = Array.isArray(sessions) ? sessions : []; const titles = overrides?.titles ?? {}; const hiddenIds = new Set(overrides?.hidden ?? []); if (hiddenIds.size === 0 && Object.keys(titles).length === 0) return list; return list .filter((session) => !hiddenIds.has(str(session?.id))) .map((session) => { const local = titles[str(session?.id)]; return typeof local === "string" && local.trim() !== "" ? { ...session, title: local.trim() } : session; }); } /** The newest recency the operator has seen for [id], or 0 when never seen. */ export function chatSeenWatermark(seen, id) { const value = seen?.seenAt?.[str(id)]; return millis(value); } /** * Record the first sight of every listed session, so a pre-existing chat is not * reported as new activity. The active session is read (it is on screen); every * other session is seeded only when it has no watermark yet and its recency is a * real timestamp. An explicit unseen mark is never cleared by seeding. */ export function seedChatSeen(seen, sessions, activeId) { let next = seen ?? emptyChatSeen(); for (const session of Array.isArray(sessions) ? sessions : []) { const id = str(session?.id); const updatedAt = millis(session?.updated_at); if (isBlank(id) || updatedAt <= 0) continue; if (id === str(activeId)) { next = readChatSeen(next, id, updatedAt); } else if (chatSeenWatermark(next, id) === 0) { next = { ...next, seenAt: { ...(next.seenAt ?? {}), [id]: updatedAt } }; } } return next; } /** * Read [id] up to [updatedAt]: the watermark advances only when the value is * strictly newer (a stale read can never rewind it) and any explicit unseen mark * is cleared. A blank id changes nothing. */ export function readChatSeen(seen, id, updatedAt) { const current = seen ?? emptyChatSeen(); const key = str(id); if (isBlank(key)) return current; const at = millis(updatedAt); const advanced = at > chatSeenWatermark(current, key); const unseen = current.unseen ?? []; const marked = unseen.includes(key); if (!advanced && !marked) return current; return { seenAt: advanced ? { ...(current.seenAt ?? {}), [key]: at } : { ...(current.seenAt ?? {}) }, unseen: marked ? unseen.filter((entry) => entry !== key) : [...unseen], }; } /** Mark [id] as moved on while it was not on screen; blank ids and duplicates no-op. */ export function markChatUnseen(seen, id) { const current = seen ?? emptyChatSeen(); const key = str(id); const unseen = current.unseen ?? []; if (isBlank(key) || unseen.includes(key)) return current; return { ...current, seenAt: { ...(current.seenAt ?? {}) }, unseen: [...unseen, key] }; } /** * The exact `ChatState.isUnseen` rule: a session is new only when it is not the * active one and either an explicit unseen mark exists or it has never been * opened here and its `updated_at` is strictly newer than the stored watermark. */ export function isChatSessionUnseen(session, { activeId = null, seen = null, opened = false } = {}) { const id = str(session?.id); if (isBlank(id) || id === str(activeId)) return false; if ((seen?.unseen ?? []).includes(id)) return true; if (opened) return false; return millis(session?.updated_at) > chatSeenWatermark(seen, id); } // --------------------------------------------------------------------------- // Session narrowing and grouping (ChatListFilter.kt) // --------------------------------------------------------------------------- /** * Whether [session] matches [query]: a case-insensitive substring over the * session's title or its directory. A blank query matches everything. */ export function sessionMatchesQuery(session, query) { const needle = str(query).trim(); if (needle === "") return true; const haystack = `${sessionTitle(session)}\u0000${str(session?.directory)}`.toLowerCase(); return haystack.includes(needle.toLowerCase()); } /** * Narrows [sessions] to those matching [query] over their title and directory. A * blank query changes nothing, and the surviving sessions keep their original * relative order, so a narrowing never re-sorts. */ export function filterSessions(sessions, query) { const list = sessions ?? []; if (isBlank(query)) return list; return list.filter((session) => sessionMatchesQuery(session, query)); } /** * Groups [sessions] by directory so sessions in the same repository sit together. * The sessions keep their incoming recency order (within each group), and the * groups are ordered by the first session they contain, so the top of the list * still leads with the newest activity. A blank directory is its own group. */ export function groupSessionsByDirectory(sessions) { const list = sessions ?? []; if (list.length === 0) return []; const order = new Map(); for (const session of list) { const directory = str(session?.directory); if (!order.has(directory)) order.set(directory, []); order.get(directory).push(session); } return [...order.entries()].map(([directory, grouped]) => ({ directory, sessions: grouped })); } /** The visible label of a directory group header. */ export function directoryLabel(directory) { return isBlank(directory) ? NO_DIRECTORY_LABEL : str(directory); } // --------------------------------------------------------------------------- // The create flow's directory choices (ChatDirectories.kt) // --------------------------------------------------------------------------- /** * The picker's choices from the server's reported directories. The first entry is * the operator's home — the one entry the server always returns first — and the * rest keep the server's most-recently-used order. A blank entry is dropped, and a * reply with nothing in it still yields the home choice, so the picker is never * empty. A recent's `label` is its full path; only the home row carries the path * as `secondary`, because its own label is `Home (~)`. */ export function directoryChoices(directories) { const cleaned = (directories ?? []).map((entry) => str(entry)).filter((entry) => !isBlank(entry)); const home = cleaned.length > 0 ? cleaned[0] : HOME_DIRECTORY; return [ { label: HOME_LABEL, path: home, home: true, createDirectory: HOME_DIRECTORY, secondary: home, }, ...cleaned.slice(1).map((path) => ({ label: path, path, home: false, createDirectory: path, secondary: null, })), ]; } /** The choice a freshly opened picker starts on: home, first. */ export function defaultDirectoryChoice(choices) { return (choices ?? [])[0] ?? null; } /** A fresh create state: home selected, the caller's operation id, not sending. */ export function newChatCreateState(operationId) { return { directory: HOME_DIRECTORY, operationId: str(operationId), creating: false, error: "", }; } /** * Choose one directory for the create. Kept pure so the view can re-render from a * single state object; the error a previous refusal left is cleared because it * described the old choice, not this one. */ export function selectChatDirectory(create, choice) { const directory = typeof choice === "string" ? choice : str(choice?.createDirectory ?? ""); if (isBlank(directory)) return { ...create }; return { ...create, directory, error: "" }; } /** The create failed: stop sending and keep the server's own reason in the pane. */ export function chatCreateFailed(create, message) { return { ...create, creating: false, error: str(message) }; } /** The create succeeded: the new session goes to the head of the list, deduped by id. */ export function chatCreateSucceeded(sessions, session) { const list = sessions ?? []; if (!session) return list; return [session, ...list.filter((entry) => entry?.id !== session.id)]; } // --------------------------------------------------------------------------- // Transcript (ChatFormat.kt) // --------------------------------------------------------------------------- /** * How the transcript renders one part: assistant text is markdown, reasoning * feeds the turn's one folded block, any other part with text is plain, and an * empty part renders nothing. */ export function partRendering(part) { if (part?.type === PART_TEXT && !isBlank(part?.text)) return "markdown"; if (part?.type === PART_REASONING && !isBlank(part?.text)) return "reasoning"; if (!isBlank(part?.text)) return "plain"; return "hidden"; } /** * One agent reply: everything the agent produced between two of the operator's * messages, however many model steps that took. `key` is the first assistant * message's id, so a reply stays one stable turn as it grows. */ export class ChatTurn { constructor(key, parts = []) { this.key = key; this.parts = parts; } /** The turn's reasoning, steps in order. */ get reasoningSteps() { return this.parts .filter((part) => part?.type === PART_REASONING && !isBlank(part.text)) .map((part) => part.text); } /** The turn's reasoning as its one block reads it, steps joined by a blank line. */ get reasoning() { return this.reasoningSteps.join("\n\n"); } /** The turn's tool calls, in the order the agent made them. */ get tools() { return this.parts.filter((part) => part?.type === PART_TOOL); } /** * The turn's answer: just its text (and any other non-tool, non-reasoning) * parts, joined in order. Reasoning feeds the folded block and a tool call its * chip, so the answer never carries thinking or a command. */ get answer() { return this.parts .filter((part) => part?.type !== PART_TOOL && partRendering(part) !== "reasoning") .map((part) => str(part?.text)) .filter((text) => text.trim() !== "") .join("\n\n"); } /** Whether the turn has anything to draw; an empty turn renders no bubble. */ get visible() { return this.reasoningSteps.length > 0 || this.tools.length > 0 || this.answer.trim() !== ""; } } /** * The elapsed time the server's own timing gives a settled turn: from the * earliest start to the latest completion across the parts that carry a timing * envelope (a tool call reports both). Null when the turn carries no usable * timing, so the collapsed line shows a duration only when there is one to show * rather than guessing one. */ export function turnElapsedMillis(parts) { const list = parts ?? []; const starts = []; for (const part of list) { const time = part?.time; if (time == null) continue; const value = Number(time.ran) > 0 ? Number(time.ran) : Number(time.created); if (value > 0) starts.push(value); } if (starts.length === 0) return null; const ends = list.map((part) => Number(part?.time?.completed)).filter((value) => value > 0); if (ends.length === 0) return null; const elapsed = Math.max(...ends) - Math.min(...starts); return elapsed > 0 ? elapsed : null; } /** * The transcript's rows for [messages]: each run of consecutive assistant * messages folds into one `{kind:"agent", key, turn}`, and each of the operator's * own messages is its own `{kind:"user", key, message}`. An assistant run with * nothing to draw produces no row. */ export function transcriptRows(messages) { const rows = []; let turnKey = null; let parts = []; const flush = () => { if (turnKey != null) { const turn = new ChatTurn(turnKey, parts); if (turn.visible) rows.push({ kind: "agent", key: turnKey, turn }); } turnKey = null; parts = []; }; for (const message of messages ?? []) { if (message?.role === ROLE_ASSISTANT) { if (turnKey == null) turnKey = message.id; parts.push(...(message.parts ?? [])); } else { flush(); rows.push({ kind: "user", key: message?.id, message }); } } flush(); return rows; } // --------------------------------------------------------------------------- // History paging (ChatStore.kt) // --------------------------------------------------------------------------- /** * Merges an authoritative history page with the turns already held. The result * is one ordered, id-deduplicated list; the page's own copy wins for an id it * carries, which is what keeps a refreshed turn authoritative without moving it. * * An older page (the operator pressed "Load older") is prepended before * everything held; a newest page keeps the turns already held in front of it, so * turns loaded from an older page stay older. `nextCursor`, `hasMore`, `loaded` * and `loading` are replaced from the page, never merged. */ export function mergeHistoryPage(previous, page, { older = false } = {}) { const held = previous?.messages ?? []; const incoming = page?.messages ?? []; const incomingById = new Map(); for (const message of incoming) { if (message?.id != null) incomingById.set(message.id, message); } const combined = older ? [...incoming, ...held] : [...held, ...incoming]; const seen = new Set(); const messages = []; for (const message of combined) { const id = message?.id; if (id == null || seen.has(id)) continue; seen.add(id); messages.push(incomingById.has(id) ? incomingById.get(id) : message); } return { messages, nextCursor: str(page?.nextCursor), hasMore: Boolean(page?.hasMore), loaded: true, loading: false, }; } // --------------------------------------------------------------------------- // Live stream folding (ChatStore.kt event/applyRemoteUser/applyDelta/applyTool, // ChatFormat.kt deltaPartId/mergeToolPart/turnPhase) // --------------------------------------------------------------------------- /** ChatEvent.Kind values pushed on the `chat_event` stream (internal/protocol/chat.go). */ export const EVENT_STEP = "step"; export const EVENT_USAGE = "usage"; export const EVENT_USER = "user"; export const EVENT_SHELL = "shell"; export const EVENT_FORM = "form"; /** ChatStep.Status values. `ended` is the one status that settles a turn. */ export const STEP_ENDED = "ended"; /** The three things an in-flight turn can be doing (ChatFormat.kt TurnPhase). */ export const TURN_PHASE_THINKING = "thinking"; export const TURN_PHASE_TOOL = "tool"; export const TURN_PHASE_WAITING = "waiting"; /** * The live-stream badge words, shared verbatim with `liveBadgeState` / * RunStream.kt: the stream is `live` only while a session is subscribed on a * connected socket, `reconnecting` while the socket is coming back (pushes are * paused in the gap) and `not live` when idle or when the server refused the * subscription. The word always carries the meaning, so colour is never the only * signal. */ export const STREAM_LIVE = "live"; export const STREAM_RECONNECTING = "reconnecting"; export const STREAM_OFFLINE = "not live"; /** The badge for [connectionKind] (`connected`/`connecting`/`disconnected`/`idle`). */ export function chatStreamState(connectionKind, subscribed) { if (connectionKind === "connected" && subscribed) return { tone: "live", label: STREAM_LIVE }; if (connectionKind === "connecting" || connectionKind === "disconnected") { return { tone: "reconnecting", label: STREAM_RECONNECTING }; } return { tone: "not-live", label: STREAM_OFFLINE }; } // --------------------------------------------------------------------------- // Background shells (C11: ChatTranscript.kt BackgroundProcessBar, ChatStore.kt // applyShell/shellsLoaded, ChatFormat.kt runningBackgroundShells/shellCommandSummary) // --------------------------------------------------------------------------- /** * ChatShell.Status values (internal/protocol/chat.go). A running shell is one * whose command has started and not yet exited; `exited` is final. */ export const SHELL_RUNNING = "running"; export const SHELL_EXITED = "exited"; /** * Per-session in-memory observation bound (ChatStore.OBSERVED_SHELL_LIMIT): the * retained shell tail a selected task can settle against. This is not task * history, only what this client itself observed. */ export const OBSERVED_SHELL_LIMIT = 16; /** * How many running-task rows the bar draws before the list scrolls instead of * growing (ChatTranscript.BACKGROUND_TASK_VISIBLE_ROWS). */ export const BACKGROUND_TASK_VISIBLE_ROWS = 3; /** The bar's heading; its count line is `{n} running`. */ export const BACKGROUND_TASKS_TITLE = "Background tasks"; export function backgroundTasksRunningLabel(count) { return `${count} running`; } /** A row's own words (ChatTranscript.BackgroundProcessLine). */ export const SHELL_ROW_LABEL = "Running"; export const SHELL_DETAILS_LABEL = "Details"; /** * The detail pane's exact wording, verbatim from * ChatTranscript.BackgroundProcessDetail. Kept as one frozen map so the pane and * its unit test share one string instead of the copy drifting. */ export const SHELL_OUTPUT_LABELS = Object.freeze({ COMMAND: "Command", UNAVAILABLE: "Unavailable", TASK_IDENTITY: "Task identity", STATUS_RUNNING: "Status: running", OUTPUT_UNAVAILABLE: "Output unavailable for this task.", NO_OUTPUT: "No output yet.", OUTPUT: "Output", OUTPUT_BOUNDED: "Output is bounded to 64 KiB.", RETRY: "Retry", REFRESH: "Refresh", }); /** * The background processes still running for a session, in the order they * started, from the shells the server reported and the session retains. A shell * that has exited is never listed — that is what clears the bar — and the set is * independent of the turn, because a background process outlives the tool call * (and often the turn) that started it. Mirrors ChatFormat.runningBackgroundShells: * only a non-blank id with status `running` is a task, and the list is never * truncated here (the visible-row cap is a view concern). */ export function runningBackgroundShells(shells) { return (shells ?? []).filter( (shell) => !isBlank(shell?.id) && str(shell?.status) === SHELL_RUNNING, ); } /** * Folds one shell frame (or a snapshot entry) into the retained shells, keyed by * id and kept in observation order. A blank incoming command keeps the command * already learned, so a later frame that omits it never blanks the row, and the * list is trimmed to the last [OBSERVED_SHELL_LIMIT] entries (ChatStore.applyShell). */ export function mergeShellFrame(shells, shell) { const id = str(shell?.id); if (shell == null || isBlank(id)) return shells ?? []; const list = (shells ?? []).slice(); const index = list.findIndex((candidate) => str(candidate?.id) === id); const prior = index >= 0 ? list[index] : null; const merged = { ...shell, id, command: isBlank(shell?.command) ? str(prior?.command) : shell.command, }; if (index >= 0) list[index] = merged; else list.push(merged); return list.slice(-OBSERVED_SHELL_LIMIT); } /** * Replaces the retained shells with the authoritative running snapshot while * keeping only exits this client itself observed, capped like every other shell * list (ChatStore.shellsLoaded). A shell the server no longer lists and that this * client never saw exit simply drops out. */ export function shellsLoaded(shells, running) { const byId = new Map(); for (const shell of shells ?? []) { if (!isBlank(shell?.id) && str(shell?.status) === SHELL_EXITED) byId.set(shell.id, shell); } for (const shell of running ?? []) { if (isBlank(shell?.id)) continue; // Map.set keeps the first-insertion position and replaces the value, exactly // like Kotlin's `observedExits + live` LinkedHashMap merge. byId.set(shell.id, shell); } return [...byId.values()].slice(-OBSERVED_SHELL_LIMIT); } /** The five shapes a selected task's output area can take. */ export const SHELL_OUTPUT_LOADING = "loading"; export const SHELL_OUTPUT_ERROR = "error"; export const SHELL_OUTPUT_UNAVAILABLE = "unavailable"; export const SHELL_OUTPUT_EMPTY = "empty"; export const SHELL_OUTPUT_READY = "output"; /** * Which branch the detail pane's output area shows for a selected task's * [output] state, or null when there is nothing to show yet — the same decision * order as ChatTranscript.BackgroundProcessDetail's `when` (loading, then error, * then the server's `unavailable`, then an empty page, then a readable page), so * the pane and its unit test share one derivation. */ export function shellOutputState(output) { if (output == null) return null; if (output.loading) return SHELL_OUTPUT_LOADING; if (str(output.error) !== "") return SHELL_OUTPUT_ERROR; const page = output.page ?? null; if (page == null) return null; if (page.unavailable === true) return SHELL_OUTPUT_UNAVAILABLE; if (str(page.output) === "") return SHELL_OUTPUT_EMPTY; return SHELL_OUTPUT_READY; } /** * The shape an open conversation holds. The first six fields are the ones a * history page fills; the rest is the live stream (see `ChatThread` in * ChatStore.kt). A Map is deliberately not used for [toolStartedAt] so a thread * stays a plain, comparable value. */ export function newChatThread(sessionId = "") { return { sessionId, messages: [], nextCursor: "", hasMore: false, loaded: false, loading: false, error: "", running: false, runningSince: 0, toolStartedAt: {}, lastDeltaAt: 0, queued: false, // C10: the session's current permission request (the last `chat_permission` // frame the server pushed) and the operator's local answer to it // (`once`/`always`/`reject`, or blank). The approval card and its controls // derive from the two (see `approvalCard`). permission: null, permissionAnswer: "", // The agent's pending structured question/form (OpenCode form.created). The // card is derived from this frame; answers are local until submitted. form: null, // The reason a refused `chat_reply` left on the thread's error line, kept // apart from any other error so a later accepted answer clears only this one. permissionError: "", // The background shells this session has observed (C11), in observation // order, the selected task and its bounded output pane. shells: [], selectedShellId: null, shellOutput: null, }; } /** * The settled form of a thread: no turn is in flight, so the elapsed stamps and * the queued flag are cleared. The one place a thread stops running, so the * indicator and its stamps can never disagree. A no-op (returns [thread]) when it * was already settled. */ export function settledThread(thread) { return { ...(thread ?? {}), running: false, runningSince: 0, toolStartedAt: {}, lastDeltaAt: 0, queued: false, }; } /** Applies a running transition, stamping `runningSince` the moment it begins. */ export function setThreadRunning(thread, running, now) { if (running) return thread.running ? thread : { ...thread, running: true, runningSince: now }; return settledThread({ ...thread }); } /** * The reconnect repair for one thread (C5/C11): the settled form plus the shell * observations dropped — a shell's exit may have been swallowed by the gap, so * the retained shells are forgotten and re-learned from the re-subscribe's * `chat_shells` snapshot. This is deliberately separate from [settledThread], * which the step-ended frame also uses: a turn ending must never clear a * background process that outlives it (ChatStore.streamResumed drops shells; * ChatStore.setRunning does not). */ export function resumedThread(thread) { return { ...settledThread(thread), shells: [], selectedShellId: null, shellOutput: null }; } /** * Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it has * settled. Pure, so the running indicator and its unit test share the derivation. */ export function threadElapsedMillis(thread, nowMillis) { const since = Number(thread?.runningSince) || 0; return thread?.running && since >= 1 && since < nowMillis ? nowMillis - since : 0; } /** Every tool call still in flight across a conversation's [messages]. */ export function threadRunningTools(messages) { return runningTools((messages ?? []).flatMap((message) => message?.parts ?? [])); } /** How long [part] has been running at [nowMillis], using the thread's own stamps. */ export function threadToolElapsedMillis(thread, part, nowMillis) { const stamps = thread?.toolStartedAt ?? {}; const startedAt = stamps instanceof Map ? (stamps.get(part?.id) ?? 0) : (stamps[part?.id] ?? 0); return runningToolElapsedMillis(part, startedAt, nowMillis); } /** * The id a text or reasoning delta must be applied to for [kind] within [parts]. * The broker gives the two kinds distinct ids (see `ChatDeltaPartID`), but a peer * that still shares one bare id between them must never have answer text appended * into a reasoning part: when another kind already holds the bare id, the delta is * moved onto a suffixed id of its own. Once a part of this kind exists under * either id, that part is the one addressed, so a stream keeps growing the part * it started. */ export function deltaPartId(parts, kind, id) { const list = parts ?? []; if (list.some((part) => part?.type === kind && part?.id === id)) return id; const suffixed = `${id}#${kind}`; if (list.some((part) => part?.type === kind && part?.id === suffixed)) return suffixed; return list.some((part) => part?.id === id) ? suffixed : id; } /** * Folds one tool frame's part onto the part retained from earlier frames. A tool * call is reported across several frames that each carry only part of it, so a * field already learned is never blanked by a later frame that omits it. A * non-empty incoming field wins; otherwise the retained value is kept. */ export function mergeToolPart(previous, incoming) { if (previous == null) return incoming; return { ...incoming, type: isBlank(incoming?.type) ? previous.type : incoming.type, name: isBlank(incoming?.name) ? previous.name : incoming.name, executed: Boolean(incoming?.executed || previous?.executed), time: incoming?.time ?? previous?.time, state: mergeToolState(previous?.state, incoming?.state), }; } function mergeToolState(prior, incoming) { if (incoming == null) return prior ?? undefined; if (prior == null) return incoming; return { ...incoming, status: isBlank(incoming.status) ? prior.status : incoming.status, input: incoming.input == null ? prior.input : incoming.input, content: (incoming.content ?? []).length > 0 ? incoming.content : prior.content, metadata: incoming.metadata ?? prior.metadata, error: incoming.error ?? prior.error, }; } /** * The running-tool start stamps after a thread's [messages] changed: every tool * part in flight keeps the stamp it already had, or is stamped with [now] when it * has just turned running, and a part that is no longer running loses its stamp. */ export function runningToolStamps(current, messages, now) { const stamps = {}; for (const message of messages ?? []) { for (const part of message?.parts ?? []) { if (!isBlank(part?.id) && part?.type === PART_TOOL && toolRunning(part)) { stamps[part.id] = current?.[part.id] ?? now; } } } return stamps; } /** * The [TURN_PHASE_*] of a running turn. [tools] are the calls the stream still * reports running. A running turn with no running call is thinking: the model may * be reasoning silently for a minute before its first delta, and calling that * "Waiting…" made the chat look idle while it was working. "Waiting…" belongs to a * prompt that is queued behind the turn already in flight, never to a live turn. * No percentage, ETA or progress is invented. */ export function turnPhase(tools) { return (tools ?? []).length > 0 ? TURN_PHASE_TOOL : TURN_PHASE_THINKING; } /** The running indicator's headline for [phase], naming what is happening. */ export function turnPhaseLabel(phase) { if (phase === TURN_PHASE_THINKING) return "Thinking…"; if (phase === TURN_PHASE_TOOL) return "Running a tool…"; return "Waiting…"; } /** * The turn's phase at [nowMillis], derived from its running tools and the time * since its last delta. Null when nothing is running, so a settled turn has no * phase at all. */ export function threadPhase(thread, nowMillis) { if (!thread?.running) return null; if (thread.queued) return TURN_PHASE_WAITING; return turnPhase(threadRunningTools(thread.messages)); } /** * Folds one form frame into a conversation. A new form replaces the previous * one; a resolved/cancelled update clears it; an update for a different id is * ignored rather than reviving a dismissed card. The form is kept as data so the * question card and every other client derive the same state. */ export function applyChatForm(thread, form) { const current = thread ?? newChatThread(str(form?.session_id)); const id = str(form?.id); if (id === "") return current; const existing = current.form ?? null; if (form?.cancelled === true) { if (str(existing?.id) !== id) return current; return { ...current, form: null }; } if (form?.resolved === true) { if (str(existing?.id) !== id) return current; return { ...current, form: { ...existing, ...form, resolved: true } }; } if (str(existing?.id) === id) { return { ...current, form: { ...existing, ...form } }; } return { ...current, form }; } /** * Applies one pushed `chat_event` frame to a conversation and returns the next * thread. Any frame clears `queued` (the turn moved on); `user` echoes another * client's prompt once (never this client's own), `text`/`reasoning` append to the * part their kind started, `tool` merges field by field, `step` drives the running * flag, and `shell` folds one background process into the retained set without * ever marking the turn running (C11). The message that a delta or tool frame * targets is created on first sight, so a live turn never gains a second bubble. */ export function applyChatEvent(thread, frame, now = Date.now()) { const current = thread?.queued ? { ...thread, queued: false } : (thread ?? newChatThread(str(frame?.session_id))); switch (frame?.kind) { case EVENT_USER: return applyRemoteUser(current, frame); case PART_TEXT: case PART_REASONING: return applyDelta(current, frame, now); case PART_TOOL: return applyTool(current, frame, now); case EVENT_STEP: return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now); // A shell frame only folds its shell into the retained set: it NEVER marks // the thread running, because a background process is not the turn — a shell // that outlives the turn keeps showing after the turn's own indicator is gone. case EVENT_SHELL: return { ...current, shells: mergeShellFrame(current.shells, frame?.shell) }; case EVENT_FORM: return applyChatForm(current, frame?.form); // `usage` is recognised but not folded; it still cleared `queued` above. case EVENT_USAGE: default: return current; } } /** * Folds a user turn another client sent into the transcript, in place, once. The * server never echoes this client's own prompts, so the sender's own message is * never duplicated; the message's `client` label says which device sent it. */ function applyRemoteUser(thread, frame) { const text = str(frame?.part?.text); const messageId = str(frame?.message_id); if (messageId === "" || text === "") return thread; const operationId = str(frame?.operation_id); const messages = thread.messages ?? []; if ( operationId !== "" && messages.some((message) => message?.role === ROLE_USER && str(message?.operation_id) === operationId) ) { return thread; } if (messages.some((message) => message?.id === messageId)) return thread; const message = { id: messageId, session_id: str(frame?.session_id), role: ROLE_USER, client: str(frame?.client), operation_id: operationId, parts: [{ type: PART_TEXT, text }], }; return { ...thread, messages: [...messages, message] }; } function applyDelta(thread, frame, now) { const rawId = str(frame?.part?.id); const delta = str(frame?.delta); if (rawId === "" || delta === "") return thread; const kind = frame.kind; return upsertParts(thread, frame, now, now, (parts) => { const id = deltaPartId(parts, kind, rawId); const index = parts.findIndex((part) => part?.id === id); if (index < 0) return [...parts, { type: kind, id, text: delta }]; const next = parts.slice(); next[index] = { ...next[index], text: str(next[index]?.text) + delta }; return next; }); } function applyTool(thread, frame, now) { const incoming = frame?.part ?? null; if (incoming == null || str(incoming.id) === "") return thread; return upsertParts(thread, frame, now, null, (parts) => { const index = parts.findIndex((part) => part?.id === incoming.id && part?.type === PART_TOOL); if (index < 0) return [...parts, mergeToolPart(null, incoming)]; const next = parts.slice(); next[index] = mergeToolPart(next[index], incoming); return next; }); } /** * Finds or creates the assistant message [frame] targets and replaces its parts * with [upsert]'s result, then marks the thread running. The text/reasoning fold * and the tool upsert share this so the two cannot drift. */ function upsertParts(thread, frame, now, deltaArrivedAt, upsert) { const messageId = str(frame?.message_id); const messages = (thread.messages ?? []).slice(); let index = -1; for (let i = messages.length - 1; i >= 0; i -= 1) { if (messages[i]?.id === messageId) { index = i; break; } } if (index < 0) { messages.push({ id: messageId, session_id: str(frame?.session_id), role: ROLE_ASSISTANT, parts: [], }); index = messages.length - 1; } const message = messages[index]; messages[index] = { ...message, parts: upsert(message.parts ?? []) }; const stamped = runningToolStamps(thread.toolStartedAt, messages, now); let next = setThreadRunning({ ...thread, messages, toolStartedAt: stamped }, true, now); if (deltaArrivedAt != null) next = { ...next, lastDeltaAt: deltaArrivedAt }; return next; } /** * The reconnect/resync replacement: the newest history page is authoritative, so * the whole turn is replaced (no stale held message survives), the cursor and * `hasMore` are replaced from the page, and any in-flight state is settled — * every frame that was feeding a running turn is gone. The retained shells are * dropped too (the reconnect re-fetches `chat_shells`), exactly like the Android * `streamResumed` path. */ export function historyResync(thread, page) { const settled = resumedThread(thread ?? newChatThread()); return { ...settled, messages: (page?.messages ?? []).slice(), nextCursor: str(page?.nextCursor), hasMore: Boolean(page?.hasMore), loaded: true, loading: false, error: "", }; } // --------------------------------------------------------------------------- // Scroll behaviour (ChatScroll.kt) // --------------------------------------------------------------------------- /** * The pixels the end of the transcript still sits below the viewport's bottom * edge, or null when the viewport does not show the last item at all or the list * has not been measured yet. A value of 0 means the end is in view. */ export function chatBottomDistancePx({ lastVisibleIndex, lastVisibleEndPx, itemCount, viewportEndPx }) { if (itemCount <= 0 || lastVisibleIndex !== itemCount - 1) return null; return Math.max(0, lastVisibleEndPx - viewportEndPx); } /** * Whether the view sits at the bottom: the end is in view and within * [thresholdPx] of the bottom edge. */ export function chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount) { return itemCount > 0 && distanceFromBottomPx != null && distanceFromBottomPx <= thresholdPx; } /** * Whether the jump-to-latest affordance is offered: only while the transcript is * not following and there is genuinely something below the fold to return to. * Never shown for an empty transcript. */ export function chatShowJumpToLatest(following, distanceFromBottomPx, thresholdPx, itemCount) { return !following && itemCount > 0 && !chatFollowsAt(distanceFromBottomPx, thresholdPx, itemCount); } /** * Whether opening a conversation should land on its newest message: only when * the operator has no position of their own there yet (a null [saved]). A * position they deliberately left — including the very top, `{index:0,offset:0}` * — is restored instead. */ export function chatOpensAtNewest(saved) { return saved == null; } /** * The position a conversation's transcript is placed at when it first shows: the * newest message for a conversation with no position of the operator's own, * otherwise the position they left, clamped to the messages that still exist. The * saved pixel offset is kept only when the saved item itself survived. */ export function chatFirstScroll(saved, itemCount) { if (itemCount <= 0) return { index: 0, offset: 0 }; if (saved == null) return { index: itemCount - 1, offset: 0 }; const rawIndex = Number(saved.index) || 0; const index = Math.min(Math.max(rawIndex, 0), itemCount - 1); const offset = index === rawIndex ? Number(saved.offset) || 0 : 0; return { index, offset }; } // --------------------------------------------------------------------------- // The composer (ChatComposer.kt) // --------------------------------------------------------------------------- /** The composer's multiline placeholder, verbatim. */ export const CHAT_COMPOSER_PLACEHOLDER = "Message the agent… or / for commands"; /** The primary control's accessible names while a turn is and is not running. */ export const CHAT_SEND_LABEL = "Send"; export const CHAT_STOP_LABEL = "Stop"; /** The composer's attach control. */ export const CHAT_ATTACH_LABEL = "Attach file"; /** The composer's queued notice, shown while a prompt waits behind a turn. */ export const CHAT_QUEUED_NOTICE = "Queued — it will send when the current turn finishes."; /** * The terminal glyph on a command notice. The app draws `Icons.Default.Terminal` * for both a successful and a failed notice and only changes the tint, so the * browser uses this one glyph for both. */ export const CHAT_COMMAND_GLYPH = ">_"; /** The two labels a local command line can carry (ChatCommandUi.kt). */ export const CHAT_COMMAND_LABEL = "Command"; export const CHAT_COMMAND_FAILED_LABEL = "Command failed"; /** The accessible name of an offerless notice's dismiss control. */ export const CHAT_COMMAND_DISMISS_LABEL = "Dismiss command notice"; /** * The label for one command notice: `Command failed` when the command could not * be honoured, else `Command` (ChatCommandUi.kt's own choice). The same flag * selects the error tint on the caller's row. */ export function chatNoticeLabel(failed) { return failed === true ? CHAT_COMMAND_FAILED_LABEL : CHAT_COMMAND_LABEL; } /** * One local command line, the app's `ChatCommandNotice` shape: it lives beside a * conversation, never inside its messages, so it is never sent to the agent. * [offer] is set only for an unrecognised command, whose draft the operator can * still choose to send as a message. */ export function makeChatNotice(id, text, { failed = false, offer = null } = {}) { return { id: str(id), text: str(text), failed: failed === true, offer: offer == null ? null : str(offer), }; } /** Append one notice to a conversation's list, preserving order. */ export function appendChatNotice(notices, notice) { return [...(notices ?? []), notice]; } /** Drop one notice by id, leaving every other notice and its order untouched. */ export function dismissChatNotice(notices, noticeId) { return (notices ?? []).filter((notice) => notice?.id !== noticeId); } /** * Take the draft an unrecognised-command notice offers, removing the notice * first (mirrors `ChatStore.takeNoticeOffer`). Returns `{notices, offer}`: * `offer` is null — and the list is returned untouched — when the notice is * missing, already taken or carries no offer, so a stale tap sends nothing. */ export function takeChatNoticeOffer(notices, noticeId) { const list = notices ?? []; const notice = list.find((entry) => entry?.id === noticeId); if (!notice || notice.offer == null) return { notices: list, offer: null }; return { notices: dismissChatNotice(list, noticeId), offer: notice.offer }; } /** The two values of [composerAction]. */ export const COMPOSER_SEND = "send"; export const COMPOSER_STOP = "stop"; /** Which action the composer's single primary control offers for a chat. */ export function composerAction(thread) { return thread?.running === true ? COMPOSER_STOP : COMPOSER_SEND; } /** True while at least one attachment carries an error. */ export function hasAttachmentErrors(thread) { return (thread?.attachments ?? []).some((attachment) => attachment?.error != null); } /** * Whether the composer's send action is allowed (mirrors `ChatThread.canSend`): a * non-blank draft with no flagged attachment. A message with a flagged attachment * is never sent, so the file is never silently dropped. */ export function composerCanSend(thread) { return !isBlank(thread?.draft) && !hasAttachmentErrors(thread); } /** True when the trimmed draft starts with a slash, so it is a command. */ export function chatDraftIsSlash(draft) { return str(draft).trimStart().startsWith("/"); } /** * Whether the Send control is enabled (mirrors ChatComposer's * `enabled = thread.canSend || slashDraft`): a non-blank draft with no failed * attachment, or a slash draft — which is always runnable, because a command never * goes to the prompt path with its attachments. */ export function composerSendEnabled(thread) { return composerCanSend(thread) || chatDraftIsSlash(thread?.draft); } /** * What pressing Enter (the composer's submit) does for [thread] with the offer * list's highlighted [selected] row — the one derivation the key handler and its * unit test share. `{kind:"command", text}` runs a slash command (the highlighted * offer row, else the operator's slash draft), `{kind:"send"}` sends the draft as * a prompt, and `{kind:"none"}` does nothing: a running turn's Enter is inert * unless the palette or a slash draft is present, so it can never send the draft * to a session mid-turn. */ export function composerSubmit(thread, selected = 0) { const draft = str(thread?.draft); const command = chatCommandForEnter(draft, selected); if (command != null) return { kind: "command", text: command }; if (chatDraftIsSlash(draft)) return { kind: "command", text: draft }; if (composerAction(thread) === COMPOSER_SEND && composerCanSend(thread)) { return { kind: "send" }; } return { kind: "none" }; } /** * The queued flag after one pushed frame for the session: any frame means the * turn the prompt was waiting behind has moved on, so the queued notice clears * (mirrors ChatStore.event). A null frame leaves the flag untouched. */ export function queuedAfterFrame(queued, frame) { if (frame == null) return queued === true; return false; } /** * The running flag after one pushed frame: a `step` frame that reports the turn * `ended` settles it, and every other frame leaves it as it was. The live * transcript owns the rest of the frame fold; this is only the turn's own * running bit, which the composer's Stop control reads. */ export function runningAfterFrame(running, frame) { if (frame?.kind === "step" && frame?.step?.status === "ended") return false; return running === true; } // --------------------------------------------------------------------------- // Attachments (ChatFormat.kt / ChatAttachments.kt) // --------------------------------------------------------------------------- /** * The largest file the composer will attach (mirrors ChatFormat.MAX_ATTACHMENT_BYTES). * A browser-side guard, so a runaway pick is refused with a reason instead of * being handed to the server; the server applies its own limits on top. */ export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024; /** The fallback display name when neither the name nor the uri gives one. */ export const ATTACHMENT_FALLBACK_NAME = "file"; /** * The name shown for an attachment, never blank (mirrors * `ChatAttachment.displayName`): its own name, else the uri's basename, else * `file`. */ export function attachmentDisplayName(name, uri) { const shown = str(name); if (!isBlank(shown)) return shown; const basename = str(uri).split("/").pop() ?? ""; if (!isBlank(basename)) return basename; return ATTACHMENT_FALLBACK_NAME; } /** * Why an attachment cannot be sent, or null when it can (mirrors * `attachmentError`). An unreadable file and a file over * [MAX_ATTACHMENT_BYTES] are each reported by name, so the operator sees which * one and why rather than losing it. The limit reads `25.0 MiB` through the one * shared `humanBytes`. */ export function attachmentError(name, sizeBytes, readable) { const display = isBlank(name) ? ATTACHMENT_FALLBACK_NAME : str(name); if (readable === false) return `"${display}" could not be read.`; if (Number(sizeBytes) > MAX_ATTACHMENT_BYTES) { return `"${display}" is too large (${humanBytes(MAX_ATTACHMENT_BYTES)} limit).`; } return null; } /** * The `files` carried by a prompt (mirrors `attachmentFiles`): the references of * the attachments that can go. One place derives the wire list from the * attachments, so the send path and the transcript's file parts can never * disagree about which files are attached. */ export function attachmentFiles(attachments) { return (attachments ?? []) .filter((attachment) => attachment?.error == null) .map((attachment) => str(attachment?.uri)); } // --------------------------------------------------------------------------- // Slash commands (ChatCommands.kt) // --------------------------------------------------------------------------- export const CHAT_COMMAND_NEW = "new"; export const CHAT_COMMAND_CLOSE = "close"; export const CHAT_COMMAND_RENAME = "rename"; export const CHAT_COMMAND_STOP = "stop"; export const CHAT_COMMAND_HELP = "help"; /** * The commands the composer understands, in the order the offer list shows them * (mirrors `CHAT_COMMANDS`). `name` is the word after the slash, `usage` is what * the operator types (including any argument) and `summary` is the few-word * description shown beside it. `takesArgument` is false for the commands that act * on the current session alone, so a stray argument is reported instead of being * silently ignored. */ export const CHAT_COMMANDS = Object.freeze([ Object.freeze({ name: CHAT_COMMAND_NEW, summary: "Start a fresh session in this directory", usage: "/new", takesArgument: false, }), Object.freeze({ name: CHAT_COMMAND_CLOSE, summary: "Finish this session for every client, keeping its history", usage: "/close", takesArgument: false, }), Object.freeze({ name: CHAT_COMMAND_RENAME, summary: "Rename this session on this device", usage: "/rename