diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d9790a..ce85afd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,13 @@ All notable changes to LLeMbas Desktop. The format follows closing either keeps the shell. Offered where the computer allows a terminal (needs the server's 2.0.0-beta.8). The app opens the connection itself, with its sign-in: the page never holds it. "Continue in a terminal" is now in the chat's menu only. +- **What a reply is doing, the same way everywhere.** The line under a reply being written now + says it in the words every LLeMbas client uses (harness spec 3.4.0): queued, waiting for a + model and why, loading it, reading the prompt (with how far), thinking, writing (with its + speed), running a tool and what it runs, waiting for you, waiting for subagents, compacting, + retrying (counting down), stopped or failed -- each with how long it has lasted, kept moving + every second. From a server that sends no such line (before 2.0.0-beta.8), the app shows the + server's own words as before. Translations come with the server's. - `tests/ui/`: the page under a headless browser against a stand-in for the app's bridge, with the server's answers as a table (`node tests/ui/run.mjs`, needs Playwright and a Chromium). diff --git a/scripts/gen-i18n.py b/scripts/gen-i18n.py index b6079f2..f3b8a21 100755 --- a/scripts/gen-i18n.py +++ b/scripts/gen-i18n.py @@ -401,6 +401,42 @@ KEYS = ( "The terminal needs a newer LLeMbas server. Ask its administrator to update it.", ) +# The progress line's sentences (ui/js/progress.js; harness spec 3.4.0, `loop.json` +# progress.texts, its `{{field}}` written as `%(field)s`). Shared with every client, so they +# are the server's to translate and never in OWN: until its catalogues have one, that sentence +# shows in English and this script says how many are waiting -- not a failure. +SERVER_PENDING = ( + "Queued", + "Queued: %(ahead)s ahead", + "Waiting for %(model)s: %(reason)s", + "Loading %(model)s", + "Reading the prompt: %(done)s / %(total)s tokens (%(percent)s%%)", + "Reading the prompt", + "Thinking", + "Writing: %(rate)s tok/s", + "Writing", + "Running %(tool)s: %(what)s", + "Running %(tool)s", + "Waiting for you: %(what)s", + "Waiting for subagents: %(running)s running", + "Compacting the conversation", + "Retrying in %(in)s s: %(reason)s", + "Stopped", + "Stopped: %(reason)s", + "Failed: %(reason)s", + "it serves one request at a time and is answering another", + "all its slots are in use", + "its server holds another model now", + "allow %(tool)s?", + "an approval", + "a question", + "the plan", + "by you", + "step limit", + "budget", + "%(text)s · %(elapsed)s", +) + # The app's own sentences. The mode names (Manual, Edit, Auto, Plan) stay English, as the # server's catalogues keep them ("Režim Edit", "Modus Edit"); "Local" is the server's word for # the device, as the server's catalogue has it. @@ -2218,6 +2254,20 @@ def main() -> None: ours = OWN.get(lang, {}) table: dict[str, str] = {} from_server = 0 + waiting = 0 + for key in SERVER_PENDING: + if key in KEYS: + continue + text = theirs.get(key) + if not text: + waiting += 1 + elif set(FIELD.findall(text)) != set(FIELD.findall(key)): + print(f"gen-i18n: {lang}: the fields of {text!r} do not match {key!r}", file=sys.stderr) + problems += 1 + else: + table[key] = text + if waiting: + print(f"gen-i18n: {lang}: {waiting} progress sentences wait for the server's catalogue (English until then)") for key in KEYS: text = theirs.get(key) if text: @@ -2238,7 +2288,7 @@ def main() -> None: print(f"gen-i18n: {lang}: OWN has {key!r}, which no page uses", file=sys.stderr) problems += 1 catalogue[lang] = table - print(f"gen-i18n: {lang}: {len(table)} of {len(KEYS)} ({from_server} from the server)") + print(f"gen-i18n: {lang}: {len(table)} sentences, {from_server} of the page's {len(KEYS)} from the server") body = json.dumps(catalogue, ensure_ascii=False, indent=2, sort_keys=True) out = ( diff --git a/tests/ui/conformance/progress.json b/tests/ui/conformance/progress.json new file mode 100644 index 0000000..6096060 --- /dev/null +++ b/tests/ui/conformance/progress.json @@ -0,0 +1,333 @@ +{ + "about": "Progress (progress.md, spec 3.4.0): the text and the line every client draws for a progress object. `progress`: the object; `now`: the client's clock (Unix ms). Expect `text` — the phase's text from loop.json progress.texts, its fields filled (numbers written plainly: integers as they are, a rate with one decimal) — and `line` — `{{text}} · {{elapsed}}` with elapsed = now − since in whole seconds (5s, 1m 05s, 1h 02m), or the text alone for stopped and failed. retrying's `in` is counted down: in − floor((now − since) / 1000), never below 0. LLeMbas: services/progress.py; CLI: session/progress.ts.", + "cases": [ + { + "about": "Queued, nothing more known.", + "progress": { + "phase": "queued", + "since": 1762790400000 + }, + "now": 1762790405000, + "expect": { + "text": "Queued", + "line": "Queued · 5s" + } + }, + { + "about": "Queued behind two turns.", + "progress": { + "phase": "queued", + "since": 1762790400000, + "ahead": 2 + }, + "now": 1762790465000, + "expect": { + "text": "Queued: 2 ahead", + "line": "Queued: 2 ahead · 1m 05s" + } + }, + { + "about": "A one-request server answering another request.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "Qwen 27B", + "reason": "busy" + }, + "now": 1762790412400, + "expect": { + "text": "Waiting for Qwen 27B: it serves one request at a time and is answering another", + "line": "Waiting for Qwen 27B: it serves one request at a time and is answering another · 12s" + } + }, + { + "about": "Every slot taken.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "coder", + "reason": "slots" + }, + "now": 1762790401000, + "expect": { + "text": "Waiting for coder: all its slots are in use", + "line": "Waiting for coder: all its slots are in use · 1s" + } + }, + { + "about": "Another model on the one-model server.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "coder", + "reason": "group" + }, + "now": 1762790400000, + "expect": { + "text": "Waiting for coder: its server holds another model now", + "line": "Waiting for coder: its server holds another model now · 0s" + } + }, + { + "about": "Loading.", + "progress": { + "phase": "loading_model", + "since": 1762790400000, + "model": "Gemma 12B" + }, + "now": 1762794125000, + "expect": { + "text": "Loading Gemma 12B", + "line": "Loading Gemma 12B · 1h 02m" + } + }, + { + "about": "Reading the prompt: the percentage is floored.", + "progress": { + "phase": "reading_prompt", + "since": 1762790400000, + "done": 1999, + "total": 3000 + }, + "now": 1762790402000, + "expect": { + "text": "Reading the prompt: 1999 / 3000 tokens (66%)", + "line": "Reading the prompt: 1999 / 3000 tokens (66%) · 2s" + } + }, + { + "about": "Reading the prompt with no counts from the server.", + "progress": { + "phase": "reading_prompt", + "since": 1762790400000 + }, + "now": 1762790402000, + "expect": { + "text": "Reading the prompt", + "line": "Reading the prompt · 2s" + } + }, + { + "about": "Thinking.", + "progress": { + "phase": "thinking", + "since": 1762790400000 + }, + "now": 1762790459999, + "expect": { + "text": "Thinking", + "line": "Thinking · 59s" + } + }, + { + "about": "Writing, the rate with one decimal.", + "progress": { + "phase": "writing", + "since": 1762790400000, + "rate": 12.46 + }, + "now": 1762790404000, + "expect": { + "text": "Writing: 12.5 tok/s", + "line": "Writing: 12.5 tok/s · 4s" + } + }, + { + "about": "Writing before a rate is measured.", + "progress": { + "phase": "writing", + "since": 1762790400000 + }, + "now": 1762790400400, + "expect": { + "text": "Writing", + "line": "Writing · 0s" + } + }, + { + "about": "A tool with what it does.", + "progress": { + "phase": "running_tool", + "since": 1762790400000, + "tool": "bash", + "what": "bun test" + }, + "now": 1762790461000, + "expect": { + "text": "Running bash: bun test", + "line": "Running bash: bun test · 1m 01s" + } + }, + { + "about": "A tool without a title.", + "progress": { + "phase": "running_tool", + "since": 1762790400000, + "tool": "recall" + }, + "now": 1762790401000, + "expect": { + "text": "Running recall", + "line": "Running recall · 1s" + } + }, + { + "about": "An approval, naming the tool.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "approval", + "tool": "bash" + }, + "now": 1762790430000, + "expect": { + "text": "Waiting for you: allow bash?", + "line": "Waiting for you: allow bash? · 30s" + } + }, + { + "about": "An approval with no tool named.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "approval" + }, + "now": 1762790400000, + "expect": { + "text": "Waiting for you: an approval", + "line": "Waiting for you: an approval · 0s" + } + }, + { + "about": "A question.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "question" + }, + "now": 1762790403000, + "expect": { + "text": "Waiting for you: a question", + "line": "Waiting for you: a question · 3s" + } + }, + { + "about": "The plan.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "plan" + }, + "now": 1762790403000, + "expect": { + "text": "Waiting for you: the plan", + "line": "Waiting for you: the plan · 3s" + } + }, + { + "about": "Subagents.", + "progress": { + "phase": "waiting_for_subagents", + "since": 1762790400000, + "running": 3 + }, + "now": 1762790490000, + "expect": { + "text": "Waiting for subagents: 3 running", + "line": "Waiting for subagents: 3 running · 1m 30s" + } + }, + { + "about": "Compacting.", + "progress": { + "phase": "compacting", + "since": 1762790400000 + }, + "now": 1762790407000, + "expect": { + "text": "Compacting the conversation", + "line": "Compacting the conversation · 7s" + } + }, + { + "about": "Retrying: `in` counts down from since.", + "progress": { + "phase": "retrying", + "since": 1762790400000, + "reason": "502 Bad Gateway", + "in": 10, + "attempt": 2 + }, + "now": 1762790403000, + "expect": { + "text": "Retrying in 7 s: 502 Bad Gateway", + "line": "Retrying in 7 s: 502 Bad Gateway · 3s" + } + }, + { + "about": "Retrying: never below 0.", + "progress": { + "phase": "retrying", + "since": 1762790400000, + "reason": "overloaded", + "in": 2 + }, + "now": 1762790405000, + "expect": { + "text": "Retrying in 0 s: overloaded", + "line": "Retrying in 0 s: overloaded · 5s" + } + }, + { + "about": "Stopped draws no elapsed time.", + "progress": { + "phase": "stopped", + "since": 1762790400000 + }, + "now": 1762790405000, + "expect": { + "text": "Stopped", + "line": "Stopped" + } + }, + { + "about": "Stopped by the person.", + "progress": { + "phase": "stopped", + "since": 1762790400000, + "reason": "person" + }, + "now": 1762790405000, + "expect": { + "text": "Stopped: by you", + "line": "Stopped: by you" + } + }, + { + "about": "Stopped at the step limit.", + "progress": { + "phase": "stopped", + "since": 1762790400000, + "reason": "steps" + }, + "now": 1762790400000, + "expect": { + "text": "Stopped: step limit", + "line": "Stopped: step limit" + } + }, + { + "about": "Failed.", + "progress": { + "phase": "failed", + "since": 1762790400000, + "reason": "connection refused" + }, + "now": 1762790405000, + "expect": { + "text": "Failed: connection refused", + "line": "Failed: connection refused" + } + } + ] +} diff --git a/tests/ui/run.mjs b/tests/ui/run.mjs index 75ec98c..6483777 100644 --- a/tests/ui/run.mjs +++ b/tests/ui/run.mjs @@ -615,6 +615,49 @@ test("B3: at 1280 px the terminal sits beside the chat, which keeps its column", assert.deepEqual(p.errors, []) }) +// --- B1: the progress line --------------------------------------------------------------------- +// +// Harness spec 3.4.0 (harness/progress.md in the LLeMbas CLI): one `progress` object, drawn by +// every client as `{{text}} · {{elapsed}}`. tests/ui/conformance/progress.json is a copy of the +// spec's conformance/progress.json (3.4.0); every case must come out word for word. + +test("B1: every conformance case of the spec draws the same text and line", async () => { + const { cases } = JSON.parse(readFileSync(join(HERE, "conformance", "progress.json"), "utf8")) + const p = await page(b3()) + const got = await p.evaluate(async (cs) => { + const m = await import("/js/progress.js") + return cs.map((c) => ({ text: m.progressText(c.progress, c.now), line: m.progressLine(c.progress, c.now) })) + }, cases) + cases.forEach((c, i) => assert.deepEqual(got[i], c.expect, c.about)) + assert.deepEqual(p.errors, []) +}) + +test("B1: a reply being written draws the stream's progress, its clock moving, and the status text without one", async () => { + const p = await page(agentChatOpen([["status", { text: "Writing…" }]])) + await openChatRow(p, "chat2") + await p.waitForSelector(".msg.is-live .msg__status") + await p.evaluate((path) => { + window.__mock.frame(path, "status", { text: "Running bake --slow", progress: { phase: "running_tool", since: Date.now() - 65000, tool: "bash", what: "bake --slow" } }) + }, STREAM2) + const line = () => p.textContent(".msg.is-live .msg__status") + assert.equal(await line(), "Running bash: bake --slow · 1m 05s") + assert.equal(await p.getAttribute(".msg.is-live .msg__status", "data-phase"), "running_tool") + await p.waitForFunction(() => document.querySelector(".msg.is-live .msg__status").textContent.endsWith("1m 06s"), null, { timeout: 2500 }) + // A data-only frame with progress (the ask frame carries it too): the line follows. + await p.evaluate((path) => window.__mock.frame(path, "ask", { cards: [], progress: { phase: "waiting_for_person", since: Date.now(), what: "approval", tool: "bash" } }), STREAM2) + assert.equal(await line(), "Waiting for you: allow bash? · 0s") + // Nothing running: `progress: null`, and the status text is drawn again. + await p.evaluate((path) => window.__mock.frame(path, "status", { text: "Writing…", progress: null }), STREAM2) + assert.equal(await line(), "Writing…") + // An older server sends no progress at all: its status text, as before. + await p.evaluate((path) => window.__mock.frame(path, "status", { text: "Running bake --slow" }), STREAM2) + assert.equal(await line(), "Running bake --slow") + // Stopped and failed have no clock. + await p.evaluate((path) => window.__mock.frame(path, "status", { text: "Stopped.", progress: { phase: "stopped", since: Date.now() - 4000, reason: "person" } }), STREAM2) + assert.equal(await line(), "Stopped: by you") + assert.deepEqual(p.errors, []) +}) + // --- Run ---------------------------------------------------------------------------------------- const only = process.argv[2] || "" diff --git a/ui/i18n.js b/ui/i18n.js index 3b48a79..692f861 100644 --- a/ui/i18n.js +++ b/ui/i18n.js @@ -253,6 +253,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Zastavit %(name)s", "Stop %(name)s and the members under it? They leave the team.": "Zastavit %(name)s a členy pod ním? Opustí tým.", "Stop the agent": "Zastavit agenta", + "Stopped": "Zastaveno", "Stopped.": "Zastaveno.", "Subagent": "Podagent", "Subagents": "Podagenti", @@ -606,6 +607,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "%(name)s stoppen", "Stop %(name)s and the members under it? They leave the team.": "%(name)s und die Mitglieder darunter stoppen? Sie verlassen das Team.", "Stop the agent": "Agent anhalten", + "Stopped": "Angehalten", "Stopped.": "Angehalten.", "Subagent": "Subagent", "Subagents": "Subagenten", @@ -959,6 +961,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Detener %(name)s", "Stop %(name)s and the members under it? They leave the team.": "¿Detener %(name)s y a los miembros que dependen de él? Dejan el equipo.", "Stop the agent": "Detener el agente", + "Stopped": "Detenido", "Stopped.": "Detenido.", "Subagent": "Subagente", "Subagents": "Subagentes", @@ -1312,6 +1315,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Arrêter %(name)s", "Stop %(name)s and the members under it? They leave the team.": "Arrêter %(name)s et les membres qui en dépendent ? Ils quittent l’équipe.", "Stop the agent": "Arrêter l'agent", + "Stopped": "Arrêté", "Stopped.": "Arrêté.", "Subagent": "Sous-agent", "Subagents": "Sous-agents", @@ -1665,6 +1669,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "%(name)s leállítása", "Stop %(name)s and the members under it? They leave the team.": "Leállítja %(name)s tagot és az alatta lévőket? Kilépnek a csapatból.", "Stop the agent": "Ügynök leállítása", + "Stopped": "Leállítva", "Stopped.": "Leállítva.", "Subagent": "Alügynök", "Subagents": "Alügynökök", @@ -2018,6 +2023,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Ferma %(name)s", "Stop %(name)s and the members under it? They leave the team.": "Fermare %(name)s e i membri sotto di lui? Lasciano la squadra.", "Stop the agent": "Ferma l'agente", + "Stopped": "Fermato", "Stopped.": "Interrotto.", "Subagent": "Sottoagente", "Subagents": "Sottoagenti", @@ -2371,6 +2377,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Zatrzymaj %(name)s", "Stop %(name)s and the members under it? They leave the team.": "Zatrzymać %(name)s i członków pod nim? Opuszczą zespół.", "Stop the agent": "Zatrzymaj agenta", + "Stopped": "Zatrzymano", "Stopped.": "Zatrzymano.", "Subagent": "Podagent", "Subagents": "Podagenci", @@ -2724,6 +2731,7 @@ const LEMBAS_I18N = { "Stop %(name)s": "Zastaviť %(name)s", "Stop %(name)s and the members under it? They leave the team.": "Zastaviť %(name)s a členov pod ním? Opustia tím.", "Stop the agent": "Zastaviť agenta", + "Stopped": "Zastavené", "Stopped.": "Zastavené.", "Subagent": "Podagent", "Subagents": "Podagenti", diff --git a/ui/js/chat.js b/ui/js/chat.js index e1dc81e..fc9da96 100644 --- a/ui/js/chat.js +++ b/ui/js/chat.js @@ -18,6 +18,7 @@ import { readyIds, sending, sent, discard } from "./attach.js" import { watchActivity, activityChanged, planList, activityButton } from "./activity.js" import { agentBlock, agentReady, agentState, onAgentChange } from "./agent.js" import { folderName } from "./list.js" +import { isProgress, progressLine, progressTicks } from "./progress.js" import { aimTerminal, terminalButton, terminalOpen, toggleTerminal } from "./terminal.js" const MODES = ["manual", "edit", "auto", "plan"] @@ -351,6 +352,24 @@ class Live { this.el = h("article", { class: "msg msg--assistant is-live", dataset: { id: messageId } }, this.steps, this.thinking, this.tail, this.jobs, this.status) this.done = false this.handle = null + this.progress = null // the stream's `progress` (spec 3.4.0), drawn in place of `status` when it comes + this.said = "" // the last `status` text, for a server that sends no progress + this.clock = 0 + } + + /** The status line: the progress object's line where the server sends one, else its text. */ + drawStatus() { + const p = this.progress + this.status.textContent = isProgress(p) ? progressLine(p) : this.said || t("Writing…") + this.status.dataset.phase = isProgress(p) ? p.phase : "" + const ticks = progressTicks(p) + if (ticks && !this.clock) this.clock = setInterval(() => (this.done ? this.stopClock() : this.drawStatus()), 1000) + else if (!ticks) this.stopClock() + } + + stopClock() { + clearInterval(this.clock) + this.clock = 0 } async start() { @@ -366,11 +385,18 @@ class Live { stop() { this.done = true + this.stopClock() this.handle?.close() } frame(event, data) { if (this.done) return + // Any frame that carries `progress` (the status frame does, from server 2.0.0-beta.8 on): + // the object, or null for nothing running -- then the status text again. + if (data && typeof data === "object" && Object.prototype.hasOwnProperty.call(data, "progress")) { + this.progress = isProgress(data.progress) ? data.progress : null + if (event !== "status") this.drawStatus() + } switch (event) { case "steps": renderSteps(this.steps, data.steps || [], this.chat) @@ -380,7 +406,8 @@ class Live { this.tailed(data) break case "status": - this.status.textContent = data.text || t("Writing…") + this.said = data.text || "" + this.drawStatus() break case "ask": renderCards(this.chat, data.cards || []) @@ -399,6 +426,7 @@ class Live { break case "done": this.done = true + this.stopClock() this.el.replaceWith(assistantMessage(data.message, this.chat)) renderCards(this.chat, []) if (data.chat?.title) setTitle(data.chat.title) @@ -424,6 +452,7 @@ class Live { end(err) { if (this.done) return this.done = true + this.stopClock() if (open?.live === this) open.live = null setRunning(false) if (err) { diff --git a/ui/js/progress.js b/ui/js/progress.js new file mode 100644 index 0000000..6d4b18a --- /dev/null +++ b/ui/js/progress.js @@ -0,0 +1,135 @@ +// What a session is doing, as one line: the harness's `progress` object (spec 3.4.0, +// harness/progress.md in the LLeMbas CLI) drawn the way every client draws it -- +// `{{text}} · {{elapsed}}`, with the shared texts (`loop.json` progress.texts) as this page's +// sentences. The server sends the object beside the old `status` text in a chat's stream; where it +// sends none (an older server), the status text is drawn as before. +// +// The texts are the spec's, with its `{{field}}` written as the page's `%(field)s`; the server's +// catalogues translate them under the same English (scripts/gen-i18n.py). + +/** The thirteen phases: a text for each, and a variant where a field may be missing. */ +const TEXTS = { + queued: "Queued", + "queued.ahead": "Queued: %(ahead)s ahead", + waiting_for_model: "Waiting for %(model)s: %(reason)s", + loading_model: "Loading %(model)s", + reading_prompt: "Reading the prompt: %(done)s / %(total)s tokens (%(percent)s%%)", + "reading_prompt.bare": "Reading the prompt", + thinking: "Thinking", + writing: "Writing: %(rate)s tok/s", + "writing.bare": "Writing", + running_tool: "Running %(tool)s: %(what)s", + "running_tool.bare": "Running %(tool)s", + waiting_for_person: "Waiting for you: %(what)s", + waiting_for_subagents: "Waiting for subagents: %(running)s running", + compacting: "Compacting the conversation", + retrying: "Retrying in %(in)s s: %(reason)s", + stopped: "Stopped", + "stopped.reason": "Stopped: %(reason)s", + failed: "Failed: %(reason)s", +} + +/** The words a field stands for. */ +const REASONS = { + busy: "it serves one request at a time and is answering another", + slots: "all its slots are in use", + group: "its server holds another model now", +} +const WHAT = { + approval: "allow %(tool)s?", + "approval.bare": "an approval", + question: "a question", + plan: "the plan", +} +const STOPPED = { person: "by you", steps: "step limit", budget: "budget" } + +/** Every sentence above, for scripts/gen-i18n.py to find (it reads `t("…")` calls by hand). */ +export const PROGRESS_SENTENCES = [...Object.values(TEXTS), ...Object.values(REASONS), ...Object.values(WHAT), ...Object.values(STOPPED), "%(text)s · %(elapsed)s"] + +const NO_ELAPSED = ["stopped", "failed"] + +const has = (p, k) => p[k] !== undefined && p[k] !== null && p[k] !== "" + +/** A sentence in the page's language, `%%` a percent sign (the server's way), then its + * `%(field)s` filled -- in that order, so a field's own text is never read as a template. */ +function say(text, fields = {}) { + return t(text) + .replace(/%%/g, "\u0000") + .replace(/%\((\w+)\)s/g, (all, name) => (Object.prototype.hasOwnProperty.call(fields, name) ? String(fields[name]) : all)) + .replace(/\u0000/g, "%") +} + +/** An integer as it is; a rate with one decimal, in the page's language (12.5, 12,5). */ +function rate(n) { + try { + return new Intl.NumberFormat(document.documentElement.lang || "en", { useGrouping: false, minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(n) + } catch { + return Number(n).toFixed(1) + } +} +const int = (n) => String(Math.trunc(Number(n) || 0)) + +/** Whole seconds, as a ticking clock writes them: 5s, 1m 05s, 1h 02m. */ +export function elapsed(ms) { + const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000)) + if (total < 60) return `${total}s` + const minutes = Math.floor(total / 60) + if (minutes < 60) return `${minutes}m ${String(total % 60).padStart(2, "0")}s` + return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m` +} + +/** Whether `p` is a progress object this page can draw (one of the thirteen phases). */ +export function isProgress(p) { + return !!p && typeof p === "object" && Object.prototype.hasOwnProperty.call(TEXTS, p.phase) +} + +/** The phase's text, its fields filled; "" for nothing this page knows. */ +export function progressText(p, now = Date.now()) { + if (!isProgress(p)) return "" + switch (p.phase) { + case "queued": + return has(p, "ahead") ? say(TEXTS["queued.ahead"], { ahead: int(p.ahead) }) : say(TEXTS.queued) + case "waiting_for_model": + return say(TEXTS.waiting_for_model, { model: p.model || "", reason: REASONS[p.reason] ? say(REASONS[p.reason]) : p.reason || "" }) + case "loading_model": + return say(TEXTS.loading_model, { model: p.model || "" }) + case "reading_prompt": + if (!has(p, "done") || !(Number(p.total) > 0)) return say(TEXTS["reading_prompt.bare"]) + return say(TEXTS.reading_prompt, { done: int(p.done), total: int(p.total), percent: int(Math.floor((Number(p.done) * 100) / Number(p.total))) }) + case "writing": + return has(p, "rate") ? say(TEXTS.writing, { rate: rate(p.rate) }) : say(TEXTS["writing.bare"]) + case "running_tool": + return has(p, "what") ? say(TEXTS.running_tool, { tool: p.tool || "", what: p.what }) : say(TEXTS["running_tool.bare"], { tool: p.tool || "" }) + case "waiting_for_person": { + const what = p.what === "approval" ? (has(p, "tool") ? say(WHAT.approval, { tool: p.tool }) : say(WHAT["approval.bare"])) : WHAT[p.what] ? say(WHAT[p.what]) : p.what || "" + return say(TEXTS.waiting_for_person, { what }) + } + case "waiting_for_subagents": + return say(TEXTS.waiting_for_subagents, { running: int(p.running) }) + case "retrying": { + const left = Math.max(0, Math.trunc(Number(p.in) || 0) - Math.floor((now - Number(p.since || now)) / 1000)) + return say(TEXTS.retrying, { in: String(left), reason: p.reason || "" }) + } + case "stopped": + return has(p, "reason") ? say(TEXTS["stopped.reason"], { reason: STOPPED[p.reason] ? say(STOPPED[p.reason]) : p.reason }) : say(TEXTS.stopped) + case "failed": + return say(TEXTS.failed, { reason: p.reason || "" }) + default: + return say(TEXTS[p.phase]) + } +} + +/** + * The line: `{{text}} · {{elapsed}}`, the text alone for stopped and failed (and where `bare`: + * a row with no room for the clock). + */ +export function progressLine(p, now = Date.now(), { bare = false } = {}) { + const text = progressText(p, now) + if (!text || bare || NO_ELAPSED.includes(p.phase) || !has(p, "since")) return text + return say("%(text)s · %(elapsed)s", { text, elapsed: elapsed(now - Number(p.since)) }) +} + +/** Whether the line changes by itself as time passes (it has a clock, or a countdown). */ +export function progressTicks(p) { + return isProgress(p) && !NO_ELAPSED.includes(p.phase) && has(p, "since") +}