web: chat composer — send, stop, attachments, draft and slash commands (C8/C9)
Add the composer at the foot of an open conversation: a growing 1–6-row textarea (Enter sends, Shift+Enter newline), an Attach file control with removable attachment chips (25 MiB limit, failed attachments block sending), one send/stop control that turns to Stop while a turn runs, and the queued notice cleared on any incoming frame. Add the five slash commands with the palette, the pure chatCommand* helpers and the command notices. The prompt carries native_message_id so OpenCode accepts it, and a rejected prompt restores the draft and attachments with the server's message. Drafts persist per chat in memory and localStorage; attachments stay memory-only. Tests cover every pure helper and the exact chat_prompt/chat_interrupt/ chat_create wire shapes; ui-smoke captures the composer, palette, a failed command notice, the attachment chips and the Stop control (a real prompt to a throwaway session that is closed in cleanup).
This commit is contained in:
+22
-2
@@ -95,8 +95,8 @@ the pipeline list already carries — rather than a pluralised verb.
|
||||
| C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | todo |
|
||||
| C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | done — the assistant turn draws, in order, its one collapsible reasoning block and its one tool-call chip (then the answer). Reasoning labels match the app: `Thinking…` / `Reasoning` for a single step and `Thinking · {N} steps` / `Reasoning · {N} steps` for several, with ` · {duration}` appended when the parts' timing gives a settled span (earliest start → latest completed), through chevrons named `Show reasoning` / `Hide reasoning`. The chip reads `1 tool called` / `{N} tools called`, announces `… expand for details`, wears the shared spinner while a call is in flight and an error tint once one failed, and opens a fixed overlay panel under the chip (flipped above / clamped into the viewport when there is no room) with the same count, a `Close tool calls` control and an internally scrolling, independently-expandable row per call: the name (else `tool`), the first of `description`/`command`/`filePath`/`file_path`/`path`/`pattern`/`query`/`url` collapsed and elided to 72 characters, the `+N -M` edit stat when present, the `formatToolDuration` value (`340ms`/`1.2s`/`2m 3s`), and `Expand {name}`/`Collapse {name}`; a failed row is marked `Failed tool call`. An expanded row shows INPUT (pretty-printed JSON, or the raw partial string), the LCS edit diff (at most 200 rendered lines with the remaining `… {N} more changed line(s) not shown`), then ERROR (the server's `error.message`, else the output) or OUTPUT (`(no output)` when settled and empty, nothing while in flight). Lifecycle words `streaming`/`running` are in flight and `completed`/`error` settled; a settled call never spins or wears the ` · long` mark. Because the panel is a fixed overlay, opening or closing it never re-flows the transcript nor moves its scroll (C14). Captured 2026-10-19 against `ses_eae413f50ffeLQDExlg8cYnscN` (one folded turn, 80 reasoning steps, 122 tool calls): `captures/51-chat-reasoning-collapsed.png`, `captures/52-chat-reasoning-expanded.png`, `captures/53-chat-tool-chip.png`, `captures/54-chat-tool-panel.png` (an opened `read` row showing INPUT + OUTPUT) and `captures/55-chat-edit-diff-sample.png`. The live history carries no failed or edit-family call, so that capture renders a labelled page-rendered sample — a `shell` row marked `Failed tool call` with INPUT + ERROR and an `edit` row with a `+2 -1` diff — through the page's own row builder; the transcript stayed put across open/close (top 43065 → 43065). **Live arrival over `chat_event` is C5**: the renderer is built from the same part shapes (`ChatPart{type,name,state{status,input,content,error},time}`) and takes a `streaming` flag plus a live elapsed source so C5 can drive in-flight calls; the chip's in-flight spinner, the ` · long` 60s mark, the panel flip-above and an edit-family call are not reachable against the live server, so they are unit-tested (`test/chat.test.mjs`) rather than claimed as captured |
|
||||
| C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `<pre>` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link |
|
||||
| C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | todo |
|
||||
| C9 | Slash commands | client-side | todo |
|
||||
| C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | done — the composer at the foot of an open conversation: a growing 1–6-row `<textarea>` (placeholder `Message the agent… or / for commands`) where Enter submits and Shift+Enter inserts a newline (the submit routing is the pure `composerSubmit`), an `Attach file` control opening a multi-file picker, a removable chip per attachment (an image thumbnail else a file glyph, the display name, then the error text or `humanBytes(size)`, and a remove control named `Remove {name}`), and one primary control: Stop (`aria-label`/title `Stop`, error tint) while a turn runs, else Send (`aria-label` `Send`, disabled unless a non-blank draft with no failed attachment — or a slash draft). The 25 MiB guard reads `"{display}" is too large (25.0 MiB limit).` and an unreadable file `"{display}" could not be read.`; the web file picker cannot produce an unreadable file, so only the limit branch is captured and both are unit-tested (`test/chat.test.mjs`). Send trims the draft, clears the draft and the attachments at once, calls `chatPrompt` with `{session_id,text,operation_id,native_message_id}` (+ `files` only when present) and reads the reply's `chat_queued` into the notice `Queued — it will send when the current turn finishes.`; a rejected prompt restores the draft and the attachments (each flagged with the server's own message) and shows the shared `Action failed` dialog. The queued flag clears on any incoming frame (the client fans unsolicited envelopes out as a `frame` event; the composer folds it). The draft is kept per chat in memory **and** mirrored into `localStorage` (`pipelines.web.chatDraft.v1`) — the web analogue of per-device persistence — while attachments stay memory-only. Captured 2026-10-19 against a **freshly created** session (never the operator's own): `captures/56-chat-composer-draft.png`, `captures/60-chat-attachment-chips.png`, `captures/61-chat-attachment-removed.png`, `captures/63-chat-composer-stop.png` (a real prompt to the throwaway session turned Send into Stop) and `captures/64-chat-throwaway-closed.png`. The throwaway session was created with `chat_create` and closed with `chat_close` in cleanup; the operator's session `ses_eae413f50ffeLQDExlg8cYnscN` was never prompted |
|
||||
| C9 | Slash commands | client-side | done — the palette appears above the composer only while the trimmed draft starts with `/` and has no whitespace, filtered case-insensitively by name prefix, each row showing `/name` and the summary and the highlighted row marked `aria-selected`; Up/Down move the highlight and Enter runs it, a tap runs a row directly, and running a command always consumes the draft and never reaches the prompt path. The five commands and their summaries are `CHAT_COMMANDS` (`/new`, `/close`, `/rename <title>`, `/stop`, `/help`), unit-tested verbatim, with `chatCommandHelp()` the `usage — summary` lines. Effects: `/new` sends `chat_create` directly (C2's item) and opens the created session, `/close` reuses the C3 `Close chat?` confirm, `/rename` is the local rename pending C13, `/stop` interrupts (`chat_interrupt`) and `/help` shows the command list. Error wording is the Android source verbatim: the unknown command reads `“{token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.` with the draft offered back and `Send as message` / `Cancel`; an extra argument on an argument-less command reads `{usage} does not take an argument.`; `/rename` with no title reads `Usage: /rename <title> — renames this session on this device.`; `/stop` with nothing running reads `No turn is running in this chat.`. A notice renders as a full-width line after the turns (not a bubble) with the label `Command` / `Command failed` and a terminal glyph, error-coloured when failed. Captured 2026-10-19: `captures/57-chat-command-palette.png`, `captures/58-chat-command-palette-selected.png` (ArrowDown moved the highlight), `captures/59-chat-command-unknown.png` (the failed notice and its offer, dismissed with Cancel), `captures/62-chat-new-session.png` (`/new`'s created session and its `Command` notice) |
|
||||
| C10 | Permission/approval cards (allow once/always/reject) | `chat_permission`, `chat_reply` | todo |
|
||||
| C11 | Background tasks bar: running shells only, capped + scrollable, bounded output page | `chat_shells`, `chat_shell_output` | todo |
|
||||
| C12 | Human-decision notices inside chat + dismiss | `chat_event` | todo |
|
||||
@@ -115,6 +115,26 @@ output: a `javascript:`/`data:` target renders as its label, never dropped and
|
||||
never a live link. The transcript, the session rows and every server string are
|
||||
built from DOM nodes and set with `textContent`, never `innerHTML`.
|
||||
|
||||
Four decisions in the composer (C8/C9), recorded here as the browser client's own
|
||||
choices and dependencies. **Attachments are not delivered to the agent yet**: the
|
||||
server's prompt path (`internal/server/chat_stream.go`) consumes only `text`
|
||||
today, so the browser collects, validates and blocks on a failed attachment and
|
||||
then sends it best-effort as the file's own reference string, but the file is not
|
||||
yet forwarded to OpenCode. **`/new` sends `chat_create` directly** because C2's
|
||||
create dialog is a separate item; it creates a session titled `New chat` in the
|
||||
current directory and opens it. **`/rename` is a local, per-device rename** until
|
||||
C13 lands (the browser item mirrors C13's dependency rather than inventing a
|
||||
server rename). And the **draft is held per chat in memory and mirrored into
|
||||
`localStorage`** (`pipelines.web.chatDraft.v1`), the web analogue of per-device
|
||||
persistence, while attachments are memory-only because a `File` handle cannot be
|
||||
serialised. The composer's Stop control appears the moment a prompt is accepted
|
||||
(optimistically, as the app does) and is released when a `chat_event` `step`
|
||||
frame reports the turn `ended`; the rest of the live-transcript fold is C5's item.
|
||||
The UI smoke creates one throwaway session per run (via `/new`) for the
|
||||
running-turn capture and closes it again; the server keeps a closed chat as
|
||||
history, so repeated runs accumulate closed `New chat` rows (there is no delete
|
||||
command).
|
||||
|
||||
## Settings, layout, platform
|
||||
| # | Feature | Protocol | Status |
|
||||
| --- | --- | --- | --- |
|
||||
|
||||
+744
-16
@@ -211,12 +211,20 @@ import {
|
||||
CLOSE_CHAT_CONFIRM,
|
||||
CLOSE_CHAT_DISMISS,
|
||||
CLOSE_CHAT_TITLE,
|
||||
COMPOSER_SEND,
|
||||
COMPOSER_STOP,
|
||||
CONVERSATION_EMPTY,
|
||||
CONVERSATION_LOADING,
|
||||
LOAD_OLDER_ACTION,
|
||||
REOPEN_ACTION,
|
||||
SELECT_CHAT_HINT,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
chatBottomDistancePx,
|
||||
chatCommandEffect,
|
||||
chatCommandHelp,
|
||||
chatCommandSuggestions,
|
||||
chatFirstScroll,
|
||||
chatFollowsAt,
|
||||
chatHeaderMeta,
|
||||
@@ -224,11 +232,18 @@ import {
|
||||
chatOpensAtNewest,
|
||||
chatShowJumpToLatest,
|
||||
closeChatConfirmation,
|
||||
composerAction,
|
||||
composerCanSend,
|
||||
composerSendEnabled,
|
||||
composerSubmit,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
groupSessionsByDirectory,
|
||||
mergeHistoryPage,
|
||||
parseChatInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
runningAfterFrame,
|
||||
runningToolElapsedMillis,
|
||||
sessionActivity,
|
||||
sessionActivityBadge,
|
||||
@@ -248,6 +263,13 @@ import {
|
||||
transcriptRows,
|
||||
turnElapsedMillis,
|
||||
} from "./chat.js";
|
||||
import {
|
||||
CHAT_ATTACH_LABEL,
|
||||
CHAT_COMPOSER_PLACEHOLDER,
|
||||
CHAT_QUEUED_NOTICE,
|
||||
CHAT_SEND_LABEL,
|
||||
CHAT_STOP_LABEL,
|
||||
} from "./chat.js";
|
||||
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
|
||||
|
||||
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
|
||||
@@ -260,6 +282,15 @@ const STORAGE_KEY = "pipelines.web.serverUrl.v2";
|
||||
*/
|
||||
const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1";
|
||||
|
||||
/**
|
||||
* The per-chat composer drafts (C8). Mirrored into localStorage, the browser
|
||||
* analogue of the Android store's per-device draft: a draft survives a reload,
|
||||
* keyed by session id (attachments are memory-only — a File handle cannot be
|
||||
* serialised). The in-memory `thread.draft` is the source of truth while the page
|
||||
* is open; this is only the persistence beside it.
|
||||
*/
|
||||
const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1";
|
||||
|
||||
/** Shown where tiles exist but the configured server URL cannot resolve them. */
|
||||
const ARTIFACT_SERVER_HINT =
|
||||
"Set the server URL in Settings to open or copy artifact links.";
|
||||
@@ -3205,6 +3236,39 @@ function saveChatScroll(sessionId, position) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The persisted per-chat drafts, or an empty map when unreadable. */
|
||||
function readChatDraftStore() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(CHAT_DRAFT_STORAGE_KEY) ?? "{}");
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror one conversation's draft into localStorage. A blank draft clears its
|
||||
* entry so the store cannot grow without bound; the in-memory `thread.draft`
|
||||
* stays the source of truth, this is only the persistence beside it.
|
||||
*/
|
||||
function saveChatDraft(sessionId, text) {
|
||||
if (!sessionId) return;
|
||||
try {
|
||||
const store = readChatDraftStore();
|
||||
if (String(text ?? "") === "") delete store[sessionId];
|
||||
else store[sessionId] = String(text);
|
||||
localStorage.setItem(CHAT_DRAFT_STORAGE_KEY, JSON.stringify(store));
|
||||
} catch {
|
||||
// storage may be full or disabled; the in-memory draft still holds
|
||||
}
|
||||
}
|
||||
|
||||
/** The persisted draft for one conversation, or "" when there is none. */
|
||||
function readChatDraft(sessionId) {
|
||||
const value = readChatDraftStore()[sessionId];
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The pixels the transcript still sits above its end (0 when at the bottom), via
|
||||
* the same pure decision the unit tests cover. `chatBottomDistancePx` measures
|
||||
@@ -3293,6 +3357,13 @@ async function openChatSession(id) {
|
||||
state.chatToolRows = new Set();
|
||||
const existing = state.chatThreads.get(id);
|
||||
state.chatThreads.set(id, {
|
||||
// The composer's own per-chat state (C8/C9) survives a switch; the draft is
|
||||
// seeded from localStorage on the first open (the per-device analogue).
|
||||
draft: existing ? existing.draft ?? "" : readChatDraft(id),
|
||||
attachments: existing?.attachments ?? [],
|
||||
notices: existing?.notices ?? [],
|
||||
queued: existing?.queued ?? false,
|
||||
running: existing?.running ?? false,
|
||||
messages: existing?.messages ?? [],
|
||||
nextCursor: existing?.nextCursor ?? "",
|
||||
hasMore: existing?.hasMore ?? false,
|
||||
@@ -3304,19 +3375,24 @@ async function openChatSession(id) {
|
||||
await loadChatHistory(id);
|
||||
}
|
||||
|
||||
/** Replace one conversation's fields, keeping every other field intact. */
|
||||
function setThread(sessionId, patch) {
|
||||
const current = state.chatThreads.get(sessionId);
|
||||
if (!current) return;
|
||||
state.chatThreads.set(sessionId, { ...current, ...patch });
|
||||
}
|
||||
|
||||
/** Load (or reload) a session's newest history page and merge it in. */
|
||||
async function loadChatHistory(id) {
|
||||
const previous = state.chatThreads.get(id) ?? { messages: [] };
|
||||
try {
|
||||
const page = await repo.chatHistory(id);
|
||||
state.chatThreads.set(id, mergeHistoryPage(previous, page, { older: false }));
|
||||
// The merged page replaces only the history fields; spreading it over the
|
||||
// held thread keeps the composer's draft, attachments and flags intact (a
|
||||
// draft typed while the page was loading is not lost).
|
||||
setThread(id, mergeHistoryPage(previous, page, { older: false }));
|
||||
} catch (error) {
|
||||
state.chatThreads.set(id, {
|
||||
...previous,
|
||||
loading: false,
|
||||
loaded: true,
|
||||
error: describeError(error),
|
||||
});
|
||||
setThread(id, { loading: false, loaded: true, error: describeError(error) });
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
@@ -3338,13 +3414,9 @@ async function loadOlderChatHistory(id) {
|
||||
try {
|
||||
const page = await repo.chatHistory(id, { cursor: thread.nextCursor });
|
||||
const current = state.chatThreads.get(id) ?? thread;
|
||||
state.chatThreads.set(id, mergeHistoryPage(current, page, { older: true }));
|
||||
setThread(id, mergeHistoryPage(current, page, { older: true }));
|
||||
} catch (error) {
|
||||
state.chatThreads.set(id, {
|
||||
...(state.chatThreads.get(id) ?? thread),
|
||||
loading: false,
|
||||
error: describeError(error),
|
||||
});
|
||||
setThread(id, { loading: false, error: describeError(error) });
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
@@ -3400,6 +3472,388 @@ function applyChatSessionUpdate(id, updated, closed) {
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The composer and its slash commands (C8 · C9)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// The per-conversation attachment and notice ids. An id is unique across the
|
||||
// page, so a chip or a command line is unambiguously removable after a re-render.
|
||||
let chatAttachmentSeq = 0;
|
||||
let chatNoticeSeq = 0;
|
||||
|
||||
/** The session row for an id, or null when the server never listed it. */
|
||||
function chatSessionById(id) {
|
||||
return state.chatSessions.find((session) => session.id === id) ?? null;
|
||||
}
|
||||
|
||||
/** Revoke an attachment's image object URL, if it created one. */
|
||||
function releaseAttachment(attachment) {
|
||||
if (attachment?.thumbUrl) {
|
||||
try {
|
||||
URL.revokeObjectURL(attachment.thumbUrl);
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Revoke every attachment's object URL (used once the message is sent/gone). */
|
||||
function releaseAttachments(attachments) {
|
||||
for (const attachment of attachments ?? []) releaseAttachment(attachment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one server push into its session's thread: any frame for the session
|
||||
* clears the queued notice (the turn it waited behind moved on), and a settled
|
||||
* step clears the running bit the Stop control reads. The live transcript owns
|
||||
* the rest of the frame fold; this only keeps the composer honest while C5 is
|
||||
* still to land.
|
||||
*/
|
||||
function onChatFrame(message) {
|
||||
const frame = message?.chat_event;
|
||||
if (!frame || !frame.session_id) return;
|
||||
const sessionId = frame.session_id;
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
const queued = queuedAfterFrame(thread.queued, frame);
|
||||
const running = runningAfterFrame(thread.running, frame);
|
||||
if (queued === thread.queued && running === thread.running) return;
|
||||
setThread(sessionId, { queued, running });
|
||||
if (sessionId === state.chatActiveId) renderContent();
|
||||
}
|
||||
|
||||
/** Add one local command line to a conversation's transcript. */
|
||||
function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
chatNoticeSeq += 1;
|
||||
const notice = { id: `notice-${chatNoticeSeq}`, text, failed, offer };
|
||||
setThread(sessionId, { notices: [...(thread.notices ?? []), notice] });
|
||||
}
|
||||
|
||||
/** Remove one local command line (the operator cancelled its offer). */
|
||||
function dismissChatNotice(sessionId, noticeId) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) });
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Take an unknown-command offer's draft, removing the notice first so a stale
|
||||
* tap can neither send the same draft twice nor send anything at all.
|
||||
*/
|
||||
function takeChatNoticeOffer(sessionId, noticeId) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
const notice = (thread?.notices ?? []).find((n) => n.id === noticeId);
|
||||
if (!notice || notice.offer == null) return null;
|
||||
setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) });
|
||||
return notice.offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer's draft field, updated in place on every keystroke: the draft is
|
||||
* mirrored into localStorage, the textarea grows to fit (1–6 rows), and the
|
||||
* palette and the send/stop control are refreshed without rebuilding the DOM (so
|
||||
* the operator keeps focus and caret).
|
||||
*/
|
||||
function onComposerInput(event, sessionId, session, controls) {
|
||||
const value = event.target.value;
|
||||
setThread(sessionId, { draft: value });
|
||||
saveChatDraft(sessionId, value);
|
||||
growComposerTextarea(event.target);
|
||||
refreshComposerControls(sessionId, session, controls);
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer's key handling. While the offer list is showing, Up/Down move the
|
||||
* highlight and Enter runs the highlighted command (mirrors ChatComposer's
|
||||
* preview handler). Enter otherwise submits — which is inert while a turn is
|
||||
* running unless the palette or a slash draft is present (see composerSubmit);
|
||||
* Shift+Enter is left to insert a newline.
|
||||
*/
|
||||
function onComposerKeydown(event, sessionId, session, controls) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
const suggestions = chatCommandSuggestions(thread.draft);
|
||||
if (suggestions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
|
||||
event.preventDefault();
|
||||
const step = event.key === "ArrowDown" ? 1 : -1;
|
||||
controls.selected = (controls.selected + step + suggestions.length) % suggestions.length;
|
||||
refreshComposerControls(sessionId, session, controls);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
submitChatComposer(sessionId, session, controls);
|
||||
}
|
||||
}
|
||||
|
||||
/** Grow the composer's textarea between one and six rows to fit its content. */
|
||||
function growComposerTextarea(el) {
|
||||
if (!el) return;
|
||||
const line = parseFloat(getComputedStyle(el).lineHeight) || 20;
|
||||
const border = el.offsetHeight - el.clientHeight;
|
||||
const maxRows = 6;
|
||||
const max = line * maxRows + border;
|
||||
el.style.height = "auto";
|
||||
el.style.height = `${Math.min(el.scrollHeight, max)}px`;
|
||||
el.style.overflowY = el.scrollHeight > max ? "auto" : "hidden";
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the composer's derived parts (the offer list, the send/stop control)
|
||||
* after a keystroke, without rebuilding the textarea. The highlighted row moves
|
||||
* only through the palette itself, so it is preserved here.
|
||||
*/
|
||||
function refreshComposerControls(sessionId, session, controls) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread || !controls) return;
|
||||
const suggestions = chatCommandSuggestions(thread.draft);
|
||||
if (controls.selected >= suggestions.length) controls.selected = 0;
|
||||
fillCommandPalette(controls.palette, suggestions, controls.selected, (index) => {
|
||||
const command = suggestions[index];
|
||||
if (command) runChatCommand(sessionId, session, `/${command.name}`);
|
||||
});
|
||||
fillComposerPrimary(controls.primary, thread, () => submitChatComposer(sessionId, session, controls));
|
||||
}
|
||||
|
||||
/** Run the composer's submit (Enter): a command runs, else the draft sends. */
|
||||
function submitChatComposer(sessionId, session, controls) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
const action = composerSubmit(thread, controls?.selected ?? 0);
|
||||
if (action.kind === "command") {
|
||||
runChatCommand(sessionId, session, action.text);
|
||||
} else if (action.kind === "send") {
|
||||
sendChatPrompt(sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one slash command against a conversation (C9). The draft is always consumed
|
||||
* here — a slash draft is never handed to the prompt path — so only an explicit
|
||||
* "Send as message" from an unknown-command offer reaches the agent. Every
|
||||
* outcome is a local transcript line.
|
||||
*/
|
||||
function runChatCommand(sessionId, session, text) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
setThread(sessionId, { draft: "" });
|
||||
saveChatDraft(sessionId, "");
|
||||
const view = { ...thread, draft: "", directory: session?.directory ?? "", running: thread.running === true };
|
||||
const effect = chatCommandEffect(parseChatInput(text), view);
|
||||
if (effect == null) return;
|
||||
applyChatCommandEffect(sessionId, session, effect);
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform one command effect. `/new` creates a session in the current directory
|
||||
* and opens it (the create request is C2's; until C2 lands the browser sends
|
||||
* `chat_create` directly); `/close` reuses the C3 confirm; `/rename` is the local
|
||||
* rename pending C13; `/stop` interrupts; `/help` shows the command list.
|
||||
*/
|
||||
function applyChatCommandEffect(sessionId, session, effect) {
|
||||
switch (effect.kind) {
|
||||
case "start-session":
|
||||
startChatSession(effect.directory);
|
||||
break;
|
||||
case "finish-session":
|
||||
if (session) openChatClose(session);
|
||||
break;
|
||||
case "rename-session":
|
||||
renameChatSessionLocally(sessionId, effect.title);
|
||||
break;
|
||||
case "stop-turn":
|
||||
stopChatTurn(sessionId);
|
||||
break;
|
||||
case "show-help":
|
||||
addChatNotice(sessionId, chatCommandHelp());
|
||||
break;
|
||||
case "report":
|
||||
addChatNotice(sessionId, effect.text, { failed: true, offer: effect.offer ?? null });
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** `/new`: create a session titled "New chat" in [directory] and open it. */
|
||||
async function startChatSession(directory) {
|
||||
const from = state.chatActiveId;
|
||||
try {
|
||||
const created = await repo.chatCreate("New chat", directory);
|
||||
// The list is the server's; insert the created session so the row is present
|
||||
// before the conversation opens, then refresh from the server.
|
||||
state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)];
|
||||
state.chatThreads.set(created.id, {
|
||||
draft: "",
|
||||
attachments: [],
|
||||
notices: [],
|
||||
queued: false,
|
||||
running: false,
|
||||
messages: [],
|
||||
nextCursor: "",
|
||||
hasMore: false,
|
||||
loaded: false,
|
||||
loading: true,
|
||||
error: "",
|
||||
});
|
||||
const title = String(created.title ?? "").trim() || "New chat";
|
||||
addChatNotice(created.id, `Started a new session “${title}” in ${directory}.`);
|
||||
await openChatSession(created.id);
|
||||
await loadChatSessions();
|
||||
} catch (error) {
|
||||
if (from) addChatNotice(from, `Couldn't start a new session in ${directory}: ${describeError(error)}`, { failed: true });
|
||||
state.actionError = describeError(error);
|
||||
renderContent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `/rename`: rename the session on this device only. C13 owns the durable local
|
||||
* rename/hide store; until it lands this renames the held row and the open
|
||||
* conversation in memory and says so.
|
||||
*/
|
||||
function renameChatSessionLocally(sessionId, title) {
|
||||
state.chatSessions = state.chatSessions.map((session) =>
|
||||
session.id === sessionId ? { ...session, title } : session,
|
||||
);
|
||||
setThread(sessionId, { title });
|
||||
addChatNotice(sessionId, `Renamed this session to “${title}” on this device only; the server's title is unchanged.`);
|
||||
}
|
||||
|
||||
/** The composer's Stop control: interrupt the session's running turn. */
|
||||
async function stopChatTurn(sessionId) {
|
||||
try {
|
||||
await repo.chatInterrupt(sessionId);
|
||||
addChatNotice(sessionId, "Stopping the running turn…");
|
||||
} catch (error) {
|
||||
state.actionError = describeError(error);
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the composer's draft with its attachments (mirrors
|
||||
* `AppViewModel.sendChatPrompt`): the draft is trimmed, the compose state is
|
||||
* cleared at once, and a rejected prompt restores the draft and the attachments
|
||||
* with the server's own message.
|
||||
*/
|
||||
async function sendChatPrompt(sessionId, session) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread || !composerCanSend(thread)) return;
|
||||
const text = String(thread.draft).trim();
|
||||
if (text === "") return;
|
||||
const attachments = thread.attachments ?? [];
|
||||
releaseAttachments(attachments);
|
||||
setThread(sessionId, { draft: "", attachments: [] });
|
||||
saveChatDraft(sessionId, "");
|
||||
renderContent();
|
||||
await postChatPrompt(sessionId, text, attachments);
|
||||
}
|
||||
|
||||
/**
|
||||
* One prompt, from the composer or an unknown-command offer. Flags the chat
|
||||
* running, posts it, and takes the attachments back out flagged with the
|
||||
* server's reason if it is rejected. The live transcript item (C5) owns the
|
||||
* optimistic bubble; this only drives the composer and its request.
|
||||
*/
|
||||
async function postChatPrompt(sessionId, text, attachments) {
|
||||
const body = String(text).trim();
|
||||
if (body === "") return;
|
||||
setThread(sessionId, { running: true });
|
||||
renderContent();
|
||||
try {
|
||||
const queued = await repo.chatPrompt(sessionId, body, attachmentFiles(attachments));
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
// Prompting a closed session reopens it on the server; clear the local mark
|
||||
// too so the list agrees without a re-fetch.
|
||||
applyChatSessionUpdate(sessionId, null, false);
|
||||
setThread(sessionId, { queued, running: true });
|
||||
renderContent();
|
||||
} catch (error) {
|
||||
const message = describeError(error);
|
||||
const restored = (attachments ?? []).map((attachment) => {
|
||||
releaseAttachment(attachment);
|
||||
return { ...attachment, thumbUrl: null, error: message };
|
||||
});
|
||||
setThread(sessionId, {
|
||||
running: false,
|
||||
queued: false,
|
||||
error: message,
|
||||
draft: body,
|
||||
attachments: restored,
|
||||
});
|
||||
saveChatDraft(sessionId, body);
|
||||
state.actionError = message;
|
||||
renderContent();
|
||||
}
|
||||
}
|
||||
|
||||
/** Send an unknown-command offer's draft through the ordinary prompt path. */
|
||||
function sendChatCommandOffer(sessionId, noticeId) {
|
||||
const offer = takeChatNoticeOffer(sessionId, noticeId);
|
||||
if (offer == null) return;
|
||||
renderContent();
|
||||
postChatPrompt(sessionId, offer, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the files the operator picked into composer attachments. Only the
|
||||
* metadata is read here (nothing is transmitted until the message is sent): the
|
||||
* browser has no `content://` reference, so the file's own name is carried as the
|
||||
* best-effort reference string. A file over the limit is returned with its error
|
||||
* set rather than dropped.
|
||||
*/
|
||||
function onChatFilesPicked(sessionId, session, fileList) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
const picked = [];
|
||||
for (const file of fileList ?? []) {
|
||||
chatAttachmentSeq += 1;
|
||||
const name = String(file?.name ?? "");
|
||||
const mime = String(file?.type ?? "");
|
||||
const size = Number(file?.size) || 0;
|
||||
picked.push({
|
||||
id: `att-${chatAttachmentSeq}`,
|
||||
name,
|
||||
uri: name,
|
||||
mime,
|
||||
size,
|
||||
error: attachmentError(name, size, true),
|
||||
thumbUrl: mime.startsWith("image/") ? createThumbUrl(file) : null,
|
||||
file,
|
||||
});
|
||||
}
|
||||
if (picked.length === 0) return;
|
||||
setThread(sessionId, { attachments: [...(thread.attachments ?? []), ...picked] });
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/** An object URL for a local image preview, or null when the browser refuses one. */
|
||||
function createThumbUrl(file) {
|
||||
try {
|
||||
return URL.createObjectURL(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove one attachment from the next message and release its preview URL. */
|
||||
function removeChatAttachment(sessionId, attachmentId) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread) return;
|
||||
const attachment = (thread.attachments ?? []).find((entry) => entry.id === attachmentId);
|
||||
releaseAttachment(attachment);
|
||||
setThread(sessionId, {
|
||||
attachments: (thread.attachments ?? []).filter((entry) => entry.id !== attachmentId),
|
||||
});
|
||||
renderContent();
|
||||
}
|
||||
|
||||
function renderChatList() {
|
||||
const list = h("div", { class: "list chat-list" });
|
||||
const toolbar = h("div", { class: "list-toolbar chat-toolbar" });
|
||||
@@ -3629,6 +4083,7 @@ function renderChatConversation() {
|
||||
if (contextMeta !== "") context.append(h("span", { class: "chat-context-meta muted", text: contextMeta }));
|
||||
pane.append(context);
|
||||
|
||||
const notices = thread?.notices ?? [];
|
||||
if (thread?.loading && !thread?.loaded) {
|
||||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_LOADING }));
|
||||
} else if (thread?.error && !thread?.loaded) {
|
||||
@@ -3644,16 +4099,20 @@ function renderChatConversation() {
|
||||
pane.append(empty);
|
||||
} else {
|
||||
const rows = transcriptRows(thread?.messages ?? []);
|
||||
if (rows.length === 0) {
|
||||
if (rows.length === 0 && notices.length === 0) {
|
||||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
|
||||
} else {
|
||||
pane.append(renderChatTranscript(state.chatActiveId, rows));
|
||||
pane.append(renderChatTranscript(state.chatActiveId, rows, notices));
|
||||
}
|
||||
if (thread?.error && thread?.loaded) {
|
||||
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
|
||||
}
|
||||
}
|
||||
|
||||
// The composer sits at the foot of the conversation, always available while a
|
||||
// chat is open (the transcript may still be loading).
|
||||
pane.append(renderChatComposer(thread, session, state.chatActiveId));
|
||||
|
||||
appendChatDialogs(pane);
|
||||
return pane;
|
||||
}
|
||||
@@ -3675,7 +4134,7 @@ function appendChatDialogs(pane) {
|
||||
* in order as the reasoning block, then the tool-call chip, then the answer
|
||||
* markdown. No timestamps, model or agent are shown inside the transcript.
|
||||
*/
|
||||
function renderChatTranscript(sessionId, rows) {
|
||||
function renderChatTranscript(sessionId, rows, notices = []) {
|
||||
const wrap = h("div", { class: "chat-transcript-wrap" });
|
||||
const transcript = h("div", {
|
||||
class: "chat-transcript",
|
||||
@@ -3686,6 +4145,9 @@ function renderChatTranscript(sessionId, rows) {
|
||||
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
|
||||
else transcript.append(renderChatAgentTurn(row.turn));
|
||||
}
|
||||
// The conversation's local command lines sit after the turns, full width and
|
||||
// deliberately unlike a message bubble (see ChatCommandNoticeItem).
|
||||
for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice));
|
||||
wrap.append(transcript);
|
||||
wrap.append(
|
||||
h("button", {
|
||||
@@ -4097,6 +4559,266 @@ function renderInlineNodes(spans) {
|
||||
});
|
||||
}
|
||||
|
||||
/** One local command line in the transcript (see ChatCommandNoticeItem). */
|
||||
function renderChatCommandNotice(sessionId, notice) {
|
||||
const failed = notice?.failed === true;
|
||||
const row = h("div", {
|
||||
class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`,
|
||||
role: "note",
|
||||
});
|
||||
const head = h("div", { class: "chat-command-notice-head" });
|
||||
head.append(
|
||||
h("span", {
|
||||
class: "chat-command-notice-glyph",
|
||||
"aria-hidden": "true",
|
||||
text: failed ? "⌨" : "▸",
|
||||
}),
|
||||
);
|
||||
head.append(
|
||||
h("span", { class: "chat-command-notice-label", text: failed ? "Command failed" : "Command" }),
|
||||
);
|
||||
row.append(head);
|
||||
row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" }));
|
||||
if (notice?.offer != null) {
|
||||
const actions = h("div", { class: "chat-command-notice-actions" });
|
||||
actions.append(
|
||||
h("button", {
|
||||
class: "ghost chat-command-send-as-message",
|
||||
type: "button",
|
||||
text: "Send as message",
|
||||
onclick: () => sendChatCommandOffer(sessionId, notice.id),
|
||||
}),
|
||||
);
|
||||
actions.append(
|
||||
h("button", {
|
||||
class: "ghost chat-command-cancel",
|
||||
type: "button",
|
||||
text: "Cancel",
|
||||
onclick: () => dismissChatNotice(sessionId, notice.id),
|
||||
}),
|
||||
);
|
||||
row.append(actions);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer at the foot of an open conversation: the queued notice, the
|
||||
* attachment chips, the slash-command offer list, the attach control, the growing
|
||||
* multiline field and the single send/stop control. All state is derived from the
|
||||
* thread and its session; every server/model string is set with textContent.
|
||||
*/
|
||||
function renderChatComposer(thread, session, sessionId) {
|
||||
const composer = h("div", { class: "chat-composer", id: "chatComposer" });
|
||||
if (!thread) return composer;
|
||||
const controls = { selected: 0, palette: null, primary: null };
|
||||
|
||||
if (thread.queued) {
|
||||
composer.append(h("div", { class: "chat-queued", id: "chatQueued", text: CHAT_QUEUED_NOTICE }));
|
||||
}
|
||||
|
||||
const strip = renderChatAttachmentStrip(sessionId, thread);
|
||||
if (strip) composer.append(strip);
|
||||
|
||||
const palette = h("div", {
|
||||
class: "chat-command-palette",
|
||||
id: "chatPalette",
|
||||
role: "listbox",
|
||||
"aria-label": "Command suggestions",
|
||||
hidden: true,
|
||||
});
|
||||
controls.palette = palette;
|
||||
composer.append(palette);
|
||||
|
||||
const row = h("div", { class: "chat-composer-row" });
|
||||
const fileInput = h("input", {
|
||||
id: "chatFileInput",
|
||||
class: "chat-file-input",
|
||||
type: "file",
|
||||
multiple: true,
|
||||
tabindex: "-1",
|
||||
"aria-hidden": "true",
|
||||
onchange: (event) => {
|
||||
onChatFilesPicked(sessionId, session, event.target.files);
|
||||
event.target.value = "";
|
||||
},
|
||||
});
|
||||
row.append(
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: "ghost chat-attach",
|
||||
id: "chatAttach",
|
||||
type: "button",
|
||||
"aria-label": CHAT_ATTACH_LABEL,
|
||||
title: CHAT_ATTACH_LABEL,
|
||||
onclick: () => fileInput.click(),
|
||||
},
|
||||
"\u{1F4CE}",
|
||||
),
|
||||
);
|
||||
row.append(fileInput);
|
||||
|
||||
const input = h("textarea", {
|
||||
id: "chatInput",
|
||||
class: "chat-composer-input",
|
||||
rows: "1",
|
||||
placeholder: CHAT_COMPOSER_PLACEHOLDER,
|
||||
"aria-label": CHAT_COMPOSER_PLACEHOLDER,
|
||||
spellcheck: "false",
|
||||
});
|
||||
input.value = thread.draft ?? "";
|
||||
input.addEventListener("input", (event) => onComposerInput(event, sessionId, session, controls));
|
||||
input.addEventListener("keydown", (event) => onComposerKeydown(event, sessionId, session, controls));
|
||||
row.append(input);
|
||||
|
||||
const primary = h("span", { class: "chat-composer-primary" });
|
||||
controls.primary = primary;
|
||||
row.append(primary);
|
||||
composer.append(row);
|
||||
|
||||
const suggestions = chatCommandSuggestions(thread.draft);
|
||||
fillCommandPalette(palette, suggestions, controls.selected, (index) => {
|
||||
const command = suggestions[index];
|
||||
if (command) runChatCommand(sessionId, session, `/${command.name}`);
|
||||
});
|
||||
fillComposerPrimary(primary, thread, () => submitChatComposer(sessionId, session, controls));
|
||||
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
requestAnimationFrame(() => growComposerTextarea(input));
|
||||
}
|
||||
return composer;
|
||||
}
|
||||
|
||||
/** The offer list above the composer: `/name` and the summary per row. */
|
||||
function fillCommandPalette(palette, suggestions, selected, onPick) {
|
||||
if (!palette) return;
|
||||
palette.replaceChildren();
|
||||
if (!suggestions || suggestions.length === 0) {
|
||||
palette.hidden = true;
|
||||
return;
|
||||
}
|
||||
palette.hidden = false;
|
||||
suggestions.forEach((command, index) => {
|
||||
palette.append(
|
||||
h(
|
||||
"div",
|
||||
{
|
||||
class: `chat-command-row${index === selected ? " selected" : ""}`,
|
||||
role: "option",
|
||||
"aria-selected": index === selected ? "true" : "false",
|
||||
tabindex: "-1",
|
||||
onclick: () => onPick(index),
|
||||
},
|
||||
h("span", { class: "chat-command-name", text: `/${command.name}` }),
|
||||
h("span", { class: "chat-command-summary", text: command.summary }),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer's single primary control: Stop while a turn is in flight (error
|
||||
* tint), else Send, disabled unless the draft is sendable (or a slash draft).
|
||||
*/
|
||||
function fillComposerPrimary(primary, thread, onActivate) {
|
||||
if (!primary) return;
|
||||
primary.replaceChildren();
|
||||
if (composerAction(thread) === COMPOSER_STOP) {
|
||||
primary.append(
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: "chat-stop",
|
||||
id: "chatStop",
|
||||
type: "button",
|
||||
"aria-label": CHAT_STOP_LABEL,
|
||||
title: CHAT_STOP_LABEL,
|
||||
onclick: onActivate,
|
||||
},
|
||||
"■",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
primary.append(
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: "chat-send",
|
||||
id: "chatSend",
|
||||
type: "button",
|
||||
"aria-label": CHAT_SEND_LABEL,
|
||||
title: CHAT_SEND_LABEL,
|
||||
disabled: !composerSendEnabled(thread),
|
||||
onclick: onActivate,
|
||||
},
|
||||
"➤",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** The removable chips for the files attached to the next message. */
|
||||
function renderChatAttachmentStrip(sessionId, thread) {
|
||||
const attachments = thread?.attachments ?? [];
|
||||
if (attachments.length === 0) return null;
|
||||
const strip = h("div", { class: "chat-attachment-strip", id: "chatAttachments" });
|
||||
for (const attachment of attachments) {
|
||||
strip.append(renderChatAttachmentChip(sessionId, attachment));
|
||||
}
|
||||
return strip;
|
||||
}
|
||||
|
||||
/** One attachment chip: its preview, its name, its size or error, and remove. */
|
||||
function renderChatAttachmentChip(sessionId, attachment) {
|
||||
const failed = attachment?.error != null;
|
||||
const display = attachmentDisplayName(attachment?.name, attachment?.uri);
|
||||
const chip = h("div", {
|
||||
class: `chat-attachment-chip${failed ? " chat-attachment-chip-failed" : ""}`,
|
||||
});
|
||||
chip.append(renderAttachmentThumb(attachment, display));
|
||||
const body = h("div", { class: "chat-attachment-body" });
|
||||
body.append(h("span", { class: "chat-attachment-name", text: display }));
|
||||
if (failed) {
|
||||
body.append(h("span", { class: "chat-attachment-meta chat-attachment-error", text: attachment.error }));
|
||||
} else if (Number(attachment?.size) > 0) {
|
||||
body.append(h("span", { class: "chat-attachment-meta", text: humanBytes(attachment.size) }));
|
||||
}
|
||||
chip.append(body);
|
||||
chip.append(
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: "ghost chat-attachment-remove",
|
||||
type: "button",
|
||||
"aria-label": `Remove ${display}`,
|
||||
title: `Remove ${display}`,
|
||||
onclick: () => removeChatAttachment(sessionId, attachment.id),
|
||||
},
|
||||
"✕",
|
||||
),
|
||||
);
|
||||
return chip;
|
||||
}
|
||||
|
||||
/** The chip's square preview: the decoded thumbnail for an image, else a glyph. */
|
||||
function renderAttachmentThumb(attachment, display) {
|
||||
if (attachment?.thumbUrl) {
|
||||
return h("img", {
|
||||
class: "chat-attachment-thumb",
|
||||
src: attachment.thumbUrl,
|
||||
alt: display,
|
||||
"aria-hidden": "true",
|
||||
});
|
||||
}
|
||||
const image = String(attachment?.mime ?? "").startsWith("image/");
|
||||
return h("span", {
|
||||
class: "chat-attachment-glyph",
|
||||
"aria-hidden": "true",
|
||||
text: image ? "🖼" : "📄",
|
||||
});
|
||||
}
|
||||
|
||||
/** The Close chat? confirm: the exact Android body naming the session title. */
|
||||
function renderChatCloseDialog(session) {
|
||||
const overlay = h("div", {
|
||||
@@ -4895,6 +5617,12 @@ client.addEventListener("state", (event) => {
|
||||
render();
|
||||
});
|
||||
|
||||
// Server pushes (a `chat_event` frame, a pushed `run_event`, …) have no matching
|
||||
// request; the client fans them out as a `frame` event and the chat composer
|
||||
// folds the ones it needs, so a queued prompt clears and a settled turn releases
|
||||
// the Stop control.
|
||||
client.addEventListener("frame", (event) => onChatFrame(event.detail));
|
||||
|
||||
// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the
|
||||
// omni-search field and the attention sheet are modal: Escape closes the topmost
|
||||
// one (the artifact viewer or the diff viewer, when either is above, owns Escape
|
||||
|
||||
+318
@@ -21,6 +21,14 @@
|
||||
// chatFirstScroll
|
||||
// ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an
|
||||
// older page, replace nextCursor/hasMore)
|
||||
// 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
|
||||
//
|
||||
// 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
|
||||
@@ -31,6 +39,7 @@
|
||||
// synthesised diff and the Changes viewer can never disagree about what a line
|
||||
// kind is called or coloured.
|
||||
import { ChangeLineKind } from "./changes.js";
|
||||
import { humanBytes } from "./artifacts.js";
|
||||
|
||||
/** ChatMessage.Role values (internal/protocol/chat.go). */
|
||||
export const ROLE_USER = "user";
|
||||
@@ -793,3 +802,312 @@ export function chatFirstScroll(saved, itemCount) {
|
||||
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 two values of [composerAction]. */
|
||||
export const COMPOSER_SEND = "send";
|
||||
export const COMPOSER_STOP = "stop";
|
||||
|
||||
/** Which action the composer's single primary control offers for a chat. */
|
||||
export function composerAction(thread) {
|
||||
return thread?.running === true ? COMPOSER_STOP : COMPOSER_SEND;
|
||||
}
|
||||
|
||||
/** True while at least one attachment carries an error. */
|
||||
export function hasAttachmentErrors(thread) {
|
||||
return (thread?.attachments ?? []).some((attachment) => attachment?.error != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the composer's send action is allowed (mirrors `ChatThread.canSend`): a
|
||||
* non-blank draft with no flagged attachment. A message with a flagged attachment
|
||||
* is never sent, so the file is never silently dropped.
|
||||
*/
|
||||
export function composerCanSend(thread) {
|
||||
return !isBlank(thread?.draft) && !hasAttachmentErrors(thread);
|
||||
}
|
||||
|
||||
/** True when the trimmed draft starts with a slash, so it is a command. */
|
||||
export function chatDraftIsSlash(draft) {
|
||||
return str(draft).trimStart().startsWith("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the Send control is enabled (mirrors ChatComposer's
|
||||
* `enabled = thread.canSend || slashDraft`): a non-blank draft with no failed
|
||||
* attachment, or a slash draft — which is always runnable, because a command never
|
||||
* goes to the prompt path with its attachments.
|
||||
*/
|
||||
export function composerSendEnabled(thread) {
|
||||
return composerCanSend(thread) || chatDraftIsSlash(thread?.draft);
|
||||
}
|
||||
|
||||
/**
|
||||
* What pressing Enter (the composer's submit) does for [thread] with the offer
|
||||
* list's highlighted [selected] row — the one derivation the key handler and its
|
||||
* unit test share. `{kind:"command", text}` runs a slash command (the highlighted
|
||||
* offer row, else the operator's slash draft), `{kind:"send"}` sends the draft as
|
||||
* a prompt, and `{kind:"none"}` does nothing: a running turn's Enter is inert
|
||||
* unless the palette or a slash draft is present, so it can never send the draft
|
||||
* to a session mid-turn.
|
||||
*/
|
||||
export function composerSubmit(thread, selected = 0) {
|
||||
const draft = str(thread?.draft);
|
||||
const command = chatCommandForEnter(draft, selected);
|
||||
if (command != null) return { kind: "command", text: command };
|
||||
if (chatDraftIsSlash(draft)) return { kind: "command", text: draft };
|
||||
if (composerAction(thread) === COMPOSER_SEND && composerCanSend(thread)) {
|
||||
return { kind: "send" };
|
||||
}
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The queued flag after one pushed frame for the session: any frame means the
|
||||
* turn the prompt was waiting behind has moved on, so the queued notice clears
|
||||
* (mirrors ChatStore.event). A null frame leaves the flag untouched.
|
||||
*/
|
||||
export function queuedAfterFrame(queued, frame) {
|
||||
if (frame == null) return queued === true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The running flag after one pushed frame: a `step` frame that reports the turn
|
||||
* `ended` settles it, and every other frame leaves it as it was. The live
|
||||
* transcript owns the rest of the frame fold; this is only the turn's own
|
||||
* running bit, which the composer's Stop control reads.
|
||||
*/
|
||||
export function runningAfterFrame(running, frame) {
|
||||
if (frame?.kind === "step" && frame?.step?.status === "ended") return false;
|
||||
return running === true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Attachments (ChatFormat.kt / ChatAttachments.kt)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The largest file the composer will attach (mirrors ChatFormat.MAX_ATTACHMENT_BYTES).
|
||||
* A browser-side guard, so a runaway pick is refused with a reason instead of
|
||||
* being handed to the server; the server applies its own limits on top.
|
||||
*/
|
||||
export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
/** The fallback display name when neither the name nor the uri gives one. */
|
||||
export const ATTACHMENT_FALLBACK_NAME = "file";
|
||||
|
||||
/**
|
||||
* The name shown for an attachment, never blank (mirrors
|
||||
* `ChatAttachment.displayName`): its own name, else the uri's basename, else
|
||||
* `file`.
|
||||
*/
|
||||
export function attachmentDisplayName(name, uri) {
|
||||
const shown = str(name);
|
||||
if (!isBlank(shown)) return shown;
|
||||
const basename = str(uri).split("/").pop() ?? "";
|
||||
if (!isBlank(basename)) return basename;
|
||||
return ATTACHMENT_FALLBACK_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why an attachment cannot be sent, or null when it can (mirrors
|
||||
* `attachmentError`). An unreadable file and a file over
|
||||
* [MAX_ATTACHMENT_BYTES] are each reported by name, so the operator sees which
|
||||
* one and why rather than losing it. The limit reads `25.0 MiB` through the one
|
||||
* shared `humanBytes`.
|
||||
*/
|
||||
export function attachmentError(name, sizeBytes, readable) {
|
||||
const display = isBlank(name) ? ATTACHMENT_FALLBACK_NAME : str(name);
|
||||
if (readable === false) return `"${display}" could not be read.`;
|
||||
if (Number(sizeBytes) > MAX_ATTACHMENT_BYTES) {
|
||||
return `"${display}" is too large (${humanBytes(MAX_ATTACHMENT_BYTES)} limit).`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `files` carried by a prompt (mirrors `attachmentFiles`): the references of
|
||||
* the attachments that can go. One place derives the wire list from the
|
||||
* attachments, so the send path and the transcript's file parts can never
|
||||
* disagree about which files are attached.
|
||||
*/
|
||||
export function attachmentFiles(attachments) {
|
||||
return (attachments ?? [])
|
||||
.filter((attachment) => attachment?.error == null)
|
||||
.map((attachment) => str(attachment?.uri));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slash commands (ChatCommands.kt)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const CHAT_COMMAND_NEW = "new";
|
||||
export const CHAT_COMMAND_CLOSE = "close";
|
||||
export const CHAT_COMMAND_RENAME = "rename";
|
||||
export const CHAT_COMMAND_STOP = "stop";
|
||||
export const CHAT_COMMAND_HELP = "help";
|
||||
|
||||
/**
|
||||
* The commands the composer understands, in the order the offer list shows them
|
||||
* (mirrors `CHAT_COMMANDS`). `name` is the word after the slash, `usage` is what
|
||||
* the operator types (including any argument) and `summary` is the few-word
|
||||
* description shown beside it. `takesArgument` is false for the commands that act
|
||||
* on the current session alone, so a stray argument is reported instead of being
|
||||
* silently ignored.
|
||||
*/
|
||||
export const CHAT_COMMANDS = Object.freeze([
|
||||
Object.freeze({
|
||||
name: CHAT_COMMAND_NEW,
|
||||
summary: "Start a fresh session in this directory",
|
||||
usage: "/new",
|
||||
takesArgument: false,
|
||||
}),
|
||||
Object.freeze({
|
||||
name: CHAT_COMMAND_CLOSE,
|
||||
summary: "Finish this session for every client, keeping its history",
|
||||
usage: "/close",
|
||||
takesArgument: false,
|
||||
}),
|
||||
Object.freeze({
|
||||
name: CHAT_COMMAND_RENAME,
|
||||
summary: "Rename this session on this device",
|
||||
usage: "/rename <title>",
|
||||
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.` };
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -184,9 +184,13 @@ export class PipelinesClient extends EventTarget {
|
||||
this.#pending.delete(message.id);
|
||||
clearTimeout(entry.timer);
|
||||
entry.resolve(message);
|
||||
return;
|
||||
}
|
||||
// Unsolicited envelopes (for example the connection's initial pipeline_list)
|
||||
// have no matching id and are intentionally dropped.
|
||||
// Unsolicited envelope: a server push (a `chat_event` frame, a pushed
|
||||
// `run_event`, or the connection's initial `pipeline_list`). It has no
|
||||
// matching request, so it is surfaced to listeners as a `frame` event for a
|
||||
// view to fold; with no listener it is simply dropped, exactly as before.
|
||||
this.dispatchEvent(new CustomEvent("frame", { detail: message }));
|
||||
}
|
||||
|
||||
#failPending(reason) {
|
||||
|
||||
@@ -43,6 +43,14 @@ export const Protocol = Object.freeze({
|
||||
CHAT_MESSAGES: "chat_messages",
|
||||
CHAT_CLOSE: "chat_close",
|
||||
CHAT_REOPEN: "chat_reopen",
|
||||
// The composer's own commands (C8/C9). `chat_prompt` carries its body in
|
||||
// `chat_prompt` (`{session_id,text,files?,operation_id}`) and its reply echoes
|
||||
// `chat_queued` when the prompt waits behind an in-flight turn; `chat_interrupt`
|
||||
// carries the same `chat_query` body as the other session-scoped commands; and
|
||||
// `chat_create` carries `chat_create` and replies with `chat_session`.
|
||||
CHAT_PROMPT: "chat_prompt",
|
||||
CHAT_INTERRUPT: "chat_interrupt",
|
||||
CHAT_CREATE: "chat_create",
|
||||
|
||||
SUCCESS_END: "#success",
|
||||
FAILURE_END: "#failure",
|
||||
@@ -60,6 +68,13 @@ export const ChatKeys = Object.freeze({
|
||||
HISTORY: "chat_history",
|
||||
MESSAGES: "chat_messages",
|
||||
CLOSE: "chat_close",
|
||||
// The composer's payloads (C8/C9). `chat_interrupt` deliberately has no key of
|
||||
// its own: its body is the same `chat_query` the other session-scoped commands
|
||||
// carry (internal/protocol/chat.go ChatQuery, Chat.kt interruptRequest), so a
|
||||
// separate field name here would put it on the wrong part of the envelope.
|
||||
PROMPT: "chat_prompt",
|
||||
CREATE: "chat_create",
|
||||
QUEUED: "chat_queued",
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -219,4 +219,100 @@ export class PipelinesRepository {
|
||||
});
|
||||
return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null };
|
||||
}
|
||||
|
||||
// ---- The composer's own commands (C8/C9) ---------------------------------
|
||||
// Mirrors PipelinesRepository.chatPrompt / chatInterrupt / chatCreate.
|
||||
|
||||
/**
|
||||
* Sends one prompt with its attached file references (mirrors
|
||||
* `PipelinesRepository.chatPrompt`): a blank session or blank text is refused
|
||||
* here rather than sent, the text is trimmed, and `files` is **omitted** when
|
||||
* empty (the shape a text-only prompt has always sent — the Android
|
||||
* `ChatPromptRequest.Files` is `omitempty` too). `operation_id` is the durable
|
||||
* idempotency key for this send. Returns true when the server queued the
|
||||
* prompt behind an in-flight turn (`chat_queued` on the reply), which is the
|
||||
* one signal the composer's queued notice is derived from.
|
||||
*
|
||||
* Note: the server's prompt path (`internal/server/chat_stream.go`) consumes
|
||||
* only `text` today — `files` is accepted on the wire but not yet forwarded to
|
||||
* OpenCode, so a browser attachment is collected, validated and made to block a
|
||||
* failed send, then sent best-effort as the file's own reference string. The
|
||||
* attachment is not yet delivered to the agent; the row note records that.
|
||||
*/
|
||||
async chatPrompt(sessionId, text, files = [], operationId = newChatOperationId()) {
|
||||
if (!String(sessionId ?? "").trim()) {
|
||||
throw new ProtocolError("Select a chat session first.");
|
||||
}
|
||||
const trimmed = String(text ?? "").trim();
|
||||
if (trimmed === "") {
|
||||
throw new ProtocolError("Enter a message before sending.");
|
||||
}
|
||||
const body = {
|
||||
session_id: sessionId,
|
||||
text: trimmed,
|
||||
operation_id: operationId,
|
||||
native_message_id: nativeChatMessageId(operationId),
|
||||
};
|
||||
if (files.length > 0) body.files = files;
|
||||
const response = await this.#client.call({ type: Protocol.CHAT_PROMPT, [ChatKeys.PROMPT]: body });
|
||||
return Boolean(response[ChatKeys.QUEUED]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the in-flight turn for a session (mirrors
|
||||
* `PipelinesRepository.chatInterrupt`). The body is the session-scoped
|
||||
* `chat_query`, exactly like the other session commands.
|
||||
*/
|
||||
async chatInterrupt(sessionId) {
|
||||
if (!String(sessionId ?? "").trim()) {
|
||||
throw new ProtocolError("Select a chat session first.");
|
||||
}
|
||||
await this.#client.call({
|
||||
type: Protocol.CHAT_INTERRUPT,
|
||||
[ChatKeys.QUERY]: { session_id: sessionId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates one session in an explicit directory (mirrors
|
||||
* `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is
|
||||
* never created in whatever directory the server happens to be running in. The
|
||||
* reply's `chat_session` is returned, or a `ProtocolError` when the server did
|
||||
* not return one.
|
||||
*/
|
||||
async chatCreate(title, directory, operationId = newChatOperationId()) {
|
||||
const response = await this.#client.call({
|
||||
type: Protocol.CHAT_CREATE,
|
||||
[ChatKeys.CREATE]: { title, directory, operation_id: operationId },
|
||||
});
|
||||
const session = response[ChatKeys.SESSION];
|
||||
if (!session) {
|
||||
throw new ProtocolError("The server did not return the new chat session.");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A durable operation id for one chat request intent, retaining the shape of the
|
||||
* Android `newRequestKey`/`newChatCreateOperationId` (a client-prefixed opaque
|
||||
* key). One create/send keeps its id across a retry so the server can dedupe it.
|
||||
*/
|
||||
export function newChatOperationId() {
|
||||
const random = Math.random().toString(36).slice(2, 10);
|
||||
return `web-chat-${Date.now().toString(36)}-${random}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The OpenCode message identity carried with a prompt, mirroring the Android
|
||||
* `nativeMessageId`: the operation id's alphanumerics, prefixed `msg_` and capped
|
||||
* at 120 characters. OpenCode persists it in history, so the live user echo and
|
||||
* an authoritative history page can be reconciled; a blank operation id yields an
|
||||
* empty id (the server then supplies its own).
|
||||
*/
|
||||
export function nativeChatMessageId(operationId) {
|
||||
const compact = String(operationId ?? "")
|
||||
.replace(/[^A-Za-z0-9]/g, "")
|
||||
.slice(0, 120);
|
||||
return compact === "" ? "" : `msg_${compact}`;
|
||||
}
|
||||
|
||||
+100
@@ -1607,6 +1607,106 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* The composer at the foot of a conversation (C8/C9). The field grows 1–6 rows;
|
||||
the primary control turns from Send to Stop while a turn is in flight. */
|
||||
.chat-composer { display: grid; gap: 8px; padding-top: 6px; border-top: 1px solid var(--border); }
|
||||
.chat-queued { font-size: 12px; color: var(--muted); }
|
||||
|
||||
.chat-attachment-strip { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.chat-attachment-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 6px 4px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.chat-attachment-chip-failed {
|
||||
border-color: var(--bad);
|
||||
background: color-mix(in srgb, var(--bad) 18%, var(--surface-2));
|
||||
}
|
||||
.chat-attachment-thumb { width: 28px; height: 28px; border-radius: 4px; object-fit: cover; }
|
||||
.chat-attachment-glyph { width: 28px; text-align: center; font-size: 18px; line-height: 1; }
|
||||
.chat-attachment-body { display: grid; gap: 1px; min-width: 0; max-width: 220px; }
|
||||
.chat-attachment-name { font-size: 12px; }
|
||||
.chat-attachment-meta { font-size: 11px; color: var(--muted); }
|
||||
.chat-attachment-error { color: var(--bad); }
|
||||
.chat-attachment-remove { padding: 1px 6px; font-size: 12px; line-height: 1; }
|
||||
|
||||
.chat-command-palette {
|
||||
max-height: 176px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.chat-command-palette[hidden] { display: none; }
|
||||
.chat-command-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: baseline;
|
||||
padding: 6px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-command-row.selected { background: color-mix(in srgb, var(--accent) 18%, var(--surface-2)); }
|
||||
.chat-command-name { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
||||
.chat-command-summary { flex: 1 1 auto; font-size: 12px; color: var(--muted); }
|
||||
|
||||
.chat-command-notice {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-2);
|
||||
}
|
||||
.chat-command-notice-failed {
|
||||
border-color: var(--bad);
|
||||
background: color-mix(in srgb, var(--bad) 16%, var(--surface-2));
|
||||
}
|
||||
.chat-command-notice-head { display: flex; gap: 6px; align-items: center; }
|
||||
.chat-command-notice-glyph { font-size: 12px; color: var(--muted); }
|
||||
.chat-command-notice-failed .chat-command-notice-glyph { color: var(--bad); }
|
||||
.chat-command-notice-label { font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); }
|
||||
.chat-command-notice-failed .chat-command-notice-label { color: var(--bad); }
|
||||
.chat-command-notice-text { font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.chat-command-notice-actions { display: flex; gap: 8px; }
|
||||
.chat-command-notice-actions button { padding: 3px 10px; font-size: 12px; }
|
||||
|
||||
.chat-composer-row { display: flex; gap: 8px; align-items: flex-end; }
|
||||
.chat-file-input { display: none; }
|
||||
.chat-attach { padding: 6px 10px; font-size: 16px; line-height: 1; }
|
||||
.chat-composer-input {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
resize: none;
|
||||
padding: 8px 10px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
font: inherit;
|
||||
line-height: 20px;
|
||||
max-height: 132px;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
.chat-composer-input:focus-visible { outline: 2px solid var(--accent); outline-offset: -1px; }
|
||||
.chat-composer-primary { display: inline-flex; align-items: flex-end; }
|
||||
.chat-send, .chat-stop {
|
||||
padding: 8px 12px;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-send:not(:disabled) { border-color: var(--accent); color: var(--accent); }
|
||||
.chat-send:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.chat-stop { border-color: var(--bad); color: var(--bad); }
|
||||
|
||||
/* The rendered markdown subset. Every node is created, never parsed from HTML. */
|
||||
.markdown { display: grid; gap: 8px; min-width: 0; }
|
||||
.markdown > * { margin: 0; }
|
||||
|
||||
@@ -5,12 +5,24 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
CHAT_COMMANDS,
|
||||
CHAT_FOLLOW_THRESHOLD_PX,
|
||||
CHAT_QUEUED_NOTICE,
|
||||
COMPOSER_SEND,
|
||||
COMPOSER_STOP,
|
||||
ChatTurn,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_RENDERED_DIFF_LINES,
|
||||
TOOL_DETAIL_MAX_LENGTH,
|
||||
TOOL_LONG_RUNNING_MILLIS,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
chatBottomDistancePx,
|
||||
chatCommandEffect,
|
||||
chatCommandForEnter,
|
||||
chatCommandHelp,
|
||||
chatCommandSuggestions,
|
||||
chatFirstScroll,
|
||||
chatFollowsAt,
|
||||
chatHeaderMeta,
|
||||
@@ -18,15 +30,22 @@ import {
|
||||
chatOpensAtNewest,
|
||||
chatShowJumpToLatest,
|
||||
closeChatConfirmation,
|
||||
composerAction,
|
||||
composerCanSend,
|
||||
composerSendEnabled,
|
||||
composerSubmit,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
formatToolDuration,
|
||||
groupSessionsByDirectory,
|
||||
lineDiff,
|
||||
mergeHistoryPage,
|
||||
parseChatInput,
|
||||
partRendering,
|
||||
prettyToolInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
runningAfterFrame,
|
||||
runningToolElapsedMillis,
|
||||
sessionActivity,
|
||||
sessionActivityBadge,
|
||||
@@ -648,3 +667,211 @@ test("a chat command rejects a server error envelope with the server's own text"
|
||||
message: "unknown command: chat_messages",
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The composer and its attachments (C8)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const thread = (overrides = {}) => ({
|
||||
draft: "",
|
||||
attachments: [],
|
||||
running: false,
|
||||
queued: false,
|
||||
directory: "/tmp/work",
|
||||
...overrides,
|
||||
});
|
||||
const attachment = (overrides = {}) => ({ id: "a1", uri: "a.txt", name: "a.txt", size: 3, error: null, ...overrides });
|
||||
|
||||
test("composerAction is Stop while a turn runs and Send otherwise", () => {
|
||||
assert.equal(composerAction(thread({ running: true })), COMPOSER_STOP);
|
||||
assert.equal(composerAction(thread()), COMPOSER_SEND);
|
||||
assert.equal(composerAction(null), COMPOSER_SEND);
|
||||
});
|
||||
|
||||
test("composerCanSend requires a non-blank draft and no flagged attachment", () => {
|
||||
assert.equal(composerCanSend(thread({ draft: "hi" })), true);
|
||||
assert.equal(composerCanSend(thread({ draft: " " })), false);
|
||||
assert.equal(composerCanSend(thread({ draft: "hi", attachments: [attachment({ error: "nope" })] })), false);
|
||||
});
|
||||
|
||||
test("composerSendEnabled also allows a slash draft with a failed attachment", () => {
|
||||
assert.equal(composerSendEnabled(thread({ draft: "/help" })), true);
|
||||
assert.equal(composerSendEnabled(thread({ draft: "/help", attachments: [attachment({ error: "nope" })] })), true);
|
||||
assert.equal(composerSendEnabled(thread({ draft: "hi", attachments: [attachment({ error: "nope" })] })), false);
|
||||
assert.equal(composerSendEnabled(thread({ draft: "" })), false);
|
||||
});
|
||||
|
||||
test("composerSubmit runs an offer row, a slash draft, a send, and nothing while running", () => {
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "hello" }), 0), { kind: "send" });
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "/" }), 1), { kind: "command", text: "/close" });
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "/ren" }), 0), { kind: "command", text: "/rename" });
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "/stop" }), 0), { kind: "command", text: "/stop" });
|
||||
// While a turn runs, Enter is inert unless the palette or a slash draft is present.
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "hello", running: true }), 0), { kind: "none" });
|
||||
assert.deepEqual(composerSubmit(thread({ draft: "/stop extra", running: true }), 0), {
|
||||
kind: "command",
|
||||
text: "/stop extra",
|
||||
});
|
||||
});
|
||||
|
||||
test("queuedAfterFrame clears the queued flag on any incoming frame", () => {
|
||||
// The flag itself is set from the prompt reply's `chat_queued` (see the
|
||||
// repository test); any frame for the session then clears it, and a null frame
|
||||
// (no push) leaves it as it was.
|
||||
assert.equal(queuedAfterFrame(true, { kind: "text", session_id: "s1" }), false);
|
||||
assert.equal(queuedAfterFrame(true, { kind: "step", step: { status: "ended" } }), false);
|
||||
assert.equal(queuedAfterFrame(true, null), true);
|
||||
assert.equal(queuedAfterFrame(false, { kind: "text" }), false);
|
||||
});
|
||||
|
||||
test("runningAfterFrame settles the running bit on a step that ended", () => {
|
||||
assert.equal(runningAfterFrame(true, { kind: "step", step: { status: "ended" } }), false);
|
||||
assert.equal(runningAfterFrame(true, { kind: "step", step: { status: "started" } }), true);
|
||||
assert.equal(runningAfterFrame(true, { kind: "text" }), true);
|
||||
assert.equal(runningAfterFrame(false, { kind: "step", step: { status: "ended" } }), false);
|
||||
});
|
||||
|
||||
test("attachmentDisplayName prefers the name, then the uri's basename, then file", () => {
|
||||
assert.equal(attachmentDisplayName("Report.pdf", "content://x/y"), "Report.pdf");
|
||||
assert.equal(attachmentDisplayName("", "content:///tmp/notes.txt"), "notes.txt");
|
||||
assert.equal(attachmentDisplayName(" ", "notes.txt"), "notes.txt");
|
||||
assert.equal(attachmentDisplayName("", ""), "file");
|
||||
});
|
||||
|
||||
test("attachmentError reports an unreadable file and the 25 MiB limit by name", () => {
|
||||
assert.equal(attachmentError("a.txt", 3, true), null);
|
||||
assert.equal(attachmentError("a.txt", 3, false), '"a.txt" could not be read.');
|
||||
assert.equal(attachmentError("", 3, false), '"file" could not be read.');
|
||||
assert.equal(MAX_ATTACHMENT_BYTES, 25 * 1024 * 1024);
|
||||
assert.equal(
|
||||
attachmentError("big.bin", MAX_ATTACHMENT_BYTES + 1, true),
|
||||
'"big.bin" is too large (25.0 MiB limit).',
|
||||
);
|
||||
// Exactly at the limit is allowed; the limit reads through the shared humanBytes.
|
||||
assert.equal(attachmentError("big.bin", MAX_ATTACHMENT_BYTES, true), null);
|
||||
});
|
||||
|
||||
test("attachmentFiles keeps only the error-free attachments, in order", () => {
|
||||
assert.deepEqual(
|
||||
attachmentFiles([
|
||||
attachment({ uri: "one.txt" }),
|
||||
attachment({ uri: "bad.txt", error: "nope" }),
|
||||
attachment({ uri: "two.txt" }),
|
||||
]),
|
||||
["one.txt", "two.txt"],
|
||||
);
|
||||
assert.deepEqual(attachmentFiles([]), []);
|
||||
});
|
||||
|
||||
test("CHAT_QUEUED_NOTICE is the app's own queued sentence", () => {
|
||||
assert.equal(CHAT_QUEUED_NOTICE, "Queued — it will send when the current turn finishes.");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slash commands (C9)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("CHAT_COMMANDS is exactly the five commands with their usage and summary", () => {
|
||||
assert.deepEqual(
|
||||
CHAT_COMMANDS.map((command) => [command.name, command.usage, command.summary]),
|
||||
[
|
||||
["new", "/new", "Start a fresh session in this directory"],
|
||||
["close", "/close", "Finish this session for every client, keeping its history"],
|
||||
["rename", "/rename <title>", "Rename this session on this device"],
|
||||
["stop", "/stop", "Stop the turn that is running"],
|
||||
["help", "/help", "List every command"],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("chatCommandHelp is one `usage — summary` line per command", () => {
|
||||
assert.equal(
|
||||
chatCommandHelp(),
|
||||
"/new — Start a fresh session in this directory\n" +
|
||||
"/close — Finish this session for every client, keeping its history\n" +
|
||||
"/rename <title> — Rename this session on this device\n" +
|
||||
"/stop — Stop the turn that is running\n" +
|
||||
"/help — List every command",
|
||||
);
|
||||
});
|
||||
|
||||
test("parseChatInput recognises the five commands case-insensitively", () => {
|
||||
for (const name of ["new", "close", "rename", "stop", "help"]) {
|
||||
const parsed = parseChatInput(`/${name.toUpperCase()}`);
|
||||
assert.equal(parsed.kind, "invocation");
|
||||
assert.equal(parsed.command.name, name);
|
||||
}
|
||||
const withArg = parseChatInput("/rename My title");
|
||||
assert.equal(withArg.argument, "My title");
|
||||
assert.equal(parseChatInput("hello").kind, "plain");
|
||||
});
|
||||
|
||||
test("parseChatInput returns Unknown with the token for a slash word that is not a command", () => {
|
||||
const parsed = parseChatInput(" /nope ");
|
||||
assert.equal(parsed.kind, "unknown");
|
||||
assert.equal(parsed.token, "/nope");
|
||||
assert.equal(parsed.text, "/nope");
|
||||
});
|
||||
|
||||
test("chatCommandSuggestions offers only a bare slash word, case-insensitively by prefix", () => {
|
||||
assert.deepEqual(chatCommandSuggestions("hello"), []);
|
||||
assert.deepEqual(chatCommandSuggestions(" /rename x"), []);
|
||||
assert.deepEqual(
|
||||
chatCommandSuggestions("/").map((command) => command.name),
|
||||
["new", "close", "rename", "stop", "help"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
chatCommandSuggestions("/ST").map((command) => command.name),
|
||||
["stop"],
|
||||
);
|
||||
assert.deepEqual(chatCommandSuggestions("/c").map((command) => command.name), ["close"]);
|
||||
});
|
||||
|
||||
test("chatCommandForEnter clamps the highlighted row and is null without a list", () => {
|
||||
assert.equal(chatCommandForEnter("/", 0), "/new");
|
||||
assert.equal(chatCommandForEnter("/", 4), "/help");
|
||||
assert.equal(chatCommandForEnter("/", 99), "/new");
|
||||
assert.equal(chatCommandForEnter("/rename x", 0), null);
|
||||
assert.equal(chatCommandForEnter("hello", 0), null);
|
||||
});
|
||||
|
||||
test("chatCommandEffect routes each command to its effect", () => {
|
||||
const view = thread({ draft: "/x", directory: "/repo" });
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/new"), view), {
|
||||
kind: "start-session",
|
||||
directory: "/repo",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/close"), view), { kind: "finish-session" });
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/rename My chat"), view), {
|
||||
kind: "rename-session",
|
||||
title: "My chat",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/stop"), thread({ running: true })), { kind: "stop-turn" });
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/help"), view), { kind: "show-help" });
|
||||
assert.equal(chatCommandEffect(parseChatInput("hello"), view), null);
|
||||
});
|
||||
|
||||
test("chatCommandEffect reports the exact Android error strings", () => {
|
||||
const view = thread({ directory: "/repo" });
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/nope"), view), {
|
||||
kind: "report",
|
||||
text: "“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.",
|
||||
offer: "/nope",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/new extra"), view), {
|
||||
kind: "report",
|
||||
text: "/new does not take an argument.",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/rename"), view), {
|
||||
kind: "report",
|
||||
text: "Usage: /rename <title> — renames this session on this device.",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/stop"), thread({ running: false })), {
|
||||
kind: "report",
|
||||
text: "No turn is running in this chat.",
|
||||
});
|
||||
assert.deepEqual(chatCommandEffect(parseChatInput("/new"), thread({ directory: " " })), {
|
||||
kind: "report",
|
||||
text: "Can't start a new session here: the server reported no directory for this chat.",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { PipelinesClient, ProtocolError } from "../src/client.js";
|
||||
import { PipelinesRepository } from "../src/repository.js";
|
||||
import { PipelinesRepository, nativeChatMessageId, newChatOperationId } from "../src/repository.js";
|
||||
import { validateServerUrl } from "../src/serverUrl.js";
|
||||
|
||||
const VALID = validateServerUrl("ws://host:8080/connect");
|
||||
@@ -231,3 +231,81 @@ test("a run action throws when the reply has no run detail", async () => {
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "run" });
|
||||
await assert.rejects(() => repo.cancelRun(7), ProtocolError);
|
||||
});
|
||||
|
||||
// ---- The composer's own commands (C8/C9) ----------------------------------
|
||||
|
||||
test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt" });
|
||||
|
||||
const queued = await repo.chatPrompt("s1", " hello ", [], "op-1");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_prompt",
|
||||
chat_prompt: {
|
||||
session_id: "s1",
|
||||
text: "hello",
|
||||
operation_id: "op-1",
|
||||
native_message_id: "msg_op1",
|
||||
},
|
||||
});
|
||||
assert.equal(queued, false);
|
||||
});
|
||||
|
||||
test("chatPrompt includes files when present and reads chat_queued", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_prompt", chat_queued: true });
|
||||
|
||||
const queued = await repo.chatPrompt("s1", "hi", ["a.txt", "b.txt"], "op-2");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_prompt",
|
||||
chat_prompt: {
|
||||
session_id: "s1",
|
||||
text: "hi",
|
||||
operation_id: "op-2",
|
||||
native_message_id: "msg_op2",
|
||||
files: ["a.txt", "b.txt"],
|
||||
},
|
||||
});
|
||||
assert.equal(queued, true);
|
||||
});
|
||||
|
||||
test("chatPrompt refuses a blank session or blank text without sending", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.chatPrompt(" ", "hi", [], "op"), ProtocolError);
|
||||
await assert.rejects(() => repo.chatPrompt("s1", " ", [], "op"), ProtocolError);
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("chatInterrupt sends the session as chat_query (not a chat_interrupt body)", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_interrupt" });
|
||||
|
||||
await repo.chatInterrupt("s1");
|
||||
assert.deepEqual(lastFrame(ws), { type: "chat_interrupt", chat_query: { session_id: "s1" } });
|
||||
});
|
||||
|
||||
test("chatCreate sends title/directory/operation_id and returns chat_session", async () => {
|
||||
const { repo, ws } = connected();
|
||||
const created = { id: "ses_new", title: "New chat" };
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: created });
|
||||
|
||||
const session = await repo.chatCreate("New chat", "/repo", "op-3");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_create",
|
||||
chat_create: { title: "New chat", directory: "/repo", operation_id: "op-3" },
|
||||
});
|
||||
assert.deepEqual(session, created);
|
||||
});
|
||||
|
||||
test("chatCreate throws when the reply carries no chat_session", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_create" });
|
||||
await assert.rejects(() => repo.chatCreate("t", "/d", "op"), ProtocolError);
|
||||
});
|
||||
|
||||
test("nativeChatMessageId mirrors the Android id: msg_ + alphanumerics, capped", () => {
|
||||
assert.equal(nativeChatMessageId("web-chat-abc-123"), "msg_webchatabc123");
|
||||
assert.equal(nativeChatMessageId(""), "");
|
||||
assert.equal(nativeChatMessageId("a".repeat(300)).length, "msg_".length + 120);
|
||||
assert.match(newChatOperationId(), /^web-chat-[a-z0-9]+-[a-z0-9]+$/);
|
||||
});
|
||||
|
||||
@@ -51,6 +51,9 @@ let serve = null;
|
||||
let browser = null;
|
||||
let page = null;
|
||||
let failed = false;
|
||||
// The throwaway chat session this run creates for the running-turn capture. It
|
||||
// is closed again in cleanup; null once closed (or when none was created).
|
||||
let throwawaySessionId = null;
|
||||
|
||||
function step(label) {
|
||||
console.log(`• ${label}`);
|
||||
@@ -66,6 +69,18 @@ async function shot(name) {
|
||||
const text = (selector) =>
|
||||
page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent ?? ""`);
|
||||
|
||||
// Bring the composer at the foot of the conversation into view before a capture:
|
||||
// the transcript above it is scrollable and can be taller than the viewport, so a
|
||||
// composer-state screenshot scrolls the page to its very bottom (past the
|
||||
// composer, into the trailing padding) rather than just to the composer's edge.
|
||||
const showComposer = () =>
|
||||
page.evaluate(`new Promise((resolve) => {
|
||||
const composer = document.querySelector("#chatComposer");
|
||||
if (composer) composer.scrollIntoView({ block: "end" });
|
||||
window.scrollTo(0, document.documentElement.scrollHeight);
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
|
||||
})`);
|
||||
|
||||
// The shared live server can drop a long-lived socket while the earlier screens
|
||||
// are captured (observed as a spurious 1006 mid-run). A capture step must not
|
||||
// depend on an unasserted connection, so this nudges the page's own recovery —
|
||||
@@ -2673,6 +2688,298 @@ try {
|
||||
`${openedId}`,
|
||||
);
|
||||
|
||||
// C8/C9: the composer — its draft, the slash-command palette, an unknown-command
|
||||
// notice, the attachment chips and the Stop control while a turn is running. No
|
||||
// prompt is ever sent to the operator's live session: the running-turn capture
|
||||
// uses a freshly created throwaway session (via `/new`), which is closed again
|
||||
// in cleanup. Every other state is reached by driving the composer without
|
||||
// submitting.
|
||||
step("C8/C9: the composer, slash commands and attachments");
|
||||
await ensureConnected();
|
||||
await page.waitForSelector("#chatInput", { timeout: 15000 });
|
||||
|
||||
// (a) A draft: the placeholder, Send present and enabled, Stop absent.
|
||||
await page.fill("#chatInput", "A draft from the smoke");
|
||||
const draftState = await page.evaluate(`(() => ({
|
||||
placeholder: document.querySelector("#chatInput")?.getAttribute("placeholder") ?? "",
|
||||
send: !!document.querySelector("#chatSend"),
|
||||
sendDisabled: document.querySelector("#chatSend")?.disabled ?? null,
|
||||
sendLabel: document.querySelector("#chatSend")?.getAttribute("aria-label") ?? "",
|
||||
stop: !!document.querySelector("#chatStop"),
|
||||
}))()`);
|
||||
if (draftState.placeholder !== "Message the agent… or / for commands") {
|
||||
throw new Error(`composer placeholder: ${draftState.placeholder}`);
|
||||
}
|
||||
if (!draftState.send || draftState.sendDisabled !== false || draftState.sendLabel !== "Send") {
|
||||
throw new Error(`composer Send control: ${JSON.stringify(draftState)}`);
|
||||
}
|
||||
if (draftState.stop) throw new Error("the composer shows Stop while no turn is running");
|
||||
console.log(` composer draft: placeholder "${draftState.placeholder}", Send enabled, no Stop`);
|
||||
await showComposer();
|
||||
await shot("56-chat-composer-draft.png");
|
||||
|
||||
// (b) The command palette for a bare "/": all five commands, the first selected.
|
||||
await page.fill("#chatInput", "/");
|
||||
await page.waitForSelector(".chat-command-palette .chat-command-row", { timeout: 10000 });
|
||||
const palette = await page.evaluate(`(() => ({
|
||||
hidden: document.querySelector(".chat-command-palette")?.hidden ?? null,
|
||||
rows: [...document.querySelectorAll(".chat-command-palette .chat-command-row")].map((row) => ({
|
||||
name: row.querySelector(".chat-command-name")?.textContent ?? "",
|
||||
summary: row.querySelector(".chat-command-summary")?.textContent ?? "",
|
||||
selected: row.getAttribute("aria-selected"),
|
||||
})),
|
||||
}))()`);
|
||||
const expectedCommands = [
|
||||
["/new", "Start a fresh session in this directory"],
|
||||
["/close", "Finish this session for every client, keeping its history"],
|
||||
["/rename", "Rename this session on this device"],
|
||||
["/stop", "Stop the turn that is running"],
|
||||
["/help", "List every command"],
|
||||
];
|
||||
if (palette.hidden || palette.rows.length !== expectedCommands.length) {
|
||||
throw new Error(`command palette: ${JSON.stringify(palette)}`);
|
||||
}
|
||||
palette.rows.forEach((row, index) => {
|
||||
if (row.name !== expectedCommands[index][0] || row.summary !== expectedCommands[index][1]) {
|
||||
throw new Error(`palette row ${index}: ${JSON.stringify(row)}`);
|
||||
}
|
||||
if (row.selected !== (index === 0 ? "true" : "false")) {
|
||||
throw new Error(`palette row ${index} selected: ${row.selected}`);
|
||||
}
|
||||
});
|
||||
console.log(` command palette: ${palette.rows.map((row) => row.name).join(" ")}`);
|
||||
await showComposer();
|
||||
await shot("57-chat-command-palette.png");
|
||||
|
||||
// Up/Down move the highlight; Enter runs the highlighted row.
|
||||
const highlight = await page.evaluate(`(() => {
|
||||
const input = document.querySelector("#chatInput");
|
||||
const key = (name) => input.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));
|
||||
key("ArrowDown");
|
||||
key("ArrowDown");
|
||||
return [...document.querySelectorAll(".chat-command-palette .chat-command-row")].map((row) => row.getAttribute("aria-selected"));
|
||||
})()`);
|
||||
if (highlight[2] !== "true" || highlight[0] !== "false") {
|
||||
throw new Error(`ArrowDown did not move the highlight: ${JSON.stringify(highlight)}`);
|
||||
}
|
||||
console.log(" ArrowDown moved the highlighted command row (Enter runs it)");
|
||||
await showComposer();
|
||||
await shot("58-chat-command-palette-selected.png");
|
||||
|
||||
// Type a prefix that narrows the list case-insensitively.
|
||||
await page.fill("#chatInput", "/ST");
|
||||
const narrowedCommands = await page.evaluate(
|
||||
`[...document.querySelectorAll(".chat-command-palette .chat-command-row .chat-command-name")].map((n) => n.textContent)`,
|
||||
);
|
||||
if (narrowedCommands.length !== 1 || narrowedCommands[0] !== "/stop") {
|
||||
throw new Error(`prefix filter: ${JSON.stringify(narrowedCommands)}`);
|
||||
}
|
||||
|
||||
// (c) An unknown command: its notice with the exact wording and the offer, then
|
||||
// Cancel. The composer is driven without submitting, so no prompt is sent.
|
||||
await page.fill("#chatInput", "/nope");
|
||||
await page.evaluate(
|
||||
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
|
||||
);
|
||||
await page.waitForSelector(".chat-command-notice-failed", { timeout: 10000 });
|
||||
const notice = await page.evaluate(`(() => {
|
||||
const node = document.querySelector(".chat-command-notice-failed");
|
||||
node.scrollIntoView({ block: "center" });
|
||||
return {
|
||||
label: node.querySelector(".chat-command-notice-label")?.textContent ?? "",
|
||||
glyph: node.querySelector(".chat-command-notice-glyph")?.textContent ?? "",
|
||||
text: node.querySelector(".chat-command-notice-text")?.textContent ?? "",
|
||||
buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent),
|
||||
draft: document.querySelector("#chatInput")?.value ?? null,
|
||||
send: !!document.querySelector("#chatSend"),
|
||||
stop: !!document.querySelector("#chatStop"),
|
||||
};
|
||||
})()`);
|
||||
if (notice.label !== "Command failed") throw new Error(`notice label: ${notice.label}`);
|
||||
if (
|
||||
notice.text !==
|
||||
"“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel."
|
||||
) {
|
||||
throw new Error(`unknown-command notice text: ${notice.text}`);
|
||||
}
|
||||
if (notice.buttons.join("|") !== "Send as message|Cancel") {
|
||||
throw new Error(`unknown-command offer buttons: ${JSON.stringify(notice.buttons)}`);
|
||||
}
|
||||
if (notice.draft !== "") throw new Error(`the command did not consume the draft: ${JSON.stringify(notice.draft)}`);
|
||||
console.log(` unknown command: "${notice.text}" (offer: ${notice.buttons.join(" / ")})`);
|
||||
await shot("59-chat-command-unknown.png");
|
||||
await page.clickText(".chat-command-notice-failed button", "Cancel");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".chat-command-notice-failed")`), {
|
||||
timeout: 5000,
|
||||
what: "the unknown-command notice to be dismissed",
|
||||
});
|
||||
|
||||
// (d) Attachment chips: a small file with its size, and a file over the 25 MiB
|
||||
// limit with its error. Driving the real file input (a DataTransfer) exercises
|
||||
// the page's own resolve path; nothing is sent. An unreadable-file error cannot
|
||||
// be produced through a browser file picker, so that branch is unit-tested only
|
||||
// and stated in PARITY.md.
|
||||
await page.fill("#chatInput", "see the attachment");
|
||||
const attached = await page.evaluate(`(() => {
|
||||
const input = document.querySelector("#chatFileInput");
|
||||
if (!input) return false;
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(new File(["hello"], "notes.txt", { type: "text/plain" }));
|
||||
transfer.items.add(new File([new Uint8Array(${26 * 1024 * 1024})], "huge.bin", { type: "application/octet-stream" }));
|
||||
input.files = transfer.files;
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return true;
|
||||
})()`);
|
||||
if (!attached) throw new Error("the composer has no file input");
|
||||
await page.waitForSelector(".chat-attachment-chip", { timeout: 10000 });
|
||||
const chips = await page.evaluate(`(() => {
|
||||
document.querySelector("#chatComposer")?.scrollIntoView({ block: "end" });
|
||||
return {
|
||||
chips: [...document.querySelectorAll(".chat-attachment-chip")].map((chip) => ({
|
||||
name: chip.querySelector(".chat-attachment-name")?.textContent ?? "",
|
||||
meta: chip.querySelector(".chat-attachment-meta")?.textContent ?? "",
|
||||
error: chip.querySelector(".chat-attachment-error")?.textContent ?? "",
|
||||
failed: chip.classList.contains("chat-attachment-chip-failed"),
|
||||
remove: chip.querySelector(".chat-attachment-remove")?.getAttribute("aria-label") ?? "",
|
||||
})),
|
||||
sendDisabled: document.querySelector("#chatSend")?.disabled ?? null,
|
||||
};
|
||||
})()`);
|
||||
if (chips.chips.length !== 2) throw new Error(`attachment chips: ${JSON.stringify(chips)}`);
|
||||
if (chips.chips[0].name !== "notes.txt" || chips.chips[0].meta !== "5 B" || chips.chips[0].failed) {
|
||||
throw new Error(`small attachment chip: ${JSON.stringify(chips.chips[0])}`);
|
||||
}
|
||||
if (chips.chips[0].remove !== "Remove notes.txt") {
|
||||
throw new Error(`attachment remove label: ${chips.chips[0].remove}`);
|
||||
}
|
||||
if (
|
||||
!chips.chips[1].failed ||
|
||||
chips.chips[1].error !== '"huge.bin" is too large (25.0 MiB limit).'
|
||||
) {
|
||||
throw new Error(`oversized attachment chip: ${JSON.stringify(chips.chips[1])}`);
|
||||
}
|
||||
if (chips.sendDisabled !== true) {
|
||||
throw new Error("a failed attachment must block sending");
|
||||
}
|
||||
console.log(
|
||||
` attachment chips: "${chips.chips[0].name}" (${chips.chips[0].meta}) + a failed ` +
|
||||
`"${chips.chips[1].name}" (${chips.chips[1].error}); Send disabled`,
|
||||
);
|
||||
await showComposer();
|
||||
await shot("60-chat-attachment-chips.png");
|
||||
|
||||
// Removing the failed chip unblocks Send (the draft is non-blank).
|
||||
await page.evaluate(
|
||||
`document.querySelectorAll(".chat-attachment-chip")[1]?.querySelector(".chat-attachment-remove")?.click()`,
|
||||
);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelectorAll(".chat-attachment-chip").length === 1`),
|
||||
{ timeout: 5000, what: "the failed attachment to be removed" },
|
||||
);
|
||||
const afterRemove = await page.evaluate(`(() => ({
|
||||
sendDisabled: document.querySelector("#chatSend")?.disabled ?? null,
|
||||
chips: document.querySelectorAll(".chat-attachment-chip").length,
|
||||
}))()`);
|
||||
if (afterRemove.sendDisabled !== false) {
|
||||
throw new Error(`Send should be enabled after removing the failed chip: ${JSON.stringify(afterRemove)}`);
|
||||
}
|
||||
console.log(" removing the failed attachment re-enabled Send");
|
||||
await showComposer();
|
||||
await shot("61-chat-attachment-removed.png");
|
||||
await page.evaluate(
|
||||
`document.querySelector(".chat-attachment-remove")?.click()`,
|
||||
);
|
||||
await eventually(() => page.evaluate(`document.querySelectorAll(".chat-attachment-chip").length === 0`), {
|
||||
timeout: 5000,
|
||||
what: "the last attachment to be removed",
|
||||
});
|
||||
await page.fill("#chatInput", "");
|
||||
|
||||
// (e) `/new` creates a fresh throwaway session (C2's chat_create, sent directly
|
||||
// until C2 lands) and opens it. The operator's session is left untouched.
|
||||
await page.fill("#chatInput", "/new");
|
||||
await page.evaluate(
|
||||
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
|
||||
);
|
||||
const throwawayId = await eventually(
|
||||
async () => {
|
||||
const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`);
|
||||
return id && id !== openedId ? id : false;
|
||||
},
|
||||
{ timeout: 25000, what: "the new throwaway session to open" },
|
||||
);
|
||||
await page.waitForSelector("#chatInput", { timeout: 10000 });
|
||||
const throwawayTitle = await page.evaluate(`document.querySelector(".chat-bar-title")?.textContent ?? ""`);
|
||||
if (throwawayTitle !== "New chat") throw new Error(`new session title: ${throwawayTitle}`);
|
||||
throwawaySessionId = throwawayId;
|
||||
const startedNotice = await page.evaluate(
|
||||
`document.querySelector(".chat-command-notice .chat-command-notice-text")?.textContent ?? ""`,
|
||||
);
|
||||
if (!startedNotice.startsWith("Started a new session “")) {
|
||||
throw new Error(`/new notice: ${startedNotice}`);
|
||||
}
|
||||
console.log(` /new opened throwaway session ${throwawayId} ("${throwawayTitle}") — ${startedNotice}`);
|
||||
await showComposer();
|
||||
await shot("62-chat-new-session.png");
|
||||
|
||||
// A real prompt to the throwaway session turns the Send control into Stop.
|
||||
await page.fill("#chatInput", "Reply with exactly one word: hi");
|
||||
await page.evaluate(
|
||||
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
|
||||
);
|
||||
await page.waitForSelector("#chatStop", { timeout: 20000 });
|
||||
const running = await page.evaluate(`(() => ({
|
||||
stopLabel: document.querySelector("#chatStop")?.getAttribute("aria-label") ?? "",
|
||||
stopTitle: document.querySelector("#chatStop")?.getAttribute("title") ?? "",
|
||||
send: !!document.querySelector("#chatSend"),
|
||||
draft: document.querySelector("#chatInput")?.value ?? null,
|
||||
}))()`);
|
||||
if (running.stopLabel !== "Stop" || running.stopTitle !== "Stop" || running.send) {
|
||||
throw new Error(`the Stop control: ${JSON.stringify(running)}`);
|
||||
}
|
||||
if (running.draft !== "") throw new Error(`the sent draft was not cleared: ${JSON.stringify(running.draft)}`);
|
||||
console.log(" a real prompt to the throwaway session turned Send into the Stop control");
|
||||
await showComposer();
|
||||
await shot("63-chat-composer-stop.png");
|
||||
|
||||
// Cleanup: `/close` the throwaway through the C3 confirm. It is the only session
|
||||
// this stage mutates and it is closed again (any in-flight turn is stopped).
|
||||
await page.fill("#chatInput", "/close");
|
||||
await page.evaluate(
|
||||
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
|
||||
);
|
||||
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
|
||||
const throwawayClose = await page.evaluate(
|
||||
`document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`,
|
||||
);
|
||||
if (!throwawayClose.startsWith("Closes ")) {
|
||||
throw new Error(`throwaway close message: ${throwawayClose}`);
|
||||
}
|
||||
await page.click(".confirm-chat-close .confirm-accept");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
|
||||
timeout: 15000,
|
||||
what: "the throwaway close dialog to close",
|
||||
});
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`!!document.querySelector('.chat-row[data-session="${throwawayId}"] .chat-closed-chip')`,
|
||||
),
|
||||
{ timeout: 15000, what: "the throwaway session to show as closed" },
|
||||
);
|
||||
const closedRow = await page.evaluate(`(() => {
|
||||
const row = document.querySelector('.chat-row[data-session="${throwawayId}"]');
|
||||
row?.scrollIntoView({ block: "center" });
|
||||
return {
|
||||
closed: !!row?.querySelector(".chat-closed-chip"),
|
||||
hasClose: !!row?.querySelector(".chat-close"),
|
||||
hasReopen: !!row?.querySelector(".chat-reopen"),
|
||||
};
|
||||
})()`);
|
||||
console.log(` /close closed the throwaway session ${throwawayId} (${JSON.stringify(closedRow)})`);
|
||||
await shot("64-chat-throwaway-closed.png");
|
||||
throwawaySessionId = null;
|
||||
|
||||
console.log("\nUI SMOKE PASS");
|
||||
for (const shot of shots) console.log(` ${shot}`);
|
||||
} catch (error) {
|
||||
@@ -2688,6 +2995,28 @@ try {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Best-effort cleanup of the throwaway session this run created: if the run
|
||||
// failed before its `/close` step, close it now so it is never left open.
|
||||
if (throwawaySessionId && page) {
|
||||
try {
|
||||
await page.evaluate(`(async () => {
|
||||
const input = document.querySelector("#chatInput");
|
||||
if (!input) return;
|
||||
input.value = "/close";
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
document.querySelector(".confirm-chat-close .confirm-accept")?.click();
|
||||
})()`);
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
|
||||
timeout: 8000,
|
||||
what: "the cleanup close to finish",
|
||||
}).catch(() => {});
|
||||
console.log(` cleanup: closed the throwaway session ${throwawaySessionId}`);
|
||||
} catch {
|
||||
// the page may already be gone; the failure above is the real signal
|
||||
}
|
||||
}
|
||||
await page?.close().catch(() => {});
|
||||
await browser?.close().catch(() => {});
|
||||
serve?.kill("SIGTERM");
|
||||
|
||||
Reference in New Issue
Block a user