xonecas.io
5875
Os

ollama-space-molt-player / commit d6d9f66

feat: add game status panel and enhance TUI with action result rendering

- Implement new game-status.ts panel for dynamic game state display
- Expand action-result.ts with comprehensive rendering logic
- Add theme colors and styling configuration
- Enhance layout management with flexible panel positioning
- Update game state tracking with additional fields
- Add test files for TUI panel validation and rendering

xonecas2026-02-02 d6d9f6695df2405e5b5451f9e1c0e30b0d52b8b0 parent 02ad716

18 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

src/game-state.ts+16−0
@@ -2,6 +2,7 @@ import type { ClientState } from "../client/src/client";
22 import type { WorldSnapshot } from "./prompt";
33 import type { TuiContext } from "./tui/index";
44 import type {
5+ ActionHistoryEntry,
56 Credentials,
67 RegistrationChoice,
78 RegistrationContext,
@@ -42,5 +43,20 @@ export class GameState {
4243 pendingActionId: number | null = null;
4344 pendingActionTimeout: ReturnType<typeof setTimeout> | null = null;
4445
46+ // Current game activity for status display
47+ currentActivity: import("./types").GameStatusType = "waiting_for_tick";
48+ activityDetails: string | null = null;
49+
50+ // Action history for result panel (max 5 entries)
51+ actionHistory: ActionHistoryEntry[] = [];
52+
4553 readonly MAX_REGISTRATION_RETRIES = 3;
54+ readonly MAX_ACTION_HISTORY = 5;
55+
56+ pushActionHistory(entry: ActionHistoryEntry): void {
57+ this.actionHistory.unshift(entry); // Add to front
58+ if (this.actionHistory.length > this.MAX_ACTION_HISTORY) {
59+ this.actionHistory.pop(); // Remove oldest
60+ }
61+ }
4662 }
src/index.ts+95−1
@@ -136,6 +136,7 @@ function updateOutput(): void {
136136 mission: gameState.currentMission,
137137 inCombat: gameState.inCombat,
138138 context: gameState.tuiContext,
139+ actionHistory: gameState.actionHistory,
139140 });
140141 }
141142
@@ -154,6 +155,8 @@ function captureActionResult(resultType: string, payload: unknown): void {
154155 clearTimeout(gameState.pendingActionTimeout);
155156 gameState.pendingActionTimeout = null;
156157 }
158+ // Push to action history when action completes
159+ pushCurrentActionToHistory();
157160 }
158161 // For "ok", only clear if it's NOT a mine action (mine waits for mining_yield)
159162 else if (resultType === "ok") {
@@ -164,6 +167,8 @@ function captureActionResult(resultType: string, payload: unknown): void {
164167 clearTimeout(gameState.pendingActionTimeout);
165168 gameState.pendingActionTimeout = null;
166169 }
170+ // Push to action history when action completes
171+ pushCurrentActionToHistory();
167172 }
168173 }
169174
@@ -173,6 +178,22 @@ function captureActionResult(resultType: string, payload: unknown): void {
173178 );
174179 }
175180
181+function pushCurrentActionToHistory(): void {
182+ const lastActionFormatted = buildLastActionResult(memory, getCurrentTick());
183+ if (lastActionFormatted && lastActionFormatted !== "No actions yet.") {
184+ const lastAction = memory.getLastActionWithResults();
185+ if (lastAction) {
186+ gameState.pushActionHistory({
187+ action: lastAction.action.action,
188+ result: lastActionFormatted,
189+ tick: getCurrentTick(),
190+ timestamp: Date.now(),
191+ });
192+ updateOutput();
193+ }
194+ }
195+}
196+
176197 function shouldStopForMaxTicks(allowFallbackCount: boolean): boolean {
177198 if (config.maxTicks === null) return false;
178199 const currentTick = client.state.currentTick;
@@ -287,9 +308,25 @@ async function startActionLoop(): Promise<void> {
287308 }
288309 try {
289310 if (inTransit) {
311+ // Update status: traveling or jumping
312+ if (gameState.travelInProgress && gameState.lastTravelTarget) {
313+ gameState.currentActivity = "traveling";
314+ gameState.activityDetails = gameState.lastTravelTarget;
315+ output.setGameStatus("traveling", gameState.lastTravelTarget);
316+ } else if (gameState.jumpInProgress && gameState.lastJumpTarget) {
317+ gameState.currentActivity = "jumping";
318+ gameState.activityDetails = gameState.lastJumpTarget;
319+ output.setGameStatus("jumping", gameState.lastJumpTarget);
320+ }
290321 await sleep(config.tickDelayMs);
291322 continue;
292323 }
324+
325+ // Update status: requesting action from AI
326+ gameState.currentActivity = "requesting_action";
327+ gameState.activityDetails = null;
328+ output.setGameStatus("requesting_action");
329+
293330 const recentHistory = memory.getRecentHistory(
294331 config.maxContextActions,
295332 config.maxContextEvents,
@@ -356,6 +393,10 @@ async function startActionLoop(): Promise<void> {
356393 output.setPrompt(prompt);
357394 output.logDebug("LLM_PROMPT", prompt);
358395
396+ // Update status: AI is thinking
397+ gameState.currentActivity = "llm_thinking";
398+ output.setGameStatus("llm_thinking");
399+
359400 const promptExcerpt = prompt.slice(0, 1000);
360401 const result = await ollama.generateJson(prompt);
361402 output.logDebug("LLM_RESPONSE_RAW", result.raw);
@@ -465,6 +506,10 @@ async function startActionLoop(): Promise<void> {
465506 action: validation.action,
466507 });
467508
509+ // Update status: processing result
510+ gameState.currentActivity = "processing_result";
511+ output.setGameStatus("processing_result");
512+
468513 if (actionName === "travel") {
469514 client.getSystem();
470515 client.getPOI();
@@ -487,6 +532,11 @@ async function startActionLoop(): Promise<void> {
487532 }
488533 }
489534
535+ // Update status: waiting for next tick
536+ gameState.currentActivity = "waiting_for_tick";
537+ gameState.activityDetails = null;
538+ output.setGameStatus("waiting_for_tick");
539+
490540 await sleep(config.tickDelayMs);
491541 }
492542
@@ -775,6 +825,10 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
775825 gameState.cachedShip = data.ship;
776826 }
777827
828+ // Track docked state changes
829+ const wasDocked = gameState.lastDocked;
830+ const isDocked = data.player ? Boolean(data.player.docked_at_base) : false;
831+
778832 if (data.player) {
779833 refreshSnapshotForLocation(data.player);
780834
@@ -799,11 +853,51 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
799853 const wasInCombat = gameState.inCombat;
800854 gameState.inCombat = data.in_combat ?? false;
801855
802- // Log combat state changes
856+ // Log combat state changes and update status
803857 if (gameState.inCombat && !wasInCombat) {
804858 output.log(formatSystemMessage("COMBAT STARTED", getCurrentTick()));
859+ const combatTarget = data.nearby?.find(
860+ (n) => n.player_id === data.target_id,
861+ );
862+ const targetName = combatTarget?.username || data.target_id || "unknown";
863+ gameState.currentActivity = "in_combat";
864+ gameState.activityDetails = targetName;
865+ output.setGameStatus("in_combat", targetName);
805866 } else if (!gameState.inCombat && wasInCombat) {
806867 output.log(formatSystemMessage("Combat ended", getCurrentTick()));
868+ // Reset to appropriate state after combat
869+ if (data.player?.docked_at_base) {
870+ gameState.currentActivity = "docked";
871+ gameState.activityDetails = data.player.current_poi || null;
872+ output.setGameStatus("docked", data.player.current_poi || undefined);
873+ } else {
874+ gameState.currentActivity = "waiting_for_tick";
875+ gameState.activityDetails = null;
876+ output.setGameStatus("waiting_for_tick");
877+ }
878+ } else if (gameState.inCombat && data.nearby) {
879+ // Update combat target name if it changed
880+ const combatTarget = data.nearby.find(
881+ (n) => n.player_id === data.target_id,
882+ );
883+ const targetName = combatTarget?.username || data.target_id || "unknown";
884+ if (targetName !== gameState.activityDetails) {
885+ gameState.activityDetails = targetName;
886+ output.setGameStatus("in_combat", targetName);
887+ }
888+ }
889+
890+ // Update docked status if changed and not in combat
891+ if (!gameState.inCombat) {
892+ if (isDocked && !wasDocked && data.player?.current_poi) {
893+ gameState.currentActivity = "docked";
894+ gameState.activityDetails = data.player.current_poi;
895+ output.setGameStatus("docked", data.player.current_poi);
896+ } else if (!isDocked && wasDocked) {
897+ gameState.currentActivity = "waiting_for_tick";
898+ gameState.activityDetails = null;
899+ output.setGameStatus("waiting_for_tick");
900+ }
807901 }
808902
809903 updateOutput();
src/output-interface.ts+2−0
@@ -1,11 +1,13 @@
11 import type { FormattedMessage } from "./tui/formatters";
22 import type { TuiUpdateData } from "./tui/index";
3+import type { GameStatusType } from "./types";
34
45 export interface OutputInterface {
56 log(message: FormattedMessage): void;
67 update(data: TuiUpdateData): void;
78 setStatus(text: string): void;
89 setPrompt(content: string): void;
10+ setGameStatus(activity: GameStatusType, details?: string): void;
911 logDebug(label: string, content: string): void;
1012 destroy(): void;
1113 onExit(handler: () => void): void;
src/output/file-logger-output.ts+7−0
@@ -54,6 +54,13 @@ export class FileLoggerOutput implements OutputInterface {
5454 // No-op in non-interactive mode.
5555 }
5656
57+ setGameStatus(
58+ _activity: import("../types").GameStatusType,
59+ _details?: string,
60+ ): void {
61+ // No-op in non-interactive mode.
62+ }
63+
5764 setPrompt(content: string): void {
5865 this.logDebug("PROMPT", content);
5966 }
src/output/tui-output.ts+7−0
@@ -26,6 +26,13 @@ export class TuiOutput implements OutputInterface {
2626 this.tui.setPrompt(content);
2727 }
2828
29+ setGameStatus(
30+ activity: import("../types").GameStatusType,
31+ details?: string,
32+ ): void {
33+ this.tui.setGameStatus(activity, details);
34+ }
35+
2936 logDebug(_label: string, _content: string): void {
3037 // No-op in interactive mode.
3138 }
src/tui/index.ts+85−5
@@ -2,11 +2,16 @@
22
33 import blessed from "blessed";
44 import type { Base, Player, POI, Ship, System } from "../../client/src/types";
5-import type { AlignmentType } from "../types";
5+import type {
6+ ActionHistoryEntry,
7+ AlignmentType,
8+ GameStatusType,
9+} from "../types";
610 import type { FormattedMessage } from "./formatters";
711 import { computeLayout, createBoxOptions } from "./layout";
812 import { renderActionResultPanel } from "./panels/action-result";
913 import { renderContextPanel } from "./panels/context";
14+import { renderGameStatusPanel } from "./panels/game-status";
1015 // Panels
1116 import { LogPanel, type LogTab } from "./panels/log";
1217 import {
@@ -74,6 +79,7 @@ export interface TuiUpdateData {
7479 maxShield?: number;
7580 };
7681 context?: TuiContext;
82+ actionHistory?: ActionHistoryEntry[];
7783 }
7884
7985 export class Tui {
@@ -86,6 +92,7 @@ export class Tui {
8692
8793 private logPanel: LogPanel;
8894 private actionResultBox: blessed.Widgets.BoxElement;
95+ private gameStatusBox: blessed.Widgets.BoxElement;
8996
9097 private tacticalBox: blessed.Widgets.BoxElement;
9198 private contextBox: blessed.Widgets.BoxElement;
@@ -96,6 +103,10 @@ export class Tui {
96103 private exitHandler: (() => void) | null = null;
97104 private debugEnabled: boolean;
98105
106+ // Spinner animation
107+ private spinnerFrame = 0;
108+ private spinnerInterval: NodeJS.Timeout | null = null;
109+
99110 // Cached state for rendering
100111 private state: TuiUpdateData = {};
101112
@@ -139,10 +150,15 @@ export class Tui {
139150 this.logPanel = new LogPanel(this.screen, layout.log);
140151
141152 this.actionResultBox = blessed.box(
142- createBoxOptions(layout.actionResult, " RESULT ", PALETTE.AMBER),
153+ createBoxOptions(layout.actionResult, " ACTIONS ", PALETTE.AMBER),
143154 );
144155 this.screen.append(this.actionResultBox);
145156
157+ this.gameStatusBox = blessed.box(
158+ createBoxOptions(layout.gameStatus, " ACTIVITY ", PALETTE.MOSS),
159+ );
160+ this.screen.append(this.gameStatusBox);
161+
146162 // -- RIGHT COLUMN --
147163 this.tacticalBox = blessed.box(
148164 createBoxOptions(layout.tactical, " TACTICAL ", THEME.BORDER_INACTIVE),
@@ -213,6 +229,13 @@ export class Tui {
213229 this.render();
214230 });
215231
232+ // Start spinner animation (updates every 100ms)
233+ this.spinnerInterval = setInterval(() => {
234+ this.spinnerFrame = (this.spinnerFrame + 1) % 10;
235+ this.updateGameStatusPanel();
236+ this.screen.render();
237+ }, 100);
238+
216239 this.render();
217240 }
218241
@@ -252,6 +275,8 @@ export class Tui {
252275 if (data.combatTarget !== undefined)
253276 this.state.combatTarget = data.combatTarget;
254277 if (data.context !== undefined) this.state.context = data.context;
278+ if (data.actionHistory !== undefined)
279+ this.state.actionHistory = data.actionHistory;
255280
256281 this.updatePanels();
257282 this.render();
@@ -268,7 +293,52 @@ export class Tui {
268293 this.screen.render();
269294 }
270295
296+ setGameStatus(activity: GameStatusType, details?: string): void {
297+ // Update state for game status
298+ if (!this.state.context) {
299+ this.state.context = {};
300+ }
301+ // Store activity in a temporary field for rendering
302+ (this.state as { currentActivity?: GameStatusType }).currentActivity =
303+ activity;
304+ (this.state as { activityDetails?: string | null }).activityDetails =
305+ details ?? null;
306+
307+ this.updateGameStatusPanel();
308+ this.screen.render();
309+ }
310+
311+ private updateGameStatusPanel(): void {
312+ const activity =
313+ (this.state as { currentActivity?: GameStatusType }).currentActivity ||
314+ "waiting_for_tick";
315+ const details =
316+ (this.state as { activityDetails?: string | null }).activityDetails ||
317+ null;
318+
319+ // Get panel width for centering ASCII art
320+ const panelWidth =
321+ typeof this.gameStatusBox.width === "number"
322+ ? this.gameStatusBox.width
323+ : 30; // Fallback
324+
325+ this.gameStatusBox.setContent(
326+ renderGameStatusPanel(
327+ {
328+ activity,
329+ details,
330+ spinnerFrame: this.spinnerFrame,
331+ },
332+ panelWidth,
333+ ),
334+ );
335+ }
336+
271337 destroy(): void {
338+ if (this.spinnerInterval) {
339+ clearInterval(this.spinnerInterval);
340+ this.spinnerInterval = null;
341+ }
272342 this.screen.destroy();
273343 }
274344
@@ -309,9 +379,18 @@ export class Tui {
309379 };
310380 this.navigationBox.setContent(renderNavigationPanel(navData));
311381
312- // Action Result
313- const lastResult = this.state.context?.lastActionResult;
314- this.actionResultBox.setContent(renderActionResultPanel(lastResult));
382+ // Action Result - pass history and panel width
383+ const history = this.state.actionHistory ?? [];
384+ const panelWidth =
385+ typeof this.actionResultBox.width === "number"
386+ ? this.actionResultBox.width
387+ : 50; // Fallback
388+ this.actionResultBox.setContent(
389+ renderActionResultPanel(history, panelWidth),
390+ );
391+
392+ // Game Status
393+ this.updateGameStatusPanel();
315394
316395 // Tactical Panel
317396 const tacticalData: TacticalData = {
@@ -371,6 +450,7 @@ export class Tui {
371450 // Center
372451 this.logPanel.updateDimensions(layout.log);
373452 this.updateBoxDims(this.actionResultBox, layout.actionResult);
453+ this.updateBoxDims(this.gameStatusBox, layout.gameStatus);
374454
375455 // Right
376456 this.updateBoxDims(this.tacticalBox, layout.tactical);
src/tui/layout.ts+19−5
@@ -28,6 +28,7 @@ export interface ComputedLayout {
2828 // Center Column
2929 log: PanelDimensions;
3030 actionResult: PanelDimensions;
31+ gameStatus: PanelDimensions;
3132
3233 // Right Column
3334 tactical: PanelDimensions;
@@ -81,9 +82,16 @@ export function computeLayout(
8182 );
8283
8384 // -- Center Column --
84- // Split: Log (75%), Action Result (25%)
85- const resultHeight = Math.max(6, Math.floor(availableHeight * 0.25));
86- const logHeight = Math.max(MIN_PANEL_HEIGHT, availableHeight - resultHeight);
85+ // Split: Log (75%), Bottom section (25%)
86+ // Bottom section splits horizontally: Result (70%) | Status (30%)
87+ const bottomSectionHeight = Math.max(6, Math.floor(availableHeight * 0.25));
88+ const logHeight = Math.max(
89+ MIN_PANEL_HEIGHT,
90+ availableHeight - bottomSectionHeight,
91+ );
92+
93+ const resultWidth = Math.floor(centerWidthAbs * 0.7);
94+ const statusWidth = centerWidthAbs - resultWidth;
8795
8896 // -- Right Column --
8997 // Split: Tactical (40%), Context (60%)
@@ -127,8 +135,14 @@ export function computeLayout(
127135 actionResult: {
128136 left: leftWidthAbs,
129137 top: logHeight,
130- width: centerWidthAbs,
131- height: resultHeight,
138+ width: resultWidth,
139+ height: bottomSectionHeight,
140+ },
141+ gameStatus: {
142+ left: leftWidthAbs + resultWidth,
143+ top: logHeight,
144+ width: statusWidth,
145+ height: bottomSectionHeight,
132146 },
133147
134148 // Right
src/tui/panels/action-result.ts+326−19
@@ -1,38 +1,345 @@
1-// Panel for displaying the result of the last action
1+// Panel for displaying the result of the last action with enhanced visuals
22
3-import { PALETTE, THEME } from "../theme";
3+import type { ActionHistoryEntry } from "../../types";
4+import { PALETTE, SYMBOLS, THEME } from "../theme";
45 import { applyBold, applyColor } from "../widgets";
56
6-export function renderActionResultPanel(
7- lastActionResult: string | null | undefined,
7+type ActionCategory = "navigation" | "resource" | "combat" | "info" | "social";
8+
9+/**
10+ * Strip blessed color tags to measure visual width
11+ * Example: "{red-fg}hello{/red-fg}" -> "hello"
12+ */
13+function stripBlessedTags(text: string): string {
14+ return text.replace(/\{[^}]*\}/g, "");
15+}
16+
17+/**
18+ * Calculate visual width (actual displayed characters)
19+ */
20+function getVisualWidth(text: string): number {
21+ return stripBlessedTags(text).length;
22+}
23+
24+/**
25+ * Pad text to target width by adding spaces on right
26+ * Preserves blessed tags but ensures visual width matches target
27+ */
28+function padToWidth(text: string, targetWidth: number): string {
29+ const visualWidth = getVisualWidth(text);
30+ const spacesNeeded = Math.max(0, targetWidth - visualWidth);
31+ return text + " ".repeat(spacesNeeded);
32+}
33+
34+/**
35+ * Create a content line with colored borders
36+ * Pads content first, then adds colored borders
37+ */
38+function createBorderedLine(
39+ content: string,
40+ contentWidth: number,
41+ borderColor: string,
42+ indent: string,
843 ): string {
9- if (!lastActionResult || !lastActionResult.trim()) {
10- return applyColor("No recent actions.", THEME.INACTIVE);
44+ const paddedContent = padToWidth(content, contentWidth);
45+ return (
46+ indent +
47+ applyColor("║", borderColor) +
48+ paddedContent +
49+ applyColor("║", borderColor)
50+ );
51+}
52+
53+function detectActionCategory(actionLine: string): ActionCategory {
54+ const lower = actionLine.toLowerCase();
55+
56+ if (
57+ lower.includes("travel") ||
58+ lower.includes("jump") ||
59+ lower.includes("dock") ||
60+ lower.includes("undock") ||
61+ lower.includes("arrived") ||
62+ lower.includes("jumped")
63+ ) {
64+ return "navigation";
1165 }
1266
67+ if (
68+ lower.includes("mine") ||
69+ lower.includes("buy") ||
70+ lower.includes("sell") ||
71+ lower.includes("refuel") ||
72+ lower.includes("repair")
73+ ) {
74+ return "resource";
75+ }
76+
77+ if (
78+ lower.includes("attack") ||
79+ lower.includes("scan") ||
80+ lower.includes("combat")
81+ ) {
82+ return "combat";
83+ }
84+
85+ if (
86+ lower.includes("forum") ||
87+ lower.includes("chat") ||
88+ lower.includes("say") ||
89+ lower.includes("faction") ||
90+ lower.includes("msg")
91+ ) {
92+ return "social";
93+ }
94+
95+ return "info";
96+}
97+
98+function getCategoryLabel(category: ActionCategory): string {
99+ switch (category) {
100+ case "navigation":
101+ return "NAVIGATION";
102+ case "resource":
103+ return "TRADE";
104+ case "combat":
105+ return "COMBAT";
106+ case "social":
107+ return "SOCIAL";
108+ case "info":
109+ return "STATUS";
110+ }
111+}
112+
113+function getCategoryBlock(category: ActionCategory): string {
114+ switch (category) {
115+ case "navigation":
116+ return SYMBOLS.NAV_BLOCK;
117+ case "resource":
118+ return SYMBOLS.RESOURCE_BLOCK;
119+ case "combat":
120+ return SYMBOLS.COMBAT_BLOCK;
121+ case "social":
122+ return SYMBOLS.INFO_BLOCK;
123+ case "info":
124+ return SYMBOLS.INFO_BLOCK;
125+ }
126+}
127+
128+function getCategoryColor(category: ActionCategory): string {
129+ switch (category) {
130+ case "navigation":
131+ return PALETTE.AMBER;
132+ case "resource":
133+ return PALETTE.MOSS;
134+ case "combat":
135+ return PALETTE.BRICK;
136+ case "social":
137+ return PALETTE.ORANGE;
138+ case "info":
139+ return PALETTE.WHITE;
140+ }
141+}
142+
143+function hasError(lines: string[]): boolean {
144+ return lines.some((line) => line.trim().startsWith("- ERROR"));
145+}
146+
147+function buildFrame(
148+ category: ActionCategory,
149+ hasError: boolean,
150+ panelWidth: number,
151+): { top: string; bottom: string; contentWidth: number; indent: string } {
152+ const block = getCategoryBlock(category);
153+ const label = getCategoryLabel(category);
154+ const color = hasError ? PALETTE.BRICK : getCategoryColor(category);
155+
156+ // Calculate frame width with padding from panel borders
157+ // panelWidth includes blessed borders (2 chars) + scrollbar (1 char when active)
158+ // We need: left padding (1) + our borders (2) + content + scrollbar (1) + blessed border (implied)
159+ const BLESSED_BORDERS = 2;
160+ const SCROLLBAR_WIDTH = 1;
161+ const LEFT_PADDING = 1;
162+ const RIGHT_MARGIN = 2; // Extra safety margin
163+ const frameWidth = Math.max(
164+ 20,
165+ panelWidth -
166+ BLESSED_BORDERS -
167+ SCROLLBAR_WIDTH -
168+ LEFT_PADDING -
169+ RIGHT_MARGIN,
170+ );
171+
172+ // Content width is what's available inside our custom borders
173+ const contentWidth = frameWidth - 2; // Minus our ║║ borders
174+ const indent = " "; // 1 space indent for left padding
175+
176+ // Top: ╔═══ LABEL ═══...╗
177+ const labelPart = ` ${label} `;
178+ const blockCount = 3;
179+ const leftBlocks = block.repeat(blockCount);
180+
181+ // Calculate remaining space for right blocks
182+ const innerWidth = frameWidth - 2; // Space between ╔ and ╗
183+ const usedWidth = blockCount + labelPart.length; // Left blocks + label
184+ const remainingWidth = Math.max(0, innerWidth - usedWidth); // Space for right blocks
185+ const rightBlocks = block.repeat(remainingWidth);
186+
187+ const topLine = `╔${leftBlocks}${labelPart}${rightBlocks}╗`;
188+ const bottomLine = `╚${"═".repeat(frameWidth - 2)}╝`;
189+
190+ return {
191+ top: applyColor(topLine, color),
192+ bottom: applyColor(bottomLine, color),
193+ contentWidth,
194+ indent,
195+ };
196+}
197+
198+function renderSingleResult(
199+ result: string,
200+ category: ActionCategory,
201+ hasErr: boolean,
202+ panelWidth: number,
203+ isLatest = false,
204+): string[] {
13205 const lines: string[] = [];
14- const raw = lastActionResult.trim();
206+ const frame = buildFrame(category, hasErr, panelWidth);
207+ const { contentWidth, indent } = frame;
208+ const borderColor = hasErr ? PALETTE.BRICK : getCategoryColor(category);
15209
16- // Try to parse standard format "Action: ... \n Result: ..."
17- // If it matches, we can style it better.
210+ // Add top border with indent
211+ lines.push(indent + frame.top);
18212
19- const parts = raw.split("\n");
213+ // Add top padding (blank line WITH borders)
214+ lines.push(createBorderedLine("", contentWidth, borderColor, indent));
20215
216+ // Process content lines
217+ const parts = result.trim().split("\n");
21218 for (const line of parts) {
22219 if (line.startsWith("Action:")) {
23- // Highlight the action header
24- lines.push(applyColor(applyBold(line), PALETTE.AMBER));
220+ // Action header - extract just the action part
221+ const actionText = line.replace(/^Action:\s*/, "");
222+ const symbol = hasErr ? SYMBOLS.ERROR : SYMBOLS.SUCCESS;
223+ const symbolColor = hasErr ? PALETTE.BRICK : PALETTE.MOSS;
224+ const latestBadge = isLatest ? " [LATEST]" : "";
225+
226+ // Calculate available space: " ✓ " = 5 chars, latestBadge = 9 chars (if present)
227+ const prefixLen = 5; // " ✓ "
228+ const badgeLen = latestBadge.length;
229+ const breathingRoom = 2; // Minimum spaces before closing ║
230+ const maxActionLen = contentWidth - prefixLen - badgeLen - breathingRoom;
231+
232+ // Truncate actionText if needed (subtract 3 for "...")
233+ const truncatedAction =
234+ actionText.length > maxActionLen
235+ ? actionText.substring(0, maxActionLen - 3) + "..."
236+ : actionText;
237+
238+ const content = ` ${applyColor(symbol, symbolColor)} ${applyColor(truncatedAction, THEME.VALUE)}${isLatest ? applyColor(applyBold(latestBadge), PALETTE.AMBER) : ""}`;
239+ lines.push(
240+ createBorderedLine(content, contentWidth, borderColor, indent),
241+ );
25242 } else if (line.startsWith("Result:")) {
26- lines.push(applyColor(line, THEME.LABEL));
243+ // Skip "Result:" header
27244 } else if (line.trim().startsWith("- ERROR")) {
28- lines.push(applyColor(line, PALETTE.BRICK));
29- } else if (line.trim().startsWith("-")) {
245+ const errorText = line.replace(/^\s*-\s*ERROR:?\s*/, "").trim();
246+ const prefixLen = 5; // " "
247+ const maxLen = contentWidth - prefixLen;
248+ const truncated =
249+ errorText.length > maxLen
250+ ? errorText.substring(0, maxLen - 3) + "..."
251+ : errorText;
252+ const content = ` ${applyColor(truncated, PALETTE.BRICK)}`;
253+ lines.push(
254+ createBorderedLine(content, contentWidth, borderColor, indent),
255+ );
256+ } else if (line.trim().startsWith("- ")) {
30257 // Bullet points
31- lines.push(applyColor(line, PALETTE.WHITE));
32- } else {
33- lines.push(applyColor(line, THEME.VALUE));
258+ const bulletText = line.replace(/^\s*-\s*/, "");
259+ const prefixLen = 5; // " "
260+ const maxLen = contentWidth - prefixLen;
261+ const truncated =
262+ bulletText.length > maxLen
263+ ? bulletText.substring(0, maxLen - 3) + "..."
264+ : bulletText;
265+ const content = ` ${applyColor(truncated, THEME.VALUE)}`;
266+ lines.push(
267+ createBorderedLine(content, contentWidth, borderColor, indent),
268+ );
269+ } else if (line.trim().startsWith("->")) {
270+ // Solution/guidance
271+ const guideText = line.replace(/^\s*->\s*/, "");
272+ // Visual layout: " → text" = 5 spaces + arrow + space + text
273+ // We build: " " + applyColor("→ " + text)
274+ // So: contentWidth = 5 + 1 + 1 + text.length
275+ const INDENT = 5; // " "
276+ const ARROW_AND_SPACE = 2; // "→ "
277+ const maxTextLen = contentWidth - INDENT - ARROW_AND_SPACE;
278+ const truncated =
279+ guideText.length > maxTextLen
280+ ? guideText.substring(0, maxTextLen - 3) + "..."
281+ : guideText;
282+ const content = ` ${applyColor(`→ ${truncated}`, PALETTE.MOSS)}`;
283+ lines.push(
284+ createBorderedLine(content, contentWidth, borderColor, indent),
285+ );
286+ } else if (line.trim()) {
287+ // Other content
288+ const text = line.trim();
289+ const prefixLen = 5; // " "
290+ const maxLen = contentWidth - prefixLen;
291+ const truncated =
292+ text.length > maxLen ? text.substring(0, maxLen - 3) + "..." : text;
293+ const content = ` ${applyColor(truncated, THEME.VALUE)}`;
294+ lines.push(
295+ createBorderedLine(content, contentWidth, borderColor, indent),
296+ );
297+ }
298+ }
299+
300+ // Add bottom padding (blank line WITH borders)
301+ lines.push(createBorderedLine("", contentWidth, borderColor, indent));
302+
303+ // Add bottom border with indent
304+ lines.push(indent + frame.bottom);
305+
306+ return lines;
307+}
308+
309+export function renderActionResultPanel(
310+ history: ActionHistoryEntry[],
311+ panelWidth: number,
312+): string {
313+ if (!history || history.length === 0) {
314+ return applyColor("No recent actions.", THEME.INACTIVE);
315+ }
316+
317+ const allLines: string[] = [];
318+
319+ // Render each action in history (most recent first)
320+ for (let i = 0; i < history.length; i++) {
321+ const entry = history[i];
322+ const parts = entry.result.trim().split("\n");
323+ const actionLine = parts.find((line) => line.startsWith("Action:")) || "";
324+ const category = detectActionCategory(actionLine);
325+ const hasErr = hasError(parts);
326+ const isLatest = i === 0;
327+
328+ const resultLines = renderSingleResult(
329+ entry.result,
330+ category,
331+ hasErr,
332+ panelWidth,
333+ isLatest,
334+ );
335+
336+ allLines.push(...resultLines);
337+
338+ // Add single blank line between entries (except after last one)
339+ if (i < history.length - 1) {
340+ allLines.push("");
34341 }
35342 }
36343
37- return lines.join("\n");
344+ return allLines.join("\n");
38345 }
src/tui/panels/game-status.ts+186−0
@@ -0,0 +1,186 @@
1+// Panel for displaying current game activity with animated spinner and ASCII art
2+
3+import type { GameStatusType } from "../../types";
4+import { ACTIVITY_ART, PALETTE, SYMBOLS, THEME } from "../theme";
5+import { applyBold, applyColor } from "../widgets";
6+
7+export interface GameStatusData {
8+ activity: GameStatusType;
9+ details?: string | null;
10+ spinnerFrame: number;
11+}
12+
13+/**
14+ * Strip blessed color tags to measure visual width
15+ */
16+function stripBlessedTags(text: string): string {
17+ return text.replace(/\{[^}]*\}/g, "");
18+}
19+
20+/**
21+ * Get visual width of text (without color tags)
22+ */
23+function getVisualWidth(text: string): number {
24+ return stripBlessedTags(text).length;
25+}
26+
27+function getActivityLabel(activity: GameStatusType): string {
28+ switch (activity) {
29+ case "waiting_for_tick":
30+ return "Waiting";
31+ case "requesting_action":
32+ return "Asking AI";
33+ case "llm_thinking":
34+ return "AI Thinking";
35+ case "traveling":
36+ return "Traveling";
37+ case "jumping":
38+ return "Jumping";
39+ case "processing_result":
40+ return "Processing";
41+ case "in_combat":
42+ return "COMBAT!";
43+ case "docked":
44+ return "Docked";
45+ }
46+}
47+
48+function getActivityColor(activity: GameStatusType): string {
49+ switch (activity) {
50+ case "in_combat":
51+ return PALETTE.BRICK;
52+ case "traveling":
53+ case "jumping":
54+ return PALETTE.AMBER;
55+ case "docked":
56+ return PALETTE.MOSS;
57+ case "llm_thinking":
58+ case "requesting_action":
59+ return PALETTE.MOSS;
60+ default:
61+ return THEME.VALUE;
62+ }
63+}
64+
65+function getActivityArt(activity: GameStatusType): string[] {
66+ return ACTIVITY_ART[activity];
67+}
68+
69+function formatDetails(
70+ details: string | null | undefined,
71+ maxLen = 15,
72+): string {
73+ if (!details || !details.trim()) return "";
74+ const trimmed = details.trim();
75+ if (trimmed.length <= maxLen) return trimmed;
76+ return `${trimmed.slice(0, maxLen - 2)}..`;
77+}
78+
79+export function renderGameStatusPanel(
80+ data: GameStatusData,
81+ panelWidth: number,
82+): string {
83+ const lines: string[] = [];
84+ const spinner = SYMBOLS.SPINNER_FRAMES[data.spinnerFrame];
85+ const activityLabel = getActivityLabel(data.activity);
86+ const activityColor = getActivityColor(data.activity);
87+
88+ // Spinner + activity label
89+ const statusLine = `${applyColor(spinner, activityColor)} ${applyColor(applyBold(activityLabel), activityColor)}`;
90+ lines.push(statusLine);
91+
92+ // Details (if available)
93+ if (data.details) {
94+ const detailsLabel =
95+ data.activity === "traveling" || data.activity === "jumping"
96+ ? "to:"
97+ : data.activity === "docked"
98+ ? "at:"
99+ : "";
100+
101+ if (detailsLabel) {
102+ lines.push(applyColor(detailsLabel, THEME.LABEL));
103+ lines.push(applyColor(formatDetails(data.details, 15), THEME.VALUE));
104+ } else {
105+ lines.push(applyColor(formatDetails(data.details, 15), THEME.VALUE));
106+ }
107+ } else {
108+ // Add secondary info line for states without details
109+ const secondaryLine =
110+ data.activity === "waiting_for_tick"
111+ ? "for tick"
112+ : data.activity === "requesting_action"
113+ ? "for action"
114+ : data.activity === "llm_thinking"
115+ ? "..."
116+ : "";
117+ if (secondaryLine) {
118+ lines.push(applyColor(secondaryLine, THEME.LABEL));
119+ }
120+ }
121+
122+ // Add spacing
123+ lines.push("");
124+
125+ // === ASCII ART WITH BORDER, SHADOW, AND CENTERING ===
126+ const art = getActivityArt(data.activity);
127+
128+ // Use fixed maximum width for consistency across all activity states
129+ // All ASCII art is normalized to exactly 12 characters
130+ const FIXED_MAX_ART_WIDTH = 12;
131+ const maxArtWidth = FIXED_MAX_ART_WIDTH;
132+
133+ // Border dimensions (2 spaces padding each side = comfortable)
134+ const padding = 2;
135+ const innerWidth = maxArtWidth + padding * 2;
136+ const borderWidth = innerWidth + 2; // +2 for │ │ borders
137+
138+ // Create border components (simple style)
139+ const shadowChar = "░";
140+ const topBorder = `┌${"─".repeat(innerWidth)}┐`;
141+ const bottomBorder = `└${"─".repeat(innerWidth)}┘`;
142+ const bottomShadow = ` ${"░".repeat(borderWidth)}`; // Bottom shadow
143+
144+ // Create bordered art lines with right shadow
145+ const borderedArt: string[] = [];
146+ for (const artLine of art) {
147+ const visualWidth = getVisualWidth(artLine);
148+ const leftPad = Math.floor((innerWidth - visualWidth) / 2);
149+ const rightPad = innerWidth - visualWidth - leftPad;
150+ const paddedLine = `│${" ".repeat(leftPad)}${artLine}${" ".repeat(rightPad)}│`;
151+ borderedArt.push(paddedLine);
152+ }
153+
154+ // Calculate centering offset in panel
155+ const availableWidth = panelWidth - 2; // Account for blessed panel borders
156+ const centerOffset = Math.max(
157+ 0,
158+ Math.floor((availableWidth - borderWidth) / 2),
159+ );
160+ const indent = " ".repeat(centerOffset);
161+
162+ // Add bordered art with centering and 45-degree shadow
163+ // Top line: no shadow (shadow starts below)
164+ lines.push(indent + applyColor(topBorder, activityColor));
165+
166+ // Content lines: shadow on right side
167+ for (const borderedLine of borderedArt) {
168+ lines.push(
169+ indent +
170+ applyColor(borderedLine, activityColor) +
171+ applyColor(shadowChar, PALETTE.GRAY),
172+ );
173+ }
174+
175+ // Bottom border: shadow on right side
176+ lines.push(
177+ indent +
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.ts+48−0
Cut short: this commit's diff is over 1000 lines.
src/types.ts+17−0
Cut short: this commit's diff is over 1000 lines.
test-arrow.ts+4−0
Cut short: this commit's diff is over 1000 lines.
test-border-alignment.ts+31−0
Cut short: this commit's diff is over 1000 lines.
test-solution-line.ts+25−0
Cut short: this commit's diff is over 1000 lines.
test-tui-render.ts+125−0
Cut short: this commit's diff is over 1000 lines.
tests/tui/panels/action-result.test.ts+129−0
Cut short: this commit's diff is over 1000 lines.
tests/tui/panels/game-status.test.ts+135−0
Cut short: this commit's diff is over 1000 lines.
tui-render-test.txt+314−0
Cut short: this commit's diff is over 1000 lines.