Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web): drive a terminal using fingers (#613)

Myriad-Dreamin18ebfcc41e62
diff --git a/changelog/unreleased/2026-09-04-terminal-touch.md b/changelog/unreleased/2026-09-04-terminal-touch.md
new file mode 100644
index 00000000..0355bb43
--- /dev/null
+++ b/changelog/unreleased/2026-09-04-terminal-touch.md
@@ -0,0 +1,20 @@
+# A terminal a finger can drive
+
+- **Date:** 2026-09-04
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#613](https://github.com/Prism-Shadow/penguin-harness/pull/613), [#645](https://github.com/Prism-Shadow/penguin-harness/pull/645)
+
+[中文版](2026-09-04-terminal-touch.zh.md)
+
+A phone's soft keyboard has no Esc, no Tab, no arrows and no Ctrl, so a terminal on one was readable and not usable. Under `(pointer: coarse)` — and only there — the terminal surface now carries a key bar: Esc, Tab, a sticky Ctrl, the four arrows, `^C`, paste, a soft-keyboard toggle, and Alt at the end. Both hosts get it, the `/terminal` page and the dock's terminal tabs. Ctrl and Alt are one shot: a tap arms the modifier and the next character typed composes with it; a paste or an IME commit arriving while one is armed goes through unmodified. The caps write their own sequences, so an arrow follows the terminal's cursor-key mode and a modified one carries xterm's modifier parameter, rather than arriving in a full-screen program as literal text.
+
+The soft keyboard also stops covering the bottom of the page: the App asks Chrome to shrink the layout viewport when a virtual keyboard is up, and the `/terminal` page sizes itself to the visual viewport for the browsers that do not implement that. Its header compacts to a phone's width — the working directory truncates, and the status shows as its dot, which names itself.
+
+A long press no longer pastes. It raises the same event a right click does but it is not one, and a finger that meant to select text was pushing the clipboard into a live shell; touch pastes from the key bar instead.
+
+A one-finger drag scrolls the terminal, including while a full-screen program has taken the mouse. xterm turns its own touch scrolling off for exactly those programs — Claude Code and every TUI like it — and Claude Code draws on the alternate screen, where the terminal has no scrollback and the transcript moves only when a wheel reports; a phone has no wheel, so everything above the newest line was out of reach. The drag is now that wheel: its travel becomes wheel events at the finger's position, dispatched through xterm so they are encoded in whatever mouse protocol the program asked for, one line per line of travel — the transcript follows the finger instead of being flung by it. A tap is still a tap: nothing scrolls until the travel passes a slop threshold, so tap-to-click still reaches a program that answers clicks. Where the mouse is free, xterm's own touch scrolling is untouched and still scrolls the scrollback.
+
+The terminal also stops handing the gesture to the browser (`touch-action: none` on the surface, touch devices only): a drag the page decides is a page scroll or a pull-to-refresh stops being cancellable mid-gesture, and the terminal loses it.
+
+The dock's own chrome follows: its header buttons and tab closes grow to a finger's size, and the bottom dock gains a height toggle — the boundary you drag to resize it is a 4px line, which a mouse can hit and a finger cannot.
diff --git a/changelog/unreleased/2026-09-04-terminal-touch.zh.md b/changelog/unreleased/2026-09-04-terminal-touch.zh.md
new file mode 100644
index 00000000..34404d9b
--- /dev/null
+++ b/changelog/unreleased/2026-09-04-terminal-touch.zh.md
@@ -0,0 +1,20 @@
+# 手指也能用的终端
+
+- **Date:** 2026-09-04
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#613](https://github.com/Prism-Shadow/penguin-harness/pull/613), [#645](https://github.com/Prism-Shadow/penguin-harness/pull/645)
+
+[English](2026-09-04-terminal-touch.md)
+
+手机软键盘没有 Esc、没有 Tab、没有方向键、也没有 Ctrl,终端在手机上因此只能读、不能用。现在在 `(pointer: coarse)` 下——且仅在该条件下——终端界面多出一条快捷键条:Esc、Tab、粘滞的 Ctrl、四个方向键、`^C`、粘贴、软键盘开关,以及排在末位的 Alt。`/terminal` 页与 Dock 中的终端标签页两处宿主一并生效。Ctrl 与 Alt 是一次性的:点一下即置位,与随后键入的下一个字符合成;置位期间到来的粘贴或输入法上屏内容则原样送出,不受修饰。按键自行组装序列,因而方向键会遵循终端当前的 cursor-key 模式、带修饰的方向键携带 xterm 的修饰参数,而不是以字面文本落进全屏程序里。
+
+软键盘也不再盖住页面底部:应用会请求 Chrome 在虚拟键盘弹出时收缩 layout viewport,`/terminal` 页则另按 visual viewport 自行定高,覆盖不实现该特性的浏览器。它的顶栏按手机宽度压缩——工作目录截断,状态收成一枚会自报其名的圆点。
+
+长按不再粘贴。它触发的事件与右键相同,但它不是右键;本想选中文字的一根手指,会把剪贴板推进一个正在运行的 shell。触摸设备改从快捷键条粘贴。
+
+单指拖动可以滚动终端,全屏程序接管了鼠标时也一样。xterm 恰恰对这类程序——Claude Code 与所有同类 TUI——关掉了自己的触摸滚动;而 Claude Code 画在备用屏(alternate screen)上,那里终端没有回滚缓冲,转录只在收到滚轮上报时才移动。手机没有滚轮,最新一行以上的内容因此全都够不着。现在拖动就是那个滚轮:拖动的位移在手指位置上变成 wheel 事件,经由 xterm 分发,因而按程序实际开启的鼠标协议编码;每移动一行的高度滚一行——转录跟着手指走,而不是被甩出去。点按仍然是点按:位移超过阈值之前什么都不滚,因此「点按即点击」照样能送达会响应点击的程序。鼠标没有被接管时,xterm 自己的触摸滚动原样保留,滚的仍是回滚缓冲。
+
+终端也不再把这个手势交给浏览器(触摸设备上给终端表面加 `touch-action: none`):一旦浏览器认定这是页面滚动或下拉刷新,手势中途就不再可取消,终端也就把它丢了。
+
+Dock 自身的构件同步跟上:头部按钮与标签页的关闭按钮放大到手指尺寸,底部 Dock 增加高度切换——用于调整它的那条边界是 4px 的细线,鼠标够得着,手指够不着。
diff --git a/packages/web/e2e/terminal-touch.spec.mjs b/packages/web/e2e/terminal-touch.spec.mjs
new file mode 100644
index 00000000..724587c1
--- /dev/null
+++ b/packages/web/e2e/terminal-touch.spec.mjs
@@ -0,0 +1,173 @@
+/**
+ * The terminal under a finger: a phone's soft keyboard has no Esc, no Tab, no arrows and no
+ * Ctrl, so the key bar is the only way to drive a shell there. What matters is that its caps
+ * reach the real pty — an arrow that types `[A` into the prompt, or a Ctrl that never
+ * composes, looks like a working button and is not one — and that none of it appears where a
+ * physical keyboard already exists.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const U = "touchuser";
+const P = "password123";
+
+/** Live shells accumulate across spec reruns on one server; MAX 12/user would 429. */
+async function killAllTerminals(request) {
+ const { terminals } = await (await request.get(`${BASE}/api/terminals`)).json();
+ for (const t of terminals) await request.delete(`${BASE}/api/terminals/${t.id}`);
+}
+
+const screenText = (page) => page.locator(".xterm-rows").innerText();
+
+/** A tap on the screen focuses xterm, which is what raises the soft keyboard. */
+async function focusShell(page) {
+ await page.locator(".xterm-screen").click();
+}
+
+async function type(page, command) {
+ await page.keyboard.type(command);
+ await page.keyboard.press("Enter");
+}
+
+/**
+ * "ready" only means the stream is attached; a login shell may still be sourcing profiles,
+ * and input typed meanwhile sits in the tty buffer until it wakes up. Probe with a sentinel.
+ */
+async function waitForShell(page, tag) {
+ await expect(page.locator(".xterm-rows")).toBeVisible({ timeout: 20000 });
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await focusShell(page);
+ await type(page, `echo ${tag.slice(0, 2)}''${tag.slice(2)}`);
+ await expect.poll(() => screenText(page), { timeout: 30000 }).toMatch(new RegExp(`${tag}$`, "m"));
+}
+
+/**
+ * One finger dragged down the middle of the screen, from one fraction of its height to
+ * another. Through CDP because that is the only way to produce touches a page cannot tell
+ * from a real one — Playwright's own touchscreen taps and nothing more, and a hand-built
+ * TouchEvent skips the hit testing and the `touch-action` the gesture depends on.
+ */
+async function dragFinger(page, from, to) {
+ const box = await page.locator(".xterm-screen").boundingBox();
+ const x = box.x + box.width / 2;
+ const y = (fraction) => box.y + box.height * fraction;
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send("Input.dispatchTouchEvent", {
+ type: "touchStart",
+ touchPoints: [{ x, y: y(from) }],
+ });
+ const steps = 10;
+ for (let i = 1; i <= steps; i++) {
+ await cdp.send("Input.dispatchTouchEvent", {
+ type: "touchMove",
+ touchPoints: [{ x, y: y(from + ((to - from) * i) / steps) }],
+ });
+ }
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
+ await cdp.detach();
+}
+
+test.describe("touch", () => {
+ test.use({ viewport: { width: 412, height: 915 }, hasTouch: true, isMobile: true });
+
+ test("the key bar drives the shell: history, interrupt, and a sticky Ctrl", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await waitForShell(page, "TOUCH_UP_1");
+
+ const bar = page.getByTestId("terminal-key-bar");
+ await expect(bar).toBeVisible();
+
+ // The keyboard cap is a toggle over xterm's focus: it dismisses the soft keyboard
+ // (which a phone otherwise leaves covering half the screen) and calls it back.
+ const keyboardCap = page.getByTestId("terminal-key-keyboard");
+ await expect(keyboardCap).toHaveAccessibleName(/收起键盘/);
+ await keyboardCap.click();
+ await expect(keyboardCap).toHaveAccessibleName(/调出键盘/);
+ await keyboardCap.click();
+ await expect(keyboardCap).toHaveAccessibleName(/收起键盘/);
+
+ // ↑ recalls the previous command. A CSI arrow reaching a shell that asked for SS3 would
+ // land as literal text instead, which is exactly what this catches.
+ await type(page, "echo HISTORY_ONE");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("HISTORY_ONE");
+ await page.getByTestId("terminal-key-up").click();
+ await page.keyboard.press("Enter");
+ await expect
+ .poll(() => screenText(page).then((t) => t.split("HISTORY_ONE").length - 1), {
+ timeout: 15000,
+ })
+ // The command echo and its output, twice over: four occurrences, not two.
+ .toBeGreaterThanOrEqual(4);
+
+ // ^C on a shell that is busy: without it the prompt would not come back for 45 seconds.
+ await type(page, "sleep 45");
+ await page.getByTestId("terminal-key-interrupt").click();
+ await type(page, "echo AFTER_INTERRUPT");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("AFTER_INTERRUPT");
+
+ // The sticky modifier: arm Ctrl on the bar, then the next character typed on the
+ // keyboard composes with it (this is the path a soft keyboard's "c" takes).
+ await type(page, "sleep 45");
+ const ctrl = page.getByTestId("terminal-key-ctrl");
+ await ctrl.click();
+ await expect(ctrl).toHaveAttribute("aria-pressed", "true");
+ await page.keyboard.type("c");
+ await expect(ctrl).toHaveAttribute("aria-pressed", "false"); // spent
+ await type(page, "echo AFTER_STICKY_CTRL");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("AFTER_STICKY_CTRL");
+ });
+
+ test("a finger scrolls a program that has taken the mouse", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await waitForShell(page, "TOUCH_UP_2");
+
+ // A plain shell: the drag is xterm's own business. It still scrolls the scrollback — the
+ // `touch-none` the host now carries must not take that away — and NOTHING may reach the
+ // pty, since a wheel report typed at a prompt is a line of garbage.
+ await type(page, "seq 1 300");
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toContain("300");
+ const scrollTop = () =>
+ page.evaluate(() => document.querySelector(".xterm-viewport").scrollTop);
+ const atBottom = await scrollTop();
+ await dragFinger(page, 0.3, 0.8);
+ await expect.poll(scrollTop, { timeout: 10000 }).toBeLessThan(atBottom);
+ await expect(page.locator(".xterm-rows")).not.toContainText("[<");
+
+ // The arrangement a TUI uses, Claude Code included: the alternate screen (no scrollback
+ // left to scroll) plus any-event mouse tracking in SGR. `cat -v` then prints what the
+ // program would have received, so the reports the finger produces are on the screen.
+ await type(
+ page,
+ String.raw`printf '\033[?1049h\033[?1000h\033[?1002h\033[?1003h\033[?1006h'; cat -v`,
+ );
+ await expect
+ .poll(() => page.evaluate(() => document.querySelector(".xterm")?.className ?? ""), {
+ timeout: 15000,
+ })
+ .toContain("enable-mouse-events");
+
+ // Up the screen: later content, which is a wheel rolled down — button 65.
+ await dragFinger(page, 0.7, 0.3);
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toMatch(/\[<65;\d+;\d+M/);
+ // And back down: earlier content, button 64.
+ await dragFinger(page, 0.3, 0.7);
+ await expect.poll(() => screenText(page), { timeout: 15000 }).toMatch(/\[<64;\d+;\d+M/);
+ });
+});
+
+test("no key bar where there is a real keyboard", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await expect(page.getByTestId("terminal-key-bar")).toHaveCount(0);
+});
diff --git a/packages/web/index.html b/packages/web/index.html
index 9cece933..b763229a 100644
--- a/packages/web/index.html
+++ b/packages/web/index.html
@@ -2,7 +2,14 @@
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <!-- interactive-widget: the soft keyboard shrinks the LAYOUT viewport, so the shell's
+ `height: 100%` reflows above it instead of the page keeping its full height and
+ letting the keyboard cover the bottom (the terminal's last rows, a composer).
+ Chrome-only; Safari is covered by useVisualViewportHeight. -->
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"
+ />
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#030712" media="(prefers-color-scheme: dark)" />
<link rel="icon" type="image/svg+xml" href="/penguin-logo.svg" />
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index e67cca27..2bd383e3 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -161,6 +161,9 @@ export function CloseButton({
);
}
+/** Plus: "add one of these" — the dock's add-tab trigger, the terminal page's new shell. */
+export const ADD_ICON = "M12 5v14M5 12h14";
+
/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */
export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";
diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsx
index e42ca1f3..c0fb12da 100644
--- a/packages/web/src/features/dock/dock-panel.tsx
+++ b/packages/web/src/features/dock/dock-panel.tsx
@@ -34,6 +34,7 @@ import {
import type { ReactNode } from "react";
import { S } from "../../lib/strings";
import {
+ ADD_ICON,
CloseIcon,
NAV_ICONS,
PANEL_BOTTOM_ICON,
@@ -45,6 +46,7 @@ import { GlyphIcon } from "../../components/ui/glyph-icon";
import { Kbd } from "../../components/ui/kbd";
import { ICON_SIZE } from "../../lib/icon-scale";
import { useDisplayedBinding, useShortcutLabel } from "../../lib/shortcuts/use-keymap";
+import { useCoarsePointer } from "../../lib/use-coarse-pointer";
import { toneDot } from "../../lib/tone";
import { useTerminalChrome } from "../terminal/terminal-appearance";
import {
@@ -98,8 +100,9 @@ import {
} from "../chat/use-panel-width";
import { usePointerDrag } from "./use-pointer-drag";
-/** Plus: the add-tab trigger. */
-const ADD_ICON = "M12 5v14M5 12h14";
+/** Four corners pushed outward / pulled inward: the touch height toggle (see maximize). */
+const MAXIMIZE_ICON = "M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5";
+const RESTORE_ICON = "M4 9h5V4M20 9h-5V4M4 15h5v5M20 15h-5v5";
/** Box with an arrow escaping to the top right: detach to its own window. */
const DETACH_ICON = "M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5";
@@ -110,6 +113,9 @@ function DockButton(props: {
onClick: () => void;
children: ReactNode;
}) {
+ // A 24px box is a comfortable mouse target and a poor finger one; the glyph inside keeps
+ // its size either way, so only the box a finger has to land in grows.
+ const coarsePointer = useCoarsePointer();
return (
<button
type="button"
@@ -117,7 +123,7 @@ function DockButton(props: {
aria-label={props.label}
data-testid={props.testId}
onClick={props.onClick}
- className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ className={`flex ${coarsePointer ? "h-8 w-8" : "h-6 w-6"} shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200`}
>
{props.children}
</button>
@@ -147,13 +153,14 @@ function DockTabButton(props: {
/** Terminal tabs keep their id on the node for tests and the strip's drag targeting. */
terminalId?: string;
}) {
+ const coarsePointer = useCoarsePointer();
return (
<div
data-testid="dock-tab"
data-tab-id={props.tabId}
{...(props.terminalId !== undefined ? { "data-terminal-id": props.terminalId } : {})}
data-active={props.active}
- className={`flex h-6 max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${
+ className={`flex ${coarsePointer ? "h-8" : "h-6"} max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${
props.active
? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
: "text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"
@@ -183,7 +190,7 @@ function DockTabButton(props: {
aria-label={`${props.closeLabel}: ${props.label}`}
data-testid="dock-tab-close"
onClick={props.onClose}
- className="flex h-4 w-4 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200"
+ className={`flex ${coarsePointer ? "h-6 w-6" : "h-4 w-4"} shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200`}
>
<CloseIcon size={10} />
</button>
@@ -561,6 +568,27 @@ export function DockPanel({
[horizontal],
);
+ // ------------------------------------------------------------------- touch height toggle
+
+ // The bottom dock's height is set by dragging its top boundary — a 4px line, which is a
+ // mouse target and not a finger one. On touch the same two heights a user actually wants
+ // (as much as the dock can take, and back to where it was) get a button. The remembered
+ // height is per mount on purpose: the ratio itself is persisted, so a dock left maximised
+ // restores to the shared default rather than to a height from another session.
+ const coarsePointer = useCoarsePointer();
+ const restoreRatio = useRef<number | null>(null);
+ const maximized = bottomRatio() >= DOCK_RATIO_MAX;
+ const toggleMaximized = useCallback(() => {
+ if (bottomRatio() >= DOCK_RATIO_MAX) {
+ const previous = restoreRatio.current;
+ if (previous === null) resetBottomRatio();
+ else setBottomRatio(previous);
+ return;
+ }
+ restoreRatio.current = bottomRatio();
+ setBottomRatio(DOCK_RATIO_MAX);
+ }, []);
+
// ------------------------------------------------------------------------------ add menu
const openPanelHere = (kind: PanelKind): void => {
@@ -783,6 +811,15 @@ export function DockPanel({
/>
</DockButton>
)}
+ {horizontal && coarsePointer && tabs.length > 0 && (
+ <DockButton
+ label={maximized ? S.dock.restore : S.dock.maximize}
+ testId="dock-maximize"
+ onClick={toggleMaximized}
+ >
+ <GlyphIcon d={maximized ? RESTORE_ICON : MAXIMIZE_ICON} size={ICON_SIZE.rowLead} />
+ </DockButton>
+ )}
<DockButton label={S.dock.hideDock} testId="dock-close" onClick={hide}>
<CloseIcon size={12} />
</DockButton>
diff --git a/packages/web/src/features/terminal/terminal-appearance.ts b/packages/web/src/features/terminal/terminal-appearance.ts
index b8c48a82..f344feb8 100644
--- a/packages/web/src/features/terminal/terminal-appearance.ts
+++ b/packages/web/src/features/terminal/terminal-appearance.ts
@@ -37,6 +37,10 @@ export interface TerminalChrome {
danger: string;
/** Bordered text button (retry, detach on the standalone page). */
outlineButton: string;
+ /** A resting cap in the touch key bar. */
+ keyCap: string;
+ /** A sticky modifier cap waiting for the character that will consume it. */
+ keyCapArmed: string;
}
const DARK: TerminalChrome = {
@@ -55,6 +59,10 @@ const DARK: TerminalChrome = {
attention: "text-amber-400",
danger: "text-red-400",
outlineButton: "border-gray-700 text-gray-300 hover:bg-gray-800",
+ keyCap: "border-gray-700 bg-gray-900 text-gray-200 active:bg-gray-800",
+ // Armed is `attention` (waiting on the user's next key); aria-pressed carries the state
+ // for anyone the colour does not reach.
+ keyCapArmed: "border-amber-500 bg-amber-500/15 text-amber-300",
};
const LIGHT: TerminalChrome = {
@@ -72,6 +80,8 @@ const LIGHT: TerminalChrome = {
attention: "text-amber-600",
danger: "text-red-600",
outlineButton: "border-gray-300 text-gray-600 hover:bg-gray-100",
+ keyCap: "border-gray-300 bg-gray-50 text-gray-700 active:bg-gray-200",
+ keyCapArmed: "border-amber-600 bg-amber-100 text-amber-700",
};
export function useTerminalChrome(): TerminalChrome {
diff --git a/packages/web/src/features/terminal/terminal-keybar.tsx b/packages/web/src/features/terminal/terminal-keybar.tsx
new file mode 100644
index 00000000..5f5c120d
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-keybar.tsx
@@ -0,0 +1,180 @@
+/**
+ * The touch key bar: the keys a phone's soft keyboard does not have.
+ *
+ * Without it a terminal on a phone is read-only in practice — no Esc, no Tab completion, no
+ * ↑ for the last command, and no Ctrl, so not even Ctrl+C. It renders only under
+ * `(pointer: coarse)`; a device with a real keyboard already has every key on it.
+ *
+ * Two things make it behave like a keyboard rather than like buttons:
+ *
+ * - **Presses never move focus.** Every cap cancels its own `mousedown` — the event that
+ * moves focus, for a tap as much as for a click — so xterm's textarea keeps it and the
+ * soft keyboard does not slide away on the first tap of Esc. It has to be `mousedown` and
+ * not `pointerdown`: cancelling a touch `pointerdown` suppresses the compatibility events
+ * that follow it, and the cap's own `click` is one of them.
+ * - **Ctrl and Alt are sticky, one shot.** A phone cannot hold a modifier down, so a tap
+ * arms it and the next character typed on the soft keyboard consumes it (the composition
+ * happens on the data path in terminal-view.tsx). Tapping again disarms.
+ */
+import { useTerminalChrome } from "./terminal-appearance";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { S } from "../../lib/strings";
+import {
+ NO_MODIFIERS,
+ arrowSequence,
+ type ArrowKey,
+ type TerminalModifiers,
+} from "./terminal-keys";
+
+/** Clipboard with a sheet on it: paste from the system clipboard. */
+const PASTE_ICON =
+ "M9 4h6v3H9zM9 5.5H6.5A1.5 1.5 0 0 0 5 7v12a1.5 1.5 0 0 0 1.5 1.5h11A1.5 1.5 0 0 0 19 19V7a1.5 1.5 0 0 0-1.5-1.5H15";
+/** Keyboard with a chevron under it: dismiss the soft keyboard. */
+const KEYBOARD_HIDE_ICON =
+ "M4 4.5h16v10H4zM7.5 8h.01M12 8h.01M16.5 8h.01M8.5 11.5h7M9 18l3 2.5 3-2.5";
+/** Keyboard with a chevron above it: bring the soft keyboard back. */
+const KEYBOARD_SHOW_ICON =
+ "M4 9.5h16v10H4zM7.5 13h.01M12 13h.01M16.5 13h.01M8.5 16.5h7M9 6.5 12 4l3 2.5";
+
+/** What the bar needs from the live terminal; null while none is attached. */
+export interface TerminalControl {
+ /** Writes into the shell's input stream — the bar's keys never reach xterm's key handler. */
+ send(data: string): void;
+ paste(): void;
+ focus(): void;
+ blur(): void;
+ /** True while a full-screen app has switched the cursor keys to SS3 (see arrowSequence). */
+ applicationCursorKeys(): boolean;
+}
+
+const ARROW_GLYPH: Record<ArrowKey, string> = { left: "←", up: "↑", down: "↓", right: "→" };
+
+export interface TerminalKeyBarProps {
+ control: React.RefObject<TerminalControl | null>;
+ modifiers: TerminalModifiers;
+ onModifiers: (mods: TerminalModifiers) => void;
+ /** Whether xterm currently holds focus — decides which way the keyboard cap points. */
+ focused: boolean;
+}
+
+export function TerminalKeyBar({ control, modifiers, onModifiers, focused }: TerminalKeyBarProps) {
+ const chrome = useTerminalChrome();
+ // The caps SHARE the width the way a keyboard row does, rather than each taking what its
+ // label needs: the whole set has to be on screen at once, because a cap that must be
+ // scrolled into view is one nobody finds. `min-w-8` is the floor a finger still hits, and
+ // it is what makes the row overflow (and scroll) on the narrowest phones instead of
+ // squeezing the caps down to slivers.
+ // Shape here, colour from the chrome — and the two tones REPLACE each other rather than
+ // stacking: this app has no class merger, so `border-gray-300` and `border-amber-600` on
+ // one element resolve by stylesheet order, not by which was written last.
+ const capShape =
+ "flex h-9 min-w-8 flex-1 basis-0 items-center justify-center rounded border px-1 text-xs font-medium";
+
+ /** Sends a sequence the bar composed itself, then spends any armed modifier. */
+ const send = (data: string): void => {
+ control.current?.send(data);
+ if (modifiers.ctrl || modifiers.alt) onModifiers(NO_MODIFIERS);
+ };
+
+ const cap = (props: {
+ testId: string;
+ label: string;
+ onPress: () => void;
+ children: React.ReactNode;
+ /** Modifier caps only: their armed state, which also makes them toggle buttons. */
+ pressed?: boolean;
+ }) => (
+ <button
+ key={props.testId}
+ type="button"
+ data-testid={props.testId}
+ aria-label={props.label}
+ title={props.label}
+ {...(props.pressed !== undefined ? { "aria-pressed": props.pressed } : {})}
+ // Keeps focus (and the soft keyboard) on the terminal — see the file header.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={props.onPress}
+ className={`${capShape} ${props.pressed === true ? chrome.keyCapArmed : chrome.keyCap}`}
+ >
+ {props.children}
+ </button>
+ );
+
+ const arrow = (key: ArrowKey) =>
+ cap({
+ testId: `terminal-key-${key}`,
+ label: S.terminal.touchKeys[key],
+ onPress: () =>
+ send(arrowSequence(key, modifiers, control.current?.applicationCursorKeys() ?? false)),
+ children: <span aria-hidden>{ARROW_GLYPH[key]}</span>,
+ });
+
+ return (
+ <div
+ role="toolbar"
+ aria-label={S.terminal.touchKeys.label}
+ data-testid="terminal-key-bar"
+ className={`no-scrollbar flex shrink-0 items-center gap-0.5 overflow-x-auto border-t pt-1 ${chrome.border}`}
+ >
+ {cap({
+ testId: "terminal-key-esc",
+ label: S.terminal.touchKeys.esc,
+ onPress: () => send("\x1b"),
+ children: "Esc",
+ })}
+ {cap({
+ testId: "terminal-key-tab",
+ label: S.terminal.touchKeys.tab,
+ onPress: () => send("\t"),
+ children: "Tab",
+ })}
+ {cap({
+ testId: "terminal-key-ctrl",
+ label: S.terminal.touchKeys.ctrl,
+ pressed: modifiers.ctrl,
+ onPress: () => onModifiers({ ...modifiers, ctrl: !modifiers.ctrl }),
+ children: "Ctrl",
+ })}
+ {arrow("left")}
+ {arrow("up")}
+ {arrow("down")}
+ {arrow("right")}
+ {cap({
+ testId: "terminal-key-interrupt",
+ label: S.terminal.touchKeys.interrupt,
+ // Its own cap rather than two taps through Ctrl: interrupting a runaway command is
+ // the one key a user reaches for with the soft keyboard already dismissed.
+ onPress: () => send("\x03"),
+ children: "^C",
+ })}
+ {cap({
+ testId: "terminal-key-paste",
+ label: S.terminal.touchKeys.paste,
+ onPress: () => control.current?.paste(),
+ children: <GlyphIcon d={PASTE_ICON} size={ICON_SIZE.rowLead} />,
+ })}
+ {cap({
+ testId: "terminal-key-keyboard",
+ label: focused ? S.terminal.touchKeys.hideKeyboard : S.terminal.touchKeys.showKeyboard,
+ onPress: () => (focused ? control.current?.blur() : control.current?.focus()),
+ children: (
+ <GlyphIcon
+ d={focused ? KEYBOARD_HIDE_ICON : KEYBOARD_SHOW_ICON}
+ size={ICON_SIZE.rowLead}
+ />
+ ),
+ })}
+ {/* Last on purpose, away from its sibling Ctrl: eleven caps are a hair wider than a
+ phone, and this is the one to leave under the fold. Alt on a phone is Alt+. and
+ word motion — worth a swipe, not worth a slot ahead of interrupting a command. */}
+ {cap({
+ testId: "terminal-key-alt",
+ label: S.terminal.touchKeys.alt,
+ pressed: modifiers.alt,
+ onPress: () => onModifiers({ ...modifiers, alt: !modifiers.alt }),
+ children: "Alt",
+ })}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/terminal/terminal-keys.ts b/packages/web/src/features/terminal/terminal-keys.ts
new file mode 100644
index 00000000..d4e2266e
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-keys.ts
@@ -0,0 +1,88 @@
+/**
+ * The byte sequences the touch key bar puts on the wire.
+ *
+ * Kept apart from the component because the bar bypasses xterm's key handling entirely: it
+ * writes into the shell's input stream directly, so everything a real keypress would have
+ * consulted on the way through — the terminal's cursor-key mode, xterm's modifier encoding,
+ * the control-code table — has to be answered here instead. Being a plain module also makes
+ * the encoding testable in this package's DOM-less test run.
+ */
+
+/** The sticky modifiers the key bar can arm; a phone keyboard has neither key. */
+export interface TerminalModifiers {
+ ctrl: boolean;
+ alt: boolean;
+}
+
+export const NO_MODIFIERS: TerminalModifiers = { ctrl: false, alt: false };
+
+export function hasModifier(mods: TerminalModifiers): boolean {
+ return mods.ctrl || mods.alt;
+}
+
+/** xterm's modifier parameter: 1 + shift(1) + alt(2) + ctrl(4). 1 is "no modifiers". */
+function modifierParam(mods: TerminalModifiers): number {
+ return 1 + (mods.alt ? 2 : 0) + (mods.ctrl ? 4 : 0);
+}
+
+export type ArrowKey = "up" | "down" | "left" | "right";
+
+const ARROW_FINAL: Record<ArrowKey, string> = { up: "A", down: "B", right: "C", left: "D" };
+
+/**
+ * An arrow press. An unmodified arrow follows the terminal's current cursor-key mode —
+ * full-screen apps and readline prompts switch to SS3 (`ESC O A`) and read the CSI form as
+ * literal text, which is how a hand-rolled arrow button ends up typing `[A` into vim — while
+ * a modified arrow is always CSI with a parameter, in both modes.
+ */
+export function arrowSequence(
+ key: ArrowKey,
+ mods: TerminalModifiers,
+ applicationCursorKeys: boolean,
+): string {
+ const final = ARROW_FINAL[key];
+ const param = modifierParam(mods);
+ if (param !== 1) return `\x1b[1;${param}${final}`;
+ return applicationCursorKeys ? `\x1bO${final}` : `\x1b[${final}`;
+}
+
+/** Ctrl pairings that are not a letter: the C0 codes above and below the alphabet. */
+const CONTROL_PUNCTUATION: Record<string, string> = {
+ "@": "\x00",
+ " ": "\x00",
+ "[": "\x1b",
+ "\\": "\x1c",
+ "]": "\x1d",
+ "^": "\x1e",
+ _: "\x1f",
+ "?": "\x7f",
+};
+
+/** Ctrl+<char> as the byte a keyboard would have sent, or null where no pairing exists. */
+export function controlCode(char: string): string | null {
+ if (char.length !== 1) return null;
+ const lower = char.toLowerCase();
+ if (lower >= "a" && lower <= "z") return String.fromCharCode(lower.charCodeAt(0) - 96);
+ return CONTROL_PUNCTUATION[char] ?? null;
+}
+
+/**
+ * What an armed modifier does to the characters typed after it.
+ *
+ * Only a lone character can carry a modifier. Anything longer — a paste, an IME commit, an
+ * escape sequence xterm produced itself — passes through untouched: under Ctrl it would
+ * otherwise collapse into a single control byte, and under Alt the ESC in front would pair
+ * with the chunk's FIRST character, so a pasted `ls -la` reaches readline as Meta-l
+ * (downcase-word) followed by `s -la`.
+ *
+ * A pairing with no control code (Ctrl+1) sends the plain character, matching what a
+ * physical keyboard does.
+ */
+export function applyModifiers(data: string, mods: TerminalModifiers): string {
+ // One code point, not one UTF-16 unit: Alt composes with a character outside the BMP too.
+ if (!hasModifier(mods) || [...data].length !== 1) return data;
+ let out = data;
+ if (mods.ctrl) out = controlCode(data) ?? data;
+ if (mods.alt) out = `\x1b${out}`;
+ return out;
+}
diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsx
index 498e039d..429cf67c 100644
--- a/packages/web/src/features/terminal/terminal-page.tsx
+++ b/packages/web/src/features/terminal/terminal-page.tsx
@@ -16,10 +16,21 @@
* When `?id=` points at a terminal that no longer exists (server restart, reaped after
* exit), a fresh shell is created with the URL's cwd/name — the page always ends in a
* usable terminal rather than a dead end.
+ *
+ * The page owns its own height rather than filling `#root`: on a touch device it is sized
+ * to the visual viewport, so a soft keyboard takes its bite out of the terminal instead of
+ * covering the bottom rows. The header compacts to fit a phone — the label and the status
+ * word go, the working directory truncates, and the marks that carry the meaning (the
+ * status dot, the "+") stay, each naming itself.
*/
import { useCallback, useMemo, useState } from "react";
+import { ADD_ICON } from "../../components/ui/icons";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ICON_SIZE } from "../../lib/icon-scale";
import { S } from "../../lib/strings";
import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { useCoarsePointer } from "../../lib/use-coarse-pointer";
+import { useVisualViewportHeight } from "../../lib/use-visual-viewport-height";
import { useTerminalChrome } from "./terminal-appearance";
import { killTerminal } from "./terminal-list";
import {
@@ -111,6 +122,8 @@ async function attachOrCreate(
export function TerminalPage() {
const chrome = useTerminalChrome();
+ const coarsePointer = useCoarsePointer();
+ const viewportHeight = useVisualViewportHeight(coarsePointer);
const [status, setStatus] = useState<TerminalStatus>("connecting");
const [detail, setDetail] = useState<string>("");
const [info, setInfo] = useState<TerminalInfo | null>(null);
@@ -177,32 +190,45 @@ export function TerminalPage() {
: `${S.terminal.status[status]}${status === "error" && detail ? ` — ${detail}` : ""}`;
return (
- <div className={`flex h-screen w-screen flex-col ${chrome.surface}`}>
+ <div
+ // dvh for the browser's collapsing toolbars, an explicit pixel height (touch only)
+ // for the soft keyboard — see useVisualViewportHeight.
+ style={viewportHeight !== null ? { height: viewportHeight } : undefined}
+ className={`flex h-[100dvh] w-full flex-col ${chrome.surface}`}
+ >
<header
- className={`flex shrink-0 items-center gap-3 border-b px-4 py-2 text-xs ${chrome.border}`}
+ className={`flex shrink-0 items-center gap-2 border-b px-3 py-2 text-xs sm:gap-3 sm:px-4 ${chrome.border}`}
>
- <span className="font-medium">{S.terminal.title}</span>
- <span className={chrome.muted}>{info?.cwd ?? params.cwd}</span>
+ <span className="hidden shrink-0 font-medium sm:inline">{S.terminal.title}</span>
+ <span className={`min-w-0 flex-1 truncate ${chrome.muted}`}>{info?.cwd ?? params.cwd}</span>
<span
data-testid="terminal-status"
data-status={status}
- className={
+ // The dot is the whole mark on a phone, so the sentence it stands for has to
+ // reach a screen reader from somewhere: the title carries it either way.
+ title={statusText}
+ className={`flex shrink-0 items-center gap-1 ${
status === "ready"
? chrome.success
: status === "connecting"
? chrome.attention
: chrome.danger
- }
+ }`}
>
- ● {statusText}
+ <span aria-hidden>●</span>
+ <span className="hidden sm:inline">{statusText}</span>
+ <span className="sr-only sm:hidden">{statusText}</span>
</span>
<button
type="button"
data-testid="terminal-new-shell"
onClick={restart}
- className={`ml-auto rounded border px-2 py-1 ${chrome.outlineButton}`}
+ aria-label={S.terminal.newShell}
+ title={S.terminal.newShell}
+ className={`flex shrink-0 items-center gap-1 rounded border px-2 py-1 ${chrome.outlineButton}`}
>
- {S.terminal.newShell}
+ <GlyphIcon d={ADD_ICON} size={ICON_SIZE.rowLead} />
+ <span className="hidden sm:inline">{S.terminal.newShell}</span>
</button>
</header>
<TerminalView
diff --git a/packages/web/src/features/terminal/terminal-touch.ts b/packages/web/src/features/terminal/terminal-touch.ts
new file mode 100644
index 00000000..d430600b
--- /dev/null
+++ b/packages/web/src/features/terminal/terminal-touch.ts
@@ -0,0 +1,85 @@
+/**
+ * A finger dragging in a terminal that a full-screen program is drawing.
+ *
+ * xterm scrolls its own scrollback when a finger drags — but only while nothing has asked
+ * for the mouse, and that is exactly the case this does not cover. A program on the
+ * ALTERNATE SCREEN (Claude Code, and every TUI like it) has no scrollback in the terminal at
+ * all: the transcript above the fold is the program's, it scrolls it itself, and the only
+ * thing that ever asks it to is a wheel. So a phone, which has no wheel, could reach none of
+ * it — the surface opened at the newest line and stayed there.
+ *
+ * The drag therefore becomes wheel reports at the finger's position (the wiring in
+ * terminal-view.tsx dispatches them through xterm, so they are encoded in whatever mouse
+ * protocol the program actually turned on). This module is the part with no DOM in it: how
+ * far a finger has travelled, whether that is a scroll or a tap yet, and how many lines the
+ * travel is worth.
+ *
+ * ONE LINE PER LINE OF TRAVEL, which is what makes it feel like the transcript is stuck to
+ * the finger rather than flung by it: the cell height is the unit, the remainder is carried
+ * to the next move, and the direction is the one every touch surface uses — a finger moving
+ * up pulls later content into view, the same as a wheel rolled down.
+ */
+
+/**
+ * How far a finger may travel before the gesture stops being a tap. Small enough that a
+ * deliberate drag is never mistaken for a press, large enough that the jitter of a finger
+ * leaving the glass is: below it nothing scrolls, and the browser's tap-to-click reaches the
+ * program untouched.
+ */
+export const TOUCH_SLOP_PX = 8;
+
+/**
+ * One finger's travel, converted to wheel lines. Fed the raw touch coordinates by the view;
+ * `start` / `end` bracket a gesture, and `move` answers with the lines that gesture has
+ * earned since the last one.
+ */
+export class TouchScroll {
+ /** Where the last move left the finger; null between gestures. */
+ private lastY: number | null = null;
+ /** Travel not yet paid out as whole lines, in pixels (positive = the finger moved up). */
+ private pending = 0;
+ private scrolling = false;
+
+ /** Whether a gesture is being followed at all. */
+ get started(): boolean {
+ return this.lastY !== null;
+ }
+
+ /** Whether the travel has passed the slop, i.e. this is a scroll and no longer a tap. */
+ get engaged(): boolean {
+ return this.scrolling;
+ }
+
+ start(y: number): void {
+ this.lastY = y;
+ this.pending = 0;
+ this.scrolling = false;
+ }
+
+ /**
+ * The finger moved to `y`; answers the wheel lines it earned — positive for content
+ * later in the transcript (a wheel rolled down), negative for earlier.
+ *
+ * Zero until the slop is passed, and zero for a cell height that is not yet measurable
+ * (a terminal mid-attach): the travel is kept, so nothing is lost by asking early.
+ */
+ move(y: number, cellHeight: number): number {
+ if (this.lastY === null) return 0;
+ this.pending += this.lastY - y;
+ this.lastY = y;
+ if (!this.scrolling) {
+ if (Math.abs(this.pending) < TOUCH_SLOP_PX) return 0;
+ this.scrolling = true;
+ }
+ if (!(cellHeight > 0)) return 0;
+ const lines = Math.trunc(this.pending / cellHeight);
+ this.pending -= lines * cellHeight;
+ return lines;
+ }
+
+ end(): void {
+ this.lastY = null;
+ this.pending = 0;
+ this.scrolling = false;
+ }
+}
diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsx
index c3fb699c..ac279f1d 100644
--- a/packages/web/src/features/terminal/terminal-view.tsx
+++ b/packages/web/src/features/terminal/terminal-view.tsx
@@ -9,15 +9,21 @@
* a fresh one, honouring URL parameters — whatever that host's policy is). This component
* only knows how to attach to whatever `ensure` resolved.
*
- * To restart with a different terminal, remount it (change the React `key`).
+ * To restart with a different terminal, remount it (change the React `key`). On a touch
+ * device the surface also carries the key bar (terminal-keybar.tsx), so both hosts get the
+ * keys a soft keyboard lacks without either of them knowing about it.
*/
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import "@xterm/xterm/css/xterm.css";
// Types only (erased at compile time): the xterm runtime stays behind loadXterm() below.
import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";
import { TerminalOpcode, decodeFrame, encodeFrame, encodeResize } from "./terminal-frames";
import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./terminal-links";
import { writeClipboard } from "../../lib/clipboard";
+import { TerminalKeyBar, type TerminalControl } from "./terminal-keybar";
+import { NO_MODIFIERS, applyModifiers, hasModifier, type TerminalModifiers } from "./terminal-keys";
+import { TouchScroll } from "./terminal-touch";
+import { useCoarsePointer } from "../../lib/use-coarse-pointer";
import { useTheme } from "../../state/theme";
import { currentPlatform } from "../../lib/shortcuts/platform";
import { keymap } from "../../lib/shortcuts/store";
@@ -239,6 +245,15 @@ export function TerminalView({
const darkRef = useRef(terminalDark);
darkRef.current = terminalDark;
const termRef = useRef<XTerminal | null>(null);
+ // Touch affordances. The bar is the only consumer of all three: the control handle the
+ // effect publishes once a terminal is live, the sticky modifiers it arms (spent on the
+ // data path below), and whether xterm holds focus (which way the keyboard cap points).
+ const coarsePointer = useCoarsePointer();
+ const control = useRef<TerminalControl | null>(null);
+ const [modifiers, setModifiers] = useState<TerminalModifiers>(NO_MODIFIERS);
+ const modifiersRef = useRef(modifiers);
+ modifiersRef.current = modifiers;
+ const [focused, setFocused] = useState(false);
useEffect(() => {
if (termRef.current) termRef.current.options.theme = terminalTheme(terminalDark);
}, [terminalDark]);
@@ -438,11 +453,22 @@ export function TerminalView({
*/
const { signal } = listenerAbort;
const appOwnsMouse = (): boolean => term.modes.mouseTrackingMode !== "none";
+ // A long press on a touchscreen also raises `contextmenu`, and it is not a right
+ // click: the finger that meant to select text would paste the clipboard into a live
+ // shell instead. Touch gets the key bar's paste cap, which says what it does.
+ let touchPointer = false;
+ container.addEventListener(
+ "pointerdown",
+ (event) => {
+ touchPointer = event.pointerType === "touch" || event.pointerType === "pen";
+ },
+ { signal },
+ );
container.addEventListener(
"contextmenu",
(event) => {
event.preventDefault(); // a terminal never shows the page's context menu
- if (appOwnsMouse()) return;
+ if (appOwnsMouse() || touchPointer) return;
// PuTTY-style right click: copy the selection if there is one, else paste.
if (term.hasSelection()) copySelection();
else pasteFromClipboard();
@@ -460,9 +486,78 @@ export function TerminalView({
},
{ signal },
);
+ /**
+ * A finger dragging while a program owns the mouse: the wheel it does not have.
+ *
+ * xterm turns its own touch scrolling off for exactly these programs, and they are the
+ * ones that need it most — a TUI on the alternate screen (Claude Code) leaves the
+ * terminal no scrollback to scroll, draws its transcript itself, and pages it only when
+ * a wheel reports. So the travel becomes wheel events (terminal-touch.ts for the
+ * arithmetic), dispatched at xterm's own element so IT encodes them in whatever
+ * protocol the program asked for — hand-rolled SGR here would be a second encoder to
+ * keep in step with the first.
+ *
+ * A tap is left alone: nothing scrolls until the travel passes the slop, so the
+ * browser's tap-to-click still reaches a program that answers clicks. Where the mouse
+ * is free, xterm's own touch handling runs first (on its element, below this one) and
+ * this stays out of the way entirely.
+ */
+ const touchScroll = new TouchScroll();
+ /** The height of one row, in pixels: the screen element is exactly rows cells tall. */
+ const cellHeight = (): number => {
+ const screen = term.element?.querySelector(".xterm-screen");
+ if (!screen || term.rows <= 0) return 0;
+ return screen.getBoundingClientRect().height / term.rows;
+ };
+ const wheelLine = (x: number, y: number, down: boolean): void => {
+ term.element?.dispatchEvent(
+ new WheelEvent("wheel", {
+ deltaY: down ? 1 : -1,
+ // Lines, not pixels: one event is one line, whatever this device's cells measure.
+ deltaMode: 1,
+ clientX: x,
+ clientY: y,
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ };
+ container.addEventListener(
+ "touchstart",
+ (event) => {
+ if (!appOwnsMouse() || event.touches.length !== 1) {
+ touchScroll.end(); // a second finger (pinch) is not a scroll
+ return;
+ }
+ touchScroll.start(event.touches[0]!.clientY);
+ },
+ { signal, passive: true },
+ );
+ container.addEventListener(
+ "touchmove",
+ (event) => {
+ const touch = event.touches[0];
+ if (!touchScroll.started || event.touches.length !== 1 || touch === undefined) return;
+ const lines = touchScroll.move(touch.clientY, cellHeight());
+ if (!touchScroll.engaged) return;
+ // The host carries `touch-none` on a touch device, so there is normally nothing
+ // left to cancel; this is for the device that reports a fine pointer and is one
+ // anyway, where the page would otherwise scroll out from under the gesture.
+ if (event.cancelable) event.preventDefault();
+ for (let i = Math.abs(lines); i > 0; i--) {
+ wheelLine(touch.clientX, touch.clientY, lines > 0);
+ }
+ },
+ { signal, passive: false },
+ );
+ container.addEventListener("touchend", () => touchScroll.end(), { signal, passive: true });
+ container.addEventListener("touchcancel", () => touchScroll.end(), { signal, passive: true });
+
// Click-to-focus anywhere in the view, padding included — finishing a selection drag
// also lands here, which is fine: focusing xterm's textarea keeps the selection.
container.addEventListener("mouseup", () => term.focus(), { signal });
+ container.addEventListener("focusin", () => setFocused(true), { signal });
+ container.addEventListener("focusout", () => setFocused(false), { signal });
// Size ownership follows the user's attention (see server size-ownership.ts): the pty
// is laid out for the most recent CLAIMING connection, and `update`s from anyone else
@@ -478,10 +573,23 @@ export function TerminalView({
{ signal },
);
- term.onData((data) => {
+ const send = (data: string): void => {
if (socket?.readyState === WebSocket.OPEN) {
socket.send(encodeFrame(TerminalOpcode.Input, data));
}
+ };
+
+ term.onData((data) => {
+ // A sticky Ctrl/Alt armed on the touch key bar composes with the next character the
+ // soft keyboard produces, then spends itself. Nothing to do when none is armed,
+ // which is every keystroke on a physical keyboard.
+ const mods = modifiersRef.current;
+ if (!hasModifier(mods)) {
+ send(data);
+ return;
+ }
+ send(applyModifiers(data, mods));
+ setModifiers(NO_MODIFIERS);
});
// Title changes ride the ordinary byte stream (OSC 0/2); this client's xterm parses
@@ -544,9 +652,20 @@ export function TerminalView({
observer.observe(container);
term.focus();
+ // What the touch key bar drives. Published after the terminal is open and dropped on
+ // dispose, so a bar tap between two attaches is a no-op rather than a throw.
+ control.current = {
+ send,
+ paste: pasteFromClipboard,
+ focus: () => term.focus(),
+ blur: () => term.blur(),
+ applicationCursorKeys: () => term.modes.applicationCursorKeysMode,
+ };
+
return () => {
disposed = true;
termRef.current = null;
+ control.current = null;
listenerAbort.abort();
observer.disconnect();
socket?.close();
@@ -555,5 +674,27 @@ export function TerminalView({
}
}, []);
- return <div ref={hostRef} className={className ?? "min-h-0 flex-1 overflow-hidden"} />;
+ // The className lands on the WRAPPER, not on the xterm host: the host has to be the
+ // flex child that takes the leftover height, so that the bar's own height comes off the
+ // terminal's grid instead of pushing the surface past its container.
+ return (
+ <div className={`flex flex-col ${className ?? "min-h-0 flex-1 overflow-hidden"}`}>
+ {/* `touch-none` on a touch device: the drag above is the gesture, and the browser
+ must not take it for its own (a page scroll, a pull-to-refresh) — which also
+ stops mid-gesture cancellation, since a taken-over touch stops being cancelable.
+ xterm's own touch scrolling sets scrollTop itself and is unaffected. */}
+ <div
+ ref={hostRef}
+ className={`min-h-0 flex-1 overflow-hidden ${coarsePointer ? "touch-none" : ""}`}
+ />
+ {coarsePointer && (
+ <TerminalKeyBar
+ control={control}
+ modifiers={modifiers}
+ onModifiers={setModifiers}
+ focused={focused}
+ />
+ )}
+ </div>
+ );
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 4c75d23b..2252d81a 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -208,6 +208,21 @@ export const en: Strings = {
},
/** Suffix shown after `status.exited`; `code` is the shell's numeric exit code. */
exitedWithCode: (code: string): string => `exit code ${code}`,
+ touchKeys: {
+ label: "Terminal keys",
+ esc: "Escape",
+ tab: "Tab",
+ ctrl: "Ctrl (tap, then the next character)",
+ alt: "Alt (tap, then the next character)",
+ up: "Arrow up",
+ down: "Arrow down",
+ left: "Arrow left",
+ right: "Arrow right",
+ interrupt: "Interrupt (Ctrl+C)",
+ paste: "Paste",
+ hideKeyboard: "Dismiss the keyboard",
+ showKeyboard: "Show the keyboard",
+ },
},
dock: {
@@ -231,6 +246,8 @@ export const en: Strings = {
launcherPanels: "Shortcuts",
launcherHide: "Hide launcher",
launcherHiddenToast: "Launcher hidden — turn it back on in Settings › Appearance",
+ maximize: "Fill the screen",
+ restore: "Restore the height",
},
builtinBrowser: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 6f2047aa..acff92e7 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -224,6 +224,28 @@ export const zh = {
},
/** Suffix shown after `status.exited`; `code` is the shell's numeric exit code. */
exitedWithCode: (code: string): string => `退出码 ${code}`,
+ /**
+ * The touch key bar (terminal-keybar.tsx), shown only under `(pointer: coarse)`: the
+ * keys a phone's soft keyboard has none of. Cap faces are the key names themselves
+ * (Esc / Tab / Ctrl / Alt / ^C) and stay untranslated, as on a physical keyboard; these
+ * are their accessible names.
+ */
+ touchKeys: {
+ label: "终端快捷键",
+ esc: "Esc 键",
+ tab: "Tab 键",
+ /** Sticky: tap to arm, the next character composes with it. */
+ ctrl: "Ctrl 键(点一下,下一个字符生效)",
+ alt: "Alt 键(点一下,下一个字符生效)",
+ up: "上方向键",
+ down: "下方向键",
+ left: "左方向键",
+ right: "右方向键",
+ interrupt: "中断(Ctrl+C)",
+ paste: "粘贴",
+ hideKeyboard: "收起键盘",
+ showKeyboard: "调出键盘",
+ },
},
/** The dock surfaces (right / bottom) every side element renders in as a tab. */
@@ -264,6 +286,9 @@ export const zh = {
/** The fan's last entry: puts the launcher away until Appearance settings bring it back. */
launcherHide: "隐藏悬浮球",
launcherHiddenToast: "悬浮球已隐藏,可在 设置 › 外观 中重新开启",
+ /** Touch-only: the bottom dock's height toggle, standing in for a boundary drag. */
+ maximize: "放大到整屏",
+ restore: "还原高度",
},
/** The built-in browser (desktop app only): its dock panel, toolbar and dialogs. */
diff --git a/packages/web/src/lib/use-coarse-pointer.ts b/packages/web/src/lib/use-coarse-pointer.ts
new file mode 100644
index 00000000..bb316dba
--- /dev/null
+++ b/packages/web/src/lib/use-coarse-pointer.ts
@@ -0,0 +1,32 @@
+/**
+ * "The primary pointer is a finger" — the one condition every touch-only affordance in the
+ * app hangs off.
+ *
+ * It is a pointer question, not a width question: a phone in landscape is wider than a
+ * small desktop window, and a desktop window narrowed to phone width still has a mouse and
+ * a full keyboard. `(pointer: coarse)` asks about the primary input device, so a touchscreen
+ * laptop — primary pointer still fine — keeps the desktop affordances it can actually use.
+ *
+ * Live, not a mount-time snapshot: a tablet switching to a paired keyboard and trackpad
+ * changes the answer without reloading the page.
+ */
+import { useEffect, useState } from "react";
+
+export const COARSE_POINTER_QUERY = "(pointer: coarse)";
+
+function matches(): boolean {
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
+ return window.matchMedia(COARSE_POINTER_QUERY).matches;
+}
+
+export function useCoarsePointer(): boolean {
+ const [coarse, setCoarse] = useState(matches);
+ useEffect(() => {
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
+ const mq = window.matchMedia(COARSE_POINTER_QUERY);
+ const onChange = (event: MediaQueryListEvent) => setCoarse(event.matches);
+ mq.addEventListener("change", onChange);
+ return () => mq.removeEventListener("change", onChange);
+ }, []);
+ return coarse;
+}
diff --git a/packages/web/src/lib/use-visual-viewport-height.ts b/packages/web/src/lib/use-visual-viewport-height.ts
new file mode 100644
index 00000000..a2340035
--- /dev/null
+++ b/packages/web/src/lib/use-visual-viewport-height.ts
@@ -0,0 +1,39 @@
+/**
+ * The height actually visible on screen, on devices where a soft keyboard eats into it.
+ *
+ * `100dvh` answers for the browser's own collapsing toolbars, not for the keyboard: the
+ * layout viewport a full-screen page is measured against does not shrink when the keyboard
+ * slides up, so the bottom of the page — a terminal's last lines, its key bar — ends up
+ * underneath it. `visualViewport` is the box that does shrink.
+ *
+ * `index.html` asks Chrome for `interactive-widget=resizes-content`, which makes the layout
+ * viewport shrink too and would be the whole fix on its own; Safari does not implement it,
+ * so this hook is what covers iOS. Where both apply they agree, and the explicit pixel
+ * height simply restates the CSS one.
+ *
+ * Returns null when it has nothing to say (disabled, or no `visualViewport`), meaning "keep
+ * whatever the stylesheet decided".
+ */
+import { useEffect, useState } from "react";
+
+export function useVisualViewportHeight(enabled: boolean): number | null {
+ const [height, setHeight] = useState<number | null>(null);
+ useEffect(() => {
+ const viewport = typeof window !== "undefined" ? window.visualViewport : undefined;
+ if (!enabled || !viewport) {
+ setHeight(null);
+ return;
+ }
+ const apply = (): void => {
+ setHeight(viewport.height);
+ // iOS scrolls the layout viewport to bring the focused element into view and never
+ // scrolls back. Once the page is sized to the visual viewport there is nothing below
+ // the fold to reveal, so that offset only pushes the header off the top.
+ if (window.scrollY !== 0) window.scrollTo(0, 0);
+ };
+ apply();
+ viewport.addEventListener("resize", apply);
+ return () => viewport.removeEventListener("resize", apply);
+ }, [enabled]);
+ return height;
+}
diff --git a/packages/web/test/terminal-touch-keys.test.ts b/packages/web/test/terminal-touch-keys.test.ts
new file mode 100644
index 00000000..502cdbfe
--- /dev/null
+++ b/packages/web/test/terminal-touch-keys.test.ts
@@ -0,0 +1,95 @@
+/**
+ * The touch key bar's wire format (terminal-keys.ts): what the bar has to get right because
+ * it bypasses xterm's own key handling.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ NO_MODIFIERS,
+ applyModifiers,
+ arrowSequence,
+ controlCode,
+ hasModifier,
+} from "../src/features/terminal/terminal-keys";
+
+const CTRL = { ctrl: true, alt: false };
+const ALT = { ctrl: false, alt: true };
+
+describe("arrowSequence", () => {
+ it("sends CSI while the terminal is in normal cursor-key mode", () => {
+ expect(arrowSequence("up", NO_MODIFIERS, false)).toBe("\x1b[A");
+ expect(arrowSequence("down", NO_MODIFIERS, false)).toBe("\x1b[B");
+ expect(arrowSequence("right", NO_MODIFIERS, false)).toBe("\x1b[C");
+ expect(arrowSequence("left", NO_MODIFIERS, false)).toBe("\x1b[D");
+ });
+
+ it("switches to SS3 when a full-screen app turned application cursor keys on", () => {
+ // The CSI form would arrive in vim as the literal text "[A".
+ expect(arrowSequence("up", NO_MODIFIERS, true)).toBe("\x1bOA");
+ expect(arrowSequence("left", NO_MODIFIERS, true)).toBe("\x1bOD");
+ });
+
+ it("encodes modifiers as xterm's parameter, in either cursor-key mode", () => {
+ expect(arrowSequence("left", CTRL, false)).toBe("\x1b[1;5D");
+ expect(arrowSequence("left", ALT, false)).toBe("\x1b[1;3D");
+ expect(arrowSequence("right", { ctrl: true, alt: true }, true)).toBe("\x1b[1;7C");
+ });
+});
+
+describe("controlCode", () => {
+ it("maps letters to their C0 code, case-insensitively", () => {
+ expect(controlCode("c")).toBe("\x03");
+ expect(controlCode("C")).toBe("\x03");
+ expect(controlCode("a")).toBe("\x01");
+ expect(controlCode("z")).toBe("\x1a");
+ });
+
+ it("maps the punctuation pairings a keyboard has", () => {
+ expect(controlCode("[")).toBe("\x1b");
+ expect(controlCode(" ")).toBe("\x00");
+ expect(controlCode("?")).toBe("\x7f");
+ });
+
+ it("has no code for an unpaired character or a longer chunk", () => {
+ expect(controlCode("1")).toBeNull();
+ expect(controlCode("ab")).toBeNull();
+ expect(controlCode("")).toBeNull();
+ });
+});
+
+describe("applyModifiers", () => {
+ it("passes data through untouched when nothing is armed", () => {
+ expect(hasModifier(NO_MODIFIERS)).toBe(false);
+ expect(applyModifiers("ls -la", NO_MODIFIERS)).toBe("ls -la");
+ });
+
+ it("composes an armed Ctrl with the next character", () => {
+ expect(applyModifiers("c", CTRL)).toBe("\x03");
+ });
+
+ it("prefixes an armed Alt with ESC, the way a meta key does", () => {
+ expect(applyModifiers("b", ALT)).toBe("\x1bb");
+ expect(applyModifiers("c", { ctrl: true, alt: true })).toBe("\x1b\x03");
+ });
+
+ it("leaves a multi-character chunk alone under Ctrl", () => {
+ // A paste or an IME commit arriving while Ctrl is armed must not collapse into one
+ // control byte.
+ expect(applyModifiers("hello", CTRL)).toBe("hello");
+ });
+
+ it("leaves a multi-character chunk alone under Alt", () => {
+ // ESC in front of a paste pairs with its first character: readline would take `ESC l` as
+ // downcase-word and the command would arrive without its first letter.
+ expect(applyModifiers("ls -la", ALT)).toBe("ls -la");
+ expect(applyModifiers("\x1b[200~ls\x1b[201~", ALT)).toBe("\x1b[200~ls\x1b[201~");
+ expect(applyModifiers("hello", { ctrl: true, alt: true })).toBe("hello");
+ });
+
+ it("counts a character outside the BMP as one", () => {
+ expect(applyModifiers("😀", ALT)).toBe("\x1b😀");
+ });
+
+ it("sends the plain character where the pairing has no control code", () => {
+ expect(applyModifiers("1", CTRL)).toBe("1");
+ });
+});
diff --git a/packages/web/test/terminal-touch.test.ts b/packages/web/test/terminal-touch.test.ts
new file mode 100644
index 00000000..765b2f42
--- /dev/null
+++ b/packages/web/test/terminal-touch.test.ts
@@ -0,0 +1,78 @@
+/**
+ * Touch travel converted to wheel lines (terminal-touch.ts): the slop that separates a tap
+ * from a scroll, the direction, and the remainder carried between moves.
+ */
+import { describe, expect, it } from "vitest";
+import { TOUCH_SLOP_PX, TouchScroll } from "../src/features/terminal/terminal-touch";
+
+const CELL = 20;
+
+describe("TouchScroll", () => {
+ it("follows nothing until a gesture starts", () => {
+ const scroll = new TouchScroll();
+ expect(scroll.started).toBe(false);
+ expect(scroll.move(100, CELL)).toBe(0);
+ });
+
+ it("a press that barely moves stays a tap", () => {
+ const scroll = new TouchScroll();
+ scroll.start(200);
+ expect(scroll.move(200 - (TOUCH_SLOP_PX - 1), CELL)).toBe(0);
+ expect(scroll.engaged).toBe(false);
+ });
+
+ it("jitter back and forth never adds up to a scroll", () => {
+ const scroll = new TouchScroll();
+ scroll.start(200);
+ for (let i = 0; i < 20; i++) {
+ scroll.move(i % 2 === 0 ? 196 : 204, CELL);
+ }
+ expect(scroll.engaged).toBe(false);
+ });
+
+ it("a finger moving up scrolls to later content, one line per cell of travel", () => {
+ const scroll = new TouchScroll();
+ scroll.start(300);
+ expect(scroll.move(300 - 3 * CELL, CELL)).toBe(3);
+ expect(scroll.engaged).toBe(true);
+ });
+
+ it("a finger moving down scrolls back to earlier content", () => {
+ const scroll = new TouchScroll();
+ scroll.start(300);
+ expect(scroll.move(300 + 2 * CELL, CELL)).toBe(-2);
+ });
+
+ it("carries the remainder, so a slow drag scrolls exactly once per cell", () => {
+ const scroll = new TouchScroll();
+ scroll.start(300);
+ let y = 300;
+ let lines = 0;
+ // Half a cell at a time: every second move is worth one line, never two.
+ for (let i = 0; i < 8; i++) {
+ y -= CELL / 2;
+ const step = scroll.move(y, CELL);
+ expect(Math.abs(step)).toBeLessThanOrEqual(1);
+ lines += step;
+ }
+ expect(lines).toBe(4);
+ });
+
+ it("keeps travel it cannot convert yet (a terminal with no measurable cell)", () => {
+ const scroll = new TouchScroll();
+ scroll.start(300);
+ expect(scroll.move(300 - 3 * CELL, 0)).toBe(0);
+ expect(scroll.move(300 - 3 * CELL, CELL)).toBe(3);
+ });
+
+ it("a new gesture starts from rest, carrying nothing from the last one", () => {
+ const scroll = new TouchScroll();
+ scroll.start(300);
+ scroll.move(300 - CELL - CELL / 2, CELL);
+ scroll.end();
+ expect(scroll.started).toBe(false);
+ scroll.start(300);
+ expect(scroll.move(300 - (TOUCH_SLOP_PX - 1), CELL)).toBe(0);
+ expect(scroll.engaged).toBe(false);
+ });
+});