@@ -0,0 +1,789 @@
1+/**
2+ * Terminal UI for mini-coder.
3+ *
4+ * Owns the cel-tui lifecycle (init/stop), renders the conversation log,
5+ * input area, animated divider, and status bar. Wires user input to the
6+ * agent loop and streams events back to the UI.
7+ *
8+ * @module
9+ */
10+
11+import { homedir } from "node:os";
12+import { Divider, Markdown, Spacer } from "@cel-tui/components";
13+import {
14+ cel,
15+ HStack,
16+ ProcessTerminal,
17+ Text,
18+ TextInput,
19+ VStack,
20+} from "@cel-tui/core";
21+import type { Node } from "@cel-tui/types";
22+import type {
23+ AssistantMessage,
24+ Message,
25+ TextContent,
26+ ThinkingContent,
27+ ToolCall,
28+} from "@mariozechner/pi-ai";
29+import { structuredPatch } from "diff";
30+import type { AgentEvent } from "./agent.ts";
31+import { runAgentLoop } from "./agent.ts";
32+import { getGitState } from "./git.ts";
33+import type { AppState } from "./index.ts";
34+import { buildPrompt, buildToolList, shutdown } from "./index.ts";
35+import { appendMessage, computeStats } from "./session.ts";
36+import { truncateOutput } from "./tools.ts";
37+
38+// ---------------------------------------------------------------------------
39+// Constants
40+// ---------------------------------------------------------------------------
41+
42+/** Max lines of shell output shown in the conversation log. */
43+const UI_MAX_SHELL_LINES = 200;
44+
45+/** Divider animation speed (ms per frame). */
46+const DIVIDER_FRAME_MS = 60;
47+
48+/** Width of the bright pulse segment in the animated divider. */
49+const PULSE_WIDTH = 5;
50+
51+// ---------------------------------------------------------------------------
52+// UI state (module-scoped, not in AppState)
53+// ---------------------------------------------------------------------------
54+
55+/** Scroll position for the conversation log. */
56+let scrollOffset = 0;
57+
58+/** Whether the log auto-scrolls to the bottom. */
59+let stickToBottom = true;
60+
61+/** Current text in the input area. */
62+let inputValue = "";
63+
64+/** Whether the text input is focused. */
65+let inputFocused = true;
66+
67+/** Animated divider frame counter. */
68+let dividerTick = 0;
69+
70+/** Divider animation timer handle. */
71+let dividerTimer: ReturnType<typeof setInterval> | null = null;
72+
73+/** Streaming text buffer for the current assistant response. */
74+let streamingText = "";
75+
76+/** Streaming thinking buffer for the current assistant response. */
77+let streamingThinking = "";
78+
79+/** Whether we are currently streaming a response. */
80+let isStreaming = false;
81+
82+/**
83+ * A tool call observed during streaming, before it lands in history.
84+ *
85+ * Stores the tool name and arguments from `tool_start`, and the
86+ * result text from `tool_end` (filled in when the tool finishes).
87+ */
88+interface PendingToolCall {
89+ /** Tool name. */
90+ name: string;
91+ /** Tool call arguments. */
92+ args: Record<string, unknown>;
93+ /** Text result, or `null` while still running. */
94+ resultText: string | null;
95+ /** Whether the tool result was an error. */
96+ isError: boolean;
97+}
98+
99+/** Tool calls collected during the current streaming turn. */
100+let pendingToolCalls: PendingToolCall[] = [];
101+
102+// ---------------------------------------------------------------------------
103+// Divider animation
104+// ---------------------------------------------------------------------------
105+
106+/** Start the scanning pulse animation on the divider. */
107+function startDividerAnimation(): void {
108+ stopDividerAnimation();
109+ dividerTick = 0;
110+ dividerTimer = setInterval(() => {
111+ dividerTick++;
112+ cel.render();
113+ }, DIVIDER_FRAME_MS);
114+}
115+
116+/** Stop the divider animation. */
117+function stopDividerAnimation(): void {
118+ if (dividerTimer) {
119+ clearInterval(dividerTimer);
120+ dividerTimer = null;
121+ }
122+}
123+
124+/**
125+ * Render the animated divider.
126+ *
127+ * When the agent is working, a bright segment sweeps across the dimmed
128+ * line. When idle, it's a static dimmed line.
129+ */
130+function renderDivider(state: AppState, width: number): Node {
131+ if (!state.running) {
132+ return Text("─", { repeat: "fill", fgColor: state.theme.divider });
133+ }
134+
135+ const total = Math.max(width, 1);
136+ const pos = dividerTick % (total + PULSE_WIDTH);
137+ const pulseStart = Math.max(0, pos - PULSE_WIDTH);
138+ const pulseEnd = Math.min(pos, total);
139+ const pulseLen = pulseEnd - pulseStart;
140+ const beforeLen = pulseStart;
141+ const afterLen = total - pulseEnd;
142+
143+ const segments: Node[] = [];
144+ if (beforeLen > 0) {
145+ segments.push(
146+ Text("─", { repeat: beforeLen, fgColor: state.theme.divider }),
147+ );
148+ }
149+ if (pulseLen > 0) {
150+ segments.push(
151+ Text("═", {
152+ repeat: pulseLen,
153+ fgColor: state.theme.dividerPulse,
154+ }),
155+ );
156+ }
157+ if (afterLen > 0) {
158+ segments.push(
159+ Text("─", { repeat: afterLen, fgColor: state.theme.divider }),
160+ );
161+ }
162+
163+ return HStack({ height: 1 }, segments);
164+}
165+
166+// ---------------------------------------------------------------------------
167+// Status bar formatting
168+// ---------------------------------------------------------------------------
169+
170+/** Abbreviate a path with ~ for the home directory. */
171+function abbreviatePath(p: string): string {
172+ const home = homedir();
173+ if (p === home) return "~";
174+ if (p.startsWith(`${home}/`)) return `~${p.slice(home.length)}`;
175+ return p;
176+}
177+
178+/** Format a token count with human-friendly units (1.2k, 45k, 1.2M). */
179+function formatTokens(n: number): string {
180+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
181+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
182+ return String(n);
183+}
184+
185+/** Format a dollar cost. */
186+function formatCost(cost: number): string {
187+ return `$${cost.toFixed(2)}`;
188+}
189+
190+/** Format the effort level for display. */
191+function formatEffort(effort: string): string {
192+ const map: Record<string, string> = {
193+ minimal: "min",
194+ low: "low",
195+ medium: "med",
196+ high: "high",
197+ xhigh: "xhigh",
198+ };
199+ return map[effort] ?? effort;
200+}
201+
202+/** Format git status for the status bar right side. */
203+function formatGitStatus(state: AppState): string {
204+ if (!state.git) return "";
205+ const parts: string[] = [state.git.branch];
206+ if (state.git.staged > 0) parts.push(`+${state.git.staged}`);
207+ if (state.git.modified > 0) parts.push(`~${state.git.modified}`);
208+ if (state.git.untracked > 0) parts.push(`?${state.git.untracked}`);
209+ if (state.git.ahead > 0) parts.push(`▲ ${state.git.ahead}`);
210+ if (state.git.behind > 0) parts.push(`▼ ${state.git.behind}`);
211+ return parts.join(" ");
212+}
213+
214+/** Format model info for the status bar left side. */
215+function formatModelInfo(state: AppState): string {
216+ if (!state.model) return "no model";
217+ return `${state.model.provider}/${state.model.id} · ${formatEffort(state.effort)}`;
218+}
219+
220+/** Format usage stats for the status bar right side. */
221+function formatUsage(state: AppState): string {
222+ if (!state.model) return "";
223+ const inp = formatTokens(state.stats.totalInput);
224+ const out = formatTokens(state.stats.totalOutput);
225+ const totalTokens = state.stats.totalInput + state.stats.totalOutput;
226+ const ctxPct =
227+ state.model.contextWindow > 0
228+ ? Math.round((totalTokens / state.model.contextWindow) * 100)
229+ : 0;
230+ return `in:${inp} out:${out} · ${ctxPct}% · ${formatCost(state.stats.totalCost)}`;
231+}
232+
233+// ---------------------------------------------------------------------------
234+// Message rendering
235+// ---------------------------------------------------------------------------
236+
237+/** Render a user message with a subtle background. */
238+function renderUserMessage(msg: Message, theme: AppState["theme"]): Node {
239+ const text =
240+ typeof msg.content === "string"
241+ ? msg.content
242+ : msg.content
243+ .filter((c): c is TextContent => c.type === "text")
244+ .map((c) => c.text)
245+ .join("");
246+
247+ return VStack({ bgColor: theme.userMsgBg, padding: { x: 1 } }, [
248+ Text(text, { wrap: "word" }),
249+ ]);
250+}
251+
252+/** Render a completed assistant message from history. */
253+function renderAssistantMessage(
254+ msg: AssistantMessage,
255+ state: AppState,
256+): Node[] {
257+ const nodes: Node[] = [];
258+
259+ for (const block of msg.content) {
260+ if (block.type === "text" && (block as TextContent).text) {
261+ nodes.push(
262+ ...Markdown((block as TextContent).text).map((n) =>
263+ HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
264+ ),
265+ );
266+ } else if (block.type === "thinking" && state.showReasoning) {
267+ const thinking = (block as ThinkingContent).thinking;
268+ if (thinking) {
269+ nodes.push(
270+ VStack({ padding: { x: 1 } }, [
271+ Text(thinking, {
272+ wrap: "word",
273+ fgColor: "color08",
274+ italic: true,
275+ }),
276+ ]),
277+ );
278+ }
279+ }
280+ }
281+
282+ if (msg.stopReason === "error" && msg.errorMessage) {
283+ nodes.push(
284+ VStack({ padding: { x: 1 } }, [
285+ Text(`Error: ${msg.errorMessage}`, {
286+ fgColor: state.theme.error,
287+ }),
288+ ]),
289+ );
290+ }
291+
292+ return nodes;
293+}
294+
295+/** Render a shell tool call with left border. */
296+function renderShellToolCall(
297+ command: string,
298+ output: string,
299+ _isError: boolean,
300+ state: AppState,
301+): Node {
302+ const displayed = state.verbose
303+ ? output
304+ : truncateOutput(output, UI_MAX_SHELL_LINES);
305+
306+ const lines: Node[] = [
307+ Text(`$ ${command}`, { fgColor: "color06", bold: true }),
308+ ];
309+ if (displayed) {
310+ lines.push(Text(displayed, { wrap: "word" }));
311+ }
312+
313+ return HStack({ padding: { x: 1 } }, [
314+ Text("│ ", { fgColor: state.theme.toolBorder }),
315+ VStack({ flex: 1, fgColor: state.theme.toolText }, lines),
316+ ]);
317+}
318+
319+/** Render an edit tool call with file path and unified diff. */
320+function renderEditToolCall(
321+ filePath: string,
322+ oldText: string,
323+ newText: string,
324+ isError: boolean,
325+ resultText: string,
326+ state: AppState,
327+): Node {
328+ if (isError) {
329+ return HStack({ padding: { x: 1 } }, [
330+ Text("│ ", { fgColor: state.theme.toolBorder }),
331+ VStack({ flex: 1 }, [Text(resultText, { fgColor: state.theme.error })]),
332+ ]);
333+ }
334+
335+ const lines: Node[] = [
336+ Text(`~ ${filePath}`, { fgColor: "color06", bold: true }),
337+ ];
338+
339+ if (oldText === "") {
340+ lines.push(Text("(new file)", { fgColor: state.theme.diffAdded }));
341+ } else {
342+ const patch = structuredPatch("", "", oldText, newText, "", "", {
343+ context: 2,
344+ });
345+ for (const hunk of patch.hunks) {
346+ for (const line of hunk.lines) {
347+ if (line.startsWith("+")) {
348+ lines.push(Text(line, { fgColor: state.theme.diffAdded }));
349+ } else if (line.startsWith("-")) {
350+ lines.push(Text(line, { fgColor: state.theme.diffRemoved }));
351+ } else {
352+ lines.push(Text(line, { fgColor: state.theme.toolText }));
353+ }
354+ }
355+ }
356+ }
357+
358+ return HStack({ padding: { x: 1 } }, [
359+ Text("│ ", { fgColor: state.theme.toolBorder }),
360+ VStack({ flex: 1 }, lines),
361+ ]);
362+}
363+
364+/** Render a generic (plugin) tool call with left border. */
365+function renderGenericToolCall(
366+ toolName: string,
367+ output: string,
368+ isError: boolean,
369+ state: AppState,
370+): Node {
371+ const fgColor = isError ? state.theme.error : state.theme.toolText;
372+
373+ return HStack({ padding: { x: 1 } }, [
374+ Text("│ ", { fgColor: state.theme.toolBorder }),
375+ VStack({ flex: 1 }, [
376+ Text(toolName, { fgColor: "color05", bold: true }),
377+ ...(output ? [Text(output, { wrap: "word", fgColor })] : []),
378+ ]),
379+ ]);
380+}
381+
382+/** Render a tool result, dispatching by tool name. */
383+function renderToolResult(
384+ toolName: string,
385+ args: Record<string, unknown>,
386+ resultText: string,
387+ isError: boolean,
388+ state: AppState,
389+): Node {
390+ if (toolName === "shell") {
391+ return renderShellToolCall(
392+ args.command as string,
393+ resultText,
394+ isError,
395+ state,
396+ );
397+ }
398+ if (toolName === "edit") {
399+ return renderEditToolCall(
400+ args.path as string,
401+ args.oldText as string,
402+ args.newText as string,
403+ isError,
404+ resultText,
405+ state,
406+ );
407+ }
408+ return renderGenericToolCall(toolName, resultText, isError, state);
409+}
410+
411+// ---------------------------------------------------------------------------
412+// Streaming response rendering
413+// ---------------------------------------------------------------------------
414+
415+/**
416+ * Render the in-progress streaming response.
417+ *
418+ * Shows thinking (if enabled), streamed markdown, and pending tool calls.
419+ */
420+function renderStreamingResponse(state: AppState): Node[] {
421+ const nodes: Node[] = [];
422+
423+ if (state.showReasoning && streamingThinking) {
424+ nodes.push(
425+ VStack({ padding: { x: 1 } }, [
426+ Text(streamingThinking, {
427+ wrap: "word",
428+ fgColor: "color08",
429+ italic: true,
430+ }),
431+ ]),
432+ );
433+ }
434+
435+ if (streamingText) {
436+ nodes.push(
437+ ...Markdown(streamingText).map((n) =>
438+ HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [n])]),
439+ ),
440+ );
441+ }
442+
443+ for (const tc of pendingToolCalls) {
444+ if (tc.resultText !== null) {
445+ nodes.push(
446+ renderToolResult(tc.name, tc.args, tc.resultText, tc.isError, state),
447+ );
448+ } else {
449+ // Tool still running — show indicator
450+ const label =
451+ tc.name === "shell"
452+ ? `$ ${tc.args.command ?? ""}…`
453+ : tc.name === "edit"
454+ ? `~ ${tc.args.path ?? ""}…`
455+ : `${tc.name}…`;
456+ nodes.push(
457+ HStack({ padding: { x: 1 } }, [
458+ Text("│ ", { fgColor: state.theme.toolBorder }),
459+ VStack({ flex: 1 }, [
460+ Text(label, { fgColor: "color06", italic: true }),
461+ ]),
462+ ]),
463+ );
464+ }
465+ }
466+
467+ return nodes;
468+}
469+
470+// ---------------------------------------------------------------------------
471+// Conversation log
472+// ---------------------------------------------------------------------------
473+
474+/** Build the full conversation log as an array of nodes. */
475+function buildConversationLog(state: AppState): Node[] {
476+ const nodes: Node[] = [];
477+
478+ // Map toolCallId → { name, args } so we can render diffs for edits.
479+ const toolCallArgs = new Map<
480+ string,
481+ { name: string; args: Record<string, unknown> }
482+ >();
483+
484+ for (const msg of state.messages) {
485+ if (msg.role === "user") {
486+ if (nodes.length > 0) nodes.push(Text(""));
487+ nodes.push(renderUserMessage(msg, state.theme));
488+ nodes.push(Text(""));
489+ } else if (msg.role === "assistant") {
490+ const am = msg as AssistantMessage;
491+ for (const block of am.content) {
492+ if (block.type === "toolCall") {
493+ const tc = block as ToolCall;
494+ toolCallArgs.set(tc.id, { name: tc.name, args: tc.arguments });
495+ }
496+ }
497+ nodes.push(...renderAssistantMessage(am, state));
498+ } else if (msg.role === "toolResult") {
499+ const info = toolCallArgs.get(msg.toolCallId);
500+ const name = info?.name ?? msg.toolName;
501+ const args = info?.args ?? {};
502+ const text = msg.content
503+ .filter((c): c is TextContent => c.type === "text")
504+ .map((c) => c.text)
505+ .join("\n");
506+ nodes.push(renderToolResult(name, args, text, msg.isError, state));
507+ }
508+ }
509+
510+ // Append in-progress streaming response
511+ if (isStreaming) {
512+ nodes.push(...renderStreamingResponse(state));
513+ }
514+
515+ // Empty state
516+ if (nodes.length === 0) {
517+ nodes.push(Spacer());
518+ nodes.push(
519+ VStack({ alignItems: "center" }, [
520+ Text(
521+ state.model
522+ ? "Ready. Type a message to start."
523+ : "No providers configured. Use /login to authenticate.",
524+ { fgColor: "color08", italic: true },
525+ ),
526+ ]),
527+ );
528+ nodes.push(Spacer());
529+ }
530+
531+ return nodes;
532+}
533+
534+// ---------------------------------------------------------------------------
535+// Agent loop wiring
536+// ---------------------------------------------------------------------------
537+
538+/** Send a plain text message and run the agent loop. */
539+async function submitMessage(text: string, state: AppState): Promise<void> {
540+ if (!text.trim() || !state.model || state.running) return;
541+
542+ const userMessage: Message = {
543+ role: "user",
544+ content: text,
545+ timestamp: Date.now(),
546+ };
547+
548+ // Append user message — returns the auto-assigned turn number
549+ const turn = appendMessage(state.db, state.session.id, userMessage);
550+ state.messages.push(userMessage);
551+ stickToBottom = true;
552+ cel.render();
553+
554+ // Refresh git state before each turn
555+ state.git = await getGitState(state.cwd);
556+
557+ const systemPrompt = buildPrompt(state);
558+ const { tools, toolHandlers } = buildToolList(state);
559+
560+ // Start agent loop
561+ state.running = true;
562+ state.abortController = new AbortController();
563+ isStreaming = true;
564+ streamingText = "";
565+ streamingThinking = "";
566+ pendingToolCalls = [];
567+ startDividerAnimation();
568+ cel.render();
569+
570+ try {
571+ await runAgentLoop({
572+ db: state.db,
573+ sessionId: state.session.id,
574+ turn,
575+ model: state.model,
576+ systemPrompt,
577+ tools,
578+ toolHandlers,
579+ messages: state.messages,
580+ cwd: state.cwd,
581+ signal: state.abortController.signal,
582+ onEvent: (event) => handleAgentEvent(event, state),
583+ });
584+ state.stats = computeStats(state.messages);
585+ } finally {
586+ state.running = false;
587+ state.abortController = null;
588+ isStreaming = false;
589+ streamingText = "";
590+ streamingThinking = "";
591+ pendingToolCalls = [];
592+ stopDividerAnimation();
593+ cel.render();
594+ }
595+}
596+
597+/** Handle events emitted by the agent loop. */
598+function handleAgentEvent(event: AgentEvent, state: AppState): void {
599+ switch (event.type) {
600+ case "text_delta":
601+ streamingText += event.delta;
602+ stickToBottom = true;
603+ cel.render();
604+ break;
605+
606+ case "thinking_delta":
607+ streamingThinking += event.delta;
608+ if (state.showReasoning) {
609+ stickToBottom = true;
610+ cel.render();
611+ }
612+ break;
613+
614+ case "tool_start":
615+ // The assistant message is appended to history before tool_start,
616+ // so clear the streaming buffers — that text is now in history.
617+ streamingText = "";
618+ streamingThinking = "";
619+ pendingToolCalls.push({
620+ name: event.name,
621+ args: event.args,
622+ resultText: null,
623+ isError: false,
624+ });
625+ stickToBottom = true;
626+ cel.render();
627+ break;
628+
629+ case "tool_end": {
630+ const pending = pendingToolCalls.find(
631+ (tc) => tc.name === event.name && tc.resultText === null,
632+ );
633+ if (pending) {
634+ pending.resultText = event.result.content
635+ .filter((c) => c.type === "text")
636+ .map((c) => (c as TextContent).text)
637+ .join("\n");
638+ pending.isError = event.result.isError;
639+ }
640+ stickToBottom = true;
641+ cel.render();
642+ break;
643+ }
644+
645+ case "done":
646+ case "error":
647+ case "aborted":
648+ // Completed messages are already in state.messages.
649+ streamingText = "";
650+ streamingThinking = "";
651+ pendingToolCalls = [];
652+ isStreaming = false;
653+ stickToBottom = true;
654+ cel.render();
655+ break;
656+ }
657+}
658+
659+// ---------------------------------------------------------------------------
660+// Graceful exit
661+// ---------------------------------------------------------------------------
662+
663+/** Shut down cleanly and exit. */
664+async function gracefulExit(state: AppState): Promise<void> {
665+ stopDividerAnimation();
666+ if (state.abortController) state.abortController.abort();
667+ cel.stop();
668+ await shutdown(state);
669+ process.exit(0);
670+}
671+
672+// ---------------------------------------------------------------------------
673+// Main
674+// ---------------------------------------------------------------------------
675+
676+/**
677+ * Start the terminal UI.
678+ *
679+ * Initializes cel-tui, sets up the viewport, and takes over the terminal.
680+ * Does not return until the user exits.
681+ *
682+ * @param state - The initialized application state from {@link init}.
683+ */
684+export function startUI(state: AppState): void {
685+ const terminal = new ProcessTerminal();
686+ cel.init(terminal);
687+
688+ cel.viewport(() => {
689+ const cols = terminal.columns;
690+
691+ return VStack(
692+ {
693+ height: "100%",
694+ onKeyPress: (key) => {
695+ if (key === "ctrl+c") {
696+ gracefulExit(state).catch(() => process.exit(1));
697+ return;
698+ }
699+ if (key === "ctrl+d" && inputValue === "") {
700+ gracefulExit(state).catch(() => process.exit(1));
701+ return;
702+ }
703+ if (key === "escape" && state.running) {
704+ if (state.abortController) state.abortController.abort();
705+ return;
706+ }
707+ return false;
708+ },
709+ },
710+ [
711+ // ── Conversation log ──
712+ VStack(
713+ {
714+ flex: 1,
715+ overflow: "scroll",
716+ scrollbar: true,
717+ scrollOffset: stickToBottom ? Infinity : scrollOffset,
718+ onScroll: (offset, maxOffset) => {
719+ scrollOffset = offset;
720+ stickToBottom = offset >= maxOffset;
721+ cel.render();
722+ },
723+ },
724+ buildConversationLog(state),
725+ ),
726+
727+ // ── Animated divider (pulse when agent is working) ──
728+ renderDivider(state, cols),
729+
730+ // ── Input area ──
731+ VStack({ padding: { x: 1 } }, [
732+ TextInput({
733+ flex: 1,
734+ maxHeight: 10,
735+ value: inputValue,
736+ onChange: (value) => {
737+ inputValue = value;
738+ cel.render();
739+ },
740+ placeholder: Text("message…", { fgColor: "color08" }),
741+ focused: inputFocused,
742+ onFocus: () => {
743+ inputFocused = true;
744+ cel.render();
745+ },
746+ onBlur: () => {
747+ inputFocused = false;
748+ cel.render();
749+ },
750+ onKeyPress: (key) => {
751+ if (key === "enter") {
752+ submitMessage(inputValue, state).catch((err) => {
753+ console.error("Submit error:", err);
754+ });
755+ inputValue = "";
756+ cel.render();
757+ return false;
758+ }
759+ },
760+ }),
761+ ]),
762+
763+ // ── Static divider ──
764+ Divider({ fgColor: state.theme.divider }),
765+
766+ // ── Status bar (2 lines) ──
767+ VStack(
768+ {
769+ height: 2,
770+ padding: { x: 1 },
771+ fgColor: state.theme.statusText,
772+ },
773+ [
774+ HStack({}, [
775+ Text(abbreviatePath(state.cwd)),
776+ Spacer(),
777+ Text(formatGitStatus(state), { fgColor: "color05" }),
778+ ]),
779+ HStack({}, [
780+ Text(formatModelInfo(state), { fgColor: "color06" }),
781+ Spacer(),
782+ Text(formatUsage(state)),
783+ ]),
784+ ],
785+ ),
786+ ],
787+ );
788+ });
789+}