From 6677ac1e9ee60e3478951dc96819ef562d4c6f09 Mon Sep 17 00:00:00 2001 From: kim Date: Mon, 13 Jul 2026 18:16:51 +0900 Subject: [PATCH] v0.5.2: full-screen alt-screen mode with a scrollable, bottom-pinned layout - Switch to the terminal's alternate screen buffer once a session starts, clearing and homing the cursor so content starts flush at (0,0) - Replace scrollback with a fixed-height viewport (overflowY hidden) that top-aligns short conversations and auto-scrolls to the latest message once content exceeds the screen, keeping the input pinned to the bottom - Rewrite ChatInput's cursor handling: track cursor offset directly instead of relying on ink-text-input, and report the real terminal cursor position via useCursor + a Yoga-tree walk (absolutePosition.ts) so CJK IME composition windows anchor at the actual caret instead of the terminal's fallback corner - Print a "resume this conversation" hint after leaving the alt screen on exit Co-Authored-By: Claude Sonnet 5 --- package-lock.json | 5 +- package.json | 3 +- src/ui/ink/App.tsx | 164 ++++++++++++++++++-------- src/ui/ink/ChatInput.tsx | 208 +++++++++++++++++++++++---------- src/ui/ink/HistoryItemView.tsx | 15 ++- src/ui/ink/absolutePosition.ts | 22 ++++ src/ui/ink/index.tsx | 30 ++++- 7 files changed, 326 insertions(+), 121 deletions(-) create mode 100644 src/ui/ink/absolutePosition.ts diff --git a/package-lock.json b/package-lock.json index fdd6ef2..7da4434 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "locode", - "version": "0.3.1", + "version": "0.5.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "locode", - "version": "0.3.1", + "version": "0.5.1", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", "@vscode/ripgrep": "^1.18.0", @@ -23,6 +23,7 @@ "marked-terminal": "^7.3.0", "openai": "^6.45.0", "react": "^19.2.7", + "string-width": "^8.2.1", "tree-kill": "^1.2.2", "zod": "^4.4.3" }, diff --git a/package.json b/package.json index ee90d8d..12cd781 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "locode", - "version": "0.5.1", + "version": "0.5.2", "description": "Agentic coding CLI for local models served via Ollama and LM Studio", "type": "module", "bin": { @@ -35,6 +35,7 @@ "marked-terminal": "^7.3.0", "openai": "^6.45.0", "react": "^19.2.7", + "string-width": "^8.2.1", "tree-kill": "^1.2.2", "zod": "^4.4.3" }, diff --git a/src/ui/ink/App.tsx b/src/ui/ink/App.tsx index 6f3424a..c8f0de0 100644 --- a/src/ui/ink/App.tsx +++ b/src/ui/ink/App.tsx @@ -1,4 +1,4 @@ -import { Box, Static, useApp, useInput } from "ink"; +import { Box, Text, useApp, useBoxMetrics, useInput, useWindowSize, type DOMElement } from "ink"; import { useCallback, useEffect, useRef, useState } from "react"; import { AgentError, @@ -57,6 +57,7 @@ import { PermissionPrompt } from "./PermissionPrompt.js"; import { SessionSelect } from "./SessionSelect.js"; import { StatusBar } from "./StatusBar.js"; import { ThinkingIndicator } from "./ThinkingIndicator.js"; +import { ACCENT_HEX } from "../theme.js"; import { nextId, type HistoryItem, type NewHistoryItem } from "./types.js"; // Cap for the input-history ring buffer used for ↑/↓ recall in the chat input. @@ -123,6 +124,14 @@ export function App({ const baseURLRef = useRef(initialBaseURL); const sessionRef = useRef(null); + // Wraps whichever branch the bottom ternary renders (permission/export prompt, a picker, or the + // normal StatusBar+ChatInput column) — measured (height only) so the history viewport above it + // knows exactly how much vertical space is left (see historyHeight). + const bottomSectionRef = useRef(null); + // Measures the history content's own natural (unclipped) height — Yoga still computes a child's + // intrinsic size even when its parent has a fixed height + overflowY:hidden, so this reports the + // *true* height regardless of clipping. Used to decide top-alignment vs bottom-alignment below. + const historyContentRef = useRef(null); // Static history items can't be retroactively expanded once printed (Ink's is // append-only), so Ctrl+O doesn't edit the collapsed compact notice in place — it prints a new // item with the full text on demand. This just remembers the most recent one to print. @@ -140,6 +149,23 @@ export function App({ // re-registered on every phase change. const phaseRef = useRef(phase); phaseRef.current = phase; + const { height: bottomSectionHeight, hasMeasured: bottomSectionMeasured } = useBoxMetrics(bottomSectionRef); + const { rows: terminalRows } = useWindowSize(); + // Estimated fallback for the one frame before bottomSectionRef's first real measurement lands + // (StatusBar ~2 rows + a single-line bordered ChatInput ~3 rows) — avoids a brief overflow/flash + // of the history viewport claiming the whole terminal height on first mount. + const FALLBACK_BOTTOM_HEIGHT = 6; + const historyHeight = Math.max( + 1, + terminalRows - (bottomSectionMeasured ? bottomSectionHeight : FALLBACK_BOTTOM_HEIGHT), + ); + const { height: historyContentHeight } = useBoxMetrics(historyContentRef); + // Short conversations (or right after connecting, with just the welcome banner) should stay + // top-aligned — flex-end would otherwise glue even a single item to the bottom of the viewport, + // leaving a large empty gap above it. Only once real content actually exceeds the available + // height does it make sense to bottom-align and clip the oldest (off-the-top) content, which is + // what makes the view auto-scroll to the latest message once a conversation grows past one screen. + const historyOverflows = historyContentHeight > historyHeight; const flushStreamingText = useCallback(() => { const accumulated = streamingAccumulatorRef.current; @@ -910,58 +936,94 @@ export function App({ } return ( - - - {(item) => } - - - {streamingText !== null && ( - - )} - {isThinking && streamingText === null && !permission && !exportPrompt && ( - - )} - - {permission ? ( - - ) : exportPrompt ? ( - - ) : phase === "starting" ? ( - - ) : phase === "connecting" ? ( - - ) : phase === "loading-models" ? ( - - ) : phase === "session-select" ? ( - - ) : phase === "model-select" ? ( - - ) : ( - - {sessionRef.current && phaseRef.current === "input" && ( - + + {/* Fixed-height, bottom-pinned viewport: overflowY="hidden" clips whatever scrolls past the + * top, and justifyContent="flex-end" keeps the *latest* content flush against the bottom + * edge — together they auto-scroll to the newest message without any manual scroll-offset + * math, the same way a normal chat view does. This replaced (permanent one-shot + * scrollback printing) because Static's already-flushed rows never participate in Yoga + * layout again, which is fundamentally incompatible with letting old items visually scroll + * out of a *bounded* viewport as new ones arrive. Trade-off: every item re-renders on every + * frame now (Static rendered each item exactly once, ever) — fine at the sizes a single + * session reaches before auto-compaction, but worth knowing if a session gets huge. */} + + + {staticItems.map((item) => ( + + ))} + {streamingText !== null && ( + + )} + {isThinking && streamingText === null && !permission && !exportPrompt && ( + )} - - )} + + + + {permission ? ( + + ) : exportPrompt ? ( + + ) : phase === "starting" ? ( + + ) : phase === "connecting" ? ( + + ) : phase === "loading-models" ? ( + + ) : phase === "session-select" ? ( + + ) : phase === "model-select" ? ( + + ) : ( + <> + {sessionRef.current && phaseRef.current === "input" && ( + + )} + {isThinking || streamingText !== null ? ( + // Swapped in for ChatInput while a turn is in flight. Closes a real (if rare) race: + // handleSubmit had no guard against firing while a turn was already running, so + // typing and hitting Enter mid-stream could submit a second overlapping turn onto + // the same session. + + Waiting for response… + + ) : ( + + )} + + )} + ); } diff --git a/src/ui/ink/ChatInput.tsx b/src/ui/ink/ChatInput.tsx index f304937..4fd80a4 100644 --- a/src/ui/ink/ChatInput.tsx +++ b/src/ui/ink/ChatInput.tsx @@ -1,7 +1,8 @@ -import { Box, Text, useInput } from "ink"; -import TextInput from "ink-text-input"; +import { Box, Text, useBoxMetrics, useCursor, useInput, useWindowSize, type DOMElement } from "ink"; import fg from "fast-glob"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; +import stringWidth from "string-width"; +import { getAbsolutePosition } from "./absolutePosition.js"; import { ACCENT_HEX } from "../theme.js"; import { getActiveMention } from "../../utils/mentions.js"; @@ -16,17 +17,40 @@ interface Props { const MAX_MATCHES = 50; const VISIBLE_SUGGESTIONS = 8; +// "> " prefix before the actual text field. +const PROMPT_WIDTH = 2; +// Border (1 col each side) + paddingX={1} (1 col each side) around the bordered box's content. +const BOX_CHROME_WIDTH = 4; export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, history = [] }: Props) { const [allFiles, setAllFiles] = useState(null); const [selectedIndex, setSelectedIndex] = useState(0); const [historyIndex, setHistoryIndex] = useState(-1); const [tempValue, setTempValue] = useState(""); - // ink-text-input tracks its cursor position internally and has no way to be told the value - // changed externally — without this, accepting a suggestion leaves the cursor at its old - // (now-wrong) offset, so further typing lands mid-string instead of at the end. Bumping this - // key remounts TextInput, which resets its cursor to the end of the new value. - const [inputKey, setInputKey] = useState(0); + // Cursor offset (index into `value`) — replaces ink-text-input's internal cursor tracking so we + // can report the real terminal cursor position via useCursor below (needed for CJK IME + // composition windows to anchor at the right spot instead of falling back to the corner of the + // screen, since Ink hides the real cursor by default and ink-text-input only ever drew a fake + // inverse-video one). + const [cursorOffset, setCursorOffset] = useState(value.length); + + const boxRef = useRef(null); + // Only `hasMeasured` is used from this — it's still the right way to know a fresh layout pass has + // landed (and, via its internal layout-listener subscription, to force a re-render whenever any + // ancestor's layout changes size/position, e.g. the history viewport above resizing). The actual + // position is computed via getAbsolutePosition below instead of this hook's own top/left, which + // are relative to this box's *immediate* parent only — composing those by hand one level at a + // time (through however many wrapper Boxes sit above this one) proved fragile in practice. + const { hasMeasured } = useBoxMetrics(boxRef); + const { setCursorPosition } = useCursor(); + // Terminal columns, not this box's own measured width: the input box is always width="100%" + // with no horizontal siblings, so its content width is deterministically `columns - + // BOX_CHROME_WIDTH`. Using the measured width instead briefly produced a near-zero value before + // the box's first real layout pass landed (hasMeasured only means the ref is attached, not that + // Yoga has computed a real width yet) — with content width floored at 1, every single typed + // character was computed as needing its own wrapped row, so the reported cursor row grew by one + // per keystroke, visibly "falling" down the screen as you typed. + const { columns: terminalColumns } = useWindowSize(); const mention = getActiveMention(value); @@ -62,6 +86,39 @@ export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, his setSelectedIndex(0); }, [query]); + // Report the real terminal cursor position so a CJK IME's composition window anchors at the + // actual caret instead of the terminal's default fallback position. Wraps onto multiple rows the + // same way the bordered box does, using string-width (not .length) so double-width characters + // (Hangul, CJK, emoji) are counted correctly — a plain .length count is exactly what caused the + // original mispositioning. + // + // Called directly during render, NOT inside a useEffect: useCursor's setCursorPosition only + // writes to a ref (see ink's use-cursor.js), and the ref's value is read and pushed to the + // terminal by useCursor's own useInsertionEffect, which fires on *every* render regardless of + // this component's own effects. A useEffect here would update that ref one render *after* the + // insertion effect for the current render already ran with the stale value — since mutating a + // ref doesn't itself trigger a re-render, the fresh position would only ever reach the terminal + // on whatever the *next* incidental re-render happened to be (e.g. the next keystroke), which is + // exactly the "shows up a message late" symptom this fixes. Calling it inline guarantees the ref + // is up to date before this same render's insertion effect runs. + if (hasMeasured) { + const origin = getAbsolutePosition(boxRef.current); + const contentWidth = Math.max(1, terminalColumns - BOX_CHROME_WIDTH); + const totalWidth = PROMPT_WIDTH + stringWidth(value.slice(0, cursorOffset)); + const row = Math.floor(totalWidth / contentWidth); + const col = totalWidth % contentWidth; + // +2 rows / +2 cols for the box's own top border and left border+padding — + // getAbsolutePosition gives the box's outer (border) edge, not where its content actually + // starts. Empirically 2 rows, not 1 — some ancestor's own contribution isn't visible from the + // Yoga tree alone (Ink applies at least one more row of vertical offset somewhere between the + // computed layout and the actual terminal row), so this constant is tuned to match reality + // rather than derived purely from the box's own chrome. + setCursorPosition({ + x: origin.x + 2 + col, + y: origin.y + 2 + row, + }); + } + // Keeps the selection centered in the visible window where possible, clamped so the window // never scrolls past either end of the match list. const windowStart = Math.max( @@ -72,12 +129,17 @@ export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, his const hiddenAbove = windowStart; const hiddenBelow = matches.length - (windowStart + visible.length); + function replaceValue(newValue: string, newCursorOffset: number) { + onChange(newValue); + setCursorOffset(Math.max(0, Math.min(newCursorOffset, newValue.length))); + } + function acceptSuggestion(file: string) { if (!mention) return; const before = value.slice(0, mention.start); const after = value.slice(mention.start + 1 + mention.query.length); - onChange(`${before}@${file} ${after}`); - setInputKey((k) => k + 1); + const inserted = `${before}@${file} ${after}`; + replaceValue(inserted, before.length + 1 + file.length + 1); } // Drops the "@query" text (but keeps whatever was typed before the "@"), so a cancelled mention @@ -85,57 +147,9 @@ export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, his // (e.g. a slash command) gets appended after it and never matches, silently doing nothing. function cancelMention() { if (!mention) return; - onChange(value.slice(0, mention.start)); - setInputKey((k) => k + 1); + replaceValue(value.slice(0, mention.start), mention.start); } - useInput( - (_input: string, key: { shift?: boolean; tab?: boolean; backTab?: boolean; upArrow?: boolean; downArrow?: boolean; escape?: boolean }) => { - // Shift+Tab: cycle permission mode (takes priority even while suggestions are open). - if ((key.shift && key.tab) || key.backTab) { - onCyclePermMode?.(); - return; - } - if (key.escape) { - cancelMention(); - return; - } - if (matches.length > 0) { - if (key.downArrow) { - setSelectedIndex((i) => Math.min(i + 1, matches.length - 1)); - return; - } else if (key.upArrow) { - setSelectedIndex((i) => Math.max(i - 1, 0)); - return; - } else if (key.tab) { - acceptSuggestion(matches[selectedIndex] ?? matches[0]!); - return; - } - } else { - // History navigation - if (key.upArrow) { - if (historyIndex < history.length - 1) { - const newIndex = historyIndex + 1; - if (historyIndex === -1) setTempValue(value); - setHistoryIndex(newIndex); - onChange(history[history.length - 1 - newIndex]!); - setInputKey((k) => k + 1); - } - return; - } else if (key.downArrow) { - if (historyIndex > -1) { - const newIndex = historyIndex - 1; - setHistoryIndex(newIndex); - const newValue = newIndex === -1 ? tempValue : history[history.length - 1 - newIndex]!; - onChange(newValue); - setInputKey((k) => k + 1); - } - return; - } - } - }, - ); - function handleSubmit(raw: string) { // Enter while the picker is open accepts the highlighted file instead of sending the message. if (matches.length > 0) { @@ -147,6 +161,78 @@ export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, his onSubmit(raw); } + useInput((input, key) => { + // Shift+Tab: cycle permission mode (takes priority even while suggestions are open). + if (key.shift && key.tab) { + onCyclePermMode?.(); + return; + } + if (key.escape) { + cancelMention(); + return; + } + if (matches.length > 0) { + if (key.downArrow) { + setSelectedIndex((i) => Math.min(i + 1, matches.length - 1)); + return; + } else if (key.upArrow) { + setSelectedIndex((i) => Math.max(i - 1, 0)); + return; + } else if (key.tab) { + acceptSuggestion(matches[selectedIndex] ?? matches[0]!); + return; + } + } else { + // History navigation + if (key.upArrow) { + if (historyIndex < history.length - 1) { + const newIndex = historyIndex + 1; + if (historyIndex === -1) setTempValue(value); + setHistoryIndex(newIndex); + const newValue = history[history.length - 1 - newIndex]!; + replaceValue(newValue, newValue.length); + } + return; + } else if (key.downArrow) { + if (historyIndex > -1) { + const newIndex = historyIndex - 1; + setHistoryIndex(newIndex); + const newValue = newIndex === -1 ? tempValue : history[history.length - 1 - newIndex]!; + replaceValue(newValue, newValue.length); + } + return; + } + } + + // --- Text editing (replaces ink-text-input, see cursorOffset above) --- + if (key.return) { + handleSubmit(value); + return; + } + if (key.leftArrow) { + setCursorOffset((o) => Math.max(0, o - 1)); + return; + } + if (key.rightArrow) { + setCursorOffset((o) => Math.min(value.length, o + 1)); + return; + } + if (key.backspace || key.delete) { + if (cursorOffset > 0) { + replaceValue(value.slice(0, cursorOffset - 1) + value.slice(cursorOffset), cursorOffset - 1); + } + return; + } + if (key.tab || key.ctrl || key.meta) { + // No suggestions open: tab does nothing (matches the old ink-text-input behavior). Ignore + // ctrl/meta combos with no handler above rather than inserting raw escape bytes as text. + return; + } + if (input) { + replaceValue(value.slice(0, cursorOffset) + input + value.slice(cursorOffset), cursorOffset + input.length); + } + }); + return ( {visible.length > 0 && ( @@ -168,9 +254,9 @@ export function ChatInput({ value, onChange, onSubmit, onCyclePermMode, cwd, his )} - + {"> "} - + {value} ); diff --git a/src/ui/ink/HistoryItemView.tsx b/src/ui/ink/HistoryItemView.tsx index 266087e..771d5ef 100644 --- a/src/ui/ink/HistoryItemView.tsx +++ b/src/ui/ink/HistoryItemView.tsx @@ -172,9 +172,22 @@ export function HistoryItemView({ item }: { item: HistoryItem }) { ); case "assistant": - case "streaming_text": return {renderMarkdown(item.text)}; + // Deliberately NOT markdown-rendered while still streaming, unlike the finished "assistant" + // case above. marked-terminal re-wraps the *entire* accumulated text from scratch on every + // throttled frame (~30fps), and its column-width math doesn't agree with Ink's own (which uses + // string-width and correctly treats Hangul/CJK as double-width) — so as more wide-character text + // streams in, marked-terminal can retroactively shift where *earlier* lines wrap, not just append + // a new one. Ink's terminal redraw assumes previously-rendered content only grows, never reshapes; + // when it does reshape, the cursor-position math it uses to move up and redraw drifts from the + // terminal's actual state, producing artifacts (a stray character left behind while the input box + // "follows" the reflowed text). Rendering raw text here sidesteps the conflict entirely — the + // final text still gets full markdown formatting exactly once, after it's committed to the + // (never-re-rendered) Static history via the "assistant" case. + case "streaming_text": + return {item.text}; + case "tool_call": return ( diff --git a/src/ui/ink/absolutePosition.ts b/src/ui/ink/absolutePosition.ts new file mode 100644 index 0000000..bdb0883 --- /dev/null +++ b/src/ui/ink/absolutePosition.ts @@ -0,0 +1,22 @@ +import type { DOMElement } from "ink"; + +/** Walks up the Yoga layout tree from a node to the render root, summing each level's position + * (Yoga reports a node's top/left relative only to its own immediate parent) to get this node's + * absolute position in Ink's coordinate space — the same space useCursor's setCursorPosition + * expects. Composing a chain of useBoxMetrics calls by hand, one per level of nesting, turned out + * fragile in practice (easy to get the parent/child relationship subtly wrong, or to miss a level + * entirely); walking the real tree instead is correct regardless of how many Boxes sit in between. */ +export function getAbsolutePosition(node: DOMElement | null | undefined): { x: number; y: number } { + let x = 0; + let y = 0; + let current = node; + while (current) { + const layout = current.yogaNode?.getComputedLayout(); + if (layout) { + x += layout.left; + y += layout.top; + } + current = current.parentNode; + } + return { x, y }; +} diff --git a/src/ui/ink/index.tsx b/src/ui/ink/index.tsx index 1807910..5b06076 100644 --- a/src/ui/ink/index.tsx +++ b/src/ui/ink/index.tsx @@ -45,15 +45,25 @@ export async function runInkApp(opts: RunInkAppOptions): Promise { // Ink render tree so cleanup() can still read it after instance.unmount() has torn everything // in App.tsx down. let currentSessionId: string | null = null; + // Whether we've switched to the terminal's alternate screen buffer — tracked so cleanup() only + // switches back if we actually switched away, and so a second session starting mid-process + // (e.g. picking a different saved session via /resume) doesn't re-enter it redundantly. + let enteredAltScreen = false; + // Entering the alternate screen alone does not guarantee the cursor starts at the top-left — + // some terminals carry the cursor row over from the main screen, leaving blank rows above + // Ink's first output until enough content has been printed to push past that row. Clear the + // new (blank) buffer and explicitly home the cursor so content always starts flush at (0, 0). + const ALT_SCREEN_ENTER = "[?1049h" + "" + ""; + const ALT_SCREEN_EXIT = "[?1049l"; // Start the UI immediately — no blocking network calls before rendering. // Model listing happens inside the App component so the user sees the UI right away. // - // NOTE: we deliberately do NOT enter the alternate screen buffer (\x1b[?1049h) here. - // Alt-screen has no scrollback, so the user couldn't scroll up through history with - // the mouse wheel / Shift+PgUp. The dashboard-above-input layout in App.tsx already - // fixes the original "prompt starts below the status bar" glitch without sacrificing - // the terminal's native scrollback — keep the main screen. + // The model-select/connecting phases before a session exists stay on the main screen (so any + // startup errors remain in normal scrollback); once a session actually starts, we switch to the + // alternate screen buffer for a clean full-screen chat view. This trades away scrollback (no + // mouse-wheel/Shift+PgUp scrolling once in the alt screen) for that full-screen feel — a + // deliberate choice, revisit if the lack of scrollback turns out to matter more in practice. const instance = render( { extraToolsPromise={extraToolsPromise} onSessionIdChange={(id) => { currentSessionId = id; + if (!enteredAltScreen) { + enteredAltScreen = true; + process.stdout.write(ALT_SCREEN_ENTER); + } }} />, ); @@ -78,6 +92,12 @@ export async function runInkApp(opts: RunInkAppOptions): Promise { const cleanup = async () => { if (cleanedUp) return; cleanedUp = true; + // Leave the alternate screen first (if we ever entered it) so everything printed below — + // hook errors, the resume hint — lands on the user's normal scrollback, not a screen that's + // about to disappear. + if (enteredAltScreen) { + process.stdout.write(ALT_SCREEN_EXIT); + } // Flush in-flight autosaves first so a fire-and-forget persist right before exit isn't lost. await flushPendingSaves(); // Best-effort: don't leave backgrounded shells (dev servers, watch builds) running as orphans.