Merge branch 'main' into web-chat-composer
# Conflicts: # web/src/app.js # web/src/client.js # web/src/protocol.js # web/test/chat.test.mjs # web/test/repository.test.mjs # web/test/ui-smoke.mjs
This commit is contained in:
+2
-2
@@ -25,7 +25,7 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu
|
||||
| P2 | Filter + sort (status/name/updated) | client-side | done — Filter menu (name contains, Runs Any/Has runs/No runs, Last run status over the 7 server states, Clear filters) + Sort menu (Server order default, Name A–Z/Z–A, Most recent run, Fewest/Most stages, Reset); server order preserved |
|
||||
| P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | done — Summary/Graph/Source tabs; Summary shows content hash (monospace), latest version (`v{n}` or blank), created/updated, and a collapsed-by-default Versions section. Graph tab shows the browser guidance note plus the rendered workflow graph (P6) |
|
||||
| P4 | Templates gallery + template detail | `list_templates`, `validate` | done |
|
||||
| P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | todo |
|
||||
| P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | done — a template detail offers the action `Create pipeline from this template`; its dialog's title is `Create from {name}` (a blank name falling back to the template key), it has one required field labelled `New pipeline name (required)`, the note `Creates a new draft pipeline on the server from this template's source; it is not run.`, and Create/Cancel buttons (Cancel reads `Close` after a success). Create is disabled while the name is blank (whitespace counts) or while sending, and the field locks while sending and after a success. Submitting validates the template's source first (`validate`); a validation refusal shows the server's own error in the still-open dialog and sends no `submit`. A passing validate submits exactly `{type:'submit',name:<trimmed>,source:<template source>,create_only:true}`, shows `Created "{name}". It is in the Pipelines list.` and refreshes `list_pipelines` so the new row is visible; a `submit` refusal shows the server's error in the still-open dialog. The pure helpers and both request shapes are unit-tested (`test/templates.test.mjs`, `test/repository.test.mjs`). Captured against a **scratch server with its own throwaway database** (never the live one): `captures/51-template-create-dialog.png` (blank name, Create disabled), `captures/52-template-created.png` (the exact success line; Cancel now `Close`) and `captures/53-pipeline-created-list.png` (the created pipeline shown in that scratch server's Pipelines list). **The live server's pipeline list was not modified**: the create flow runs only under `ui-smoke.mjs`'s explicit `--scratch` flag, the default run sends no `submit`, and the scratch server was stopped and its database deleted afterwards |
|
||||
| P6 | Workflow graph rendering (nodes, edges, stage panes) | `get_pipeline` | done (captured 2026-10-19: nodes + labelled outcome edges + success/failure terminals, an opened stage definition pane and the expanded view — `captures/08-pipeline-graph.png`, `captures/08a-pipeline-graph-stage-pane.png`, `captures/08b-pipeline-graph-expanded.png`). Reusable `src/graph.js` (`mount` + pure helpers: layout, edges, `error*`, lanes, fit/clamp/zoom, hit-test, stage-definition fields); the definition view (every route executed, no legend) plus, since R5, a run-mode view driven by `runState` (executed/not-executed stages and routes, the Executed / Not executed legend, the live halo/elapsed badge). Pane labels match the app's own vocabulary (`Outcomes`, `Tools`) rather than the checklist's category words |
|
||||
|
||||
## Runs
|
||||
@@ -92,7 +92,7 @@ the pipeline list already carries — rather than a pluralised verb.
|
||||
| C2 | Create a chat (directory picker) | `chat_directories`, `chat_create` | todo |
|
||||
| C3 | Open / close / reopen a session | `chat_close`, `chat_reopen` | done — captured 2026-10-19: `captures/49-chat-close-confirm.png`. Selecting a row opens the conversation (see C4); an open row offers `Close chat…` and a closed row offers `Reopen`. The confirm is the Android copy verbatim: title `Close chat?`, the body naming the session title (`Closes "{title}" and marks it closed on every device. A turn that is running is stopped first. Nothing is deleted — the chat and its history are kept, and you can reopen it from the list.`), confirm `Close chat`, dismiss `Cancel`; only the confirm sends `chat_close` (and `Reopen` sends `chat_reopen`), then the list is refreshed from the server. The `Close chat…` action is offered on every open row, so its confirm is rendered from the pane's overlays **whether or not a conversation is open** — the smoke exercises the row-level path with no session selected (`ui-smoke` asserts the confirm appears and dismisses it), not only the path after opening the row. **Shown, not executed**: the live server has exactly one session — `ses_eae413f50ffeLQDExlg8cYnscN`, the operator's own — so the dialog was shown, captured and dismissed with `Cancel`; **no `chat_close` was sent** and that session was not closed or reopened by this stage |
|
||||
| C4 | History with paging / "load older" | `chat_messages` | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the opened `ses_eae413f50ffeLQDExlg8cYnscN` transcript with the `Load older messages` control beside the conversation's identity while the server reports `has_more`) and `captures/48-chat-load-older-empty.png` (after pressing it: the live session's own opaque cursor returned an empty older page, so `has_more` went false and the control disappeared — the honest result of the server's cursor, distinct from 45). The request is exactly `{type:"chat_messages",chat_query:{session_id,limit:200,cursor}}`; the newest page is read with an empty cursor and an older page with the server's own opaque `next_cursor` passed back verbatim (never interpreted), and the reply is `chat_history.{messages,next_cursor,has_more}` with an older server's bare `chat_messages` falling back to `hasMore:false`. `mergeHistoryPage` prepends an older page, dedupes by id (order-preserving, the page's copy winning) and replaces `nextCursor`/`hasMore`; the prepend itself is unit-tested (`test/chat.test.mjs`) because the live server returned no older rows. Nothing auto-loads on scroll and there is no end-of-history row |
|
||||
| C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | todo |
|
||||
| C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | done — captured 2026-10-19: `captures/56-chat-live-turn.png` (the answer text growing inside the existing single agent bubble while the reasoning step count grows), `captures/57-chat-running.png` (the running indicator: spinner + `Running a tool…` + `· 1s` + the `shell npm run build` line), `captures/58-chat-long-call.png` (a 61 s-old call tinted ` · long`), `captures/59-chat-settled.png` (the tools completed and the step ended: no indicator, the same one agent bubble). Opening a conversation attaches its shared live stream with exactly `{type:'chat_subscribe',chat_subscribe:{session_id}}` (the `chat_subscribe` field, **not** `chat_query`; internal/protocol/message.go, chat_stream.go) and folds every pushed `chat_event` into the open thread; the session is never read-only and any number of clients may watch it. `client.js` surfaces an envelope with no matching pending id as a DOM-free `frame` event (a matched reply is still resolved by id and not broadcast) and `src/app.js` folds only `chat_event` frames for a session this client has open. There is **no** `chat_unsubscribe` on the wire: the server detaches a subscription when the connection closes (chat_hub.detachClient / websocket.go), so on a socket drop the page clears its subscription set and settles every running thread, and on reconnect re-subscribes the open chat and replaces its conversation with the newest history page wholesale (`historyResync`, no stale held turn) — captured by the smoke's own reconnect. The pure fold lives in `src/chat.js` (`applyChatEvent` and helpers) and is unit-tested: a `user` frame needs a non-blank message id and text, is ignored when the id already exists and keeps the sender's `client` label (the server never echoes this client's own prompt); `text`/`reasoning` deltas append to the part their kind started (`deltaPartId`, so the two kinds can never share a part) and a live turn that spans several assistant message ids stays one `transcriptRows` agent bubble; `tool` frames merge field by field (a non-empty incoming field wins, `state.status/input/content/metadata/error` each retained when omitted, `executed` sticky, `time` retained), so a later frame never blanks what an earlier one taught; `step` runs the turn unless the status is `ended`; a `shell` frame is C11's and never marks the turn running; `usage` is not folded; any frame clears `queued`. The live badge uses the same words as the run badge — `live` while subscribed on a connected socket, `reconnecting` while the socket is coming back, `not live` when idle/refused (`chatStreamState`, unit-tested; the smoke logs all three). The running indicator (under the transcript, after the last agent turn) is a spinner plus the phase headline (`Thinking…` / `Running a tool…` / `Waiting…`) and ` · {elapsed}`, then one line per running tool with its own elapsed; a call at or past 60 s is tinted and marked ` · long`. **Replayed vs real, stated plainly**: the live server had no turn to prompt (its only session is the operator's, and this stage does not write to it), so `ui-smoke.mjs` subscribes through the real server and every history reply is real, then replays exact `chat_event` frames through the socket's own `onmessage` (a WebSocket recorder shim installed before the page's scripts via `Page.addScriptToEvaluateOnNewDocument`); the smoke log names the replayed frames and asserts the subscribe ack and history came from the real server |
|
||||
| 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` | 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), `captures/63b-chat-stop-interrupt.png` (the Stop control was **clicked**: it sent `chat_interrupt` and the page showed `Stopping the running turn…`, with no `Action failed` — the control is wired to `chat_interrupt`, never to the inert submit path) and `captures/64-chat-throwaway-closed.png` (after `/close`, the closed row plus the conversation pane left for the list). The throwaway session was created with `chat_create`, really prompted, really interrupted and closed with `chat_close`; the operator's session `ses_eae413f50ffeLQDExlg8cYnscN` was never prompted |
|
||||
|
||||
+482
-28
@@ -3,7 +3,7 @@
|
||||
// that came from the server is set with textContent, never innerHTML.
|
||||
import { PipelinesClient } from "./client.js";
|
||||
import { PipelinesRepository } from "./repository.js";
|
||||
import { PROTOCOL_VERSION } from "./protocol.js";
|
||||
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
|
||||
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
|
||||
import {
|
||||
ForegroundAction,
|
||||
@@ -78,6 +78,15 @@ import {
|
||||
runFiltersActiveCount,
|
||||
} from "./runs.js";
|
||||
import {
|
||||
CREATE_ACTION_LABEL,
|
||||
CREATE_NAME_LABEL,
|
||||
CREATE_NOTE,
|
||||
createConfirmLabel,
|
||||
createDismissLabel,
|
||||
createFormTitle,
|
||||
createFormValid,
|
||||
createSuccessMessage,
|
||||
createdPipelineName,
|
||||
effectiveStageType,
|
||||
templateCard,
|
||||
templateDetailName,
|
||||
@@ -224,6 +233,7 @@ import {
|
||||
LOAD_OLDER_ACTION,
|
||||
REOPEN_ACTION,
|
||||
SELECT_CHAT_HINT,
|
||||
applyChatEvent,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
@@ -237,6 +247,7 @@ import {
|
||||
chatNoMatchMessage,
|
||||
chatOpensAtNewest,
|
||||
chatShowJumpToLatest,
|
||||
chatStreamState,
|
||||
closeChatConfirmation,
|
||||
composerAction,
|
||||
composerCanSend,
|
||||
@@ -245,7 +256,9 @@ import {
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
groupSessionsByDirectory,
|
||||
historyResync,
|
||||
mergeHistoryPage,
|
||||
newChatThread,
|
||||
parseChatInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
@@ -258,16 +271,26 @@ import {
|
||||
sessionStatusLabel,
|
||||
sessionTitle,
|
||||
sessionWorkLabel,
|
||||
settledThread,
|
||||
formatToolDuration,
|
||||
threadElapsedMillis,
|
||||
threadPhase,
|
||||
threadRunningTools,
|
||||
threadToolElapsedMillis,
|
||||
TURN_PHASE_WAITING,
|
||||
toolCallCount,
|
||||
toolCallRow,
|
||||
toolCallsAnnouncement,
|
||||
toolCallsLabel,
|
||||
toolDetail,
|
||||
toolFailed,
|
||||
toolLabel,
|
||||
toolLongRunning,
|
||||
toolRunning,
|
||||
toolsRunning,
|
||||
transcriptRows,
|
||||
turnElapsedMillis,
|
||||
turnPhaseLabel,
|
||||
} from "./chat.js";
|
||||
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
|
||||
|
||||
@@ -350,6 +373,16 @@ const state = {
|
||||
templateGraphs: new Map(),
|
||||
selectedTemplateKey: null,
|
||||
templateTab: "summary",
|
||||
// The create-from-template dialog (P5): whether it is open, the name being
|
||||
// typed, whether a validate+submit is in flight, the server's refusal text and
|
||||
// the created pipeline's name (null until a success, which is also what makes
|
||||
// Cancel read Close and the field lock). The dialog validates the template's
|
||||
// source first, then submits it create-only; nothing runs.
|
||||
templateCreateOpen: false,
|
||||
templateCreateName: "",
|
||||
templateCreateSending: false,
|
||||
templateCreateError: "",
|
||||
templateCreateCreated: null,
|
||||
loading: false,
|
||||
error: "",
|
||||
runFilters: defaultRunFilters(),
|
||||
@@ -434,6 +467,12 @@ const state = {
|
||||
// report for a refused close/reopen.
|
||||
chatClose: null,
|
||||
chatBusy: false,
|
||||
// C5: the session ids this connection currently has subscribed to their shared
|
||||
// live stream. The server detaches a subscription when the connection closes
|
||||
// (there is no chat_unsubscribe), so this is cleared on every socket drop and
|
||||
// re-established for the open chat on reconnect. A refused subscription simply
|
||||
// never joins the set, so the badge reads "not live" honestly.
|
||||
chatSubscriptions: new Set(),
|
||||
};
|
||||
|
||||
let runPoll = null;
|
||||
@@ -451,6 +490,12 @@ let listNow = Date.now();
|
||||
let detailClock = null;
|
||||
let detailNow = Date.now();
|
||||
|
||||
// The chat running indicator's own live clock (C5): it ticks once a second only
|
||||
// while the open conversation has a turn in flight, updating just the indicator
|
||||
// in place (never a full re-render), so the transcript's scroll is not disturbed.
|
||||
let chatClock = null;
|
||||
let chatNow = Date.now();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DOM helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -912,8 +957,10 @@ function renderContent() {
|
||||
afterChatRender();
|
||||
stopListClock();
|
||||
stopDetailClock();
|
||||
refreshChatClock();
|
||||
return;
|
||||
}
|
||||
stopChatClock();
|
||||
if (state.view === "runs") {
|
||||
refreshListClock();
|
||||
refreshDetailClock();
|
||||
@@ -1320,6 +1367,7 @@ function renderTemplateDetail() {
|
||||
return pane;
|
||||
}
|
||||
const graph = templateGraphFor(entry.key);
|
||||
pane.append(renderTemplateDetailActions());
|
||||
pane.append(
|
||||
h(
|
||||
"div",
|
||||
@@ -1332,9 +1380,190 @@ function renderTemplateDetail() {
|
||||
if (state.templateTab === "graph") pane.append(renderTemplateGraphTab(graph));
|
||||
else if (state.templateTab === "source") pane.append(renderTemplateSourceTab(entry, graph));
|
||||
else pane.append(renderTemplateSummaryTab(entry, graph));
|
||||
if (state.templateCreateOpen) pane.append(renderTemplateCreateDialog(entry));
|
||||
return pane;
|
||||
}
|
||||
|
||||
/**
|
||||
* The template detail's action row: the one "Create pipeline from this
|
||||
* template" action (P5), matching the app's top-bar add action. It opens the
|
||||
* dialog; it never submits on its own.
|
||||
*/
|
||||
function renderTemplateDetailActions() {
|
||||
return h(
|
||||
"div",
|
||||
{ class: "detail-actions" },
|
||||
h("button", {
|
||||
class: "ghost template-create-open",
|
||||
type: "button",
|
||||
text: CREATE_ACTION_LABEL,
|
||||
onclick: () => openTemplateCreateDialog(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Open the create dialog with a fresh, empty name; nothing is sent until Create. */
|
||||
function openTemplateCreateDialog() {
|
||||
state.templateCreateOpen = true;
|
||||
state.templateCreateName = "";
|
||||
state.templateCreateSending = false;
|
||||
state.templateCreateError = "";
|
||||
state.templateCreateCreated = null;
|
||||
renderContent();
|
||||
document.querySelector(".template-create-name")?.focus();
|
||||
}
|
||||
|
||||
/** Dismiss the create dialog (never while a validate+submit is in flight). */
|
||||
function closeTemplateCreateDialog() {
|
||||
if (state.templateCreateSending) return;
|
||||
state.templateCreateOpen = false;
|
||||
state.templateCreateName = "";
|
||||
state.templateCreateError = "";
|
||||
state.templateCreateCreated = null;
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* The create dialog (P5): the title, the one required name field, the note, the
|
||||
* server's refusal text or the success line, and Create/Cancel (Cancel reads
|
||||
* Close after a success). Create is disabled while the name is blank or while
|
||||
* sending; the field locks while sending and after a success. Every server
|
||||
* string is set with textContent.
|
||||
*/
|
||||
function renderTemplateCreateDialog(entry) {
|
||||
const title = createFormTitle(entry);
|
||||
const overlay = h("div", {
|
||||
class: "template-create-dialog",
|
||||
role: "dialog",
|
||||
"aria-modal": "true",
|
||||
"aria-label": title,
|
||||
});
|
||||
overlay.addEventListener("click", (event) => {
|
||||
if (event.target === overlay) closeTemplateCreateDialog();
|
||||
});
|
||||
const panel = h("div", { class: "template-create-panel" });
|
||||
panel.append(h("h2", { class: "template-create-title", text: title }));
|
||||
|
||||
const field = h("label", { class: "template-create-field" });
|
||||
field.append(h("span", { class: "template-create-label", text: CREATE_NAME_LABEL }));
|
||||
field.append(
|
||||
h("input", {
|
||||
class: "template-create-name",
|
||||
type: "text",
|
||||
value: state.templateCreateName,
|
||||
spellcheck: "false",
|
||||
autocomplete: "off",
|
||||
disabled: state.templateCreateSending || state.templateCreateCreated != null,
|
||||
oninput: (event) => {
|
||||
// Update in place (no re-render) so the field keeps focus and its caret;
|
||||
// only the confirm button's enabled state depends on the name.
|
||||
state.templateCreateName = event.target.value;
|
||||
const confirm = overlay.querySelector(".template-create-confirm");
|
||||
if (confirm) {
|
||||
confirm.disabled = !createFormValid(state.templateCreateName, {
|
||||
sending: state.templateCreateSending,
|
||||
created: state.templateCreateCreated,
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
panel.append(field);
|
||||
panel.append(h("p", { class: "template-create-note muted", text: CREATE_NOTE }));
|
||||
if (state.templateCreateError) {
|
||||
panel.append(h("div", { class: "template-create-error bad", text: state.templateCreateError }));
|
||||
}
|
||||
if (state.templateCreateCreated != null) {
|
||||
panel.append(
|
||||
h("div", {
|
||||
class: "template-create-success",
|
||||
text: createSuccessMessage(state.templateCreateCreated),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const actions = h("div", { class: "template-create-actions" });
|
||||
actions.append(
|
||||
h("button", {
|
||||
class: "ghost template-create-cancel",
|
||||
type: "button",
|
||||
text: createDismissLabel(state.templateCreateCreated),
|
||||
disabled: state.templateCreateSending,
|
||||
onclick: closeTemplateCreateDialog,
|
||||
}),
|
||||
);
|
||||
actions.append(
|
||||
h("button", {
|
||||
class: "template-create-confirm",
|
||||
type: "button",
|
||||
text: createConfirmLabel(state.templateCreateSending),
|
||||
disabled: !createFormValid(state.templateCreateName, {
|
||||
sending: state.templateCreateSending,
|
||||
created: state.templateCreateCreated,
|
||||
}),
|
||||
onclick: () => createFromTemplate(entry),
|
||||
}),
|
||||
);
|
||||
panel.append(actions);
|
||||
overlay.append(panel);
|
||||
return overlay;
|
||||
}
|
||||
|
||||
/**
|
||||
* The P5 submit flow, exactly the app's: validate the template's source first
|
||||
* and, when the server refuses to parse it, show its own error in the dialog and
|
||||
* send nothing; otherwise submit the source create-only with the chosen name. On
|
||||
* success remember the created name, refresh the pipeline list so the new row is
|
||||
* visible and leave the dialog open (Cancel now reads Close); on failure show
|
||||
* the server's error without closing.
|
||||
*/
|
||||
async function createFromTemplate(entry) {
|
||||
if (
|
||||
!createFormValid(state.templateCreateName, {
|
||||
sending: state.templateCreateSending,
|
||||
created: state.templateCreateCreated,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const name = state.templateCreateName;
|
||||
state.templateCreateSending = true;
|
||||
state.templateCreateError = "";
|
||||
renderContent();
|
||||
try {
|
||||
await repo.validate(entry.source);
|
||||
} catch (error) {
|
||||
state.templateCreateSending = false;
|
||||
state.templateCreateError = describeError(error);
|
||||
renderContent();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const detail = await repo.submit(name, entry.source);
|
||||
state.templateCreateSending = false;
|
||||
state.templateCreateCreated = createdPipelineName(detail, name);
|
||||
await refreshPipelines();
|
||||
} catch (error) {
|
||||
state.templateCreateSending = false;
|
||||
state.templateCreateError = describeError(error);
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh just the pipeline summaries after a create so the new row appears when
|
||||
* the operator returns to the Pipelines list. A failed refresh keeps the created
|
||||
* name and is surfaced through the banner rather than discarded.
|
||||
*/
|
||||
async function refreshPipelines() {
|
||||
try {
|
||||
state.pipelines = await repo.listPipelines();
|
||||
state.pipelinesLoaded = true;
|
||||
} catch (error) {
|
||||
state.error = describeError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function templateTabButton(tab, label) {
|
||||
return h("button", {
|
||||
class: `minitab${state.templateTab === tab ? " active" : ""}`,
|
||||
@@ -1586,7 +1815,7 @@ function renderRunToolbar() {
|
||||
function renderLiveBadge(info) {
|
||||
return h(
|
||||
"span",
|
||||
{ class: `live-badge live-${info.tone}`, title: "Live run stream" },
|
||||
{ class: `live-badge live-${info.tone}`, title: info.title ?? "Live run stream" },
|
||||
h("span", { class: "live-dot", "aria-hidden": "true" }),
|
||||
h("span", { class: "live-word", text: info.label }),
|
||||
);
|
||||
@@ -3342,7 +3571,7 @@ async function loadChatSessions(force = false) {
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/** Open a session: select it and load its newest history page. */
|
||||
/** Open a session: select it, subscribe its stream and load its newest history page. */
|
||||
async function openChatSession(id) {
|
||||
if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return;
|
||||
// Remember where the operator left the conversation being closed.
|
||||
@@ -3356,21 +3585,22 @@ async function openChatSession(id) {
|
||||
state.chatToolRows = new Set();
|
||||
const existing = state.chatThreads.get(id);
|
||||
state.chatThreads.set(id, {
|
||||
...newChatThread(id),
|
||||
...(existing ?? {}),
|
||||
// The composer's own per-chat state (C8/C9) survives a switch; the draft is
|
||||
// seeded from localStorage on the first open (the per-device analogue).
|
||||
// seeded from localStorage on the first open (the per-device analogue). The
|
||||
// live-stream fields (C5) come from `newChatThread`.
|
||||
draft: existing ? existing.draft ?? "" : readChatDraft(id),
|
||||
attachments: existing?.attachments ?? [],
|
||||
notices: existing?.notices ?? [],
|
||||
queued: existing?.queued ?? false,
|
||||
running: existing?.running ?? false,
|
||||
messages: existing?.messages ?? [],
|
||||
nextCursor: existing?.nextCursor ?? "",
|
||||
hasMore: existing?.hasMore ?? false,
|
||||
loaded: false,
|
||||
loading: true,
|
||||
error: "",
|
||||
});
|
||||
renderContent();
|
||||
// Attach the shared live stream once per session per connection; its failure is
|
||||
// non-fatal — history stays usable and the badge reads "not live".
|
||||
subscribeChatSession(id);
|
||||
await loadChatHistory(id);
|
||||
}
|
||||
|
||||
@@ -3381,9 +3611,78 @@ function setThread(sessionId, patch) {
|
||||
state.chatThreads.set(sessionId, { ...current, ...patch });
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach one session's shared live stream (C5): `chat_subscribe` with the session
|
||||
* id as the body. Idempotent per connection — a session already subscribed is not
|
||||
* asked for again. A refusal (an older server that does not know the command, or
|
||||
* any other error) leaves history usable and the live badge `not live`.
|
||||
*/
|
||||
async function subscribeChatSession(id) {
|
||||
if (!id || state.connection.kind !== "connected") return;
|
||||
if (state.chatSubscriptions.has(id)) return;
|
||||
try {
|
||||
await repo.subscribeChat(id);
|
||||
state.chatSubscriptions = new Set(state.chatSubscriptions).add(id);
|
||||
} catch {
|
||||
// The subscription is not live; nothing else changes. The badge says so.
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/** Drop the per-connection subscriptions (the server detaches them on close). */
|
||||
function clearChatSubscriptions() {
|
||||
if (state.chatSubscriptions.size > 0) state.chatSubscriptions = new Set();
|
||||
}
|
||||
|
||||
/**
|
||||
* Settle every conversation that was running. A socket drop (or a close) removes
|
||||
* the frames feeding the turn, so no thread keeps claiming to run until a fresh
|
||||
* frame proves otherwise.
|
||||
*/
|
||||
function settleChatThreads() {
|
||||
for (const [id, thread] of state.chatThreads) {
|
||||
if (thread?.running || thread?.queued) state.chatThreads.set(id, settledThread(thread));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one pushed `chat_event` frame into its conversation. Only a conversation
|
||||
* this client has open is folded (a frame for a session nobody opened is
|
||||
* ignored); the server only pushes frames for sessions this connection subscribed
|
||||
* to, so this is a no-op in practice until a chat is opened.
|
||||
*/
|
||||
function onChatEvent(frame) {
|
||||
const sessionId = String(frame?.session_id ?? "").trim();
|
||||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now()));
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* The reconnect repair (C5): re-attach the open chat's stream and replace its
|
||||
* conversation with the newest history page wholesale. Everything the gap could
|
||||
* have missed is repaired; a turn that was in flight is settled. Only the open
|
||||
* conversation is repaired — the others are not on screen.
|
||||
*/
|
||||
async function resyncOpenChat() {
|
||||
const id = state.chatActiveId;
|
||||
if (!id || state.connection.kind !== "connected") return;
|
||||
await subscribeChatSession(id);
|
||||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||||
state.chatThreads.set(id, settledThread(previous));
|
||||
try {
|
||||
const page = await repo.chatHistory(id);
|
||||
state.chatThreads.set(id, historyResync(previous, page));
|
||||
} catch {
|
||||
// The history refresh failed; the settled thread stands and the badge is honest.
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/** Load (or reload) a session's newest history page and merge it in. */
|
||||
async function loadChatHistory(id) {
|
||||
const previous = state.chatThreads.get(id) ?? { messages: [] };
|
||||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||||
try {
|
||||
const page = await repo.chatHistory(id);
|
||||
// The merged page replaces only the history fields; spreading it over the
|
||||
@@ -3442,12 +3741,20 @@ async function acceptChatClose(session) {
|
||||
try {
|
||||
const { session: updated } = await repo.closeChat(session.id);
|
||||
applyChatSessionUpdate(session.id, updated, true);
|
||||
// Closing finishes the session for every client: the turn is stopped and the
|
||||
// conversation leaves the pane, back to the list (mirrors Android's
|
||||
// `finishSession` calling `chatStore.close`). A rejection above leaves the
|
||||
// conversation exactly as it was.
|
||||
// A closed chat's turn was stopped on the server: settle its conversation and
|
||||
// stop treating it as a live subscription. Nothing is deleted and it can be
|
||||
// reopened from the list.
|
||||
const thread = state.chatThreads.get(session.id);
|
||||
if (thread) state.chatThreads.set(session.id, settledThread(thread));
|
||||
if (state.chatSubscriptions.has(session.id)) {
|
||||
state.chatSubscriptions = new Set(state.chatSubscriptions);
|
||||
state.chatSubscriptions.delete(session.id);
|
||||
}
|
||||
// Closing also finishes the session for this client: the conversation leaves
|
||||
// the pane, back to the list (mirrors Android's `finishSession` calling
|
||||
// `chatStore.close`). A rejection above leaves the conversation exactly as it
|
||||
// was; `settledThread` has already cleared the running/queued bits.
|
||||
if (state.chatActiveId === session.id) {
|
||||
setThread(session.id, { running: false, queued: false });
|
||||
state.chatActiveId = null;
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -4089,6 +4396,14 @@ function renderChatConversation() {
|
||||
text: sessionStatusLabel(thread?.running === true, session?.closed === true),
|
||||
}),
|
||||
);
|
||||
// The live-stream badge (C5): live while this session is subscribed, the same
|
||||
// words as the run badge (`live` / `reconnecting` / `not live`).
|
||||
context.append(
|
||||
renderLiveBadge({
|
||||
...chatStreamState(state.connection.kind, state.chatSubscriptions.has(state.chatActiveId)),
|
||||
title: "Live chat stream",
|
||||
}),
|
||||
);
|
||||
const contextMeta = [session?.directory, session?.model]
|
||||
.map((value) => String(value ?? "").trim())
|
||||
.filter((value) => value !== "")
|
||||
@@ -4112,10 +4427,11 @@ function renderChatConversation() {
|
||||
pane.append(empty);
|
||||
} else {
|
||||
const rows = transcriptRows(thread?.messages ?? []);
|
||||
if (rows.length === 0 && notices.length === 0) {
|
||||
const running = thread?.running === true;
|
||||
if (rows.length === 0 && notices.length === 0 && !running) {
|
||||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
|
||||
} else {
|
||||
pane.append(renderChatTranscript(state.chatActiveId, rows, notices));
|
||||
pane.append(renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now() }));
|
||||
}
|
||||
if (thread?.error && thread?.loaded) {
|
||||
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
|
||||
@@ -4147,17 +4463,30 @@ 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, notices = []) {
|
||||
function renderChatTranscript(sessionId, rows, { notices = [], running = false, now = Date.now() } = {}) {
|
||||
const wrap = h("div", { class: "chat-transcript-wrap" });
|
||||
const transcript = h("div", {
|
||||
class: "chat-transcript",
|
||||
id: "chatTranscript",
|
||||
"data-session": sessionId,
|
||||
});
|
||||
for (const row of rows) {
|
||||
const thread = state.chatThreads.get(sessionId) ?? null;
|
||||
let lastAgent = -1;
|
||||
rows.forEach((row, index) => {
|
||||
if (row.kind === "agent") lastAgent = index;
|
||||
});
|
||||
rows.forEach((row, index) => {
|
||||
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
|
||||
else transcript.append(renderChatAgentTurn(row.turn));
|
||||
}
|
||||
else {
|
||||
const streaming = running && index === lastAgent;
|
||||
const elapsed = (part) => threadToolElapsedMillis(thread, part, now);
|
||||
transcript.append(renderChatAgentTurn(row.turn, streaming, elapsed));
|
||||
}
|
||||
});
|
||||
// The running indicator sits under the transcript, after the last agent turn:
|
||||
// a spinner, the phase headline, the turn's elapsed, then one line per running
|
||||
// tool (a call over 60 s is tinted and marked `· long`).
|
||||
if (running && thread) transcript.append(renderChatRunningIndicator(thread, now));
|
||||
// The conversation's local command lines sit after the turns, full width and
|
||||
// deliberately unlike a message bubble (see ChatCommandNoticeItem).
|
||||
for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice));
|
||||
@@ -4180,6 +4509,53 @@ function renderChatTranscript(sessionId, rows, notices = []) {
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
|
||||
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
|
||||
* with its own elapsed. A call that has passed [TOOL_LONG_RUNNING_MILLIS] is
|
||||
* tinted and marked `· long` — the same threshold the tool chip uses.
|
||||
*/
|
||||
function renderChatRunningIndicator(thread, now) {
|
||||
const wrap = h("div", { class: "chat-running", id: "chatRunning" });
|
||||
const head = h("div", { class: "chat-running-head" });
|
||||
head.append(h("span", { class: "spinner chat-running-spinner", "aria-hidden": "true" }));
|
||||
head.append(
|
||||
h("span", {
|
||||
class: "chat-running-label",
|
||||
text: turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING),
|
||||
}),
|
||||
);
|
||||
head.append(
|
||||
h("span", {
|
||||
class: "chat-running-elapsed",
|
||||
text: `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`,
|
||||
}),
|
||||
);
|
||||
wrap.append(head);
|
||||
for (const part of threadRunningTools(thread.messages)) {
|
||||
wrap.append(renderChatRunningTool(thread, part, now));
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function renderChatRunningTool(thread, part, now) {
|
||||
const line = h("div", { class: "chat-running-tool", "data-part-id": String(part?.id ?? "") });
|
||||
const name = toolLabel(part);
|
||||
const detail = toolDetail(part);
|
||||
line.append(h("span", { class: "chat-running-tool-text", text: detail == null ? name : `${name} ${detail}` }));
|
||||
line.append(
|
||||
h("span", {
|
||||
class: "chat-running-tool-elapsed muted",
|
||||
text: formatToolDuration(threadToolElapsedMillis(thread, part, now)),
|
||||
}),
|
||||
);
|
||||
if (toolLongRunning(threadToolElapsedMillis(thread, part, now))) {
|
||||
line.classList.add("chat-running-tool-long");
|
||||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
/** One operator turn, right-aligned, carrying its sender label when present. */
|
||||
function renderChatUserMessage(message) {
|
||||
const turn = h("div", { class: "chat-turn chat-turn-user" });
|
||||
@@ -4197,13 +4573,13 @@ function renderChatUserMessage(message) {
|
||||
}
|
||||
|
||||
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
|
||||
function renderChatAgentTurn(turn, streaming = false) {
|
||||
function renderChatAgentTurn(turn, streaming = false, elapsedMillis = () => 0) {
|
||||
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
|
||||
const bubble = h("div", { class: "chat-bubble agent-bubble" });
|
||||
const steps = turn.reasoningSteps;
|
||||
if (steps.length > 0) bubble.append(renderChatReasoning(turn, streaming));
|
||||
if (turn.tools.length > 0) {
|
||||
const tools = renderChatToolCalls(turn, { streaming });
|
||||
const tools = renderChatToolCalls(turn, { streaming, elapsedMillis });
|
||||
if (tools) bubble.append(tools);
|
||||
}
|
||||
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
|
||||
@@ -5497,6 +5873,13 @@ async function validateTemplate(entry) {
|
||||
function selectTemplate(key) {
|
||||
state.selectedTemplateKey = key;
|
||||
state.templateTab = "summary";
|
||||
// A different template reseeds the create dialog, so a name typed for one
|
||||
// template can never be submitted against another.
|
||||
state.templateCreateOpen = false;
|
||||
state.templateCreateName = "";
|
||||
state.templateCreateSending = false;
|
||||
state.templateCreateError = "";
|
||||
state.templateCreateCreated = null;
|
||||
renderContent();
|
||||
}
|
||||
|
||||
@@ -5617,6 +6000,53 @@ function stopDetailClock() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)start the chat indicator's clock: it ticks once a second only while the
|
||||
* open conversation has a turn in flight, updating the phase, the elapsed and the
|
||||
* per-tool `· long` marks in place (never a full re-render).
|
||||
*/
|
||||
function refreshChatClock() {
|
||||
stopChatClock();
|
||||
chatNow = Date.now();
|
||||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||||
if (state.view === "chat" && thread?.running) {
|
||||
chatClock = setInterval(() => {
|
||||
chatNow = Date.now();
|
||||
updateChatIndicator(chatNow);
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function stopChatClock() {
|
||||
if (chatClock) {
|
||||
clearInterval(chatClock);
|
||||
chatClock = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh the running indicator in place from the thread's own state at [now]. */
|
||||
function updateChatIndicator(now) {
|
||||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||||
const el = document.getElementById("chatRunning");
|
||||
if (!thread?.running || !el) return;
|
||||
const label = el.querySelector(".chat-running-label");
|
||||
if (label) label.textContent = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING);
|
||||
const elapsed = el.querySelector(".chat-running-elapsed");
|
||||
if (elapsed) elapsed.textContent = `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`;
|
||||
for (const part of threadRunningTools(thread.messages)) {
|
||||
const line = el.querySelector(`.chat-running-tool[data-part-id="${String(part?.id ?? "")}"]`);
|
||||
if (!line) continue;
|
||||
const age = threadToolElapsedMillis(thread, part, now);
|
||||
const toolElapsed = line.querySelector(".chat-running-tool-elapsed");
|
||||
if (toolElapsed) toolElapsed.textContent = formatToolDuration(age);
|
||||
const mark = line.querySelector(".chat-tool-long");
|
||||
if (toolLongRunning(age) && !mark) {
|
||||
line.classList.add("chat-running-tool-long");
|
||||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Boot
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -5633,15 +6063,34 @@ client.addEventListener("state", (event) => {
|
||||
stopRunPoll();
|
||||
stopListClock();
|
||||
stopDetailClock();
|
||||
stopChatClock();
|
||||
// The socket dropped: the server detaches every chat subscription with it
|
||||
// (there is no chat_unsubscribe), and the frames feeding any running turn are
|
||||
// gone, so no thread keeps claiming to run until a fresh frame proves it.
|
||||
clearChatSubscriptions();
|
||||
settleChatThreads();
|
||||
}
|
||||
// A reconnect (not a first connect): re-attach the open chat's stream and
|
||||
// refresh its history wholesale, so a gap that swallowed the end of a turn is
|
||||
// repaired rather than shown stale.
|
||||
if (next.kind === "connected" && (previousKind === "connecting" || previousKind === "disconnected")) {
|
||||
resyncOpenChat();
|
||||
}
|
||||
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 client surfaces every unsolicited envelope as a DOM-free `frame` event
|
||||
// (client.js). A `chat_event` frame is folded twice, on purpose: the live
|
||||
// transcript (C5) folds the frame itself, and the composer's own bookkeeping
|
||||
// clears the queued notice and releases the Stop control. A frame for any other
|
||||
// type is ignored.
|
||||
client.addEventListener("frame", (event) => {
|
||||
const message = event.detail;
|
||||
if (!message || message.type !== Protocol.CHAT_EVENT) return;
|
||||
const frame = message[ChatKeys.EVENT];
|
||||
if (frame) onChatEvent(frame);
|
||||
onChatFrame(message);
|
||||
});
|
||||
|
||||
// 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
|
||||
@@ -5657,6 +6106,11 @@ document.addEventListener("keydown", (event) => {
|
||||
return;
|
||||
}
|
||||
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
|
||||
if (state.templateCreateOpen) {
|
||||
event.preventDefault();
|
||||
closeTemplateCreateDialog();
|
||||
return;
|
||||
}
|
||||
if (state.actionError) {
|
||||
event.preventDefault();
|
||||
dismissActionError();
|
||||
|
||||
+353
@@ -747,6 +747,359 @@ export function mergeHistoryPage(previous, page, { older = false } = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Live stream folding (ChatStore.kt event/applyRemoteUser/applyDelta/applyTool,
|
||||
// ChatFormat.kt deltaPartId/mergeToolPart/turnPhase)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** ChatEvent.Kind values pushed on the `chat_event` stream (internal/protocol/chat.go). */
|
||||
export const EVENT_STEP = "step";
|
||||
export const EVENT_USAGE = "usage";
|
||||
export const EVENT_USER = "user";
|
||||
export const EVENT_SHELL = "shell";
|
||||
|
||||
/** ChatStep.Status values. `ended` is the one status that settles a turn. */
|
||||
export const STEP_ENDED = "ended";
|
||||
|
||||
/**
|
||||
* How recently a text or reasoning delta must have arrived for a turn to read as
|
||||
* still thinking. Long enough that the indicator's tick cannot flicker between
|
||||
* thinking and waiting on a steady stream, short enough that a stalled turn
|
||||
* starts reading as waiting while the operator still wonders.
|
||||
*/
|
||||
export const TURN_THINKING_WINDOW_MILLIS = 2500;
|
||||
|
||||
/** The three things an in-flight turn can be doing (ChatFormat.kt TurnPhase). */
|
||||
export const TURN_PHASE_THINKING = "thinking";
|
||||
export const TURN_PHASE_TOOL = "tool";
|
||||
export const TURN_PHASE_WAITING = "waiting";
|
||||
|
||||
/**
|
||||
* The live-stream badge words, shared verbatim with `liveBadgeState` /
|
||||
* RunStream.kt: the stream is `live` only while a session is subscribed on a
|
||||
* connected socket, `reconnecting` while the socket is coming back (pushes are
|
||||
* paused in the gap) and `not live` when idle or when the server refused the
|
||||
* subscription. The word always carries the meaning, so colour is never the only
|
||||
* signal.
|
||||
*/
|
||||
export const STREAM_LIVE = "live";
|
||||
export const STREAM_RECONNECTING = "reconnecting";
|
||||
export const STREAM_OFFLINE = "not live";
|
||||
|
||||
/** The badge for [connectionKind] (`connected`/`connecting`/`disconnected`/`idle`). */
|
||||
export function chatStreamState(connectionKind, subscribed) {
|
||||
if (connectionKind === "connected" && subscribed) return { tone: "live", label: STREAM_LIVE };
|
||||
if (connectionKind === "connecting" || connectionKind === "disconnected") {
|
||||
return { tone: "reconnecting", label: STREAM_RECONNECTING };
|
||||
}
|
||||
return { tone: "not-live", label: STREAM_OFFLINE };
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape an open conversation holds. The first six fields are the ones a
|
||||
* history page fills; the rest is the live stream (see `ChatThread` in
|
||||
* ChatStore.kt). A Map is deliberately not used for [toolStartedAt] so a thread
|
||||
* stays a plain, comparable value.
|
||||
*/
|
||||
export function newChatThread(sessionId = "") {
|
||||
return {
|
||||
sessionId,
|
||||
messages: [],
|
||||
nextCursor: "",
|
||||
hasMore: false,
|
||||
loaded: false,
|
||||
loading: false,
|
||||
error: "",
|
||||
running: false,
|
||||
runningSince: 0,
|
||||
toolStartedAt: {},
|
||||
lastDeltaAt: 0,
|
||||
queued: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The settled form of a thread: no turn is in flight, so the elapsed stamps and
|
||||
* the queued flag are cleared. The one place a thread stops running, so the
|
||||
* indicator and its stamps can never disagree. A no-op (returns [thread]) when it
|
||||
* was already settled.
|
||||
*/
|
||||
export function settledThread(thread) {
|
||||
return {
|
||||
...(thread ?? {}),
|
||||
running: false,
|
||||
runningSince: 0,
|
||||
toolStartedAt: {},
|
||||
lastDeltaAt: 0,
|
||||
queued: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Applies a running transition, stamping `runningSince` the moment it begins. */
|
||||
export function setThreadRunning(thread, running, now) {
|
||||
if (running) return thread.running ? thread : { ...thread, running: true, runningSince: now };
|
||||
return settledThread({ ...thread });
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it has
|
||||
* settled. Pure, so the running indicator and its unit test share the derivation.
|
||||
*/
|
||||
export function threadElapsedMillis(thread, nowMillis) {
|
||||
const since = Number(thread?.runningSince) || 0;
|
||||
return thread?.running && since >= 1 && since < nowMillis ? nowMillis - since : 0;
|
||||
}
|
||||
|
||||
/** Every tool call still in flight across a conversation's [messages]. */
|
||||
export function threadRunningTools(messages) {
|
||||
return runningTools((messages ?? []).flatMap((message) => message?.parts ?? []));
|
||||
}
|
||||
|
||||
/** How long [part] has been running at [nowMillis], using the thread's own stamps. */
|
||||
export function threadToolElapsedMillis(thread, part, nowMillis) {
|
||||
const stamps = thread?.toolStartedAt ?? {};
|
||||
const startedAt = stamps instanceof Map ? (stamps.get(part?.id) ?? 0) : (stamps[part?.id] ?? 0);
|
||||
return runningToolElapsedMillis(part, startedAt, nowMillis);
|
||||
}
|
||||
|
||||
/**
|
||||
* The id a text or reasoning delta must be applied to for [kind] within [parts].
|
||||
* The broker gives the two kinds distinct ids (see `ChatDeltaPartID`), but a peer
|
||||
* that still shares one bare id between them must never have answer text appended
|
||||
* into a reasoning part: when another kind already holds the bare id, the delta is
|
||||
* moved onto a suffixed id of its own. Once a part of this kind exists under
|
||||
* either id, that part is the one addressed, so a stream keeps growing the part
|
||||
* it started.
|
||||
*/
|
||||
export function deltaPartId(parts, kind, id) {
|
||||
const list = parts ?? [];
|
||||
if (list.some((part) => part?.type === kind && part?.id === id)) return id;
|
||||
const suffixed = `${id}#${kind}`;
|
||||
if (list.some((part) => part?.type === kind && part?.id === suffixed)) return suffixed;
|
||||
return list.some((part) => part?.id === id) ? suffixed : id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds one tool frame's part onto the part retained from earlier frames. A tool
|
||||
* call is reported across several frames that each carry only part of it, so a
|
||||
* field already learned is never blanked by a later frame that omits it. A
|
||||
* non-empty incoming field wins; otherwise the retained value is kept.
|
||||
*/
|
||||
export function mergeToolPart(previous, incoming) {
|
||||
if (previous == null) return incoming;
|
||||
return {
|
||||
...incoming,
|
||||
type: isBlank(incoming?.type) ? previous.type : incoming.type,
|
||||
name: isBlank(incoming?.name) ? previous.name : incoming.name,
|
||||
executed: Boolean(incoming?.executed || previous?.executed),
|
||||
time: incoming?.time ?? previous?.time,
|
||||
state: mergeToolState(previous?.state, incoming?.state),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeToolState(prior, incoming) {
|
||||
if (incoming == null) return prior ?? undefined;
|
||||
if (prior == null) return incoming;
|
||||
return {
|
||||
...incoming,
|
||||
status: isBlank(incoming.status) ? prior.status : incoming.status,
|
||||
input: incoming.input == null ? prior.input : incoming.input,
|
||||
content: (incoming.content ?? []).length > 0 ? incoming.content : prior.content,
|
||||
metadata: incoming.metadata ?? prior.metadata,
|
||||
error: incoming.error ?? prior.error,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The running-tool start stamps after a thread's [messages] changed: every tool
|
||||
* part in flight keeps the stamp it already had, or is stamped with [now] when it
|
||||
* has just turned running, and a part that is no longer running loses its stamp.
|
||||
*/
|
||||
export function runningToolStamps(current, messages, now) {
|
||||
const stamps = {};
|
||||
for (const message of messages ?? []) {
|
||||
for (const part of message?.parts ?? []) {
|
||||
if (!isBlank(part?.id) && part?.type === PART_TOOL && toolRunning(part)) {
|
||||
stamps[part.id] = current?.[part.id] ?? now;
|
||||
}
|
||||
}
|
||||
}
|
||||
return stamps;
|
||||
}
|
||||
|
||||
/**
|
||||
* The [TURN_PHASE_*] of a turn in flight. [tools] are the calls the stream still
|
||||
* reports running; [silentMillis] is how long ago the last text or reasoning
|
||||
* delta arrived, or null when none has. No percentage, ETA or progress is
|
||||
* invented — the only inputs are the calls the stream reported and the time since
|
||||
* the last delta.
|
||||
*/
|
||||
export function turnPhase(tools, silentMillis) {
|
||||
if ((tools ?? []).length > 0) return TURN_PHASE_TOOL;
|
||||
if (silentMillis != null && silentMillis >= 0 && silentMillis < TURN_THINKING_WINDOW_MILLIS) {
|
||||
return TURN_PHASE_THINKING;
|
||||
}
|
||||
return TURN_PHASE_WAITING;
|
||||
}
|
||||
|
||||
/** The running indicator's headline for [phase], naming what is happening. */
|
||||
export function turnPhaseLabel(phase) {
|
||||
if (phase === TURN_PHASE_THINKING) return "Thinking…";
|
||||
if (phase === TURN_PHASE_TOOL) return "Running a tool…";
|
||||
return "Waiting…";
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn's phase at [nowMillis], derived from its running tools and the time
|
||||
* since its last delta. Null when nothing is running, so a settled turn has no
|
||||
* phase at all.
|
||||
*/
|
||||
export function threadPhase(thread, nowMillis) {
|
||||
if (!thread?.running) return null;
|
||||
const last = Number(thread.lastDeltaAt) || 0;
|
||||
const silent = last >= 1 && last < nowMillis ? nowMillis - last : null;
|
||||
return turnPhase(threadRunningTools(thread.messages), silent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one pushed `chat_event` frame to a conversation and returns the next
|
||||
* thread. Any frame clears `queued` (the turn moved on); `user` echoes another
|
||||
* client's prompt once (never this client's own), `text`/`reasoning` append to the
|
||||
* part their kind started, `tool` merges field by field, `step` drives the running
|
||||
* flag, and `shell`/`usage` are recognised but not folded here (C11 owns shells
|
||||
* and the turn totals are not shown). The message that a delta or tool frame
|
||||
* targets is created on first sight, so a live turn never gains a second bubble.
|
||||
*/
|
||||
export function applyChatEvent(thread, frame, now = Date.now()) {
|
||||
const current = thread?.queued
|
||||
? { ...thread, queued: false }
|
||||
: (thread ?? newChatThread(str(frame?.session_id)));
|
||||
switch (frame?.kind) {
|
||||
case EVENT_USER:
|
||||
return applyRemoteUser(current, frame);
|
||||
case PART_TEXT:
|
||||
case PART_REASONING:
|
||||
return applyDelta(current, frame, now);
|
||||
case PART_TOOL:
|
||||
return applyTool(current, frame, now);
|
||||
case EVENT_STEP:
|
||||
return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now);
|
||||
// `shell` is C11's (it never marks the turn running) and `usage` is not
|
||||
// folded; both still clear `queued`, which happened above.
|
||||
case EVENT_SHELL:
|
||||
case EVENT_USAGE:
|
||||
default:
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a user turn another client sent into the transcript, in place, once. The
|
||||
* server never echoes this client's own prompts, so the sender's own message is
|
||||
* never duplicated; the message's `client` label says which device sent it.
|
||||
*/
|
||||
function applyRemoteUser(thread, frame) {
|
||||
const text = str(frame?.part?.text);
|
||||
const messageId = str(frame?.message_id);
|
||||
if (messageId === "" || text === "") return thread;
|
||||
const operationId = str(frame?.operation_id);
|
||||
const messages = thread.messages ?? [];
|
||||
if (
|
||||
operationId !== "" &&
|
||||
messages.some((message) => message?.role === ROLE_USER && str(message?.operation_id) === operationId)
|
||||
) {
|
||||
return thread;
|
||||
}
|
||||
if (messages.some((message) => message?.id === messageId)) return thread;
|
||||
const message = {
|
||||
id: messageId,
|
||||
session_id: str(frame?.session_id),
|
||||
role: ROLE_USER,
|
||||
client: str(frame?.client),
|
||||
operation_id: operationId,
|
||||
parts: [{ type: PART_TEXT, text }],
|
||||
};
|
||||
return { ...thread, messages: [...messages, message] };
|
||||
}
|
||||
|
||||
function applyDelta(thread, frame, now) {
|
||||
const rawId = str(frame?.part?.id);
|
||||
const delta = str(frame?.delta);
|
||||
if (rawId === "" || delta === "") return thread;
|
||||
const kind = frame.kind;
|
||||
return upsertParts(thread, frame, now, now, (parts) => {
|
||||
const id = deltaPartId(parts, kind, rawId);
|
||||
const index = parts.findIndex((part) => part?.id === id);
|
||||
if (index < 0) return [...parts, { type: kind, id, text: delta }];
|
||||
const next = parts.slice();
|
||||
next[index] = { ...next[index], text: str(next[index]?.text) + delta };
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function applyTool(thread, frame, now) {
|
||||
const incoming = frame?.part ?? null;
|
||||
if (incoming == null || str(incoming.id) === "") return thread;
|
||||
return upsertParts(thread, frame, now, null, (parts) => {
|
||||
const index = parts.findIndex((part) => part?.id === incoming.id && part?.type === PART_TOOL);
|
||||
if (index < 0) return [...parts, mergeToolPart(null, incoming)];
|
||||
const next = parts.slice();
|
||||
next[index] = mergeToolPart(next[index], incoming);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds or creates the assistant message [frame] targets and replaces its parts
|
||||
* with [upsert]'s result, then marks the thread running. The text/reasoning fold
|
||||
* and the tool upsert share this so the two cannot drift.
|
||||
*/
|
||||
function upsertParts(thread, frame, now, deltaArrivedAt, upsert) {
|
||||
const messageId = str(frame?.message_id);
|
||||
const messages = (thread.messages ?? []).slice();
|
||||
let index = -1;
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
if (messages[i]?.id === messageId) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (index < 0) {
|
||||
messages.push({
|
||||
id: messageId,
|
||||
session_id: str(frame?.session_id),
|
||||
role: ROLE_ASSISTANT,
|
||||
parts: [],
|
||||
});
|
||||
index = messages.length - 1;
|
||||
}
|
||||
const message = messages[index];
|
||||
messages[index] = { ...message, parts: upsert(message.parts ?? []) };
|
||||
const stamped = runningToolStamps(thread.toolStartedAt, messages, now);
|
||||
let next = setThreadRunning({ ...thread, messages, toolStartedAt: stamped }, true, now);
|
||||
if (deltaArrivedAt != null) next = { ...next, lastDeltaAt: deltaArrivedAt };
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reconnect/resync replacement: the newest history page is authoritative, so
|
||||
* the whole turn is replaced (no stale held message survives), the cursor and
|
||||
* `hasMore` are replaced from the page, and any in-flight state is settled —
|
||||
* every frame that was feeding a running turn is gone.
|
||||
*/
|
||||
export function historyResync(thread, page) {
|
||||
const settled = settledThread(thread ?? newChatThread());
|
||||
return {
|
||||
...settled,
|
||||
messages: (page?.messages ?? []).slice(),
|
||||
nextCursor: str(page?.nextCursor),
|
||||
hasMore: Boolean(page?.hasMore),
|
||||
loaded: true,
|
||||
loading: false,
|
||||
error: "",
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scroll behaviour (ChatScroll.kt)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+9
-6
@@ -1,7 +1,9 @@
|
||||
// A single, reused WebSocket connection to /connect, mirroring
|
||||
// android/.../data/transport/PipelinesClient.kt: requests are serialized, each
|
||||
// carries a client-generated stable id, replies are matched by id, and
|
||||
// unsolicited envelopes are dropped. There is no authentication of any kind.
|
||||
// carries a client-generated stable id, replies are matched by id, and an
|
||||
// unsolicited envelope is surfaced as a DOM-free `frame` event (the app folds the
|
||||
// frames it cares about) rather than misattributed to a request. There is no
|
||||
// authentication of any kind.
|
||||
//
|
||||
// DOM-free on purpose: the browser app and the Node smoke test share this exact
|
||||
// module, so the smoke test exercises the real client, not a re-implementation.
|
||||
@@ -186,10 +188,11 @@ export class PipelinesClient extends EventTarget {
|
||||
entry.resolve(message);
|
||||
return;
|
||||
}
|
||||
// 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.
|
||||
// No pending request matches: the envelope is unsolicited — the connection's
|
||||
// initial `pipeline_list`, or a server push such as a `chat_event` frame or a
|
||||
// `run_event` — and is surfaced as a DOM-free `frame` event for a view to fold;
|
||||
// with no listener it is simply dropped. It is never misattributed to a
|
||||
// request, which is still matched by id.
|
||||
this.dispatchEvent(new CustomEvent("frame", { detail: message }));
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,12 @@ export const Protocol = Object.freeze({
|
||||
VALIDATE: "validate",
|
||||
VALIDATED: "validated",
|
||||
|
||||
// Publishing a new create-only draft from a source (internal/protocol/message.go
|
||||
// Submit/Submitted; mirrors PipelinesRepository.createPipeline). The reply
|
||||
// carries the new pipeline `detail`.
|
||||
SUBMIT: "submit",
|
||||
SUBMITTED: "submitted",
|
||||
|
||||
LIST_RUNS: "list_runs",
|
||||
RUNS: "runs",
|
||||
GET_RUN: "get_run",
|
||||
@@ -43,6 +49,13 @@ export const Protocol = Object.freeze({
|
||||
CHAT_MESSAGES: "chat_messages",
|
||||
CHAT_CLOSE: "chat_close",
|
||||
CHAT_REOPEN: "chat_reopen",
|
||||
// The shared live stream (C5). `chat_subscribe` attaches this connection to one
|
||||
// session's stream (body: the session id); the server then pushes `chat_event`
|
||||
// frames without a matching request id, so every client watching a session sees
|
||||
// the same turn. There is no `chat_unsubscribe` on the wire — the server
|
||||
// detaches a subscription when the connection closes.
|
||||
CHAT_SUBSCRIBE: "chat_subscribe",
|
||||
CHAT_EVENT: "chat_event",
|
||||
// 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`
|
||||
@@ -68,6 +81,10 @@ export const ChatKeys = Object.freeze({
|
||||
HISTORY: "chat_history",
|
||||
MESSAGES: "chat_messages",
|
||||
CLOSE: "chat_close",
|
||||
// `chat_subscribe` (the request body naming the session) and `chat_event` (the
|
||||
// unsolicited pushed frame on the shared stream).
|
||||
SUBSCRIBE: "chat_subscribe",
|
||||
EVENT: "chat_event",
|
||||
// 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
|
||||
|
||||
@@ -60,6 +60,29 @@ export class PipelinesRepository {
|
||||
return response.graph;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new pipeline from a definition `source` (the `submit` command),
|
||||
* create-only, mirroring `PipelinesRepository.createPipeline`: the name must
|
||||
* not already exist, so this can only ever add a draft and never overwrite a
|
||||
* retained pipeline. A blank name is refused before anything is sent, exactly
|
||||
* like the Android client; the sent name is trimmed. No run is started.
|
||||
*/
|
||||
async submit(name, source) {
|
||||
if (!String(name ?? "").trim()) {
|
||||
throw new ProtocolError("Enter a pipeline name.");
|
||||
}
|
||||
const response = await this.#client.call({
|
||||
type: Protocol.SUBMIT,
|
||||
name: String(name).trim(),
|
||||
source,
|
||||
create_only: true,
|
||||
});
|
||||
if (!response.detail) {
|
||||
throw new ProtocolError("The server returned no pipeline detail.");
|
||||
}
|
||||
return response.detail;
|
||||
}
|
||||
|
||||
async listRuns() {
|
||||
const response = await this.#client.call({ type: Protocol.LIST_RUNS });
|
||||
return { runs: response.runs ?? [], usage: response.usage ?? null };
|
||||
@@ -197,6 +220,26 @@ export class PipelinesRepository {
|
||||
return { messages: response[ChatKeys.MESSAGES] ?? [], nextCursor: "", hasMore: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches this connection to one session's shared live stream (C5). The body
|
||||
* is exactly `{type:'chat_subscribe', chat_subscribe:{session_id}}` — the
|
||||
* `chat_subscribe` field, not `chat_query` (internal/protocol/message.go); the
|
||||
* server replies with an id-matched echo once the subscription is attached and
|
||||
* then pushes `chat_event` frames without an id, which `client.js` surfaces as a
|
||||
* `frame` event. Any number of clients may watch one session; the session is
|
||||
* never read-only. There is no `chat_unsubscribe`: the server drops a
|
||||
* subscription when the connection closes.
|
||||
*/
|
||||
async subscribeChat(sessionId) {
|
||||
if (!String(sessionId ?? "").trim()) {
|
||||
throw new ProtocolError("Select a chat session first.");
|
||||
}
|
||||
return this.#client.call({
|
||||
type: Protocol.CHAT_SUBSCRIBE,
|
||||
[ChatKeys.SUBSCRIBE]: { session_id: sessionId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes a session and records it closed on the server (nothing is
|
||||
* deleted). The reply echoes the updated session (`chat_session`) and the
|
||||
|
||||
@@ -91,3 +91,68 @@ export function templateStageSummary(graph) {
|
||||
export function templateGraphNote(graph) {
|
||||
return graph == null ? TEMPLATE_UNPARSED_GRAPH_NOTE : TEMPLATE_GRAPH_NOTE;
|
||||
}
|
||||
|
||||
// --- Create a pipeline from this template (P5) -----------------------------
|
||||
// The wording, verbatim from android/.../TemplateDetailScreen.kt's
|
||||
// CreateFromTemplateDialog. The dialog validates the template's source first,
|
||||
// then submits it create-only; nothing runs and an existing name is never
|
||||
// overwritten.
|
||||
|
||||
/** The template-detail action that opens the create dialog. */
|
||||
export const CREATE_ACTION_LABEL = "Create pipeline from this template";
|
||||
|
||||
/** The dialog's single required field label. */
|
||||
export const CREATE_NAME_LABEL = "New pipeline name (required)";
|
||||
|
||||
/** The dialog's explanatory note (verbatim; states that nothing runs). */
|
||||
export const CREATE_NOTE =
|
||||
"Creates a new draft pipeline on the server from this template's source; it is not run.";
|
||||
|
||||
/** The confirm button's idle label. */
|
||||
export const CREATE_CONFIRM = "Create";
|
||||
|
||||
/** The confirm button's in-flight label. */
|
||||
export const CREATE_SENDING = "Creating…";
|
||||
|
||||
/** The dismiss button's label before a success. */
|
||||
export const CREATE_CANCEL = "Cancel";
|
||||
|
||||
/** The dismiss button's label after a success. */
|
||||
export const CREATE_CLOSE = "Close";
|
||||
|
||||
/** The dialog's title: `Create from {name}`, a blank name falling back to the key. */
|
||||
export function createFormTitle(entry) {
|
||||
return `Create from ${templateDetailName(entry)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the dialog can submit: not while sending, not once a pipeline has
|
||||
* been created, and never with a blank (or whitespace-only) name.
|
||||
*/
|
||||
export function createFormValid(name, { sending = false, created = null } = {}) {
|
||||
return !sending && created == null && String(name ?? "").trim() !== "";
|
||||
}
|
||||
|
||||
/** The confirm button's label: "Creating…" while in flight, else "Create". */
|
||||
export function createConfirmLabel(sending) {
|
||||
return sending ? CREATE_SENDING : CREATE_CONFIRM;
|
||||
}
|
||||
|
||||
/** The dismiss button's label: "Close" once a pipeline was created, else "Cancel". */
|
||||
export function createDismissLabel(created) {
|
||||
return created != null ? CREATE_CLOSE : CREATE_CANCEL;
|
||||
}
|
||||
|
||||
/** The dialog's success line: `Created "{name}". It is in the Pipelines list.` */
|
||||
export function createSuccessMessage(created) {
|
||||
return `Created "${created}". It is in the Pipelines list.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The name to report after a successful submit: the created pipeline's own name
|
||||
* when the server returned one, else the name the operator submitted (trimmed),
|
||||
* mirroring `created = it.name.ifBlank { name.trim() }`.
|
||||
*/
|
||||
export function createdPipelineName(detail, submittedName) {
|
||||
return String(detail?.name ?? "").trim() || String(submittedName ?? "").trim();
|
||||
}
|
||||
|
||||
@@ -1367,6 +1367,49 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
|
||||
.confirm-accept { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
.action-failed-ok { justify-self: end; }
|
||||
|
||||
/* Create a pipeline from a template (P5): the detail action and its dialog. */
|
||||
.detail-actions { display: flex; gap: 8px; align-items: center; padding: 8px 12px 0; }
|
||||
.template-create-open { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
.template-create-dialog {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
.template-create-panel {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
width: min(460px, 100%);
|
||||
padding: 16px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.template-create-title { margin: 0; font-size: 16px; }
|
||||
.template-create-field { display: grid; gap: 4px; }
|
||||
.template-create-label { font-size: 12px; color: var(--muted); }
|
||||
.template-create-name {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
}
|
||||
.template-create-name:focus { outline: none; border-color: var(--accent); }
|
||||
.template-create-note { margin: 0; line-height: 1.5; font-size: 13px; }
|
||||
.template-create-error { font-size: 13px; }
|
||||
.template-create-success { font-size: 13px; color: var(--ok); }
|
||||
.template-create-actions { display: flex; gap: 8px; justify-content: flex-end; }
|
||||
.template-create-confirm { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
.template-create-confirm:disabled, .template-create-cancel:disabled { opacity: 0.5; }
|
||||
|
||||
/* The inline rename control on the Summary title row. */
|
||||
.run-title-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
|
||||
.run-title-row .run-detail-title { margin: 0; }
|
||||
@@ -1495,6 +1538,25 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
|
||||
.chat-tool-chevron { color: var(--muted); }
|
||||
.chat-tool-spinner { width: 11px; height: 11px; border-width: 2px; }
|
||||
|
||||
/* C5: the in-flight turn's indicator, under the transcript after the last agent
|
||||
turn — a spinner, the phase headline, the turn's elapsed and one line per
|
||||
running tool. A call over the long threshold is tinted and marked `.chat-tool-long`. */
|
||||
.chat-running { display: flex; flex-direction: column; gap: 4px; padding: 6px 2px 2px; color: var(--muted); font-size: 12px; }
|
||||
.chat-running-head { display: flex; align-items: center; gap: 8px; }
|
||||
.chat-running-spinner { width: 12px; height: 12px; border-width: 2px; }
|
||||
.chat-running-label { color: var(--text); }
|
||||
.chat-running-elapsed { color: var(--muted); }
|
||||
.chat-running-tool { display: flex; align-items: center; gap: 8px; padding-left: 20px; min-width: 0; }
|
||||
.chat-running-tool-text {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 420px;
|
||||
}
|
||||
.chat-running-tool-elapsed { font-size: 11px; }
|
||||
.chat-running-tool-long { color: var(--bad); }
|
||||
|
||||
.chat-tool-panel {
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
|
||||
@@ -208,6 +208,14 @@ export async function launchChrome({ width = 1440, height = 900, chromePath } =
|
||||
{ what: `load of ${nextUrl}` },
|
||||
);
|
||||
},
|
||||
/**
|
||||
* Install a script that runs in every document created from now on, before
|
||||
* the page's own scripts — the CDP hook a UI check uses to wrap a global
|
||||
* (for example to record the page's WebSocket) before the app boots.
|
||||
*/
|
||||
async addInitScript(source) {
|
||||
await session("Page.addScriptToEvaluateOnNewDocument", { source });
|
||||
},
|
||||
/** Set an input's value and fire input/change so the app sees it. */
|
||||
async fill(selector, value) {
|
||||
const ok = await api.evaluate(`(() => {
|
||||
|
||||
@@ -16,6 +16,11 @@ import {
|
||||
MAX_RENDERED_DIFF_LINES,
|
||||
TOOL_DETAIL_MAX_LENGTH,
|
||||
TOOL_LONG_RUNNING_MILLIS,
|
||||
TURN_PHASE_THINKING,
|
||||
TURN_PHASE_TOOL,
|
||||
TURN_PHASE_WAITING,
|
||||
TURN_THINKING_WINDOW_MILLIS,
|
||||
applyChatEvent,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
@@ -30,17 +35,22 @@ import {
|
||||
chatNoMatchMessage,
|
||||
chatOpensAtNewest,
|
||||
chatShowJumpToLatest,
|
||||
chatStreamState,
|
||||
closeChatConfirmation,
|
||||
composerAction,
|
||||
composerCanSend,
|
||||
composerSendEnabled,
|
||||
composerSubmit,
|
||||
deltaPartId,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
formatToolDuration,
|
||||
groupSessionsByDirectory,
|
||||
historyResync,
|
||||
lineDiff,
|
||||
mergeHistoryPage,
|
||||
mergeToolPart,
|
||||
newChatThread,
|
||||
parseChatInput,
|
||||
partRendering,
|
||||
prettyToolInput,
|
||||
@@ -48,6 +58,7 @@ import {
|
||||
reasoningLabel,
|
||||
runningAfterFrame,
|
||||
runningToolElapsedMillis,
|
||||
runningToolStamps,
|
||||
sessionActivity,
|
||||
sessionActivityBadge,
|
||||
sessionChipLabel,
|
||||
@@ -56,6 +67,11 @@ import {
|
||||
sessionStatusLabel,
|
||||
sessionTitle,
|
||||
sessionWorkLabel,
|
||||
settledThread,
|
||||
threadElapsedMillis,
|
||||
threadPhase,
|
||||
threadRunningTools,
|
||||
threadToolElapsedMillis,
|
||||
toolCallCount,
|
||||
toolCallRow,
|
||||
toolCallsAnnouncement,
|
||||
@@ -71,6 +87,8 @@ import {
|
||||
toolsRunning,
|
||||
transcriptRows,
|
||||
turnElapsedMillis,
|
||||
turnPhase,
|
||||
turnPhaseLabel,
|
||||
} from "../src/chat.js";
|
||||
import { ChangeLineKind } from "../src/changes.js";
|
||||
|
||||
@@ -882,3 +900,271 @@ test("chatCommandEffect reports the exact Android error strings", () => {
|
||||
text: "Can't start a new session here: the server reported no directory for this chat.",
|
||||
});
|
||||
});
|
||||
|
||||
// --- C5: live stream folding ------------------------------------------------
|
||||
// Every frame below is the server's `chat_event` shape (internal/protocol/chat.go
|
||||
// ChatEventFrame). The synthetic frames prove the pure fold; the ui-smoke replays
|
||||
// the same shapes against the real page.
|
||||
|
||||
const evt = (kind, extra = {}) => ({ session_id: "s1", kind, ...extra });
|
||||
|
||||
test("a text delta appends to the part the first frame started", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "a1#text#0" }, delta: "Hel" }), 1000);
|
||||
thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "a1#text#0" }, delta: "lo" }), 1001);
|
||||
|
||||
assert.equal(thread.messages.length, 1);
|
||||
assert.equal(thread.messages[0].role, "assistant");
|
||||
assert.equal(thread.messages[0].parts.length, 1);
|
||||
assert.equal(thread.messages[0].parts[0].text, "Hello");
|
||||
assert.equal(thread.running, true);
|
||||
assert.equal(thread.runningSince, 1000);
|
||||
assert.equal(thread.lastDeltaAt, 1001);
|
||||
});
|
||||
|
||||
test("a text delta and a reasoning delta sharing a bare id land in separate parts", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "x" }, delta: "answer" }), 1000);
|
||||
thread = applyChatEvent(thread, evt("reasoning", { message_id: "a1", part: { id: "x" }, delta: "think" }), 1001);
|
||||
|
||||
const parts = thread.messages[0].parts;
|
||||
assert.equal(parts.length, 2);
|
||||
const text = parts.find((part) => part.type === "text");
|
||||
const reasoning = parts.find((part) => part.type === "reasoning");
|
||||
assert.equal(text.id, "x");
|
||||
assert.equal(text.text, "answer");
|
||||
assert.equal(reasoning.id, "x#reasoning");
|
||||
assert.equal(reasoning.text, "think");
|
||||
// The id derivation is the one the broker uses once the kinds are distinct.
|
||||
assert.equal(deltaPartId(parts, "text", "x"), "x");
|
||||
assert.equal(deltaPartId(parts, "reasoning", "x"), "x#reasoning");
|
||||
});
|
||||
|
||||
test("tool frames merge field by field without blanking what an earlier frame taught", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", {
|
||||
message_id: "a1",
|
||||
part: { type: "tool", id: "t1", name: "read", state: { status: "running", input: { filePath: "a.js" } } },
|
||||
}),
|
||||
1000,
|
||||
);
|
||||
// A later frame carries the result but no name and no input: both are retained.
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", {
|
||||
message_id: "a1",
|
||||
part: { type: "tool", id: "t1", state: { status: "completed", content: [{ type: "text", text: "done" }] } },
|
||||
}),
|
||||
1001,
|
||||
);
|
||||
// A final frame carries the error but no content: the content is retained too.
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", {
|
||||
message_id: "a1",
|
||||
part: { type: "tool", id: "t1", state: { status: "error", error: { message: "boom" } } },
|
||||
}),
|
||||
1002,
|
||||
);
|
||||
|
||||
const tool = thread.messages[0].parts.find((part) => part.type === "tool");
|
||||
assert.equal(tool.name, "read");
|
||||
assert.deepEqual(tool.state.input, { filePath: "a.js" });
|
||||
assert.equal(tool.state.content[0].text, "done");
|
||||
assert.equal(tool.state.error.message, "boom");
|
||||
assert.equal(tool.state.status, "error");
|
||||
// And the pure merge keeps a non-empty incoming field while retaining the prior.
|
||||
const merged = mergeToolPart(
|
||||
{ type: "tool", id: "t1", name: "read", executed: true, state: { status: "running", input: { a: 1 } } },
|
||||
{ type: "tool", id: "t1", name: "", state: { status: "", input: { b: 2 } } },
|
||||
);
|
||||
assert.equal(merged.name, "read");
|
||||
assert.equal(merged.executed, true);
|
||||
assert.equal(merged.state.status, "running");
|
||||
assert.deepEqual(merged.state.input, { b: 2 });
|
||||
});
|
||||
|
||||
test("a repeated user message id adds no second turn and keeps a non-blank client", () => {
|
||||
let thread = newChatThread("s1");
|
||||
const frame = evt("user", { message_id: "u9", part: { text: "hi there" }, client: "Pixel" });
|
||||
thread = applyChatEvent(thread, frame, 1000);
|
||||
thread = applyChatEvent(thread, frame, 1001);
|
||||
|
||||
assert.equal(thread.messages.filter((message) => message.role === "user").length, 1);
|
||||
assert.equal(thread.messages[0].client, "Pixel");
|
||||
assert.equal(thread.messages[0].parts[0].text, "hi there");
|
||||
// Another id with no text or no id at all is ignored.
|
||||
thread = applyChatEvent(thread, evt("user", { message_id: "u10", part: { text: "" } }), 1002);
|
||||
thread = applyChatEvent(thread, evt("user", { part: { text: "no id" } }), 1003);
|
||||
assert.equal(thread.messages.length, 1);
|
||||
});
|
||||
|
||||
test("step started runs the turn and step ended settles it", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(thread, evt("step", { step: { status: "started", index: 1 } }), 1000);
|
||||
assert.equal(thread.running, true);
|
||||
assert.equal(thread.runningSince, 1000);
|
||||
|
||||
// A tool call in flight leaves a stamp; ending the step clears running and the stamp.
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "running" } } }),
|
||||
1001,
|
||||
);
|
||||
assert.equal(thread.toolStartedAt.t1, 1001);
|
||||
thread = applyChatEvent(thread, evt("step", { step: { status: "ended" } }), 2000);
|
||||
assert.equal(thread.running, false);
|
||||
assert.equal(thread.runningSince, 0);
|
||||
assert.deepEqual(thread.toolStartedAt, {});
|
||||
assert.equal(thread.lastDeltaAt, 0);
|
||||
});
|
||||
|
||||
test("any frame clears the queued flag", () => {
|
||||
for (const frame of [
|
||||
evt("text", { message_id: "a1", part: { id: "p" }, delta: "x" }),
|
||||
evt("step", { step: { status: "started" } }),
|
||||
evt("usage", { usage: { input_tokens: 1 } }),
|
||||
evt("shell", { shell: { id: "sh1", status: "running" } }),
|
||||
]) {
|
||||
const queued = { ...newChatThread("s1"), queued: true };
|
||||
assert.equal(applyChatEvent(queued, frame, 1000).queued, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("a shell frame never marks the thread running", () => {
|
||||
const thread = applyChatEvent(
|
||||
newChatThread("s1"),
|
||||
evt("shell", { shell: { id: "sh1", status: "running", command: "go test ./..." } }),
|
||||
1000,
|
||||
);
|
||||
assert.equal(thread.running, false);
|
||||
assert.equal(thread.runningSince, 0);
|
||||
});
|
||||
|
||||
test("a usage frame changes nothing", () => {
|
||||
const before = newChatThread("s1");
|
||||
const after = applyChatEvent(before, evt("usage", { usage: { input_tokens: 5, cost: 0.01 } }), 1000);
|
||||
assert.deepEqual(after, before);
|
||||
});
|
||||
|
||||
test("settling a thread (a socket drop) clears running, its stamps and queued", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(thread, evt("text", { message_id: "a1", part: { id: "p" }, delta: "x" }), 1000);
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", { message_id: "a1", part: { type: "tool", id: "t1", state: { status: "running" } } }),
|
||||
1001,
|
||||
);
|
||||
assert.equal(thread.running, true);
|
||||
assert.equal(thread.toolStartedAt.t1, 1001);
|
||||
|
||||
const settled = settledThread(thread);
|
||||
assert.equal(settled.running, false);
|
||||
assert.equal(settled.runningSince, 0);
|
||||
assert.deepEqual(settled.toolStartedAt, {});
|
||||
assert.equal(settled.lastDeltaAt, 0);
|
||||
assert.equal(settled.queued, false);
|
||||
// The conversation itself is untouched by settling.
|
||||
assert.equal(settled.messages.length, 1);
|
||||
});
|
||||
|
||||
test("historyResync replaces the turn wholesale and settles it", () => {
|
||||
const held = {
|
||||
...newChatThread("s1"),
|
||||
messages: [assistant("a1", [{ type: "text", text: "stale" }])],
|
||||
nextCursor: "old",
|
||||
hasMore: true,
|
||||
loaded: true,
|
||||
running: true,
|
||||
runningSince: 555,
|
||||
toolStartedAt: { t1: 555 },
|
||||
lastDeltaAt: 600,
|
||||
};
|
||||
const page = {
|
||||
messages: [user("u1", "hi"), assistant("a2", [{ type: "text", text: "fresh" }])],
|
||||
nextCursor: "",
|
||||
hasMore: false,
|
||||
};
|
||||
|
||||
const resynced = historyResync(held, page);
|
||||
assert.deepEqual(resynced.messages, page.messages);
|
||||
assert.ok(!resynced.messages.some((message) => message.id === "a1"));
|
||||
assert.equal(resynced.nextCursor, "");
|
||||
assert.equal(resynced.hasMore, false);
|
||||
assert.equal(resynced.loaded, true);
|
||||
assert.equal(resynced.running, false);
|
||||
assert.equal(resynced.runningSince, 0);
|
||||
assert.deepEqual(resynced.toolStartedAt, {});
|
||||
assert.equal(resynced.lastDeltaAt, 0);
|
||||
});
|
||||
|
||||
test("the chat stream badge uses the live / reconnecting / not live words", () => {
|
||||
assert.deepEqual(chatStreamState("connected", true), { tone: "live", label: "live" });
|
||||
assert.equal(chatStreamState("connected", false).label, "not live");
|
||||
assert.equal(chatStreamState("connecting", true).label, "reconnecting");
|
||||
assert.equal(chatStreamState("disconnected", true).label, "reconnecting");
|
||||
assert.equal(chatStreamState("idle", false).label, "not live");
|
||||
});
|
||||
|
||||
test("the turn phase names what is happening", () => {
|
||||
assert.equal(turnPhase([], 1000), TURN_PHASE_THINKING);
|
||||
assert.equal(turnPhaseLabel(TURN_PHASE_THINKING), "Thinking…");
|
||||
assert.equal(turnPhase([{ type: "tool", id: "t", state: { status: "running" } }], 100000), TURN_PHASE_TOOL);
|
||||
assert.equal(turnPhaseLabel(TURN_PHASE_TOOL), "Running a tool…");
|
||||
assert.equal(turnPhase([], null), TURN_PHASE_WAITING);
|
||||
assert.equal(turnPhase([], TURN_THINKING_WINDOW_MILLIS), TURN_PHASE_WAITING);
|
||||
assert.equal(turnPhaseLabel(TURN_PHASE_WAITING), "Waiting…");
|
||||
});
|
||||
|
||||
test("only a call at or past 60s reads as long", () => {
|
||||
assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1), false);
|
||||
assert.equal(toolLongRunning(TOOL_LONG_RUNNING_MILLIS), true);
|
||||
assert.equal(TOOL_LONG_RUNNING_MILLIS, 60000);
|
||||
});
|
||||
|
||||
test("a live turn interleaving reasoning, text and tool frames folds to one agent row", () => {
|
||||
let thread = newChatThread("live");
|
||||
const frames = [
|
||||
evt("reasoning", { message_id: "a1", part: { id: "r0" }, delta: "think" }),
|
||||
evt("text", { message_id: "a1", part: { id: "t0" }, delta: "Hel" }),
|
||||
evt("tool", { message_id: "a1", part: { type: "tool", id: "tool1", name: "read", state: { status: "running" } } }),
|
||||
evt("tool", {
|
||||
message_id: "a1",
|
||||
part: { type: "tool", id: "tool1", state: { status: "completed", content: [{ type: "text", text: "ok" }] } },
|
||||
}),
|
||||
evt("reasoning", { message_id: "a2", part: { id: "r0" }, delta: "more" }),
|
||||
evt("text", { message_id: "a2", part: { id: "t0" }, delta: "lo" }),
|
||||
];
|
||||
for (const frame of frames) thread = applyChatEvent(thread, frame, 1000);
|
||||
|
||||
const rows = transcriptRows(thread.messages);
|
||||
const agentRows = rows.filter((row) => row.kind === "agent");
|
||||
assert.equal(agentRows.length, 1);
|
||||
assert.equal(agentRows[0].key, "a1");
|
||||
assert.deepEqual(agentRows[0].turn.reasoningSteps, ["think", "more"]);
|
||||
assert.equal(agentRows[0].turn.tools.length, 1);
|
||||
assert.equal(agentRows[0].turn.answer, "Hel\n\nlo");
|
||||
assert.equal(threadRunningTools(thread.messages).length, 0);
|
||||
});
|
||||
|
||||
test("the running indicator's elapsed and per-tool timing use the thread's own stamps", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatEvent(thread, evt("step", { step: { status: "started" } }), 1000);
|
||||
thread = applyChatEvent(
|
||||
thread,
|
||||
evt("tool", {
|
||||
message_id: "a1",
|
||||
part: { type: "tool", id: "t1", name: "shell", state: { status: "running", input: { command: "go build" } } },
|
||||
}),
|
||||
1500,
|
||||
);
|
||||
|
||||
assert.equal(threadElapsedMillis(thread, 3000), 2000);
|
||||
assert.equal(formatToolDuration(threadToolElapsedMillis(thread, thread.messages[0].parts[0], 3000)), "1.5s");
|
||||
assert.equal(threadPhase(thread, 3000), TURN_PHASE_TOOL);
|
||||
// runningToolStamps keeps a stamp it already had and drops one that settled.
|
||||
assert.deepEqual(runningToolStamps({ t1: 42 }, thread.messages, 9999), { t1: 42 });
|
||||
assert.deepEqual(runningToolStamps({ t1: 42 }, [], 9999), {});
|
||||
});
|
||||
|
||||
@@ -90,9 +90,11 @@ test("an error reply surfaces the server text as a ProtocolError", async () => {
|
||||
await assert.rejects(() => client.call({ type: "get_run" }), ProtocolError);
|
||||
});
|
||||
|
||||
test("an unsolicited envelope with no matching id is dropped, not misattributed", async () => {
|
||||
test("an unsolicited envelope is surfaced as a frame event and not misattributed", async () => {
|
||||
const { client, ws } = connectedClient();
|
||||
ws.reply = undefined;
|
||||
const frames = [];
|
||||
client.addEventListener("frame", (event) => frames.push(event.detail));
|
||||
|
||||
const pending = client.call({ type: "ping" });
|
||||
let settled = false;
|
||||
@@ -102,10 +104,29 @@ test("an unsolicited envelope with no matching id is dropped, not misattributed"
|
||||
ws.push({ type: "pipelines", pipelines: [] }); // no id
|
||||
await flush();
|
||||
assert.equal(settled, false);
|
||||
assert.deepEqual(frames, [{ type: "pipelines", pipelines: [] }]);
|
||||
|
||||
const frame = ws.sent.at(-1);
|
||||
ws.push({ id: frame.id, type: "pong" });
|
||||
assert.equal((await pending).type, "pong");
|
||||
// A matched reply is not also broadcast as an unsolicited frame.
|
||||
assert.equal(frames.length, 1);
|
||||
});
|
||||
|
||||
test("a server-pushed chat_event frame reaches a frame listener", async () => {
|
||||
const { client, ws } = connectedClient();
|
||||
const frames = [];
|
||||
client.addEventListener("frame", (event) => frames.push(event.detail));
|
||||
|
||||
ws.push({
|
||||
type: "chat_event",
|
||||
chat_event: { session_id: "ses_1", message_id: "a1", kind: "text", delta: "hi" },
|
||||
});
|
||||
await flush();
|
||||
|
||||
assert.equal(frames.length, 1);
|
||||
assert.equal(frames[0].type, "chat_event");
|
||||
assert.equal(frames[0].chat_event.session_id, "ses_1");
|
||||
});
|
||||
|
||||
test("a malformed frame is ignored and does not reject a pending call", async () => {
|
||||
|
||||
@@ -105,6 +105,67 @@ test("validate throws when the reply has no graph", async () => {
|
||||
await assert.rejects(() => repo.validate("empty"), ProtocolError);
|
||||
});
|
||||
|
||||
/** The new pipeline detail a `submitted` reply carries in these tests. */
|
||||
const SUBMITTED_DETAIL = { id: 91, name: "Release helper", version: 1 };
|
||||
|
||||
test("submit sends exactly {type:'submit',name,source,create_only:true} and returns the detail", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "submitted", detail: SUBMITTED_DETAIL });
|
||||
|
||||
const detail = await repo.submit("Release helper", "the source");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "submit",
|
||||
name: "Release helper",
|
||||
source: "the source",
|
||||
create_only: true,
|
||||
});
|
||||
assert.deepEqual(detail, SUBMITTED_DETAIL);
|
||||
});
|
||||
|
||||
test("submit trims the name before sending it", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "submitted", detail: SUBMITTED_DETAIL });
|
||||
|
||||
await repo.submit(" Release helper ", "the source");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "submit",
|
||||
name: "Release helper",
|
||||
source: "the source",
|
||||
create_only: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("submit refuses a blank name without sending anything", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = () => ({ id: "unused", type: "submitted", detail: SUBMITTED_DETAIL });
|
||||
|
||||
await assert.rejects(() => repo.submit(" ", "the source"), {
|
||||
name: "ProtocolError",
|
||||
message: "Enter a pipeline name.",
|
||||
});
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("submit rejects a server error envelope with the server's own text", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "error", error: 'a pipeline named "Release helper" already exists' });
|
||||
|
||||
await assert.rejects(() => repo.submit("Release helper", "the source"), {
|
||||
name: "ProtocolError",
|
||||
message: 'a pipeline named "Release helper" already exists',
|
||||
});
|
||||
});
|
||||
|
||||
test("submit throws when the reply has no pipeline detail", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "submitted", name: "Release helper" });
|
||||
|
||||
await assert.rejects(() => repo.submit("Release helper", "the source"), {
|
||||
name: "ProtocolError",
|
||||
message: "The server returned no pipeline detail.",
|
||||
});
|
||||
});
|
||||
|
||||
test("search sends exactly {type:'search',search:{query,kind:'',limit:0}} and returns search_results", async () => {
|
||||
const { repo, ws } = connected();
|
||||
const payload = { query: "release", results: [{ kind: "run" }], cap: 50, scanned_steps: 3 };
|
||||
@@ -309,3 +370,29 @@ test("nativeChatMessageId mirrors the Android id: msg_ + alphanumerics, capped",
|
||||
assert.equal(nativeChatMessageId("a".repeat(300)).length, "msg_".length + 120);
|
||||
assert.match(newChatOperationId(), /^web-chat-[a-z0-9]+-[a-z0-9]+$/);
|
||||
});
|
||||
|
||||
test("subscribeChat sends exactly {type:'chat_subscribe',chat_subscribe:{session_id}}", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_subscribe" });
|
||||
|
||||
await repo.subscribeChat("ses_eae413f50ffeLQDExlg8cYnscN");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_subscribe",
|
||||
chat_subscribe: { session_id: "ses_eae413f50ffeLQDExlg8cYnscN" },
|
||||
});
|
||||
});
|
||||
|
||||
test("subscribeChat rejects a blank session id without sending anything", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.subscribeChat(" "), ProtocolError);
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("subscribeChat surfaces a server refusal as a ProtocolError", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_subscribe" });
|
||||
await assert.rejects(() => repo.subscribeChat("ses_1"), {
|
||||
name: "ProtocolError",
|
||||
message: "unknown command: chat_subscribe",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,18 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
CREATE_CANCEL,
|
||||
CREATE_CLOSE,
|
||||
CREATE_CONFIRM,
|
||||
CREATE_NAME_LABEL,
|
||||
CREATE_NOTE,
|
||||
CREATE_SENDING,
|
||||
createConfirmLabel,
|
||||
createDismissLabel,
|
||||
createFormTitle,
|
||||
createFormValid,
|
||||
createSuccessMessage,
|
||||
createdPipelineName,
|
||||
effectiveStageType,
|
||||
stageCountText,
|
||||
templateCard,
|
||||
@@ -85,3 +97,55 @@ test("templateGraphNote picks the unparsed or parsed note", () => {
|
||||
assert.equal(templateGraphNote(null), TEMPLATE_UNPARSED_GRAPH_NOTE);
|
||||
assert.equal(templateGraphNote({ stages: [] }), TEMPLATE_GRAPH_NOTE);
|
||||
});
|
||||
|
||||
test("createFormTitle names the template, a blank name falling back to the key", () => {
|
||||
assert.equal(createFormTitle({ key: "task", name: "Complete a task" }), "Create from Complete a task");
|
||||
assert.equal(createFormTitle({ key: "task", name: "" }), "Create from task");
|
||||
assert.equal(createFormTitle({ key: "task", name: " " }), "Create from task");
|
||||
});
|
||||
|
||||
test("createFormValid rejects blank/whitespace, sending and an existing creation", () => {
|
||||
assert.equal(createFormValid("a pipeline"), true);
|
||||
assert.equal(createFormValid(""), false);
|
||||
assert.equal(createFormValid(" "), false);
|
||||
assert.equal(createFormValid(null), false);
|
||||
assert.equal(createFormValid("a pipeline", { sending: true }), false);
|
||||
assert.equal(createFormValid("a pipeline", { created: "a pipeline" }), false);
|
||||
assert.equal(createFormValid("a pipeline", { created: "" }), false);
|
||||
// Defaults: a non-blank name with no options is valid.
|
||||
assert.equal(createFormValid("a pipeline", {}), true);
|
||||
});
|
||||
|
||||
test("createConfirmLabel switches Create / Creating…", () => {
|
||||
assert.equal(createConfirmLabel(false), CREATE_CONFIRM);
|
||||
assert.equal(createConfirmLabel(true), CREATE_SENDING);
|
||||
});
|
||||
|
||||
test("createDismissLabel is Cancel until a creation, then Close", () => {
|
||||
assert.equal(createDismissLabel(null), CREATE_CANCEL);
|
||||
assert.equal(createDismissLabel(undefined), CREATE_CANCEL);
|
||||
assert.equal(createDismissLabel("Made"), CREATE_CLOSE);
|
||||
});
|
||||
|
||||
test("createSuccessMessage is the exact success line", () => {
|
||||
assert.equal(createSuccessMessage("Release helper"), 'Created "Release helper". It is in the Pipelines list.');
|
||||
});
|
||||
|
||||
test("createdPipelineName prefers the returned name, else the trimmed submitted name", () => {
|
||||
assert.equal(createdPipelineName({ name: "Server name" }, "Typed name"), "Server name");
|
||||
assert.equal(createdPipelineName({ name: " " }, " Typed name "), "Typed name");
|
||||
assert.equal(createdPipelineName(null, " Typed name "), "Typed name");
|
||||
assert.equal(createdPipelineName({}, ""), "");
|
||||
});
|
||||
|
||||
test("the create dialog's fixed wording is the app's", () => {
|
||||
assert.equal(CREATE_NAME_LABEL, "New pipeline name (required)");
|
||||
assert.equal(
|
||||
CREATE_NOTE,
|
||||
"Creates a new draft pipeline on the server from this template's source; it is not run.",
|
||||
);
|
||||
assert.equal(CREATE_CONFIRM, "Create");
|
||||
assert.equal(CREATE_SENDING, "Creating…");
|
||||
assert.equal(CREATE_CANCEL, "Cancel");
|
||||
assert.equal(CREATE_CLOSE, "Close");
|
||||
});
|
||||
|
||||
+340
-2
@@ -2,11 +2,16 @@
|
||||
// Chrome, connect to a running Pipelines server through the page's own proxy,
|
||||
// and capture what actually rendered.
|
||||
//
|
||||
// node test/ui-smoke.mjs [--port 8091] [--pipelines 127.0.0.1:8080] [--out DIR]
|
||||
// node test/ui-smoke.mjs [--port 8091] [--pipelines 127.0.0.1:8080] [--out DIR] [--scratch]
|
||||
//
|
||||
// This is the UI evidence a review stage produces: real screenshots of the
|
||||
// rendered client, not a claim. It needs a running Pipelines server (the live one
|
||||
// or a scratch one) and the installed Chrome; it has no npm dependencies.
|
||||
//
|
||||
// `--scratch` drives ONLY the P5 create-from-template flow (captures 51/52/53)
|
||||
// against a scratch server and skips the live suite, which needs the operator's
|
||||
// real runs and chat session. The default run never sends a `submit`: the live
|
||||
// server's pipeline list is never mutated.
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
@@ -38,6 +43,9 @@ const pipelines = flag(process.argv, "--pipelines", process.env.PIPELINES_TARGET
|
||||
const out = resolve(
|
||||
flag(process.argv, "--out", process.env.WEB_UI_OUT ?? join(tmpdir(), "pipelines-web-ui")),
|
||||
);
|
||||
// Scratch mode: only the P5 create-from-template flow runs, against a throwaway
|
||||
// server with its own database. The default (live) run sends no submit.
|
||||
const scratch = process.argv.includes("--scratch");
|
||||
|
||||
// The page must connect through its own proxy (the server rejects a cross-origin
|
||||
// upgrade), but serve.mjs only proxies /connect — not /artifacts. Point the URL
|
||||
@@ -124,6 +132,87 @@ async function openRunDetail(runId) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- P5: create a pipeline from a template (scratch server only) -----------
|
||||
// The scratch server has no real runs and no live chat, so this is the whole
|
||||
// point of a `--scratch` run. It opens a template, opens the create action,
|
||||
// captures the blank/disabled dialog, fills a unique name, creates it, captures
|
||||
// the success dialog and then the Pipelines list holding the new row. It sends a
|
||||
// real validate + submit, but only ever against the scratch database.
|
||||
async function runScratchCreate() {
|
||||
step("P5: creating a pipeline from a template (scratch server)");
|
||||
await ensureConnected();
|
||||
await page.clickText("nav.tabs button.tab", "Templates");
|
||||
await page.waitForSelector(".cards button.card", { timeout: 25000 });
|
||||
await page.click(".cards button.card");
|
||||
await page.waitForSelector(".detail .tabstrip", { timeout: 25000 });
|
||||
await page.waitForSelector(".template-create-open", { timeout: 15000 });
|
||||
|
||||
const actionLabel = await text(".template-create-open");
|
||||
if (actionLabel !== "Create pipeline from this template") {
|
||||
throw new Error(`create action label: ${actionLabel}`);
|
||||
}
|
||||
await page.click(".template-create-open");
|
||||
await page.waitForSelector(".template-create-dialog", { timeout: 15000 });
|
||||
|
||||
const blank = await page.evaluate(`(() => ({
|
||||
title: document.querySelector(".template-create-title")?.textContent ?? "",
|
||||
label: document.querySelector(".template-create-label")?.textContent ?? "",
|
||||
note: document.querySelector(".template-create-note")?.textContent ?? "",
|
||||
confirm: document.querySelector(".template-create-confirm")?.textContent ?? "",
|
||||
dismiss: document.querySelector(".template-create-cancel")?.textContent ?? "",
|
||||
confirmDisabled: document.querySelector(".template-create-confirm")?.disabled ?? null,
|
||||
fieldDisabled: document.querySelector(".template-create-name")?.disabled ?? null,
|
||||
}))()`);
|
||||
if (!blank.title.startsWith("Create from ")) throw new Error(`create dialog title: ${blank.title}`);
|
||||
if (blank.label !== "New pipeline name (required)") throw new Error(`create field label: ${blank.label}`);
|
||||
if (blank.note !== "Creates a new draft pipeline on the server from this template's source; it is not run.") {
|
||||
throw new Error(`create note: ${blank.note}`);
|
||||
}
|
||||
if (blank.confirm !== "Create") throw new Error(`create confirm: ${blank.confirm}`);
|
||||
if (blank.dismiss !== "Cancel") throw new Error(`create dismiss: ${blank.dismiss}`);
|
||||
if (blank.confirmDisabled !== true) throw new Error("Create was enabled with a blank name");
|
||||
if (blank.fieldDisabled !== false) throw new Error("the name field started disabled");
|
||||
console.log(` blank dialog: "${blank.title}" — Create disabled, field enabled, Cancel offered`);
|
||||
await shot("51-template-create-dialog.png");
|
||||
|
||||
const newName = `Scratch create ${Date.now()}`;
|
||||
await page.fill(".template-create-name", newName);
|
||||
await eventually(
|
||||
() => page.evaluate(`!document.querySelector(".template-create-confirm")?.disabled`),
|
||||
{ timeout: 5000, what: "Create to enable after a non-blank name" },
|
||||
);
|
||||
await page.click(".template-create-confirm");
|
||||
await page.waitForText(`Created "${newName}". It is in the Pipelines list.`, { timeout: 25000 });
|
||||
const success = await page.evaluate(`(() => ({
|
||||
text: document.querySelector(".template-create-success")?.textContent ?? "",
|
||||
dismiss: document.querySelector(".template-create-cancel")?.textContent ?? "",
|
||||
fieldDisabled: document.querySelector(".template-create-name")?.disabled ?? null,
|
||||
}))()`);
|
||||
if (success.text !== `Created "${newName}". It is in the Pipelines list.`) {
|
||||
throw new Error(`create success line: ${success.text}`);
|
||||
}
|
||||
if (success.dismiss !== "Close") throw new Error(`dismiss after success: ${success.dismiss}`);
|
||||
if (success.fieldDisabled !== true) throw new Error("the name field was not locked after a success");
|
||||
console.log(` created: ${JSON.stringify(success.text)}; dismiss now reads ${success.dismiss}`);
|
||||
await shot("52-template-created.png");
|
||||
|
||||
// Cancel now reads Close: dismissing it leaves the Templates view, then the
|
||||
// refreshed Pipelines list must hold the new row.
|
||||
await page.click(".template-create-cancel");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".template-create-dialog")`), {
|
||||
timeout: 5000,
|
||||
what: "the create dialog to close",
|
||||
});
|
||||
await page.clickText("nav.tabs button.tab", "Pipelines");
|
||||
await page.waitForText(newName, { timeout: 25000 });
|
||||
const listed = await page.evaluate(
|
||||
`document.querySelector("#pipelineRows")?.textContent.includes(${JSON.stringify(newName)}) ?? false`,
|
||||
);
|
||||
if (!listed) throw new Error("the created pipeline is not in the Pipelines list");
|
||||
console.log(" the created pipeline appears in the scratch server's Pipelines list");
|
||||
await shot("53-pipeline-created-list.png");
|
||||
}
|
||||
|
||||
// --- Omni-search (S1/S2) ---------------------------------------------------
|
||||
// The page's own search UI drives every one of the helpers below; nothing is
|
||||
// stubbed. `searchTargets` opens the panel (if it is not already open), types the
|
||||
@@ -281,6 +370,30 @@ try {
|
||||
browser = await launchChrome({ width: 1440, height: 900 });
|
||||
page = await browser.openPage(`http://127.0.0.1:${port}/`);
|
||||
|
||||
// C5 evidence needs to replay exact `chat_event` frames against the real page
|
||||
// (a real live turn is not available on demand without disrupting the operator's
|
||||
// server). A tiny WebSocket shim is installed before the page's own scripts on
|
||||
// every document from now on: it constructs the real socket and records it on
|
||||
// `window`, so the smoke can hand frames to the socket's own `onmessage` and the
|
||||
// app folds them through its real path. Every other frame (the subscribe ack, the
|
||||
// history reply) still comes from the real server.
|
||||
step("installing the WebSocket recorder shim before the page scripts");
|
||||
await page.addInitScript(`(() => {
|
||||
const Native = window.WebSocket;
|
||||
if (!Native || window.__pipelinesSocketShim) return;
|
||||
window.__pipelinesSocketShim = true;
|
||||
window.__pipelinesSockets = [];
|
||||
function Shim(url, protocols) {
|
||||
const ws = protocols === undefined ? new Native(url) : new Native(url, protocols);
|
||||
window.__pipelinesSockets.push(ws);
|
||||
window.__pipelinesSocket = ws;
|
||||
return ws;
|
||||
}
|
||||
Shim.prototype = Native.prototype;
|
||||
for (const key of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]) Shim[key] = Native[key];
|
||||
window.WebSocket = Shim;
|
||||
})()`);
|
||||
|
||||
// Deterministic dismissals: the attention set is read from localStorage once at
|
||||
// boot, so clear the key and reload before connecting so the surface derives
|
||||
// from an empty set regardless of any stale profile state.
|
||||
@@ -292,8 +405,23 @@ try {
|
||||
step("connecting the page to the server through its own proxy");
|
||||
await page.fill("#url", `ws://127.0.0.1:${port}/connect`);
|
||||
await page.click("#connectBtn");
|
||||
await page.waitForSelector(".row-title", { timeout: 25000 });
|
||||
// A scratch server starts with no pipelines at all, so the pipeline row that
|
||||
// proves the live list rendered is skipped there; the connection banner is
|
||||
// still awaited either way.
|
||||
if (!scratch) await page.waitForSelector(".row-title", { timeout: 25000 });
|
||||
await page.waitForText("connected", { timeout: 25000 });
|
||||
|
||||
// Scratch mode runs only the P5 create flow above and skips the live suite,
|
||||
// which needs the operator's real pipelines, runs and chat session. The guard
|
||||
// below wraps the live steps without reindenting them, keeping this diff
|
||||
// reviewable; both branches share this file's cleanup in the `finally`.
|
||||
if (scratch) {
|
||||
await runScratchCreate();
|
||||
console.log("\nUI SMOKE PASS");
|
||||
for (const shot of shots) console.log(` ${shot}`);
|
||||
}
|
||||
|
||||
if (!scratch) {
|
||||
const pipelineCount = await page.evaluate(
|
||||
`document.querySelectorAll("#pipelineRows button.row").length`,
|
||||
);
|
||||
@@ -3016,8 +3144,218 @@ try {
|
||||
await shot("64-chat-throwaway-closed.png");
|
||||
throwawaySessionId = null;
|
||||
|
||||
// C5: the shared live stream. A real live turn needs a prompt the operator's
|
||||
// server may not be running, so the real page is subscribed to the real
|
||||
// session and then exact `chat_event` frames are replayed through the socket's
|
||||
// own `onmessage` (see the shim installed before the page's scripts). The
|
||||
// subscribe ack and every history reply are real server traffic; only the
|
||||
// frames replayed below are synthetic, and this log says so explicitly.
|
||||
step("C5: the live stream — subscribe, replayed chat_event frames, stream state");
|
||||
await ensureConnected();
|
||||
await page.evaluate(`document.querySelector("#chatJump")?.click()`);
|
||||
|
||||
const chatBadge = () =>
|
||||
page.evaluate(
|
||||
`document.querySelector(".chat-context .live-badge .live-word")?.textContent ?? ""`,
|
||||
);
|
||||
const chatLive = await chatBadge();
|
||||
if (chatLive !== "live") {
|
||||
throw new Error(`chat stream badge should read "live" while subscribed, got ${JSON.stringify(chatLive)}`);
|
||||
}
|
||||
console.log(` chat stream badge while subscribed: "${chatLive}" (real chat_subscribe ack + real history)`);
|
||||
|
||||
const sessionId = openedId;
|
||||
const replayFrames = (frames) =>
|
||||
page.evaluate(`(() => {
|
||||
const ws = window.__pipelinesSocket;
|
||||
if (!ws || typeof ws.onmessage !== "function") return false;
|
||||
for (const frame of ${JSON.stringify(frames)}) {
|
||||
ws.onmessage({ data: JSON.stringify({ type: "chat_event", chat_event: frame }) });
|
||||
}
|
||||
return true;
|
||||
})()`);
|
||||
const agentCount = () => page.evaluate(`document.querySelectorAll("#chatTranscript .chat-turn-agent").length`);
|
||||
const indicator = () =>
|
||||
page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatRunning");
|
||||
if (!el) return null;
|
||||
return {
|
||||
spinner: !!el.querySelector(".spinner"),
|
||||
label: el.querySelector(".chat-running-label")?.textContent ?? "",
|
||||
elapsed: el.querySelector(".chat-running-elapsed")?.textContent ?? "",
|
||||
tools: [...el.querySelectorAll(".chat-running-tool")].map((line) => ({
|
||||
text: line.querySelector(".chat-running-tool-text")?.textContent ?? "",
|
||||
long: line.querySelector(".chat-tool-long")?.textContent ?? "",
|
||||
longTinted: line.classList.contains("chat-running-tool-long"),
|
||||
})),
|
||||
};
|
||||
})()`);
|
||||
|
||||
const applyFrames = async (frames, label) => {
|
||||
const ok = await replayFrames(frames);
|
||||
if (!ok) throw new Error(`C5: the socket shim did not expose the live socket to replay ${label}`);
|
||||
await eventually(() => page.evaluate(`!!document.querySelector("#chatTranscript")`), {
|
||||
what: "the transcript to render",
|
||||
});
|
||||
};
|
||||
|
||||
const agentBefore = await agentCount();
|
||||
const sessionFrame = (extra) => ({ session_id: sessionId, ...extra });
|
||||
|
||||
// 1. Reasoning and text deltas on one assistant message id: the answer grows
|
||||
// inside the existing agent bubble.
|
||||
await applyFrames(
|
||||
[
|
||||
sessionFrame({ message_id: "cap-live-1", kind: "reasoning", part: { id: "cap-live-1#reasoning#0" }, delta: "Planning the live capture." }),
|
||||
sessionFrame({ message_id: "cap-live-1", kind: "text", part: { id: "cap-live-1#text#0" }, delta: "The live turn is " }),
|
||||
sessionFrame({ message_id: "cap-live-1", kind: "text", part: { id: "cap-live-1#text#0" }, delta: "growing." }),
|
||||
],
|
||||
"the reasoning/text deltas",
|
||||
);
|
||||
const liveTurn = await page.evaluate(`(() => {
|
||||
const transcript = document.querySelector("#chatTranscript");
|
||||
const bubbles = [...transcript.querySelectorAll(".chat-turn-agent")];
|
||||
return {
|
||||
agents: bubbles.length,
|
||||
answers: bubbles.filter((b) => b.textContent.includes("The live turn is growing.")).length,
|
||||
reasoning: bubbles.some((b) => b.textContent.includes("Planning the live capture.")),
|
||||
};
|
||||
})()`);
|
||||
console.log(
|
||||
` replayed 3 frames (reasoning + 2 text deltas) → ${liveTurn.answers} agent bubble carries ` +
|
||||
`"The live turn is growing." + reasoning (transcript agent bubbles ${agentBefore} -> ${liveTurn.agents})`,
|
||||
);
|
||||
if (liveTurn.answers !== 1 || !liveTurn.reasoning || liveTurn.agents !== agentBefore) {
|
||||
throw new Error(`C5: the replayed deltas did not grow one agent bubble: ${JSON.stringify(liveTurn)}`);
|
||||
}
|
||||
await shot("56-chat-live-turn.png");
|
||||
|
||||
// 2. A running tool: the indicator's headline is `Running a tool…` with a
|
||||
// running-tool line and a live `· {elapsed}`.
|
||||
await applyFrames(
|
||||
[sessionFrame({ message_id: "cap-live-1", kind: "tool", part: { type: "tool", id: "cap-tool-1", name: "shell", state: { status: "running", input: { command: "npm run build" } } } })],
|
||||
"the running tool",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1300));
|
||||
const runningIndicator = await indicator();
|
||||
if (
|
||||
!runningIndicator ||
|
||||
!runningIndicator.spinner ||
|
||||
runningIndicator.label !== "Running a tool…" ||
|
||||
!/^· \d/.test(runningIndicator.elapsed) ||
|
||||
runningIndicator.tools.length < 1
|
||||
) {
|
||||
throw new Error(`C5: the running indicator is wrong: ${JSON.stringify(runningIndicator)}`);
|
||||
}
|
||||
console.log(
|
||||
` running indicator: spinner=${runningIndicator.spinner}, "${runningIndicator.label}", "${runningIndicator.elapsed}", ` +
|
||||
`${runningIndicator.tools.length} running-tool line(s) — "${runningIndicator.tools[0].text}"`,
|
||||
);
|
||||
await shot("57-chat-running.png");
|
||||
|
||||
// 3. A second running tool that started 61 s ago (protocol `time.ran`): the
|
||||
// `· long` mark, tinted with the error hue. Two assistant message ids are in
|
||||
// play now and the turn is still one bubble.
|
||||
await applyFrames(
|
||||
[
|
||||
sessionFrame({
|
||||
message_id: "cap-live-2",
|
||||
kind: "reasoning",
|
||||
part: { id: "cap-live-2#reasoning#0" },
|
||||
delta: "Streaming the second step.",
|
||||
}),
|
||||
sessionFrame({
|
||||
message_id: "cap-live-2",
|
||||
kind: "tool",
|
||||
part: { type: "tool", id: "cap-tool-2", name: "shell", state: { status: "running", input: { command: "npm run long" } }, time: { ran: Date.now() - 61000 } },
|
||||
}),
|
||||
],
|
||||
"the long-running tool",
|
||||
);
|
||||
const longCall = await indicator();
|
||||
const longLine = longCall?.tools.find((line) => line.long !== "");
|
||||
if (!longLine || !longLine.longTinted || !longLine.long.includes("long")) {
|
||||
throw new Error(`C5: no tinted long-running tool line: ${JSON.stringify(longCall)}`);
|
||||
}
|
||||
const agentsWithTwoIds = await agentCount();
|
||||
console.log(` long-call line: "${longLine.text}${longLine.long}" tinted=${longLine.longTinted}`);
|
||||
if (agentsWithTwoIds !== agentBefore) {
|
||||
throw new Error(`C5: two assistant message ids fragmented the live turn into ${agentsWithTwoIds} bubbles`);
|
||||
}
|
||||
await shot("58-chat-long-call.png");
|
||||
|
||||
// 4. Finish the tools and end the step: the indicator disappears and the same
|
||||
// single agent bubble stands, settled.
|
||||
await applyFrames(
|
||||
[
|
||||
sessionFrame({ message_id: "cap-live-1", kind: "tool", part: { type: "tool", id: "cap-tool-1", state: { status: "completed", content: [{ type: "text", text: "build ok" }] } } }),
|
||||
sessionFrame({ message_id: "cap-live-2", kind: "tool", part: { type: "tool", id: "cap-tool-2", state: { status: "completed", content: [{ type: "text", text: "long ok" }] } } }),
|
||||
sessionFrame({ message_id: "cap-live-2", kind: "step", step: { status: "ended" } }),
|
||||
],
|
||||
"the completed tools and the ended step",
|
||||
);
|
||||
const settled = await page.evaluate(`(() => {
|
||||
const transcript = document.querySelector("#chatTranscript");
|
||||
return {
|
||||
indicator: !!document.querySelector("#chatRunning"),
|
||||
agents: transcript.querySelectorAll(".chat-turn-agent").length,
|
||||
answers: [...transcript.querySelectorAll(".chat-turn-agent")].filter((b) => b.textContent.includes("The live turn is growing.")).length,
|
||||
};
|
||||
})()`);
|
||||
if (settled.indicator) throw new Error("C5: the running indicator survived the ended step");
|
||||
if (settled.agents !== agentBefore || settled.answers !== 1) {
|
||||
throw new Error(`C5: the settled turn is not the same single agent bubble: ${JSON.stringify(settled)}`);
|
||||
}
|
||||
console.log(
|
||||
` after the tools completed and the step ended: no indicator, still ${settled.agents} agent bubble ` +
|
||||
`carrying the live answer (unchanged from ${agentBefore})`,
|
||||
);
|
||||
await shot("59-chat-settled.png");
|
||||
|
||||
// The stream-state words. Dropping the socket unexpectedly reads `reconnecting`
|
||||
// while the client comes back; the reconnect re-subscribes the open chat and
|
||||
// refreshes its history wholesale, so the replayed turn above is gone — which is
|
||||
// exactly the promised wholesale replacement.
|
||||
await page.evaluate(`window.__pipelinesSocket && window.__pipelinesSocket.close(4000, "smoke drop")`);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector(".chat-context .live-badge .live-word")?.textContent === "reconnecting"`),
|
||||
{ timeout: 10000, what: "the chat badge to read reconnecting" },
|
||||
);
|
||||
console.log(` chat stream badge after an unexpected drop: "${await chatBadge()}"`);
|
||||
await ensureConnected(30000);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector(".chat-context .live-badge .live-word")?.textContent === "live"`),
|
||||
{ timeout: 30000, what: "the chat badge to return to live after reconnect" },
|
||||
);
|
||||
// The badge turns live as soon as the subscription is re-attached; the history
|
||||
// refresh that replaces the conversation follows it, so wait for the replayed
|
||||
// marker to actually disappear rather than racing the fetch.
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`!document.querySelector("#chatTranscript")?.textContent?.includes("The live turn is growing.")`,
|
||||
),
|
||||
{ timeout: 20000, what: "the reconnect to replace the conversation with fresh history" },
|
||||
);
|
||||
console.log(
|
||||
' after reconnect: chat badge "live" again and history replaced the replayed turn wholesale (marker gone)',
|
||||
);
|
||||
|
||||
// The third word: disconnecting entirely reads `not live`.
|
||||
await page.click("#connectBtn");
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector(".chat-context .live-badge .live-word")?.textContent === "not live"`),
|
||||
{ timeout: 15000, what: "the chat badge to read not live while idle" },
|
||||
);
|
||||
console.log(` chat stream badge after Disconnect: "${await chatBadge()}"`);
|
||||
|
||||
console.log(
|
||||
" NOTE: the chat_subscribe ack and every chat_history reply above came from the real server; only the chat_event frames were replayed",
|
||||
);
|
||||
|
||||
console.log("\nUI SMOKE PASS");
|
||||
for (const shot of shots) console.log(` ${shot}`);
|
||||
}
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
console.error(`\nUI SMOKE FAIL: ${error.message}`);
|
||||
|
||||
Reference in New Issue
Block a user