// 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"; import { normalizeChatUsage } from "./chatUsage.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"; export const PART_FILE = "file"; /** 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"; /** The behavior brief preloaded into a new web chat's session instructions. */ export const DEFAULT_CHAT_INSTRUCTIONS = "Act as a careful coding agent. Read the repository's AGENTS.md and the relevant skills before acting. Inspect the current state, keep changes scoped to the request, run the relevant checks, and report exactly what changed and what was not verified. Ask only about real ambiguity, destructive actions or changes outside the request."; 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`, and `1 tool` for a single call — a * count of one is never pluralised. */ export function toolCallsLabel(count) { return count === 1 ? "1 tool" : `${count} tools`; } /** * 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; } /** Errors belong to individual calls, not the entire turn's tool total. */ export function toolFailureCount(parts) { return (parts ?? []).filter((part) => part?.type === PART_TOOL && toolFailed(part.state)).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"; } /** * How long ago the session last changed, in the list's own words: `just now`, * `2 min ago`, `3 hr ago`, `2 days ago`, then a short date for older chats. The * server's `updated_at` is milliseconds, matching the seen watermark. */ export function relativeSessionTime(updatedAt, now = Date.now()) { const then = millis(updatedAt); if (then <= 0) return ""; const elapsed = Math.max(0, Number(now) - then); const seconds = Math.floor(elapsed / 1000); if (seconds < 45) return "just now"; const minutes = Math.max(1, Math.floor(seconds / 60)); if (minutes < 60) return `${minutes} min ago`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours} hr ago`; const days = Math.floor(hours / 24); if (days < 7) return days === 1 ? "1 day ago" : `${days} days ago`; return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short" }).format( new Date(then), ); } /** * 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 = "This name is shared with every 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); } /** * Narrow a model list by a case-insensitive substring over its display name, * model id and provider. A blank query returns the whole list in its existing * (server) order; the picker never re-sorts. */ export function filterChatModels(models, query) { const list = (models ?? []).filter((model) => model && (model.id || model.name)); const needle = str(query).trim().toLowerCase(); if (needle === "") return list; return list.filter((model) => `${str(model.name)}\u0000${str(model.id)}\u0000${str(model.provider)}`.toLowerCase().includes(needle), ); } // --------------------------------------------------------------------------- // 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 home prefix shared by the server's reported directories, or "" when none * looks like a user home. The server always returns home first in * chat_directories; session paths are the fallback so the list can abbreviate * before the create picker has ever been opened. macOS /Users/, Linux * /home/ and /root are recognised; any other absolute path is left alone. */ export function homeDirectoryFor(paths) { for (const value of paths ?? []) { const match = str(value).match(/^(\/Users\/[^/]+|\/home\/[^/]+|\/root)(?=\/|$)/); if (match) return match[1]; } return ""; } /** Replace [home] and its descendants with `~` for a compact directory label. */ export function abbreviateHome(path, home) { const directory = str(path).trim(); if (isBlank(directory)) return directory; const prefix = str(home).trim().replace(/\/+$/, ""); if (prefix === "" || prefix === "~") return directory; if (directory === prefix) return "~"; if (directory.startsWith(prefix + "/")) return `~${directory.slice(prefix.length)}`; return 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, backend: "opencode", instructions: DEFAULT_CHAT_INSTRUCTIONS, 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: "" }; } /** Choose the harness for a new chat. */ export function selectChatBackend(create, backend) { const value = str(backend); if (value === "") return { ...create }; return { ...create, backend: value, 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_COMPACTION = "compaction"; export const EVENT_USAGE = "usage"; export const EVENT_USER = "user"; export const EVENT_SHELL = "shell"; export const EVENT_FORM = "form"; export const EVENT_RESYNC = "resync"; /** ChatStep.Status values. `ended` is the one status that settles a turn. */ export const STEP_ENDED = "ended"; /** Native activity phases; compaction extends the ordinary turn phases. */ export const TURN_PHASE_THINKING = "thinking"; export const TURN_PHASE_TOOL = "tool"; export const TURN_PHASE_WAITING = "waiting"; export const TURN_PHASE_COMPACTING = "compacting"; /** * 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, nativeTurnId: "", runningSince: 0, compaction: null, usage: null, 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, nativeTurnId: "", runningSince: 0, compaction: null, 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_COMPACTING) return "Compacting context…"; 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.compaction?.status === "running") return TURN_PHASE_COMPACTING; 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; const forms = [...(current.forms ?? (existing ? [existing] : []))].filter((entry) => entry.id !== id); if (form?.resolved !== true && form?.cancelled !== true) forms.push(form); const next = { ...current, forms }; if (form?.cancelled === true) { if (str(existing?.id) !== id) return next; return { ...next, form: forms.at(-1) ?? null }; } if (form?.resolved === true) { if (str(existing?.id) !== id) return next; return { ...next, form: forms.at(-1) ?? { ...existing, ...form, resolved: true } }; } if (str(existing?.id) === id) { return { ...next, form: { ...existing, ...form } }; } return { ...next, form }; } /** * Applies one pushed `chat_event` frame to a conversation and returns the next * thread. Turn frames clear `queued` (usage/compaction do not admit a queued prompt); * `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()) { if (frame?.kind === EVENT_USAGE) { const current = thread ?? newChatThread(str(frame?.session_id)); if (current.sessionId && frame.session_id !== current.sessionId) return current; const usage = normalizeChatUsage(frame.usage); return usage ? { ...current, usage } : current; } if (frame?.kind === EVENT_COMPACTION) return applyChatCompaction(thread, frame, now); if (frame?.kind === EVENT_RESYNC) return thread ?? newChatThread(str(frame?.session_id)); if (frame?.kind === EVENT_STEP && frame.step?.status === STEP_ENDED && frame.step?.turn_id && frame.step.turn_id !== thread?.nativeTurnId) return thread ?? newChatThread(str(frame?.session_id)); 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: if (frame?.step?.intermediate) return current; if (frame?.step?.turn_id && frame.step.status === STEP_ENDED && frame.step.turn_id !== current.nativeTurnId) return current; return { ...setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now), nativeTurnId: frame.step?.status === STEP_ENDED ? "" : frame.step?.turn_id || current.nativeTurnId || "" }; // 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); default: return current; } } /** Native session activity, not a synthetic tool call or assistant message. */ function applyChatCompaction(thread, frame, now) { const current = thread ?? newChatThread(str(frame?.session_id)); if (current.sessionId && frame.session_id !== current.sessionId) return current; const incoming = frame.compaction; if (!incoming || !["running", "completed", "failed"].includes(incoming.status)) return current; const nativeTurnId = str(frame.native_turn_id); if (nativeTurnId && current.nativeTurnId && nativeTurnId !== current.nativeTurnId) return current; if (incoming.status === "running") { return setThreadRunning({ ...current, nativeTurnId: nativeTurnId || current.nativeTurnId || "", compaction: { id: str(incoming.id), status: "running" } }, true, now); } if (!current.compaction || (incoming.id && current.compaction.id && incoming.id !== current.compaction.id)) return current; // A compacted context can immediately continue the same model turn. Only a // real final step/interrupt/disconnect settles the turn and its Stop control. return { ...current, compaction: null }; } /** * 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 files = (frame?.attachments ?? []).filter( (part) => part?.type === PART_FILE && (str(part?.name) !== "" || str(part?.uri) !== ""), ); 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 }, ...files], }; 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, { preserveActivity = false } = {}) { // Reconnect callers clear stale activity BEFORE reattaching. Anything learned // after that reset is fresh native state and must survive the history read. const settled = preserveActivity ? (thread ?? newChatThread()) : 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 }; // A running turn accepts a follow-up too: the server queues it behind the // current turn instead of making the operator wait for Send to reappear. if (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). Null/usage/compaction frames leave it untouched: * usage reporting or context maintenance alone does not admit the queued prompt. */ export function queuedAfterFrame(queued, frame) { if (frame == null || frame.kind === EVENT_COMPACTION || frame.kind === EVENT_USAGE) 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 === EVENT_COMPACTION && frame.compaction?.status === "running") return true; if (frame?.kind === "step" && frame?.step?.status === "ended" && !frame?.step?.intermediate) 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 = 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 ", takesArgument: true, }), Object.freeze({ name: CHAT_COMMAND_STOP, summary: "Stop the turn that is running", usage: "/stop", takesArgument: false, }), Object.freeze({ name: CHAT_COMMAND_HELP, summary: "List every command", usage: "/help", takesArgument: false, }), ]); /** * Parses [text] as a slash command (mirrors `parseChatInput`). Only the start of * the draft counts, the command word is the run of non-space characters after the * slash, and the rest (trimmed) is its argument. Recognition is case-insensitive; * a recognised command is always the canonical entry from [CHAT_COMMANDS]. * Returns `{kind:"plain"}`, `{kind:"invocation", command, argument}` or * `{kind:"unknown", text, token}`. */ export function parseChatInput(text) { const trimmed = str(text).trim(); if (!trimmed.startsWith("/")) return { kind: "plain" }; const match = /^\S+/.exec(trimmed); const token = match ? match[0] : trimmed; const argument = trimmed.slice(token.length).trim(); const name = token.startsWith("/") ? token.slice(1) : token; const command = CHAT_COMMANDS.find((entry) => entry.name.toLowerCase() === name.toLowerCase()); if (!command) return { kind: "unknown", text: trimmed, token }; return { kind: "invocation", command, argument }; } /** * The commands the offer list shows for [draft] (mirrors * `chatCommandSuggestions`): every command after a bare `/`, narrowed by a * case-insensitive name-prefix filter as the operator keeps typing. Once an * argument begins (whitespace after the word) the list hides, and text that does * not start with a slash offers nothing. */ export function chatCommandSuggestions(draft) { const trimmed = str(draft).trimStart(); if (!trimmed.startsWith("/")) return []; if (/\s/.test(trimmed)) return []; const query = trimmed.slice(1).toLowerCase(); return CHAT_COMMANDS.filter((entry) => entry.name.toLowerCase().startsWith(query)); } /** * The command text Enter runs for [draft] while the offer list is showing * (mirrors `chatCommandForEnter`). The list's highlighted entry wins (clamped to * the list), so a partially typed word (`/clo`) is runnable without also being * sent as a prompt. Returns null when no list is showing, which is when the * ordinary send path applies. */ export function chatCommandForEnter(draft, selected) { const suggestions = chatCommandSuggestions(draft); if (suggestions.length === 0) return null; const command = suggestions[selected] ?? suggestions[0]; return `/${command.name}`; } /** The `/help` reply (mirrors `chatCommandHelp`): `usage — summary` per line. */ export function chatCommandHelp() { return CHAT_COMMANDS.map((entry) => `${entry.usage} — ${entry.summary}`).join("\n"); } /** * Routes parsed [input] to one effect (mirrors `chatCommandEffect`), or null for * text that is not a command at all. `thread` supplies the directory `/new` must * reuse and whether a turn is running, which `/stop` needs. Every effect is a * plain object: `{kind:"start-session", directory}`, * `{kind:"finish-session"}`, `{kind:"rename-session", title}`, * `{kind:"stop-turn"}`, `{kind:"show-help"}`, or * `{kind:"report", text, offer?}`. `offer` carries the operator's draft for an * unknown command, so the notice can offer to send it as a message. */ export function chatCommandEffect(input, thread) { if (input == null || input.kind === "plain") return null; if (input.kind === "unknown") { return { kind: "report", text: `“${input.token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.`, offer: input.text, }; } const command = input.command; if (!command.takesArgument && !isBlank(input.argument)) { return { kind: "report", text: `${command.usage} does not take an argument.` }; } switch (command.name) { case CHAT_COMMAND_NEW: if (isBlank(thread?.directory)) { return { kind: "report", text: "Can't start a new session here: the server reported no directory for this chat.", }; } return { kind: "start-session", directory: str(thread.directory) }; case CHAT_COMMAND_CLOSE: return { kind: "finish-session" }; case CHAT_COMMAND_RENAME: if (isBlank(input.argument)) { return { kind: "report", text: `Usage: ${command.usage} — renames this session on this device.`, }; } return { kind: "rename-session", title: str(input.argument) }; case CHAT_COMMAND_STOP: return thread?.running === true ? { kind: "stop-turn" } : { kind: "report", text: "No turn is running in this chat." }; case CHAT_COMMAND_HELP: return { kind: "show-help" }; default: return { kind: "report", text: `“/${command.name}” is not a command.` }; } } // --------------------------------------------------------------------------- // Permission approvals (C10) — ui/chat/ChatFormat.kt ApprovalCard/approvalCard/ // permissionRiskText/decisionLabel and the ChatProtocol.DECISION_* values // --------------------------------------------------------------------------- /** The three decision values the server accepts (ChatProtocol.DECISION_*). */ export const DECISION_ONCE = "once"; export const DECISION_ALWAYS = "always"; export const DECISION_REJECT = "reject"; /** Every acceptable decision, in the Android client's own order. */ export const DECISIONS = Object.freeze([DECISION_ONCE, DECISION_ALWAYS, DECISION_REJECT]); /** A decision's human label (ChatFormat.kt decisionLabel), blank-safe. */ export const DECISION_LABEL_ONCE = "Allowed once"; export const DECISION_LABEL_ALWAYS = "Always allowed"; export const DECISION_LABEL_REJECT = "Rejected"; export const DECISION_LABEL_RESOLVED = "Resolved"; export function decisionLabel(decision) { switch (str(decision)) { case DECISION_ONCE: return DECISION_LABEL_ONCE; case DECISION_ALWAYS: return DECISION_LABEL_ALWAYS; case DECISION_REJECT: return DECISION_LABEL_REJECT; default: return DECISION_LABEL_RESOLVED; } } /** How one approval request stands (ChatFormat.kt ApprovalState). */ export const APPROVAL_PENDING = "pending"; export const APPROVAL_ANSWERED = "answered"; export const APPROVAL_RESOLVED = "resolved"; /** The card's fixed wording (ChatFormat.kt ApprovalCard and ApprovalCardItem). */ export const APPROVAL_BLANK_ACTION = "tool call"; export const APPROVAL_HEADLINE_RESOLVED = "Already resolved"; export const APPROVAL_STATUS_PENDING = "Waiting for your response"; export const APPROVAL_STATUS_ANSWERED = "Waiting for the agent to continue…"; export const APPROVAL_STATUS_RESOLVED = "Another client already answered this request."; export const RISK_REVIEW_LABEL = "RISK REVIEW"; export const WAITING_FOR_APPROVAL_LABEL = "Waiting for your approval"; /** The once/always/reject control labels (ChatApprovalCard.kt), in their order. */ export const APPROVAL_CONTROL_ONCE = "Allow once"; export const APPROVAL_CONTROL_ALWAYS = "Always allow"; export const APPROVAL_CONTROL_REJECT = "Reject"; /** How many resource lines the card shows before the remainder is elided. */ export const MAX_APPROVAL_RESOURCE_LINES = 6; /** * The text in the amber risk-review box (ChatFormat.kt permissionRiskText): the * server's own summary when it carries one, otherwise a neutral sentence naming * the action (or `a tool call`) so the box is never blank. */ export function permissionRiskText(permission) { const message = str(permission?.message); if (!isBlank(message)) return message; const what = isBlank(permission?.action) ? "a tool call" : str(permission.action); return `The agent is asking to run ${what}; review the request before allowing.`; } /** * The request's resources with the blanks dropped, in the server's own order * (ChatFormat.kt ApprovalCard.resources). No entry is discarded here: the line * cap belongs to the joined text, so an embedded newline counts as its own line * instead of hiding a later resource. */ export function approvalResources(permission) { return (permission?.resources ?? []) .filter((resource) => !isBlank(resource)) .map((resource) => str(resource)); } /** * The resource block as the card renders it (ChatFormat.kt * `resources.joinToString("\n")` with `maxLines = 6, overflow = Ellipsis`): the * non-blank resources joined by newlines and capped at * [MAX_APPROVAL_RESOURCE_LINES] lines, an embedded newline counting as a line, * with an ellipsis on the last kept line when the rest was dropped. The rendered * box clamps to the same six lines (chat.css), so a single long resource that * wraps is elided too rather than spilling onto a seventh line. */ export function approvalResourceText(permission) { const lines = approvalResources(permission).flatMap((resource) => resource.split("\n")); if (lines.length <= MAX_APPROVAL_RESOURCE_LINES) return lines.join("\n"); const kept = lines.slice(0, MAX_APPROVAL_RESOURCE_LINES); kept[kept.length - 1] = `${kept[kept.length - 1]}\u2026`; return kept.join("\n"); } /** The card headline (ChatFormat.kt ApprovalCard.headline). */ export function approvalHeadline(state, decision, action) { if (state === APPROVAL_PENDING) { return `Approve ${isBlank(action) ? APPROVAL_BLANK_ACTION : str(action)}`; } if (state === APPROVAL_ANSWERED) return decisionLabel(decision); return isBlank(decision) ? APPROVAL_HEADLINE_RESOLVED : decisionLabel(decision); } /** The card's one-line status (ChatFormat.kt ApprovalCard.statusLine). */ export function approvalStatusLine(state, note) { if (state === APPROVAL_PENDING) return APPROVAL_STATUS_PENDING; if (state === APPROVAL_ANSWERED) return APPROVAL_STATUS_ANSWERED; return isBlank(note) ? APPROVAL_STATUS_RESOLVED : str(note); } /** * What the conversation renders for one permission request (ChatFormat.kt * approvalCard): derived purely from the server's [permission] frame plus the * operator's local [answer], so a server resolution always outranks a local * answer and a stale tap can never reopen controls for a request already done. * Returns null when there is no request to show (a null frame or a blank * request id). `actionable` is true only while the request is open; `showRisk` * mirrors the app (open, or answered with a rejection). */ export function approvalCard(permission, answer) { if (permission == null || isBlank(permission.request_id)) return null; const resolvedByServer = permission.resolved === true || !isBlank(permission.decision); const state = resolvedByServer ? APPROVAL_RESOLVED : !isBlank(answer) ? APPROVAL_ANSWERED : APPROVAL_PENDING; const decision = resolvedByServer ? str(permission.decision) : str(answer); const note = resolvedByServer ? str(permission.message) : ""; return { requestId: str(permission.request_id), action: str(permission.action), resources: approvalResources(permission), resourceText: approvalResourceText(permission), risk: permissionRiskText(permission), state, decision, note, actionable: state === APPROVAL_PENDING, showRisk: state === APPROVAL_PENDING || (state === APPROVAL_ANSWERED && decision === DECISION_REJECT), headline: decision === DECISION_ALWAYS && permission.always_label === "Allow for session" ? "Allowed for session" : approvalHeadline(state, decision, str(permission.action)), statusLine: approvalStatusLine(state, note), }; } /** * Folds one pushed `chat_permission` frame into [thread] (ChatStore.permission): * a frame for a *new* request replaces any settled card and clears the local * answer, while a frame for the *same* request (for example a resolved re-push) * keeps the answer the operator already gave. The frame itself is stored; the * card derives from it, so a server resolution always wins. */ export function applyChatPermission(thread, frame) { const current = thread ?? newChatThread(str(frame?.session_id)); const requestId = str(frame?.request_id); const sameRequest = requestId !== "" && str(current.permission?.request_id) === requestId; const permissions = [...(current.permissions ?? (current.permission ? [current.permission] : []))] .filter((entry) => str(entry?.request_id) !== requestId && entry?.resolved !== true); if (requestId && frame?.resolved !== true) permissions.push(frame); return { ...current, permissions, permission: frame ?? null, permissionAnswer: sameRequest ? str(current.permissionAnswer) : "", }; } export function chatApprovalCards(thread) { return (thread?.permissions ?? (thread?.permission ? [thread.permission] : [])) .map((frame) => approvalCard(frame, thread?.permissionAnswers?.[frame.request_id] ?? (frame.request_id === thread?.permission?.request_id ? thread.permissionAnswer : ""))) .filter(Boolean); } export function chatPendingForms(thread) { return (thread?.forms ?? (thread?.form ? [thread.form] : [])) .filter((form) => form?.resolved !== true && form?.cancelled !== true); }