diff --git a/CHANGELOG.md b/CHANGELOG.md index 8541081..f62f938 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,22 @@ Harness spec 3.7.0: one display in every client. `cmd.exe` — started without `-l`, which none of them takes. (The runtime's pseudo-terminal is documented for Linux and macOS only, and there is no Windows build of the CLI yet: where a terminal cannot be opened, the refusal now says so in a sentence.) +- **Tool calls are shown as spec 3.7.0 says.** A call has one title from its start to its end — + the command, the pattern, the path — the same in the transcript, on the progress line, in + `lembas run` and over the link (a `bash` call used to be titled by its description in the + transcript and by its command elsewhere; a `grep` by its directory on the progress line). After + the title come what the result adds (`+12 −3`, `exit 2`, `14 hits`, the lines read) and how long + it took; a denied call shows its reason and no time; a call cut off by a stop no longer stays + "running". +- **A reply that was stopped or failed says so on the reply**, in the spec's words — `Stopped: by + you`, `Stopped: step limit`, `Stopped: budget`, `Failed: …` — once, in place of the separate + "cancelled" notice and the raw error line; a session opened again from the store says it again. +- **One clock on the working line**: the phase's own (`Running bash: bun test · 12s`); once the + turn has gone on longer than the phase it reads `12s of 1m 05s`, instead of a second + `turn 1m 05s`. +- **`Waiting for subagents: N running` counts the subagents that are running** (it always said 1). +- **Numbers in your locale's format** (`LC_ALL`, `LC_NUMERIC`, `LANG`): token counts, rates, hits. + Durations stay as they are; with no locale set, English grouping as before. - **Completing an `@file` or moving through the prompt box now counts columns as the box does**: with a wide character (CJK, an emoji) before the cursor, the `@` list could replace the wrong part of the line. diff --git a/src/acp/agent.ts b/src/acp/agent.ts index 4431d22..0f8290a 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -31,6 +31,7 @@ import { ToolError } from "../tool/tool.ts" import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts" import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts" import { pickShell, shellLaunch } from "./shellrc.ts" +import { callTitle } from "../session/display.ts" import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts" import { expandHome } from "../config/paths.ts" import { asMode, MODES, type Mode } from "../config/schema.ts" @@ -303,7 +304,7 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien sessionId, toolCall: { toolCallId: o.toolCallId ?? crypto.randomUUID(), - title: req.request.command ?? req.tool, + title: callTitle(req.args) ?? req.request.command ?? req.tool, kind: toolKind(req.tool), status: "pending", rawInput: req.args, @@ -1442,17 +1443,26 @@ export class AcpAgent { case "reasoning": return this.update(s, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: e.text } }) case "tool_start": - return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args }) + // One title for a call (display.md §1): the same as the transcript's and the progress line's. + return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.title ?? callTitle(e.args) ?? e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args }) case "tool_end": return this.update(s, { sessionUpdate: "tool_call_update", toolCallId: e.id, status: e.result.isError ? "failed" : "completed", - ...(e.result.title ? { title: e.result.title } : {}), content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }], }) case "tool_denied": - return this.update(s, { sessionUpdate: "tool_call_update", toolCallId: e.id, status: "failed", content: [{ type: "content", content: { type: "text", text: e.reason } }] }) + // Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas. + // Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas. + return this.update(s, { + sessionUpdate: "tool_call_update", + toolCallId: e.id, + status: "failed", + ...(e.title ? { title: e.title } : {}), + content: [{ type: "content", content: { type: "text", text: e.reason } }], + _meta: { lembas: { denied: true } }, + }) case "plan": return this.update(s, planUpdate(e.plan)) case "mode": diff --git a/src/bus/index.ts b/src/bus/index.ts index 9eef27d..668b674 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -26,9 +26,10 @@ export type Event = | { type: "tool_call_delta"; index: number; name?: string; argsDelta: string } /** The server reading the prompt, before the reply (llama.cpp): tokens in all, from its cache, read so far. */ | { type: "progress"; total: number; cache: number; processed: number; ms: number } - | { type: "tool_start"; id: string; name: string; args: unknown } + /** `title`: the call's one short title (harness display.md §1), made from `args` when it starts. */ + | { type: "tool_start"; id: string; name: string; args: unknown; title?: string } | { type: "tool_end"; id: string; name: string; result: ToolResult; ms: number } - | { type: "tool_denied"; id: string; name: string; reason: string } + | { type: "tool_denied"; id: string; name: string; reason: string; args?: unknown; title?: string } | { type: "usage" usage: Usage diff --git a/src/headless.ts b/src/headless.ts index 06b5856..58c4969 100644 --- a/src/headless.ts +++ b/src/headless.ts @@ -7,6 +7,9 @@ import type { PlanReply, PlanRequest } from "./tool/plan_submit.ts" import type { IconSet } from "./tui/icons.ts" import { loadTheme, type Theme } from "./tui/palette.ts" import { duration } from "./duration.ts" +import { blockOf, callTitle, resultFacts } from "./session/display.ts" +import { endLine, endOf, type Progress } from "./session/progress.ts" +import { num } from "./tui/locale.ts" /** The theme's colours as 24-bit escapes — the same theme the TUI uses (`theme` in config.yaml). */ function escapes(theme: Theme) { @@ -26,6 +29,8 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo let inReasoning = false let atLineStart = true let started = false + const titles = new Map() + let failure: string | undefined const out = (s: string) => { if (!s) return process.stdout.write(s) @@ -53,11 +58,20 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo inReasoning = true out(c(C.think, e.text)) break + case "tool_start": + titles.set(e.id, e.title ?? callTitle(e.args)) + break case "tool_end": { + // A call as every client shows it (harness display.md): its one title, what the result + // adds, how long it took. const verb = e.name.padEnd(6) const mark = e.result.isError ? c(C.err, "✗") : "" - const title = e.result.title ?? (e.result.isError ? e.result.output.split("\n")[0]!.slice(0, 120) : "") - line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title} ${c(C.dim, duration(e.ms))} ${mark}`) + const title = titles.get(e.id) + titles.delete(e.id) + const facts = resultFacts(blockOf(e.name), title, e.result, num) + if (e.result.isError && !facts.length) facts.push(e.result.output.trim().split("\n")[0]!.slice(0, 120)) + const after = [...facts, duration(e.ms)].join(" · ") + line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title ? `${title} ${c(C.dim, `· ${after}`)}` : c(C.dim, after)} ${mark}`) break } case "sub_tool": @@ -72,7 +86,7 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo else if (e.state === "end") line(`${c(C.dim, "┊")} ${c(C.label, e.job.id)} ${e.job.state}${e.job.exit !== undefined ? ` (${e.job.exit === null ? "stopped" : `exit ${e.job.exit}`})` : ""} · ${e.job.description}`) break case "tool_denied": - line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.reason.split("\n")[0]!.slice(0, 140)}`) + line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.title ? `${e.title} ${c(C.dim, "·")} ` : ""}${e.reason.split("\n")[0]!.slice(0, 140)}`) break case "retract": if (!atLineStart) out("\n") @@ -82,12 +96,20 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo line(c(C.warn, `⚠ ${e.message}`)) break case "error": - line(c(C.err, `✗ ${e.message}`)) + // Said once, as the line that ends the reply. + failure = e.message break - case "done": + case "done": { if (!atLineStart) out("\n") - if (e.reason === "steps") line(c(C.warn, "⚠ stopped at the step limit")) + // How a reply that did not finish ended: the spec's line (display.md §4). + const end = endOf(e.reason, failure) + const text = end && endLine({ ...end, since: 0 } as Progress, 0, num) + if (text) line(end!.phase === "failed" ? c(C.err, `✗ ${text}`) : c(C.warn, `■ ${text}`)) + const more = end?.phase === "failed" ? failure?.trim().split("\n").slice(1).join("\n").trim() : "" + if (more) line(c(C.err, more)) + failure = undefined break + } } }) } diff --git a/src/jobs/registry.ts b/src/jobs/registry.ts index 5d9e1b5..0ee9994 100644 --- a/src/jobs/registry.ts +++ b/src/jobs/registry.ts @@ -466,7 +466,7 @@ export class JobRegistry { case "tool_end": case "tool_denied": { job.tools = (job.tools ?? 0) + 1 - const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `denied — ${e.reason.split("\n")[0]!.slice(0, 80)}` + const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `${e.title ? `${e.title} · ` : ""}denied — ${e.reason.split("\n")[0]!.slice(0, 80)}` const isError = e.type === "tool_denied" || e.result.isError === true this.append(job, `\n[${e.name}] ${title}${isError && e.type === "tool_end" ? " (error)" : ""}\n`) if (job.ownerCallId) owner?.bus.emit({ type: "sub_tool", callId: job.ownerCallId, jobId: job.id, name: e.name, title, ...(isError ? { isError } : {}) }) diff --git a/src/session/display.ts b/src/session/display.ts index 3ffebbc..aa140dc 100644 --- a/src/session/display.ts +++ b/src/session/display.ts @@ -1,7 +1,8 @@ // Display (harness spec 3.7.0, harness/display.md): what every client says about a tool call, the // end of a reply and a number — the title, the states, the facts after the title. Pure: the TUI, // the progress tracker and the ACP agent all read these. -import { LOOP } from "../harness.ts" +import { LOOP, TOOL_SPECS } from "../harness.ts" +import { resolveCall } from "../tool/names.ts" import { fillPrompt } from "../prompt/fill.ts" import { duration } from "../duration.ts" @@ -149,3 +150,26 @@ export function callFacts(f: { block?: string; diff?: string; exit?: number | nu /** Whether a tool's block is drawn as a call at all (display.md §3). */ export const drawnBlock = (block: string | undefined) => !D.not_drawn.includes(block ?? "tool") + +/** What a finished call's result adds after its title in this client's transcript: the spec's + * facts where the block has them (display.md §2), else what the tool's own summary says beyond + * the title ("anything else an implementation knows"): the lines read, a job's state. */ +export function resultFacts(block: string | undefined, title: string | undefined, result: { title?: string; meta?: Record }, num: NumberFormat = plainNumber): string[] { + const meta = result.meta ?? {} + const facts = callFacts( + { block, diff: typeof meta.diff === "string" ? meta.diff : undefined, exit: typeof meta.exit === "number" ? meta.exit : undefined, hits: typeof meta.hits === "number" ? meta.hits : undefined }, + num, + ) + // An edit says its change and a command that exited says its code (none for 0): nothing more. + if (facts.length || block === "edit" || (block === "shell" && typeof meta.exit === "number")) return facts + const said = result.title?.trim() + if (!said || said === title) return [] + const cut = said.lastIndexOf(" · ") + if (cut >= 0) return [said.slice(cut + 3)] + if (title && said.startsWith(title)) return [said.slice(title.length).trim()].filter(Boolean) + return [said] +} + +/** How a tool's call is read (its `block` in the spec), under its former names too; a tool the + * spec does not know (an MCP tool) is the generic block. */ +export const blockOf = (name: string): string => TOOL_SPECS[resolveCall(name, {}).name]?.block ?? "tool" diff --git a/src/session/engine.ts b/src/session/engine.ts index 3acbd14..4599d6b 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -24,9 +24,22 @@ import { memoryResults, presentIds, ResultContext } from "./results.ts" import { render } from "../plan/plan.ts" import { personTexts } from "../team/subagents.ts" import { ProgressTracker } from "./progress.ts" +import { callTitle } from "./display.ts" import type { Verdict } from "../team/delegation.ts" import { compactAsk, isNote, NO_CHANGING, noteFor, offeredFor, PREFIX_META, summaryOf, today, toldAt, unavailable, type Changing, type Kept, type Now, type Requirement, type Told } from "./prefix.ts" +/** A refused call's arguments and title, for those who draw it: the arguments as the model wrote + * them, when they are an object at all. */ +function deniedTitle(raw: string): { args?: unknown; title?: string } { + try { + const args: unknown = raw.trim() ? JSON.parse(raw) : {} + const title = callTitle(args) + return { args, ...(title ? { title } : {}) } + } catch { + return {} + } +} + export interface EngineOptions { bus: Bus asker: Asker @@ -137,6 +150,8 @@ const MAX_NUDGES = LOOP.nudges.max const wrapUpText = (limit: string) => fillPrompt(LOOP.wrap_up.message, { limit }) /** The session_meta key the plan is kept under. */ export const PLAN_META = "plan" +/** How the session's last turn ended when it did not finish (display.md §4): `{ reason, error? }`. */ +export const END_META = "ended" export class Engine { messages: Message[] = [] @@ -205,6 +220,15 @@ export class Engine { constructor(readonly o: EngineOptions) { this.progress = new ProgressTracker(o.bus) + // How a turn ended is kept with the session, so a reply that was stopped or failed says so + // again when the session is shown from the store (display.md §4). + let failure: string | undefined + o.bus.on((e) => { + if (e.type === "error") failure = e.message + if (e.type !== "done") return + if (this.o.store && this.sessionId) this.o.store.setMeta(this.sessionId, END_META, e.reason === "stop" ? null : { reason: e.reason, ...(e.reason === "error" && failure ? { error: failure } : {}) }) + failure = undefined + }) this.mode = o.mode this._effort = o.effort this.model = o.model @@ -353,6 +377,13 @@ export class Engine { return new ResultContext(this.o.store && sessionId ? this.o.store.results(sessionId) : memoryResults(), () => presentIds(this.messages)) } + /** How this session's last turn ended, when it did not finish — from the store. */ + storedEnd(): { reason: string; error?: string } | undefined { + if (!this.o.store || !this.sessionId) return undefined + const e = this.o.store.meta<{ reason?: unknown; error?: unknown } | null>(this.sessionId, END_META) + return e && typeof e.reason === "string" ? { reason: e.reason, ...(typeof e.error === "string" ? { error: e.error } : {}) } : undefined + } + /** The plan the store holds for this session, if any. */ private storedPlan(): Plan | undefined { if (!this.o.store || !this.sessionId) return undefined @@ -843,7 +874,7 @@ export class Engine { const decided = await this.decide(call, toolMap, cut) if ("result" in decided) { results.set(call.id, decided.result) - if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output }) + if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output, ...deniedTitle(call.args) }) } else { runnable.push({ call, ...decided }) argsOf.set(call.id, decided.args) @@ -883,7 +914,8 @@ export class Engine { for (const group of groups) { await Promise.all( group.map(async ({ call, tool, args, edited }) => { - bus.emit({ type: "tool_start", id: call.id, name: call.name, args }) + const title = callTitle(args) + bus.emit({ type: "tool_start", id: call.id, name: call.name, args, ...(title ? { title } : {}) }) const t0 = performance.now() let result: ToolResult try { diff --git a/src/session/progress.ts b/src/session/progress.ts index ff6c2b8..bbd6a4a 100644 --- a/src/session/progress.ts +++ b/src/session/progress.ts @@ -3,6 +3,7 @@ import { LOOP } from "../harness.ts" import { fillPrompt } from "../prompt/fill.ts" import { duration } from "../duration.ts" +import { callTitle, plainNumber, type NumberFormat } from "./display.ts" const P = LOOP.progress @@ -40,29 +41,28 @@ export const PHASES = P.phases as readonly Phase[] const fill = (t: string, v: Record) => fillPrompt(t, Object.fromEntries(Object.entries(v).map(([k, x]) => [k, String(x)]))) -/** A call's short title as `what`: one line, at most what_max characters. */ -export function shortWhat(s: string | undefined): string | undefined { - if (!s) return undefined - const line = s.split("\n")[0]!.trim() - if (!line) return undefined - return line.length > P.what_max ? `${line.slice(0, P.what_max - 1)}…` : line +/** An error or a reason as one line (progress.md §2: "one line"). */ +export function oneLine(s: string | undefined): string | undefined { + const line = s?.trim().split("\n")[0]?.trim() + return line || undefined } -/** The phase's text (progress.md §2), its fields filled; `now` for retrying's countdown. */ -export function progressText(p: Progress, now = Date.now()): string { +/** The phase's text (progress.md §2), its fields filled; `now` for retrying's countdown; `num` + * how numbers are written — plain unless the client passes its locale's (display.md §6). */ +export function progressText(p: Progress, now = Date.now(), num: NumberFormat = plainNumber): string { const T = P.texts as Record switch (p.phase) { case "queued": - return p.ahead !== undefined ? fill(T["queued.ahead"]!, { ahead: p.ahead }) : T.queued! + return p.ahead !== undefined ? fill(T["queued.ahead"]!, { ahead: num(p.ahead) }) : T.queued! case "waiting_for_model": return fill(T.waiting_for_model!, { model: p.model ?? "", reason: (P.reason as Record)[p.reason ?? ""] ?? p.reason ?? "" }) case "loading_model": return fill(T.loading_model!, { model: p.model ?? "" }) case "reading_prompt": if (p.total === undefined || p.done === undefined || p.total <= 0) return T["reading_prompt.bare"]! - return fill(T.reading_prompt!, { done: p.done, total: p.total, percent: Math.floor((p.done * 100) / p.total) }) + return fill(T.reading_prompt!, { done: num(p.done), total: num(p.total), percent: num(Math.floor((p.done * 100) / p.total)) }) case "writing": - return p.rate !== undefined && Number.isFinite(p.rate) ? fill(T.writing!, { rate: p.rate.toFixed(1) }) : T["writing.bare"]! + return p.rate !== undefined && Number.isFinite(p.rate) ? fill(T.writing!, { rate: num(p.rate, 1) }) : T["writing.bare"]! case "running_tool": return p.what ? fill(T.running_tool!, { tool: p.tool ?? "", what: p.what }) : fill(T["running_tool.bare"]!, { tool: p.tool ?? "" }) case "waiting_for_person": { @@ -71,7 +71,7 @@ export function progressText(p: Progress, now = Date.now()): string { return fill(T.waiting_for_person!, { what }) } case "waiting_for_subagents": - return fill(T.waiting_for_subagents!, { running: p.running ?? 0 }) + return fill(T.waiting_for_subagents!, { running: num(p.running ?? 0) }) case "retrying": { const left = Math.max(0, (p.in ?? 0) - Math.floor((now - p.since) / 1000)) return fill(T.retrying!, { in: left, reason: p.reason ?? "" }) @@ -87,17 +87,25 @@ export function progressText(p: Progress, now = Date.now()): string { /** The line a client draws (progress.md §3): the text and the time since it began, or the text * alone for stopped and failed. */ -export function progressLine(p: Progress, now = Date.now()): string { - const text = progressText(p, now) +export function progressLine(p: Progress, now = Date.now(), num: NumberFormat = plainNumber): string { + const text = progressText(p, now, num) if ((P.no_elapsed as string[]).includes(p.phase)) return text return fill(P.line, { text, elapsed: duration(now - p.since, true) }) } /** The line that stays on a reply that did not finish (display.md §4): the text of `stopped` or * `failed`, alone; nothing for a reply that finished, or a phase that is not an end. */ -export function endLine(p: Progress | null | undefined, now = Date.now()): string | undefined { +export function endLine(p: Progress | null | undefined, now = Date.now(), num: NumberFormat = plainNumber): string | undefined { if (!p || !LOOP.display.end.includes(p.phase)) return undefined - return progressLine(p, now) + return progressLine(p, now, num) +} + +/** How a turn that did not finish ended, from the engine's `done` reason (and the error said + * before it): the progress whose line stays on the reply (display.md §4). */ +export function endOf(reason: string, error?: string): Pick | undefined { + if (reason === "stop") return undefined + if (reason === "error") return { phase: "failed", reason: oneLine(error) ?? "error" } + return { phase: "stopped", reason: reason === "cancelled" ? "person" : reason } } /** Whether two objects are the same phase for the same thing (so `since` is kept). */ @@ -110,14 +118,6 @@ export function samePhase(a: Progress | null | undefined, b: Omit - for (const k of ["command", "path", "file_path", "pattern", "query", "url", "description", "name"]) if (typeof a[k] === "string" && a[k]) return shortWhat(a[k] as string) - return undefined -} - type BusLike = { on(fn: (e: any) => void): () => void; emit(e: any): void } /** The progress of one engine, derived from the events it emits (progress.md §4), and said on its @@ -128,6 +128,7 @@ export class ProgressTracker { current: Progress | null = null private rate: number | undefined private running = new Map>() + private subagents = new Set() private lastEmit = 0 private pendingTimer: ReturnType | undefined private error: string | undefined @@ -196,6 +197,19 @@ export class ProgressTracker { this.bus.emit({ type: "phase", progress: this.current ? { ...this.current } : null }) } + /** waiting_for_subagents with the count as it is now: the foreground task calls of this step, + * or every subagent of the session that is running, whichever is more. */ + private counted(p: Omit): Omit { + if (p.phase !== "waiting_for_subagents") return p + const calls = [...this.running.values()].filter((x) => x.phase === "waiting_for_subagents").length + return { ...p, running: Math.max(1, calls, this.subagents.size) } + } + + /** The count changed while the phase holds: the same phase, its data anew (`since` kept). */ + private recount() { + if (this.current?.phase === "waiting_for_subagents") this.set(this.counted({ phase: "waiting_for_subagents" })) + } + private on(e: any) { switch (e.type) { case "task": @@ -220,22 +234,31 @@ export class ProgressTracker { return case "tool_start": { const a = (e.args ?? {}) as Record - const p: Omit = e.name === "task" && a.background !== true ? { phase: "waiting_for_subagents", running: 1 } : { phase: "running_tool", tool: e.name, ...(callWhat(e.args) ? { what: callWhat(e.args) } : {}) } + // One title for a call (display.md §1): the event's, made when the call started. + const what: string | undefined = e.title ?? callTitle(e.args) + const p: Omit = e.name === "task" && a.background !== true ? { phase: "waiting_for_subagents", running: 1 } : { phase: "running_tool", tool: e.name, ...(what ? { what } : {}) } this.running.set(e.id, p) - if (this.running.size === 1) this.set(p) + if (this.running.size === 1) this.set(this.counted(p)) + else this.recount() return } case "tool_end": { this.running.delete(e.id) const next = this.running.values().next() - if (!next.done) this.set(next.value) + if (!next.done) this.set(this.counted(next.value)) return } + case "job": + // The subagents working now, for waiting_for_subagents' count: this session's jobs. + if (e.job?.kind !== "subagent") return + if (e.state !== "end" && e.job.state === "running") this.subagents.add(e.job.id) + else this.subagents.delete(e.job.id) + return this.recount() case "notice": - if (e.retry) this.set({ phase: "retrying", reason: shortWhat(e.retry.reason) ?? "", in: e.retry.in, ...(e.retry.attempt ? { attempt: e.retry.attempt } : {}) }) + if (e.retry) this.set({ phase: "retrying", reason: oneLine(e.retry.reason) ?? "", in: e.retry.in, ...(e.retry.attempt ? { attempt: e.retry.attempt } : {}) }) return case "error": - this.error = shortWhat(String(e.message ?? "")) ?? "error" + this.error = oneLine(String(e.message ?? "")) ?? "error" return case "done": this.running.clear() diff --git a/src/tui/clipboard.ts b/src/tui/clipboard.ts index a7d2f15..cb67970 100644 --- a/src/tui/clipboard.ts +++ b/src/tui/clipboard.ts @@ -5,6 +5,8 @@ // machine itself, the system clipboard through wl-copy / xclip / xsel / pbcopy. VTE terminals // (GNOME Terminal, LXTerminal, Tilix) take neither OSC 52 nor synchronized output. +import { num } from "./locale.ts" + export interface ClipboardRenderer { readonly capabilities: { readonly remote: boolean; readonly osc52_support: "supported" | "unsupported" | "unknown" } | null copyToClipboardOSC52(text: string): boolean @@ -55,7 +57,7 @@ export function copyText(r: ClipboardRenderer, text: string, env: Env = process. * here (its probe often answers "unknown" and copies anyway — LXTerminal does), so a copy that * went out is not second-guessed. Only one that could go nowhere says how to copy instead. */ export function copiedMessage(n: number, c: Copied): { text: string; warn: boolean } { - const what = `${n.toLocaleString("en")} character${n === 1 ? "" : "s"}` + const what = `${num(n)} character${n === 1 ? "" : "s"}` if (c.via.length) return { text: `copied ${what}`, warn: false } return { text: `could not copy ${what}: hold Shift while you drag to select with the terminal itself, then Ctrl+Shift+C (or set mouse: false in config.yaml)`, warn: true } } diff --git a/src/tui/commands.ts b/src/tui/commands.ts index a116ae7..6ee756b 100644 --- a/src/tui/commands.ts +++ b/src/tui/commands.ts @@ -562,7 +562,7 @@ export const COMMANDS: Command[] = [ if (other(id)) return c.view.info(`that session is in ${store.session(id)?.root} — resume it there (lembas -c, /sessions)`, "warn") const why = await (c.share?.release(id) ?? Promise.resolve(undefined)) if (why) return c.view.info(`not resumed: ${why}`, "warn") - c.view.load(c.app.resume(id)) + c.view.load(c.app.resume(id), c.app.engine.storedEnd()) c.view.info(`resumed ${id}`) }, }) diff --git a/src/tui/components/messages.tsx b/src/tui/components/messages.tsx index 7604bb9..be6704b 100644 --- a/src/tui/components/messages.tsx +++ b/src/tui/components/messages.tsx @@ -5,31 +5,17 @@ import { estimateTokens } from "../../provider/tokens.ts" import { useTui } from "../context.ts" import type { Item } from "../state.ts" import { clipDiff } from "../diffclip.ts" -import { TOOL_SPECS } from "../../harness.ts" -import { resolveCall } from "../../tool/names.ts" +import { blockOf, callDuration, callTitle, drawnBlock, type CallState } from "../../session/display.ts" +import { num } from "../locale.ts" import { splitPrototypes } from "../../prototype/fence.ts" /** A call the transcript does not draw: a plan change (the panel above the prompt follows it) or a * tool the spec marks hidden — under its former name too (a stored session's `todo`). */ -const undrawn = (name: string) => { - const block = TOOL_SPECS[resolveCall(name, {}).name]?.block - return block === "plan" || block === "hidden" -} +const undrawn = (name: string) => !drawnBlock(blockOf(name)) const FILETYPES: Record = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", mjs: "javascript", md: "markdown", zig: "zig" } export const filetypeOf = (diff: string) => FILETYPES[/^\+\+\+ \S*\.(\w+)/m.exec(diff)?.[1] ?? ""] -/** The one-line summary of a call before its result says more, e.g. the command or the path. */ -function argSummary(args: unknown): string { - if (!args || typeof args !== "object") return "" - const a = args as Record - if (Array.isArray(a.questions)) return (a.questions as { header?: string }[]).map((q) => q.header).filter(Boolean).join(" · ") || "asking" - if (Array.isArray(a.phases)) return String(a.title ?? "").slice(0, 120) - if (typeof a.patch === "string") return [...a.patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1]).join(", ") - const v = a.description ?? a.command ?? a.path ?? a.pattern ?? a.id ?? "" - return String(v).split("\n")[0]!.slice(0, 120) -} - function UserMessage(p: { item: Extract }) { const { theme } = useTui() return ( @@ -95,7 +81,7 @@ function Reasoning(p: { item: Extract }) { }) const tokens = () => { const n = p.item.tokens ?? estimateTokens(p.item.text) - return `${p.item.tokens === undefined ? "~" : ""}${n.toLocaleString("en")} token${n === 1 ? "" : "s"}` + return `${p.item.tokens === undefined ? "~" : ""}${num(n)} token${n === 1 ? "" : "s"}` } const dots = () => ".".repeat(1 + (Math.floor((now() - p.item.started) / 400) % 3)) const line = () => (p.item.streaming ? `Thinking${dots()}` : p.item.ms !== undefined ? `Thought for ${duration(p.item.ms)} · ${tokens()}` : `Thought · ${tokens()}`) @@ -124,8 +110,15 @@ function ToolLine(p: { item: Extract }) { const { theme, view } = useTui() const c = () => theme().colors const emoji = () => (p.item.status === "denied" ? theme().icons.denied : (theme().toolEmoji[p.item.name] ?? (p.item.name.startsWith("mcp__") ? theme().icons.mcp : theme().icons.other))) - const title = () => p.item.title ?? argSummary(p.item.args) - const time = () => (p.item.status === "running" ? "…" : p.item.ms !== undefined ? duration(p.item.ms) : "") + // One title for a call, in every state (display.md §1); what its result adds comes after it. + const title = () => p.item.title ?? callTitle(p.item.args) ?? "" + const state = (): CallState => (p.item.status === "error" ? "failed" : p.item.status) + /** After the title: the facts, a failure's or a refusal's first line, and how long it took — + * never for a call that is running (a mark) or was denied (it did not run). */ + const after = () => { + if (state() === "running") return "…" + return [...(p.item.facts ?? []), ...(p.item.note ? [p.item.note] : []), ...[callDuration(state(), p.item.ms)].filter((x): x is string => !!x)].join(" · ") + } const tail = () => (p.item.output ?? "").trimEnd().split("\n").slice(-12).join("\n") // Short in the transcript, whole with ctrl+o; always a diff the renderer can parse. const shown = () => (view.state.expandTools ? { diff: p.item.diff ?? "", hidden: 0 } : clipDiff(p.item.diff ?? "", 24)) @@ -135,8 +128,8 @@ function ToolLine(p: { item: Extract }) { {theme().branding.toolPrefix} {emoji()}{" "} {p.item.name.padEnd(6)}{" "} - {title()}{" "} - {time()} + {title()} + {after() ? `${title() && after() !== "…" ? " · " : " "}${after()}` : ""} ✗ @@ -261,6 +254,27 @@ function ErrorLine(p: { item: Extract }) { ) } +/** How a reply that did not finish ended: the spec's line, kept on the reply (display.md §4). */ +function EndLine(p: { item: Extract }) { + const { theme } = useTui() + const fg = () => (p.item.failed ? theme().colors.error : theme().colors.muted) + return ( + + + {p.item.failed ? "✗ " : "■ "} + {p.item.line} + + + + + {p.item.more} + + + + + ) +} + export function Messages() { const { view } = useTui() return ( @@ -285,6 +299,9 @@ export function Messages() { } /> + + } /> + } /> diff --git a/src/tui/components/spinner.tsx b/src/tui/components/spinner.tsx index b74283b..ef6c76a 100644 --- a/src/tui/components/spinner.tsx +++ b/src/tui/components/spinner.tsx @@ -3,6 +3,8 @@ import { duration } from "../../duration.ts" import { progressLine } from "../../session/progress.ts" import { useTui } from "../context.ts" import { fmtTokens } from "./status.tsx" +import { LOOP } from "../../harness.ts" +import { num } from "../locale.ts" /** "reading the prompt 64% · 90k of 140k · ~2m left": the server's own count (llama.cpp's * return_progress). The time left is guessed from the reading so far, once there is enough of it; @@ -34,6 +36,15 @@ export function Spinner() { const sp = () => theme().spinner const pick = (list: string[], every: number) => list[Math.floor(tick() / every) % list.length] ?? "" const elapsed = () => (tick(), view.state.busySince ? duration(Date.now() - view.state.busySince, true) : "0s") + // One clock on the line. The spec's line carries the phase's own (`Thinking · 12s`, + // progress.md §3); the turn's time is said beside it only once it is another number — the turn + // has gone through more than this phase — and then as "12s of 1m 05s", not as a second clock. + const ofTurn = () => { + const s = view.state + if (!s.now || (LOOP.progress.no_elapsed as string[]).includes(s.now.phase) || !s.busySince) return "" + const turn = Date.now() - s.busySince + return Math.floor(turn / 1000) - Math.floor((Date.now() - s.now.since) / 1000) >= 2 ? ` of ${duration(turn, true)}` : "" + } const tokens = () => { tick() const { n, estimated } = view.taskTokens() @@ -49,7 +60,7 @@ export function Spinner() { const reading = s.now.phase === "reading_prompt" && s.progress const now = reading ? { ...s.now, done: s.progress!.done, total: s.progress!.total } : s.now const eta = reading ? etaOf(s.progress!) : "" - return `${progressLine(now)}${eta ? ` · ${eta}` : ""}` + return `${progressLine(now, Date.now(), num)}${ofTurn()}${eta ? ` · ${eta}` : ""}` } if (s.preparing) return `preparing ${s.preparing}` if (s.phase === "waiting" && s.progress) return reading(s.progress) @@ -64,7 +75,8 @@ export function Spinner() { {pick(sp().frames, 1)} {what()}{view.state.now ? " · " : "… "} - {view.state.now ? `turn ${elapsed()}` : elapsed()} · {tokens()} · esc to stop + {view.state.now ? "" : `${elapsed()} · `} + {tokens()} · esc to stop diff --git a/src/tui/index.tsx b/src/tui/index.tsx index f09ac4a..cb10d03 100644 --- a/src/tui/index.tsx +++ b/src/tui/index.tsx @@ -72,7 +72,7 @@ export function Boot(p: { options: TuiOptions; onQuit: () => void; onReload?: (a else if (id) void releaseForResume(id).then((why) => { if (why) fresh(`not resumed: ${why}`) - else view.load(a.resume(id)) + else view.load(a.resume(id), a.engine.storedEnd()) }) else fresh("no earlier session in this project to continue") } diff --git a/src/tui/locale.ts b/src/tui/locale.ts new file mode 100644 index 0000000..2b1b679 --- /dev/null +++ b/src/tui/locale.ts @@ -0,0 +1,5 @@ +// Numbers as the person's locale writes them (harness display.md §6): the terminal's LC_ALL, +// LC_NUMERIC or LANG. With none of them, or the C locale, English grouping as before. +import { localeNumber, terminalLocale } from "../session/display.ts" + +export const num = localeNumber(terminalLocale() ?? "en") diff --git a/src/tui/state.ts b/src/tui/state.ts index 7d85104..ea070d9 100644 --- a/src/tui/state.ts +++ b/src/tui/state.ts @@ -17,6 +17,11 @@ import { splitPrototypes, titleFor, type PrototypeKind } from "../prototype/fenc import { savePrototype } from "../prototype/store.ts" import { CHARS_PER_TOKEN } from "../provider/tokens.ts" import { isNote } from "../session/prefix.ts" +import { blockOf, callTitle, resultFacts as factsOf } from "../session/display.ts" +import { endLine, endOf, type Progress } from "../session/progress.ts" +import { num } from "./locale.ts" + +const resultFacts = (name: string, title: string | undefined, result: { title?: string; meta?: Record }) => factsOf(blockOf(name), title, result, num) export type Item = /** `mid`: sent while the agent worked, and given to it at a step boundary. `machine`: the harness @@ -31,7 +36,13 @@ export type Item = name: string args: unknown status: "running" | "done" | "error" | "denied" + /** The call's one short title (harness display.md §1), from its arguments: the same from + * its start to its end. */ title?: string + /** What its result adds after the title: `+3 −1`, `exit 2`, `14 hits`, the lines read. */ + facts?: string[] + /** A failed call's error, or why a call was denied: its first line. */ + note?: string ms?: number output?: string diff?: string @@ -45,6 +56,9 @@ export type Item = | { kind: "notice"; id: string; text: string; level: "info" | "warn" } | { kind: "diff"; id: string; title: string; patch: string } | { kind: "error"; id: string; text: string } + /** How a reply that did not finish ended: the spec's line (`Stopped: by you`, `Failed: …`), + * and for an error with more than one line, the rest of it. */ + | { kind: "end"; id: string; line: string; failed: boolean; more?: string } export type Phase = "idle" | "waiting" | "thinking" | "writing" | "tools" @@ -132,6 +146,15 @@ const byRunning = (a: JobInfo, b: JobInfo) => Number(b.state === "running") - Nu let seq = 0 const nextId = () => `i${++seq}` +/** The item that ends a reply which did not finish; none for one that did. */ +function endItem(reason: string, error?: string): Extract | undefined { + const end = endOf(reason, error) + const line = end && endLine({ ...end, since: 0 } as Progress, 0, num) + if (!end || !line) return undefined + const more = end.phase === "failed" ? error?.trim().split("\n").slice(1).join("\n").trim() : undefined + return { kind: "end", id: nextId(), line, failed: end.phase === "failed", ...(more ? { more } : {}) } +} + export function createView(bus: Bus) { const [state, set] = createStore({ items: [], phase: "idle", busySince: 0, showReasoning: false, expandTools: false, queued: { texts: [], mode: "steer" }, jobs: [] }) let stepStart = 0 @@ -139,6 +162,8 @@ export function createView(bus: Bus) { // streaming now, counted as it arrives so the number moves before the step's usage comes in. // Not in the store: the spinner reads them on its own tick. let inTask = false + /** The error of the turn that is ending, until its `done` draws it. */ + let failure: string | undefined let taskTokens = 0 let liveChars = 0 const startTask = () => { @@ -231,7 +256,7 @@ export function createView(bus: Bus) { set( produce((s) => { settle(s) - s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "running" }) + s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "running", title: e.title ?? callTitle(e.args) }) s.phase = "tools" s.preparing = undefined }), @@ -244,7 +269,9 @@ export function createView(bus: Bus) { produce((it) => { if (it.kind !== "tool") return it.status = e.result.isError ? "error" : "done" - it.title = e.result.title ?? (e.result.isError ? e.result.output.split("\n")[0] : undefined) + it.facts = resultFacts(it.name, it.title, e.result) + // A failure that says nothing beside its title says its first line. + if (e.result.isError && !it.facts.length) it.note = e.result.output.trim().split("\n")[0] it.ms = e.ms it.output = e.result.output it.diff = typeof e.result.meta?.diff === "string" ? (e.result.meta.diff as string) : undefined @@ -256,7 +283,7 @@ export function createView(bus: Bus) { ) break case "tool_denied": - set(produce((s) => void s.items.push({ kind: "tool", id: e.id, name: e.name, args: undefined, status: "denied", title: e.reason.split("\n")[0] }))) + set(produce((s) => void s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "denied", title: e.title ?? callTitle(e.args), note: e.reason.split("\n")[0] }))) break case "retract": set(produce((s) => void s.items.splice(stepStart))) @@ -323,7 +350,8 @@ export function createView(bus: Bus) { set(produce((s) => void s.items.push({ kind: "notice", id: nextId(), text: e.message, level: "warn" }))) break case "error": - set(produce((s) => void s.items.push({ kind: "error", id: nextId(), text: e.message }))) + // Said once, as the line that ends the reply (`Failed: …`), when the turn is done. + failure = e.message break case "done": set( @@ -332,10 +360,13 @@ export function createView(bus: Bus) { s.phase = "idle" s.preparing = undefined s.progress = undefined - if (e.reason === "cancelled") s.items.push({ kind: "notice", id: nextId(), text: "cancelled", level: "info" }) - if (e.reason === "steps") s.items.push({ kind: "notice", id: nextId(), text: "stopped at the step limit", level: "warn" }) + // A call still running when the turn ended never got its result: failed, not spinning. + for (const it of s.items) if (it.kind === "tool" && it.status === "running" && !it.jobId) it.status = "error" + const end = endItem(e.reason, failure) + if (end) s.items.push(end) }), ) + failure = undefined break } }) @@ -435,14 +466,14 @@ export function createView(bus: Bus) { set(produce((s) => void s.items.push({ kind: "tool", id, name: "bash", args: { command }, status: "running", title: `! ${command.split("\n")[0]}` }))) return id }, - shellEnd(id: string, r: { output: string; title?: string; isError?: boolean }, ms: number) { + shellEnd(id: string, r: { output: string; title?: string; isError?: boolean; meta?: Record }, ms: number) { set( "items", (it) => it.kind === "tool" && it.id === id, produce((it) => { if (it.kind !== "tool") return it.status = r.isError ? "error" : "done" - it.title = `${it.title} · ${r.title?.split(" · ").pop() ?? ""}` + it.facts = resultFacts("bash", undefined, r) it.output = r.output it.ms = ms }), @@ -472,8 +503,8 @@ export function createView(bus: Bus) { toggleTools() { set("expandTools", (v) => !v) }, - /** Show a stored conversation. */ - load(messages: Message[]) { + /** Show a stored conversation. `ended`: how its last turn ended, when it did not finish. */ + load(messages: Message[], ended?: { reason: string; error?: string }) { const items: Item[] = [] const tools = new Map>() for (const m of messages) { @@ -501,7 +532,7 @@ export function createView(bus: Bus) { try { args = JSON.parse(p.args) } catch {} - const t: Extract = { kind: "tool", id: p.id, name: p.name, args, status: "done" } + const t: Extract = { kind: "tool", id: p.id, name: p.name, args, status: "done", title: callTitle(args) } tools.set(p.id, t) items.push(t) } @@ -511,10 +542,13 @@ export function createView(bus: Bus) { if (t) { t.status = m.isError ? "error" : "done" t.output = m.content - t.title = m.content.split("\n")[0]!.slice(0, 100) + // A stored call keeps its title (its arguments are stored); its duration and facts were not. + if (m.isError) t.note = m.content.trim().split("\n")[0]!.slice(0, 100) } } } + const end = ended ? endItem(ended.reason, ended.error) : undefined + if (end) items.push(end) set({ items, usage: undefined, used: undefined }) }, } diff --git a/tests/acp.test.ts b/tests/acp.test.ts index 44c2e1b..c39d904 100644 --- a/tests/acp.test.ts +++ b/tests/acp.test.ts @@ -332,9 +332,34 @@ test("an approval nobody answers is a denial", async () => { await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "x" }] }) const u = updates.find((x) => x.sessionUpdate === "tool_call_update" && x.toolCallId === "t1") expect(u.status).toBe("failed") + // Refused, not run (spec 3.7.0 display.md): marked denied, under the call's one title. + expect(u._meta.lembas.denied).toBe(true) + expect(u.title).toBe("echo never") expect(fake.requests[1].messages.at(-1).content).toContain("Nobody answered") }) +test("a tool call's title over the link is the call's short title, and its result does not change it", async () => { + fake = fakeProvider([ + { chunks: [toolCall(0, "t1", "bash", JSON.stringify({ command: "echo one\necho two", description: "Say two things" })), toolCall(1, "t2", "job_list", "{}")] }, + { chunks: [delta({ content: "ok" })] }, + ]) + config(fake.url, "mode: auto\n") + const root = project() + const { c, updates, events } = await client({ roots: [root], maxMode: "auto", approvalTimeoutMs: 50, requireTrust: true }) + const s: any = await c.request("session/new", { cwd: root }) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "x" }] }) + const call = updates.find((x) => x.sessionUpdate === "tool_call" && x.toolCallId === "t1") + expect(call.title).toBe("echo one") + // A call with nothing to title it by goes by its tool's name. + expect(updates.find((x) => x.sessionUpdate === "tool_call" && x.toolCallId === "t2").title).toBe("job_list") + const done = updates.find((x) => x.sessionUpdate === "tool_call_update" && x.toolCallId === "t1") + expect(done.status).toBe("completed") + expect(done.title).toBeUndefined() + // The same title on the engine's own event, and as `what` of the progress. + expect(events.find((e: any) => e.type === "tool_start" && e.id === "t1").title).toBe("echo one") + expect(events.find((e: any) => e.type === "phase" && e.progress?.phase === "running_tool").progress.what).toBe("echo one") +}) + test("the link dials out with the token, says hello, is driven, and stops when refused", async () => { fake = fakeProvider([{ chunks: [delta({ content: "linked reply" })] }]) const root = project() diff --git a/tests/display.test.ts b/tests/display.test.ts new file mode 100644 index 0000000..40f2443 --- /dev/null +++ b/tests/display.test.ts @@ -0,0 +1,104 @@ +// Display per harness spec 3.7.0 (harness/display.md): one title for a call wherever it is said, +// the real count of running subagents, numbers in the terminal's locale. The spec's own cases are +// in harness/conformance/display.json (tests/conformance.test.ts). +import { expect, test } from "bun:test" +import { Bus } from "../src/bus/index.ts" +import { callTitle, localeNumber, plainNumber, resultFacts, terminalLocale } from "../src/session/display.ts" +import { endOf, ProgressTracker, progressLine, progressText, type Progress } from "../src/session/progress.ts" +import { permissionParams } from "../src/acp/agent.ts" + +const phases = (bus: Bus) => { + const seen: (Progress | null)[] = [] + bus.on((e) => e.type === "phase" && seen.push(e.progress as Progress | null)) + return seen +} + +test("the progress line's `what` is the call's title: the event's, else made from the arguments", () => { + const bus = new Bus() + const seen = phases(bus) + const t = new ProgressTracker(bus) + bus.emit({ type: "tool_start", id: "a", name: "grep", args: { pattern: "TODO", path: "src" } }) + expect(seen.at(-1)).toMatchObject({ phase: "running_tool", tool: "grep", what: "TODO" }) + bus.emit({ type: "tool_end", id: "a", name: "grep", result: { output: "" }, ms: 1 }) + bus.emit({ type: "tool_start", id: "b", name: "bash", args: { command: "bun test", description: "Run the tests" }, title: "bun test" }) + expect(seen.at(-1)).toMatchObject({ phase: "running_tool", tool: "bash", what: "bun test" }) + expect(callTitle({ command: "bun test", description: "Run the tests" })).toBe("bun test") + t.dispose() +}) + +test("waiting_for_subagents counts the subagents that are running, not always one", async () => { + const bus = new Bus() + const seen = phases(bus) + const t = new ProgressTracker(bus) + const job = (id: string, state: string) => ({ id, kind: "subagent", state, description: id, started: 0, unread: 0 }) as never + bus.emit({ type: "tool_start", id: "t1", name: "task", args: { description: "one", prompt: "p" } }) + expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 1 }) + const since = seen.at(-1)!.since + // Two more calls in the same step: three foreground subagents. + bus.emit({ type: "tool_start", id: "t2", name: "task", args: { description: "two", prompt: "p" } }) + bus.emit({ type: "tool_start", id: "t3", name: "task", args: { description: "three", prompt: "p" } }) + await Bun.sleep(300) // a change of the count is data: paced, and `since` kept + expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 3, since }) + // The session's subagent jobs count too — one more than the calls of this step. + for (const id of ["job1", "job2", "job3", "job4"]) bus.emit({ type: "job", state: "start", job: job(id, "running") }) + await Bun.sleep(300) + expect(seen.at(-1)).toMatchObject({ running: 4 }) + bus.emit({ type: "job", state: "end", job: job("job4", "done") }) + bus.emit({ type: "job", state: "end", job: job("job3", "done") }) + bus.emit({ type: "tool_end", id: "t3", name: "task", result: { output: "" }, ms: 1 }) + await Bun.sleep(300) + expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 2 }) + // A command in the background is not a subagent. + bus.emit({ type: "job", state: "start", job: { ...(job("job9", "running") as object), kind: "command" } as never }) + await Bun.sleep(300) + expect(seen.at(-1)).toMatchObject({ running: 2 }) + expect(progressText(seen.at(-1)!)).toBe("Waiting for subagents: 2 running") + t.dispose() +}) + +test("numbers in the terminal's locale; durations and the plain format untouched", () => { + expect(terminalLocale({ LANG: "sk_SK.UTF-8" })).toBe("sk-SK") + expect(terminalLocale({ LANG: "en_US.UTF-8", LC_NUMERIC: "de_DE.UTF-8" })).toBe("de-DE") + expect(terminalLocale({ LANG: "en_US.UTF-8", LC_NUMERIC: "de_DE.UTF-8", LC_ALL: "fr_FR@euro" })).toBe("fr-FR") + expect(terminalLocale({ LANG: "C.UTF-8" })).toBeUndefined() + expect(terminalLocale({ LC_ALL: "POSIX" })).toBeUndefined() + expect(terminalLocale({})).toBeUndefined() + expect(terminalLocale({ LANG: "not a locale!" })).toBeUndefined() + const de = localeNumber("de-DE") + const en = localeNumber("en-US") + expect([de(12480), de(12.46, 1), de(7)]).toEqual(["12.480", "12,5", "7"]) + expect([en(12480), en(12.46, 1), en(1234567)]).toEqual(["12,480", "12.5", "1,234,567"]) + expect([plainNumber(12480), plainNumber(12.46, 1)]).toEqual(["12480", "12.5"]) + expect(localeNumber(undefined)(12480)).toBe("12480") + expect(localeNumber("xx-not-a-locale-")(12480)).toBe("12480") + const reading: Progress = { phase: "reading_prompt", since: 0, done: 90000, total: 140000 } + expect(progressText(reading, 0, de)).toBe("Reading the prompt: 90.000 / 140.000 tokens (64%)") + expect(progressText(reading, 0)).toBe("Reading the prompt: 90000 / 140000 tokens (64%)") + // The clock is not a locale number. + expect(progressLine({ phase: "writing", since: 0, rate: 1234.56 }, 65_000, de)).toBe("Writing: 1.234,6 tok/s · 1m 05s") +}) + +test("what a finished call adds after its title", () => { + const diff = "--- a.txt\n+++ a.txt\n@@ -1,2 +1,3 @@\n one\n+two\n three\n" + expect(resultFacts("edit", "a.txt", { title: "a.txt +1 −0", meta: { diff } })).toEqual(["+1 −0"]) + expect(resultFacts("shell", "bun test", { title: "bun test · exit 0", meta: { exit: 0 } })).toEqual([]) + expect(resultFacts("shell", "bun test", { title: "bun test · exit 3", meta: { exit: 3 } })).toEqual(["exit 3"]) + // Stopped by a signal: no exit code, so what the tool says. + expect(resultFacts("shell", "sleep 9", { title: "sleep 9 · stopped (SIGTERM)", meta: { exit: null } })).toEqual(["stopped (SIGTERM)"]) + expect(resultFacts("search", "TODO", { title: "/TODO/ · 1234 matches", meta: { hits: 1234 } }, localeNumber("en-US"))).toEqual(["1,234 hits"]) + expect(resultFacts("read", "src/a.ts", { title: "src/a.ts · 1–200 of 950" })).toEqual(["1–200 of 950"]) + expect(resultFacts("tool", "theme", { title: "theme = moria (global)" })).toEqual(["= moria (global)"]) + expect(resultFacts("tool", "job3", { title: "job3 · stopped" })).toEqual(["stopped"]) + expect(resultFacts("read", "notes", { title: "notes" })).toEqual([]) + expect(resultFacts("tool", undefined, {})).toEqual([]) +}) + +test("over the link an approval's title is the call's title; how a turn ended, as the spec's progress", () => { + const p = permissionParams("s1", { tool: "bash", args: { command: "rm -rf build\necho done", description: "Clean" }, request: { command: "rm -rf build\necho done", patterns: [] }, decision: { reason: "asks", always: [] } } as never) + expect(p.toolCall.title).toBe("rm -rf build") + expect(endOf("stop")).toBeUndefined() + expect(endOf("cancelled")).toEqual({ phase: "stopped", reason: "person" }) + expect(endOf("steps")).toEqual({ phase: "stopped", reason: "steps" }) + expect(endOf("budget")).toEqual({ phase: "stopped", reason: "budget" }) + expect(endOf("error", "401 Unauthorized\nrun lembas login")).toEqual({ phase: "failed", reason: "401 Unauthorized" }) +}) diff --git a/tests/tui/app.test.tsx b/tests/tui/app.test.tsx index a574172..6fdb307 100644 --- a/tests/tui/app.test.tsx +++ b/tests/tui/app.test.tsx @@ -32,7 +32,8 @@ test("a prompt runs; a bash call asks; y allows it; the answer renders as markdo const f = t.frame() expect(f).toContain("❯ Ask") // the y that answered did not also land in the prompt expect(f).toContain("┃ make a file") - expect(f).toContain("┊ 💻 bash Write out.txt · exit 0") + // The call's one title — the command — and, finished, how long it took (spec 3.7.0 display.md). + expect(f).toMatch(/┊ 💻 bash echo hi > out\.txt · \d+\.\ds/) expect(f).not.toContain("## Done") // heading marker concealed expect(f).toContain("ctx 12k/33k 37%") expect(await Bun.file(`${t.cwd}/out.txt`).text()).toBe("hi\n") @@ -385,7 +386,8 @@ test("while it thinks: the thought says only Thinking…; the line at the bottom expect(await t.until("~15 tokens")).toBe(true) const frame = t.frame() expect(frame).toMatch(/^\s*Thinking\.{1,3}\s*$/m) - expect(frame).toMatch(/Thinking · \d+s · turn \d+s · ~15 tokens · esc to stop/) + // One clock: the phase's own; the turn's time joins it ("of 12s") only once it differs. + expect(frame).toMatch(/Thinking · \d+s( of \d+s)? · ~15 tokens · esc to stop/) expect(frame).not.toContain("HIDDEN-WHILE-THINKING") expect(await t.until("Done thinking.")).toBe(true) expect(t.frame()).toMatch(/Thought for \d\.\ds · ~15 tokens/) @@ -403,7 +405,7 @@ test("the line at the bottom counts the whole task: the clock and the tokens go // The spinner line redraws on its own tick, slower than the reply's text: on a slow machine the // frame that first shows "Half" can still carry the line from before. The 1.2 s gap holds this // state, so wait for the line within it rather than reading the first frame. - const counted = /Writing(: [\d.]+ tok\/s)? · \d+s · turn \d+s · ~4\d tokens · esc to stop/ + const counted = /Writing(: [\d.]+ tok\/s)? · \d+s( of \d+s)? · ~4\d tokens · esc to stop/ for (let i = 0; i < 20 && !counted.test(t.frame()); i++) await Bun.sleep(50), await t.settle() expect(t.frame()).toMatch(counted) expect(await t.until("way.")).toBe(true) @@ -881,7 +883,7 @@ test("esc mid-reply, then ctrl+g: it continues, and the model sees what it had a t.input.pressEnter() expect(await t.until("Step one is done.")).toBe(true) t.input.pressEscape() - expect(await t.until("cancelled")).toBe(true) + expect(await t.until("■ Stopped: by you")).toBe(true) await t.settle() t.input.pressKey("g", { ctrl: true }) expect(await t.until("↻ continue")).toBe(true) @@ -930,7 +932,7 @@ test("while the server reads a long prompt: the line at the bottom says how far t.input.pressEnter() // At 100 columns the line is cut in its middle; its start and its end are what is checked. expect(await t.until("~1m 40s left")).toBe(true) - expect(t.frame()).toContain("Reading the prompt: 90000 / 140000 tokens (64%") + expect(t.frame()).toContain("Reading the prompt: 90,000 / 140,000 tokens (64%") expect(await t.until("Read it all.")).toBe(true) await t.settle() expect(t.frame()).not.toContain("Reading the prompt") diff --git a/tests/tui/display.test.tsx b/tests/tui/display.test.tsx new file mode 100644 index 0000000..29abd7e --- /dev/null +++ b/tests/tui/display.test.tsx @@ -0,0 +1,79 @@ +// How the transcript draws a tool call and the end of a reply (harness spec 3.7.0, display.md). +import { afterEach, expect, test } from "bun:test" +import { delta, toolCall, usage } from "../fake-provider.ts" +import { tui } from "./harness.tsx" + +let t: Awaited> | undefined +afterEach(() => t?.stop()) + +test("a call keeps one title; done shows its facts and how long it took, failed its exit code, denied its reason and no time", async () => { + t = await tui( + [ + { + chunks: [ + toolCall(0, "c1", "grep", '{"pattern":"hello","path":"."}'), + toolCall(1, "c2", "edit", '{"path":"hello.txt","old":"hello world","new":"hello there\\nworld"}'), + toolCall(2, "c3", "bash", '{"command":"exit 3","description":"Fail on purpose"}'), + toolCall(3, "c4", "bash", '{"command":"git push origin main","description":"Push"}'), + ], + }, + { chunks: [delta({ content: "All done." }), usage(100, 5)] }, + ], + { width: 110, height: 34 }, + "mode: auto\npermission:\n bash:\n 'git push *': deny\n", + ) + await t.input.typeText("@hello.txt do things") + t.input.pressEnter() + expect(await t.until("All done.")).toBe(true) + const f = t.frame() + // A search is titled by its pattern, and says its hits. + expect(f).toMatch(/grep hello · 1 hit · \d+\.\ds/) + // An edit: the path, +added −removed, the time. + expect(f).toMatch(/edit hello\.txt · \+2 −1 · \d+\.\ds/) + // A command that failed: its own line as the title (not its description), the exit code. + expect(f).toMatch(/bash exit 3 · exit 3 · \d+\.\ds ✗/) + // Denied: the same title, the reason, and no duration — it never ran. + const denied = f.split("\n").find((l) => l.includes("git push origin main"))! + expect(denied).toContain("git push origin main · ") + expect(denied).not.toMatch(/\d+\.\ds/) + expect(denied).not.toContain("✗") +}) + +test("a reply that fails ends with the spec's line, once; one stopped by esc says Stopped: by you", async () => { + t = await tui([ + { status: 400, body: '{"error":{"message":"the model is not loaded"}}' }, + { status: 400, body: '{"error":{"message":"the model is not loaded"}}' }, + { status: 400, body: '{"error":{"message":"the model is not loaded"}}' }, + { chunks: [delta({ content: "Slow" }), delta({ content: "er" }), delta({ content: " still" }), delta({ content: " going" })], gapMs: 400 }, + ]) + await t.input.typeText("go") + t.input.pressEnter() + expect(await t.until("✗ Failed: ")).toBe(true) + const f = t.frame() + expect(f).toContain("the model is not loaded") + // Said once: no second, raw copy of the error beside the line. + expect(f.split("the model is not loaded").length - 1).toBe(1) + expect(f.split("Failed").length - 1).toBe(1) + await t.input.typeText("again") + t.input.pressEnter() + expect(await t.until("Slow")).toBe(true) + t.input.pressEscape() + expect(await t.until("■ Stopped: by you")).toBe(true) + // The earlier reply still says how it ended: the line stays on it. + expect(t.frame()).toContain("✗ Failed: ") + expect(t.frame()).not.toContain("cancelled") +}) + +test("a session shown again from the store says how its last reply ended", async () => { + t = await tui([{ chunks: [delta({ content: "Half an ans" }), delta({ content: "wer" }), delta({ content: " and" }), delta({ content: " more" })], gapMs: 400 }], undefined, "", { store: true }) + await t.input.typeText("tell me") + t.input.pressEnter() + expect(await t.until("Half an ans")).toBe(true) + t.input.pressEscape() + expect(await t.until("■ Stopped: by you")).toBe(true) + const id = t.app.engine.sessionId! + expect(t.app.engine.storedEnd()).toEqual({ reason: "cancelled" }) + t.view.load(t.app.resume(id), t.app.engine.storedEnd()) + await t.settle() + expect(t.frame()).toContain("■ Stopped: by you") +}) diff --git a/tests/tui/jobs.test.tsx b/tests/tui/jobs.test.tsx index 9514719..f3cd81d 100644 --- a/tests/tui/jobs.test.tsx +++ b/tests/tui/jobs.test.tsx @@ -244,7 +244,7 @@ test("ctrl+b moves the foreground command to the background: the call returns, t t.input.pressEnter() expect(await t.until("Allow once")).toBe(true) await t.input.typeText("y") - expect(await t.until("wait a while …")).toBe(true) + expect(await t.until("echo early; sleep 20; echo late …")).toBe(true) await Bun.sleep(300) t.input.pressKey("b", { ctrl: true }) expect(await t.until("Moved on.")).toBe(true)