Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(tui): cols-based widths for narrow terminals (P2.8, ROADMAP §3B)

Salman Qureshi1356a3c00440
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index b3e93e92..aa2f8d6a 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -12,6 +12,7 @@ import { highlightCodeBlock } from '../utils/highlight.js';
import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';
import { useTerminalSize as useSharedTerminalSize } from './use-terminal-size.js';
import { CursorCell } from './cursor-anchor.js';
+import { isNarrow, ruleWidth, sidePanelWidth, fitText, fitTail, hintColumns } from './layout.js';
import { useTick, spinnerFrame, elapsedSeconds, SPINNER_FRAMES } from './tick-store.js';
import { loadInputHistory, saveInputHistory } from './input-history-store.js';
import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, parseChunkIndex, splitFinalMessage, splitStreamingMessage, type MercuryTranscriptLine } from './mercury-transcript.js';
@@ -780,11 +781,45 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
}
});
+ if (state.mode === 'splash' && isNarrow(terminalSize.cols)) {
+ // Narrow (< 60 cols, e.g. Termux portrait): one column, no logo art,
+ // every row truncated instead of wrapped.
+ const w = Math.max(1, terminalSize.cols - 2);
+ const provider = state.provider ? `${state.provider.name} · ${state.provider.model}` : 'Detecting...';
+ return (
+ <Box flexDirection="column" flexGrow={1}>
+ <Box flexDirection="column" paddingX={1}>
+ <Text wrap="truncate-end"><Text color={BRAND.logo}>☿ </Text><Text bold color={BRAND.title}>MERCURY</Text></Text>
+ <Text color={BRAND.subtitle} wrap="truncate-end">Your soul-driven AI agent</Text>
+ <Text color="gray">{'─'.repeat(ruleWidth(terminalSize.cols, 56))}</Text>
+ <Text color="green" wrap="truncate-end">● Core {splashPhase === 'ready' ? 'ready' : 'booting'}</Text>
+ <Text color={state.provider ? 'green' : 'yellow'} wrap="truncate-end">{state.provider ? '●' : '◐'} Provider {state.provider ? 'ready' : 'loading'}</Text>
+ <Text color={skillsLoaded >= state.skills.length ? 'green' : 'yellow'} wrap="truncate-end">{skillsLoaded >= state.skills.length ? '●' : '◐'} Skills {skillsLoaded}/{state.skills.length}</Text>
+ <Text color="gray">{'─'.repeat(ruleWidth(terminalSize.cols, 56))}</Text>
+ <Text wrap="truncate-end">Version: <Text color="cyan">{state.version}</Text></Text>
+ <Text wrap="truncate-end">Provider: <Text color={BRAND.accent}>{fitText(provider, Math.max(1, w - 10))}</Text></Text>
+ <Text color="gray">{'─'.repeat(ruleWidth(terminalSize.cols, 56))}</Text>
+ <Text dimColor wrap="truncate-end">{splashPhase === 'ready' ? 'Enter: open chat · D: details' : 'Initializing Mercury...'}</Text>
+ {showStartupDetails && state.skills.slice(0, skillsLoaded).map((skill, i) => (
+ <Text key={i} dimColor wrap="truncate-end">- {skill.name}</Text>
+ ))}
+ </Box>
+ {state.permissionPrompt && (
+ <PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx} />
+ )}
+ </Box>
+ );
+ }
+
if (state.mode === 'splash') {
+ // Two columns: the mark column is sized to its art (26) + gutter; the
+ // session column takes the rest, its rules capped at what remains.
+ const markColWidth = 34;
+ const sessionRule = '─'.repeat(ruleWidth(terminalSize.cols - markColWidth, 56));
return (
<Box flexDirection="column" flexGrow={1}>
<Box flexDirection="row" flexGrow={1} paddingX={1}>
- <Box flexDirection="column" width={34} paddingRight={2}>
+ <Box flexDirection="column" width={markColWidth} paddingRight={2} flexShrink={0}>
{MERCURY_MARK.map((line, i) => (
<Text key={i} color={BRAND.logo}>{line}</Text>
))}
@@ -800,7 +835,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
</Box>
<Box flexDirection="column" flexGrow={1}>
<Text bold color="white">Session</Text>
- <Text color="gray">{'─'.repeat(56)}</Text>
+ <Text color="gray">{sessionRule}</Text>
<Text>Version: <Text color="cyan">{state.version}</Text>{isDevBuild(state.version) && <Text color="yellow"> ⚠ development build</Text>}</Text>
<Text>Provider: <Text color={BRAND.accent}>{state.provider ? `${state.provider.name} · ${state.provider.model}` : 'Detecting...'}</Text></Text>
<Text>Mode: <Text color="yellow">Startup</Text></Text>
@@ -808,7 +843,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
<Text>Budget: <Text color="green">{state.tokenInfo.used.toLocaleString()}/{state.tokenInfo.budget.toLocaleString()} ({state.tokenInfo.percentage}%)</Text></Text>
)}
<Text>Web: {state.web?.enabled ? <Text color="green">Serving · http://127.0.0.1:{state.web.port}</Text> : <Text color="gray">Disabled</Text>}</Text>
- <Text color="gray">{'─'.repeat(56)}</Text>
+ <Text color="gray">{sessionRule}</Text>
<Text bold color="white">Capabilities</Text>
<Text>Skills loaded: <Text color="cyan">{skillsLoaded}</Text> / {state.skills.length}</Text>
{showStartupDetails ? (
@@ -820,7 +855,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
) : (
<Text dimColor>Details hidden (press D)</Text>
)}
- <Text color="gray">{'─'.repeat(56)}</Text>
+ <Text color="gray">{sessionRule}</Text>
<Text>{splashPhase === 'ready' ? 'Mercury is live.' : 'Initializing Mercury...'}</Text>
{splashPhase === 'ready' && <Text color="green">Ready. Enter to open chat.</Text>}
{!state.provider && <Text color="yellow">Waiting for provider handshake...</Text>}
@@ -836,7 +871,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
return (
<Box flexDirection="column" flexGrow={1}>
- {state.backgroundTasks.length > 0 && <BackgroundBarView tasks={state.backgroundTasks} />}
+ {state.backgroundTasks.length > 0 && <BackgroundBarView tasks={state.backgroundTasks} cols={terminalSize.cols} />}
{state.mode === 'mercury-code' ? (
<MercuryCodeView
state={state}
@@ -876,6 +911,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
turnRunning={turnRunning}
ctrlCHint={ctrlCHint}
cursorActive={inputOwnsKeys}
+ cols={terminalSize.cols}
/>
)}
{showInput && state.mode !== 'mercury-code' && slashSuggestions.length > 0 && (
@@ -889,7 +925,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
);
}
-function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {
+function BackgroundBarView({ tasks, cols }: { tasks: BackgroundTaskInfo[]; cols: number }) {
if (tasks.length === 0) return null;
const statusIcons: Record<string, string> = {
@@ -904,12 +940,12 @@ function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {
const more = tasks.length > 3 ? ` +${tasks.length - 3} more` : '';
return (
- <Box paddingX={1} paddingBottom={0} flexShrink={0}>
- <Text color="gray">{'─'.repeat(50)}</Text>
+ <Box paddingX={1} paddingBottom={0} flexShrink={0} flexDirection="column">
+ <Text color="gray">{'─'.repeat(ruleWidth(cols, 50))}</Text>
<Box flexDirection="column" width="100%">
- <Box>
+ <Box height={1} overflow="hidden">
<Text dimColor>⏥ Background:</Text>
- <Text> {visible.map((t) => {
+ <Text wrap="truncate-end"> {visible.map((t) => {
const icon = statusIcons[t.status] || '·';
const label = t.command || t.task || t.id;
const short = label.length > 25 ? label.slice(0, 22) + '...' : label;
@@ -944,17 +980,17 @@ const MAX_STATIC_MESSAGES = 100;
*/
const staticItemKey = (item: string | ChatMessage): string => typeof item === 'string' ? item : item.id;
-function HeaderBanner(): React.ReactNode {
+function HeaderBanner({ cols }: { cols: number }): React.ReactNode {
return (
<Box flexDirection="column" flexShrink={0}>
<Box paddingX={1}>
<Text color={BRAND.logo}>☿</Text>
<Text> </Text>
<Text bold color={BRAND.title}>MERCURY</Text>
- <Text color={BRAND.subtitle}> · Your soul-driven AI agent</Text>
+ {!isNarrow(cols) && <Text color={BRAND.subtitle}> · Your soul-driven AI agent</Text>}
</Box>
<Box paddingX={1}>
- <Text color="gray">{'─'.repeat(50)}</Text>
+ <Text color="gray">{'─'.repeat(ruleWidth(cols, 50))}</Text>
</Box>
</Box>
);
@@ -1075,14 +1111,14 @@ function ChatBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDynami
const staticItems: Array<string | ChatMessage> = [HEADER_SENTINEL_ID, ...staticMessages];
return (
<Box flexDirection="row" flexGrow={1}>
- {state.sidebarSections.length > 0 && <SidebarView sections={state.sidebarSections} />}
+ {state.sidebarSections.length > 0 && sidePanelWidth(cols, 24) > 0 && <SidebarView sections={state.sidebarSections} />}
<Box flexDirection="column" flexGrow={1}>
<Static items={staticItems} itemKey={staticItemKey}>
{(item) => typeof item === 'string'
- ? <HeaderBanner key={item} />
+ ? <HeaderBanner key={item} cols={cols} />
: <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}
</Static>
- <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 ? 30 : 0)} />
+ <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 && sidePanelWidth(cols, 24) > 0 ? 30 : 0)} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
{state.botChat && !state.isThinking && (
@@ -1094,7 +1130,7 @@ function ChatBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDynami
botRoster={state.botRoster}
/>
)}
- {state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}
+ {state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} cols={cols} />}
</Box>
</Box>
);
@@ -1115,10 +1151,12 @@ function CodingBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDyna
const dynamicMessages = state.chatMessages.filter((message) => message.streaming && !message.id.startsWith('heartbeat-'));
const staticItems: Array<string | ChatMessage> = [HEADER_SENTINEL_ID, ...staticMessages];
+ const sidebarWidth = sidePanelWidth(cols, 26);
return (
<Box flexDirection="row" flexGrow={1}>
- <Box flexDirection="column" width={26} paddingX={1}>
- <Text color="gray">{'─'.repeat(24)}</Text>
+ {sidebarWidth > 0 && (
+ <Box flexDirection="column" width={sidebarWidth} paddingX={1} flexShrink={0}>
+ <Text color="gray">{'─'.repeat(sidebarWidth - 2)}</Text>
<Text bold color="cyan">Workspace</Text>
<Box marginTop={1}>
<Text color={modeInfo.color} bold>{modeInfo.label}</Text>
@@ -1133,15 +1171,17 @@ function CodingBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDyna
))}
</Box>
)}
- {state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}
+ {state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} cols={sidebarWidth} />}
</Box>
+ )}
<Box flexDirection="column" flexGrow={1}>
+ {sidebarWidth === 0 && state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} cols={cols} />}
<Static items={staticItems} itemKey={staticItemKey}>
{(item) => typeof item === 'string'
- ? <HeaderBanner key={item} />
+ ? <HeaderBanner key={item} cols={cols} />
: <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}
</Static>
- <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 ? 30 : 0)} />
+ <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 && sidePanelWidth(cols, 24) > 0 ? 30 : 0)} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
{state.botChat && !state.isThinking && (
@@ -1153,8 +1193,8 @@ function CodingBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDyna
botRoster={state.botRoster}
/>
)}
- <Box paddingX={1} marginTop={1}>
- <Text dimColor>Mode shortcuts: Ctrl+P Plan · Ctrl+X Execute (Auto runs by default)</Text>
+ <Box paddingX={1} marginTop={1} height={1} overflow="hidden">
+ <Text dimColor wrap="truncate-end">{isNarrow(cols) ? 'Ctrl+P Plan · Ctrl+X Execute' : 'Mode shortcuts: Ctrl+P Plan · Ctrl+X Execute (Auto runs by default)'}</Text>
</Box>
</Box>
</Box>
@@ -2051,11 +2091,11 @@ function BotFleetLiveRegion({ botId, botName, botLiveActivity, botStreamTails, b
);
}
-function AgentPanelView({ agents }: { agents: SubAgentInfo[] }) {
+function AgentPanelView({ agents, cols }: { agents: SubAgentInfo[]; cols: number }) {
if (agents.length === 0) return null;
return (
<Box flexDirection="column" marginTop={1} paddingX={1}>
- <Text color="gray">{'─'.repeat(30)}</Text>
+ <Text color="gray">{'─'.repeat(ruleWidth(cols, 30))}</Text>
<Text bold color="cyan">Agents</Text>
{agents.map((agent) => {
const cfg = STATUS_ICONS[agent.status] || STATUS_ICONS.pending;
@@ -2151,6 +2191,7 @@ function InputBox({
turnRunning,
ctrlCHint,
cursorActive = true,
+ cols = 80,
}: {
input: string;
cursorPos: number;
@@ -2166,14 +2207,29 @@ function InputBox({
ctrlCHint?: boolean;
/** The composer owns the keyboard: park the hardware cursor on its cell. */
cursorActive?: boolean;
+ /** Terminal width: every chrome row is fitted to it (never wraps). */
+ cols?: number;
}) {
const inWorkspace = mode === 'workspace';
const inCoding = mode === 'coding' || inWorkspace;
const promptColor = botChat ? 'magenta' : inWorkspace ? 'cyan' : inCoding ? 'green' : 'yellow';
const label = botChat ? `[BOT ${botChat.botId}]` : inWorkspace ? '[IDE CHAT]' : inCoding ? '[CODING]' : '[CHAT]';
- const contextLabel = projectContext && projectContext.length > 52
- ? `...${projectContext.slice(-49)}`
- : (projectContext || 'No project context');
+ // Header row budget: label + " mode=EXECUTE" + bots chip; the context
+ // label gets what is left (and disappears first when narrow).
+ const modeText = `mode=${programmingMode.toUpperCase()}`;
+ const botsText = botsWorking && botsWorking > 0 ? ` 🤖 ${botsWorking} working` : '';
+ const contextBudget = Math.min(52, cols - 2 - label.length - 2 - modeText.length - 1 - botsText.length - 2);
+ const contextLabel = contextBudget >= 8 ? fitTail(projectContext || 'No project context', contextBudget) : '';
+ const narrow = isNarrow(cols);
+ const hint = ctrlCHint
+ ? CTRL_C_EXIT_HINT
+ : turnRunning
+ ? (narrow ? 'Esc stop · Ctrl+C clear' : 'Esc interrupt · Ctrl+C clear input')
+ : inWorkspace
+ ? (narrow ? 'Tab panels · Esc exit' : 'Tab switch panels · Ctrl+J chat · Ctrl+P Plan · Ctrl+X Execute · Esc back/exit')
+ : inCoding
+ ? (narrow ? 'Ctrl+P Plan · Ctrl+X Exec' : 'Coding chat active. Ctrl+P Plan · Ctrl+X Execute.')
+ : (narrow ? 'Enter send · /help keys' : 'Enter send · Shift+Enter/Ctrl+N newline · Ctrl+C clear · /help keys');
// Split input into lines and figure out which line/col the cursor is on
const lines = input.split('\n');
@@ -2191,10 +2247,10 @@ function InputBox({
return (
<Box flexDirection="column">
- <Text color="dim">{'─'.repeat(60)}</Text>
- <Box paddingX={1}>
+ <Text color="dim">{'─'.repeat(ruleWidth(cols, 60, 0))}</Text>
+ <Box paddingX={1} height={1} overflow="hidden">
<Text color={promptColor} bold>{label}</Text>
- <Text dimColor> {contextLabel} </Text>
+ <Text dimColor>{contextLabel ? ` ${contextLabel} ` : ' '}</Text>
<Text color={programmingMode === 'execute' ? 'green' : programmingMode === 'plan' ? 'yellow' : 'gray'}>
mode={programmingMode.toUpperCase()}
</Text>
@@ -2220,12 +2276,10 @@ function InputBox({
</Box>
))}
</Box>
- <Box paddingX={1}>
+ <Box paddingX={1} height={1} overflow="hidden">
{ctrlCHint
- ? <Text color="yellow">{CTRL_C_EXIT_HINT}</Text>
- : turnRunning
- ? <Text dimColor>Esc interrupt · Ctrl+C clear input</Text>
- : <Text dimColor>{inWorkspace ? 'Tab switch panels · Ctrl+J chat · Ctrl+P Plan · Ctrl+X Execute · Esc back/exit' : inCoding ? 'Coding chat active. Ctrl+P Plan · Ctrl+X Execute.' : 'Enter send · Shift+Enter/Ctrl+N newline · Ctrl+C clear · /help keys'}</Text>}
+ ? <Text color="yellow" wrap="truncate-end">{hint}</Text>
+ : <Text dimColor wrap="truncate-end">{hint}</Text>}
</Box>
</Box>
);
@@ -2346,17 +2400,20 @@ const THEME_ACCENT = IS_LIGHT_TERMINAL ? 'blue' : 'cyan';
function MercuryCodeHints({ cols }: { cols: number }): React.ReactNode {
const cmdW = Math.max(...CODE_HINTS.map((h) => h[0].length));
const descW = Math.max(...CODE_HINTS.map((h) => h[1].length));
- const rowLen = cmdW + 2 + descW + 2 + 8;
+ const keyW = Math.max(...CODE_HINTS.map((h) => h[2].length));
+ // Drop the description column (then the key column) rather than wrap.
+ const fit = hintColumns(cols, cmdW, descW, keyW);
+ const rowLen = cmdW + (fit.desc ? 2 + descW : 0) + (fit.key ? 2 + keyW : 0);
const indent = Math.max(0, Math.floor((cols - rowLen) / 2));
return (
<Box flexDirection="column" alignItems="flex-start" paddingLeft={indent} marginTop={2}>
{CODE_HINTS.map(([cmd, desc, key]) => (
<Box key={cmd}>
<Text bold color={THEME_ACCENT}>{cmd.padEnd(cmdW)}</Text>
- <Text> </Text>
- <Text dimColor>{desc.padEnd(descW)}</Text>
- <Text> </Text>
- <Text color="blue">{key}</Text>
+ {fit.desc && <Text> </Text>}
+ {fit.desc && <Text dimColor>{desc.padEnd(descW)}</Text>}
+ {fit.key && <Text> </Text>}
+ {fit.key && <Text color="blue">{key}</Text>}
</Box>
))}
</Box>
@@ -2831,8 +2888,8 @@ export function MercuryCodeView({
{state.planProgress && state.planProgress.length > 0 && <PlanProgressView steps={state.planProgress} />}
<MercuryLiveFeedback state={state} />
{state.permissionPrompt && <PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx ?? 0} />}
- {mc.exitConfirm && <MercuryCodeExitConfirm boxWidth={Math.max(40, cols - 4)} />}
- <MercuryCodeInput input={input ?? ''} cursorPos={cursorPos ?? 0} mode={state.programmingMode} boxWidth={Math.max(40, cols - 4)} cursorActive={!state.permissionPrompt && !mc.exitConfirm} />
+ {mc.exitConfirm && <MercuryCodeExitConfirm boxWidth={Math.max(12, cols - 4)} />}
+ <MercuryCodeInput input={input ?? ''} cursorPos={cursorPos ?? 0} mode={state.programmingMode} boxWidth={Math.max(12, cols - 4)} cursorActive={!state.permissionPrompt && !mc.exitConfirm} />
<Box height={1} overflow="hidden" paddingX={2} flexShrink={0}>
<Text dimColor={!ctrlCHint} color={ctrlCHint ? 'yellow' : undefined}>{leftHint}</Text>
<Spacer />
diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsx
index 24653d30..26b8242e 100644
--- a/src/ui/attach-tui.tsx
+++ b/src/ui/attach-tui.tsx
@@ -181,7 +181,7 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
// Same input width as the main TUI's chat/Code input (App.tsx).
const terminalSize = useTerminalSize();
- const inputWidth = Math.max(40, terminalSize.cols - 4);
+ const inputWidth = Math.max(12, terminalSize.cols - 4);
// Live event stream for the attached session.
React.useEffect(() => {
diff --git a/src/ui/layout.ts b/src/ui/layout.ts
new file mode 100644
index 00000000..33560269
--- /dev/null
+++ b/src/ui/layout.ts
@@ -0,0 +1,51 @@
+/**
+ * Width rules for the TUI (ROADMAP §3B / P2.8). Every horizontal measure is
+ * derived from the live terminal width instead of fixed 60/50/34+56/26
+ * constants, so Termux phones and split panes (40–60 columns) never wrap a
+ * live-region row into a second line — a wrapped row changes the live
+ * region's height, which is what makes ink's erase arithmetic churn.
+ */
+
+/** Below this width the splash and the side panels collapse to one column. */
+export const NARROW_COLS = 60;
+
+export function isNarrow(cols: number): boolean {
+ return cols < NARROW_COLS;
+}
+
+/** A horizontal rule that fits inside `gutter` columns of padding. */
+export function ruleWidth(cols: number, max: number, gutter = 2): number {
+ return Math.max(1, Math.min(max, cols - gutter));
+}
+
+/** Width of the coding/chat side panel, or 0 when it collapses. */
+export function sidePanelWidth(cols: number, preferred: number): number {
+ return isNarrow(cols) ? 0 : preferred;
+}
+
+/** Truncate to `max` display cells (ASCII-safe; callers pass plain labels). */
+export function fitText(text: string, max: number): string {
+ if (max <= 0) return '';
+ if (text.length <= max) return text;
+ if (max === 1) return '…';
+ return text.slice(0, max - 1) + '…';
+}
+
+/** Keep the END of a path-like label (the useful part), e.g. "…/src/ui". */
+export function fitTail(text: string, max: number): string {
+ if (max <= 0) return '';
+ if (text.length <= max) return text;
+ if (max <= 3) return text.slice(-max);
+ return '...' + text.slice(-(max - 3));
+}
+
+/**
+ * Columns of the Mercury Code hint table that fit: command · description ·
+ * key at full width, dropping the description (then the key) when narrow.
+ */
+export function hintColumns(cols: number, cmdW: number, descW: number, keyW: number): { desc: boolean; key: boolean } {
+ const avail = cols - 4;
+ if (cmdW + 2 + descW + 2 + keyW <= avail) return { desc: true, key: true };
+ if (cmdW + 2 + keyW <= avail) return { desc: false, key: true };
+ return { desc: false, key: false };
+}
diff --git a/src/ui/narrow-terminal.test.tsx b/src/ui/narrow-terminal.test.tsx
new file mode 100644
index 00000000..9d1196b6
--- /dev/null
+++ b/src/ui/narrow-terminal.test.tsx
@@ -0,0 +1,184 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ process.env.CI = '0';
+});
+
+import React from 'react';
+import { render } from 'ink';
+import { EventEmitter } from 'node:events';
+import stringWidth from 'string-width';
+import { TuiApp, MercuryCodeView } from './App.js';
+import { CLIChannel, type TuiState } from '../channels/cli.js';
+import { hintColumns, isNarrow, ruleWidth, sidePanelWidth, fitTail } from './layout.js';
+
+/**
+ * Narrow terminals (ROADMAP §3B / P2.8 — Termux portrait, split panes).
+ * At 50 columns nothing may wrap into a second live-region row: every chrome
+ * row (rules, input header, hint row, status bar) is fitted to `cols`, the
+ * splash collapses to one column and the coding sidebar disappears.
+ */
+
+const COLS = 50;
+const ESC = String.fromCharCode(27);
+const stripAnsi = (s: string) => s.replace(new RegExp(`${ESC}\\[[0-9;?]*[A-Za-z]`, 'g'), '');
+
+class FakeStdout extends EventEmitter {
+ chunks: string[] = [];
+ columns = COLS;
+ rows = 40;
+ isTTY = true;
+ write(chunk: string): boolean {
+ this.chunks.push(chunk);
+ return true;
+ }
+ get output(): string {
+ return this.chunks.join('');
+ }
+}
+
+class FakeStdin extends EventEmitter {
+ isTTY = true;
+ setEncoding(): void {}
+ setRawMode(): void {}
+ resume(): void {}
+ pause(): void {}
+ ref(): void {}
+ unref(): void {}
+ read(): null { return null; }
+}
+
+async function waitFor(pred: () => boolean, timeoutMs = 4000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline && !pred()) await new Promise((r) => setTimeout(r, 20));
+ if (!pred()) throw new Error('condition not met in time');
+}
+
+/** Visible rows of the last chunk that contains `marker` (a full frame). */
+function frameRows(stdout: FakeStdout, marker: string): string[] {
+ const chunk = [...stdout.chunks].reverse().find((c) => stripAnsi(c).includes(marker))!;
+ return stripAnsi(chunk).split('\n').map((r) => r.replace(/\s+$/, '')).filter((r, i, all) => i < all.length - 1 || r !== '');
+}
+
+async function renderApp(state: TuiState, marker: string): Promise<{ rows: string[]; unmount: () => void }> {
+ const channel = { getTuiStateSnapshot: () => state, subscribeToTuiState: () => () => {} };
+ const stdout = new FakeStdout();
+ const { unmount } = render(
+ <TuiApp channel={channel} onInput={() => {}} onPermissionResolve={() => {}} onExit={() => {}} />,
+ { stdout: stdout as any, stdin: new FakeStdin() as any, exitOnCtrlC: false, patchConsole: false },
+ );
+ await waitFor(() => stripAnsi(stdout.output).includes(marker));
+ await new Promise((r) => setTimeout(r, 60));
+ return { rows: frameRows(stdout, marker), unmount };
+}
+
+const LONG_CONTEXT = '/home/user/projects/very/deeply/nested/workspace/mercury-agent';
+
+function state(patch: Record<string, unknown>): TuiState {
+ return {
+ ...new CLIChannel().getTuiStateSnapshot(),
+ version: '1.3.1',
+ provider: { name: 'deepseek', model: 'deepseek-chat' },
+ tokenInfo: { used: 1200, budget: 100000, percentage: 1 },
+ projectContext: LONG_CONTEXT,
+ ...patch,
+ } as unknown as TuiState;
+}
+
+function expectFits(rows: string[]): void {
+ for (const row of rows) expect(stringWidth(row), `row wider than ${COLS}: "${row}"`).toBeLessThanOrEqual(COLS);
+}
+
+describe('layout rules', () => {
+ it('derive every width from cols', () => {
+ expect(isNarrow(59)).toBe(true);
+ expect(isNarrow(60)).toBe(false);
+ expect(ruleWidth(50, 60, 0)).toBe(50);
+ expect(ruleWidth(200, 50)).toBe(50);
+ expect(ruleWidth(1, 50)).toBe(1);
+ expect(sidePanelWidth(50, 26)).toBe(0);
+ expect(sidePanelWidth(80, 26)).toBe(26);
+ expect(fitTail(LONG_CONTEXT, 12)).toBe('...ury-agent');
+ expect(fitTail(LONG_CONTEXT, 12)).toHaveLength(12);
+ expect(hintColumns(120, 13, 40, 7)).toEqual({ desc: true, key: true });
+ expect(hintColumns(50, 13, 40, 7)).toEqual({ desc: false, key: true });
+ expect(hintColumns(16, 13, 40, 7)).toEqual({ desc: false, key: false });
+ });
+});
+
+describe(`TUI at ${COLS} columns`, () => {
+ it('splash collapses to one column with no logo art', async () => {
+ const { rows, unmount } = await renderApp(state({ mode: 'splash' }), 'Core');
+ expectFits(rows);
+ expect(rows.join('\n')).not.toContain('╭─╮'); // the 26-col mark is gone
+ expect(rows[0]).toContain('MERCURY');
+ expect(rows.some((r) => r.includes('Provider: deepseek · deepseek-chat'))).toBe(true);
+ // snapshot-ish: the whole collapsed splash, row by row
+ expect(rows.map((r) => r.trimStart())).toEqual([
+ '☿ MERCURY',
+ 'Your soul-driven AI agent',
+ '─'.repeat(48),
+ '● Core booting',
+ '● Provider ready',
+ '● Skills 0/0',
+ '─'.repeat(48),
+ 'Version: 1.3.1',
+ 'Provider: deepseek · deepseek-chat',
+ '─'.repeat(48),
+ 'Initializing Mercury...',
+ ]);
+ unmount();
+ });
+
+ it('chat: input chrome is exactly four rows and the sidebar collapses', async () => {
+ const { rows, unmount } = await renderApp(state({
+ mode: 'chat',
+ sidebarSections: [{ title: 'Files', items: [{ icon: '•', label: 'src/index.ts' }] }],
+ }), '[CHAT]');
+ expectFits(rows);
+ expect(rows.join('\n')).not.toContain('src/index.ts'); // sidebar collapsed
+ const header = rows.findIndex((r) => r.includes('[CHAT]'));
+ expect(header).toBeGreaterThan(0);
+ // rule · header · prompt · hint — no wrapped continuation rows between.
+ expect(rows[header - 1]).toBe('─'.repeat(COLS));
+ expect(rows[header]).toBe(' [CHAT] ...ed/workspace/mercury-agent mode=OFF');
+ expect(rows[header + 1]).toBe(' >');
+ expect(rows[header + 2]).toBe(' Enter send · /help keys');
+ expect(rows[header + 3]).toMatch(/^ ─+$/); // token bar rule follows directly
+ unmount();
+ });
+
+ it('coding: no fixed 26-column sidebar, shortcuts row fits', async () => {
+ const { rows, unmount } = await renderApp(state({
+ mode: 'coding',
+ subAgents: [{ id: 'a1', status: 'running', task: 'Investigate the flaky test in the scheduler module', startedAt: Date.now() }],
+ }), '[CODING]');
+ expectFits(rows);
+ expect(rows.join('\n')).not.toContain('Workspace'); // sidebar collapsed
+ expect(rows.some((r) => r.trim() === 'Ctrl+P Plan · Ctrl+X Execute')).toBe(true);
+ const header = rows.findIndex((r) => r.includes('[CODING]'));
+ expect(rows[header + 1]).toBe(' >');
+ expect(rows[header + 2]).toBe(' Ctrl+P Plan · Ctrl+X Exec');
+ unmount();
+ });
+
+ it('Mercury Code: hint table drops the description column instead of wrapping', async () => {
+ const stdout = new FakeStdout();
+ const s = state({
+ mode: 'mercury-code',
+ chatMessages: [],
+ mercuryCode: { cwd: '/tmp/proj', dirName: 'proj', git: { branch: 'main', ahead: 0, behind: 0, dirty: 0 }, scrollOffset: 0, exitConfirm: false },
+ });
+ const { unmount } = render(<MercuryCodeView state={s} cols={COLS} rows={40} input="" cursorPos={0} />, { stdout: stdout as any, exitOnCtrlC: false, patchConsole: false });
+ await waitFor(() => stripAnsi(stdout.output).includes('/code plan'));
+ await new Promise((r) => setTimeout(r, 60));
+ const rows = frameRows(stdout, '/code plan');
+ expectFits(rows);
+ const plan = rows.find((r) => r.includes('/code plan'))!;
+ expect(plan).not.toContain('analyze & propose');
+ expect(plan).toMatch(/\/code plan\s+ctrl\+p$/);
+ // input box spans the terminal minus the 2+2 gutter
+ expect(rows.some((r) => r.trim().startsWith('╭') && stringWidth(r.trim()) === COLS - 4)).toBe(true);
+ unmount();
+ });
+});