瀏覽代碼

fix: restore complete TUI viewports and clear stale history hints (#257)

Cover Tasks, Rewind, and other feature panels through scrolling, resizing, nested views, and chat restoration. Register viewport regressions in the public verification suite.

Assisted-by: codex-cli reason:tui-viewport-sync
DanielWalnut 2 月之前
父節點
當前提交
73a2581c6c

+ 13 - 0
docs/tui-capabilities.md

@@ -80,3 +80,16 @@ the configured default. Omitting `--model` preserves existing startup behavior.
 The untargeted `--session` picker cannot be combined with `--model`; provide an ID
 or use `--continue` instead. If opening or continuing a Session fails, the override
 and initial prompt are not applied.
+
+## Feature panels and chat restoration
+
+In regular mode, independent feature panels occupy the complete visible terminal
+area, including short Rewind previews and scope pickers. Closing a panel restores
+the current conversation. When running content shrinks across the native scrolling
+boundary, the renderer reconstructs the current session to fill the viewport and
+keep its history unique. This reconstruction clears earlier shell scrollback;
+ordinary updates keep native scrolling and selection behavior.
+
+Rewind and Fork history-loading hints disappear as soon as their lists are ready.
+Returning from a cancelled operation must not leave a stale loading message in the
+Composer. Rewind displays its completed result after a successful operation.

+ 3 - 0
packages/tui/src/tui/controller/product/session-mutation-flow.ts

@@ -708,6 +708,7 @@ export class TuiSessionMutationFlow {
       ...(this.options.nowMs ? { nowMs: this.options.nowMs() } : {}),
     });
     this.options.setHint(undefined);
+    this.options.onChanged();
     const handle = this.options.surfaceHost.pushFeature({ screen: picker, focus: picker });
     this.mutationScreen = handle;
     this.invocations.set(sequence, {
@@ -1201,6 +1202,7 @@ export class TuiSessionMutationFlow {
       ...(this.options.nowMs ? { nowMs: this.options.nowMs() } : {}),
     });
     this.options.setHint(undefined);
+    this.options.onChanged();
     const handle = this.options.surfaceHost.pushFeature({
       screen: picker,
       focus: picker,
@@ -1446,6 +1448,7 @@ export class TuiSessionMutationFlow {
     if (sequence === this.mutationSequence) {
       this.closeMutationScreen();
       this.options.setHint(undefined);
+      this.options.onChanged();
     }
     this.invocations.delete(sequence);
   }

+ 2 - 2
packages/tui/src/tui/engine/LOCAL_CHANGES.json

@@ -163,11 +163,11 @@
     },
     {
       "path": "tui-main-screen.ts",
-      "currentSha256": "146fd4222ae5a48d1f439de2f280b111789151a30c1bdd2735e32fff07329b9d",
+      "currentSha256": "daf48c4d9a594abd282d4d4fd855373d17cb1033d0b5bdc2396e1727c2186153",
       "changeIds": ["L005", "L017", "L027", "L033", "L034"],
       "upstreamCommit": "6c4f360264397c59801f6da2bdac13e3b1fcbe91",
       "reason": "Keep strict TypeScript fixes and stream full and differential renders through Pi's bounded terminal writer. 缩放期间仅重绘可见尾部 常规模式在差分比较前剥离行首 OSC 133 zone 标记。 内容收缩或历史内容变化触发回退重绘时仅更新可见区域。",
-      "behaviorImpact": "Large regular-mode renders preserve output order without constructing a single V8-limited terminal string. 150ms 后及退出前重放完整投影历史。 内部导航标记不再写入终端,避免 iTerm2 左侧箭头和命令条噪声。 Session 结束后的状态更新不再发送 ESC 3J 清除原生滚动历史,当前视口仍显示最新内容。"
+      "behaviorImpact": "Regular updates preserve native scrollback. When document shrink reveals previously scrolled rows, replay the complete current session to fill the viewport and avoid duplicate history. Rebuilding clears pre-launch shell scrollback. Resize retains the existing delayed history replay."
     },
     {
       "path": "tui.ts",

+ 8 - 0
packages/tui/src/tui/engine/LOCAL_CHANGES.md

@@ -115,3 +115,11 @@ Remove `L024` when the selected Pi baseline natively matches legacy-terminal `Ct
 - Adaptation: the original contribution widened hits over two live content columns. The reserved gutter prevents those presses from swallowing content clicks or text selection. `chat-layout.ts` opts into the three-column gutter.
 - Evidence: `test/unit/tui-scrollbar-interaction.test.ts` drives SGR press, motion, release and wheel events through VirtualTerminal, covering track jumps, thumb grabs, narrow terminals, content routing, selection, overlays and the actual fullscreen ChatLayout.
 - Removal condition: the selected Pi baseline provides equivalent reserved-gutter track and drag interaction and MCode migrates to it.
+
+## L034: Regular viewport reconstruction after document shrink
+
+- Product contract: after running content or a feature panel closes, show the complete current chat viewport with its Composer and status line. Every current-session row must occur once in native history.
+- Minimal difference: when a shorter document would move the viewport origin backwards, clear and replay the complete current projection. Other updates retain differential rendering and resize retains the existing delayed history replay.
+- Tradeoff: structural reconstruction clears native scrollback, including shell history from before TUI startup. Initial short chat documents retain natural document placement.
+- Evidence: local-delta tests assert every visible row and the complete history, while real Tasks and feature lifecycle tests cover short/long content, background growth, paging, resize, nested panels and return to chat. Virtual terminals do not establish native iTerm2 touchpad acceptance.
+- Removal condition: the selected Pi baseline provides equivalent complete viewport and unique-history behavior.

+ 9 - 0
packages/tui/src/tui/engine/tui-main-screen.ts

@@ -398,6 +398,15 @@ export class TuiMainScreen extends TuiBase implements TUI {
 			return;
 		}
 
+		// A shorter document can bring previously scrolled rows back into view.
+		// Rebuild the complete projection so the viewport is full and native history
+		// contains each row once; neither tail replay nor blank padding can do both.
+		if (Math.max(0, newLines.length - height) < prevViewportTop) {
+			logRedraw("document shrink reveals scrolled rows");
+			fullRender(true);
+			return;
+		}
+
 		// Content shrunk below the working area and no overlays - re-render to clear empty rows
 		// (overlays need the padding, so only do this when no overlays are active)
 		// Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var

+ 1 - 1
packages/tui/src/tui/features/session-mutation/copy.en.ts

@@ -142,7 +142,7 @@ export const SESSION_MUTATION_COPY = {
   'sessionMutation.hint.editSubmitting': 'Replacing the message and rewinding history…',
   'sessionMutation.hint.editResubmit': 'Edited draft preserved · Enter resubmit · Esc cancel',
   'sessionMutation.hint.loadingFork': 'Loading fork history…',
-  'sessionMutation.hint.loadingRewind': 'Loading rewind history…',
+  'sessionMutation.hint.loadingRewind': 'Finding messages to rewind to…',
   'sessionMutation.hint.loadingEdit': 'Loading the latest message…',
   'sessionMutation.hint.noForkPrompts':
     'No persisted user prompts are available. Send a message, then retry /fork.',

+ 1 - 1
packages/tui/src/tui/features/session-mutation/copy.zh-Hans.ts

@@ -130,7 +130,7 @@ export const ZH_HANS_SESSION_MUTATION_COPY = {
   'sessionMutation.hint.editSubmitting': '正在替换消息并回退历史…',
   'sessionMutation.hint.editResubmit': '编辑草稿已保留 · Enter 重新提交 · Esc 取消',
   'sessionMutation.hint.loadingFork': '正在加载分支历史…',
-  'sessionMutation.hint.loadingRewind': '正在加载回退历史…',
+  'sessionMutation.hint.loadingRewind': '正在查找可回退的消息…',
   'sessionMutation.hint.loadingEdit': '正在加载最新消息…',
   'sessionMutation.hint.noForkPrompts': '暂无可用的已持久化用户提示词。发送消息后请重试 /fork。',
   'sessionMutation.confirm.fork.title': '确认创建分支',

+ 4 - 1
packages/tui/src/tui/shell/regular-feature-presenter.ts

@@ -89,7 +89,10 @@ class TuiRegularFeatureViewport implements Component {
   render(width: number): string[] {
     if (this.screen.renderViewport && !getLayoutNode(this.screen.layoutRoot)) {
       this.layout = undefined;
-      return [...this.screen.renderViewport(width, Math.max(1, this.terminal.rows))];
+      const height = Math.max(1, this.terminal.rows);
+      const lines = this.screen.renderViewport(width, height);
+      // Feature screens own the viewport even when their content is short.
+      return Array.from({ length: height }, (_, index) => lines[index] ?? '');
     }
     this.layout = renderLayoutFrame(
       this.screen.layoutRoot,

+ 46 - 0
packages/tui/test/unit/tui-app.test.ts

@@ -7980,6 +7980,49 @@ describe("createTuiApp", () => {
     await app.stop();
   });
 
+  it.each(['/rewind', '/fork'])(
+    'clears the loading hint after %s history loads and stays clear after cancellation',
+    async (command) => {
+      const terminal = new FakeTerminal();
+      const runtime = createRuntime();
+      let resolveHistory!: (
+        value: Awaited<ReturnType<TuiRuntime['listSessionInputSummaries']>>,
+      ) => void;
+      vi.mocked(runtime.listSessionInputSummaries).mockImplementation(
+        () =>
+          new Promise((resolve) => {
+            resolveHistory = resolve;
+          }),
+      );
+      const app = createTuiApp({ runtime, terminal, version: '0.1.0', workspaceDir: '/workspace' });
+      app.start();
+      try {
+        await app.ready;
+        await app.submit('Seed session');
+        await app.submit(command);
+        const loadingChat = stripAnsi(app.tui.render(120).join('\n'));
+        expect(loadingChat).toMatch(/Loading|Finding/);
+        resolveHistory([{ userMessageId: 'history-user', timestamp: 1, fileChangeCount: 0 }]);
+        await vi.waitFor(() =>
+          expect(app.surfaceHost.getActiveSurface()).toEqual({
+            kind: 'feature',
+            id: 'session-mutation:history',
+          }),
+        );
+        expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
+          /Loading (?:rewind|fork) history|Finding messages/,
+        );
+        terminal.input?.('\x1b');
+        expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+        expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
+          /Loading (?:rewind|fork) history|Finding messages/,
+        );
+      } finally {
+        await app.stop();
+      }
+    },
+  );
+
   it("cancels /rewind preview and ignores duplicate scope submission", async () => {
     const terminal = new FakeTerminal();
     const runtime = createRuntime();
@@ -8065,6 +8108,9 @@ describe("createTuiApp", () => {
       id: "session-mutation:rewind-confirm",
     });
     resolveRewind({ rewound: true });
+    await vi.waitFor(() => expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' }));
+    expect(stripAnsi(app.tui.render(120).join('\n'))).toContain('Rewound 1 turn');
+    expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(/Loading rewind history|Finding messages/);
     await app.stop();
   });
 

+ 95 - 0
packages/tui/test/unit/tui-background-work-panel.test.ts

@@ -4,6 +4,8 @@ import { describe, expect, it, vi } from "vitest";
 import { TuiBackgroundWorkPanel } from "../../src/tui/background-work/panel.js";
 import type { TuiBackgroundTask } from "../../src/runtime/port.js";
 import type { TuiAgentTeamSnapshot } from "../../src/tui/agent-team/model.js";
+import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
+import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
 import { TuiAltScreen } from "../../src/tui/engine/tui-alt-screen.js";
 import { VirtualTerminal } from "../pi-084-upstream/virtual-terminal.js";
 import { visibleWidth } from "../../src/tui/rendering/text.js";
@@ -332,3 +334,96 @@ describe("TuiBackgroundWorkPanel", () => {
     );
   });
 });
+
+describe('Tasks in the regular terminal viewport', () => {
+  it.each([1, 8, 15])(
+    'keeps tasks reachable after shrinking by %i rows without leaking duplicate tasks into scrollback',
+    async (shrinkRows) => {
+      const terminal = new VirtualTerminal(80, 16);
+      const tui = new TuiMainScreen(terminal);
+      const chatLines = Array.from({ length: 40 }, (_, index) => `chat-line-${index}`);
+      tui.addChild({ render: () => [...chatLines, 'COMPOSER', 'STATUS'], invalidate() {} });
+      const tasks = Array.from({ length: 30 }, (_, index) => ({
+        ...backgroundTasks()[0]!,
+        taskId: `task-${index}`,
+        description: `task-row-${String(index).padStart(2, '0')}`,
+      }));
+      const panel = new TuiBackgroundWorkPanel({
+        agentTeam: () => ({ ...teamSnapshot(), members: [] }),
+        backgroundTasks: () => tasks,
+        activeSessionId: () => 'root',
+        onOpenAgent: vi.fn(),
+        onCancel: vi.fn(),
+        requestRender: () => tui.requestRender(),
+      });
+      tui.start();
+      try {
+        await terminal.waitForRender();
+        chatLines.splice(-shrinkRows);
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(
+          [...chatLines, 'COMPOSER', 'STATUS'].slice(-terminal.rows),
+        );
+        const presenter = new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
+          tui.requestRender(),
+        );
+        let handle = presenter.show(panel, panel);
+        tui.setFocus(handle.focus);
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport().join('\n')).toContain('Tasks');
+        expect(terminal.getViewport().join('\n')).toContain('task-row-00');
+        handle.close();
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(
+          [...chatLines, 'COMPOSER', 'STATUS'].slice(-terminal.rows),
+        );
+        expect(terminal.getScrollBuffer()).toEqual([...chatLines, 'COMPOSER', 'STATUS']);
+        handle = presenter.show(panel, panel);
+        tui.setFocus(handle.focus);
+        tui.renderNow();
+        await terminal.flush();
+        const seen = new Set<string>();
+        for (let index = 0; index < 30; index++) {
+          chatLines.push(`live-chat-${index}`);
+          tui.renderNow();
+          await terminal.flush();
+          const viewport = terminal.getViewport().join('\n');
+          for (const match of viewport.matchAll(/task-row-\d+/g)) seen.add(match[0]);
+          expect(viewport).toContain(`task-row-${String(index).padStart(2, '0')}`);
+          expect(terminal.getScrollBuffer().slice(0, -terminal.rows).join('\n')).not.toContain(
+            'task-row-',
+          );
+          terminal.sendInput('\u001B[B');
+        }
+        expect(seen.size).toBe(30);
+        terminal.sendInput('\u001B[6~');
+        tui.renderNow();
+        await terminal.flush();
+        terminal.sendInput('\u001B[5~');
+        tui.renderNow();
+        await terminal.flush();
+        terminal.resize(60, 12);
+        await terminal.waitForRender();
+        terminal.sendInput('\u001B[B');
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport().join('\n')).toContain('Tasks');
+        handle.close();
+        tui.renderNow();
+        await terminal.flush();
+        await vi.waitFor(async () => {
+          await terminal.flush();
+          expect(terminal.getScrollBuffer().join('\n')).not.toContain('task-row-');
+        });
+        for (const line of chatLines)
+          expect(terminal.getScrollBuffer().filter((row) => row === line)).toHaveLength(1);
+        expect(terminal.getViewport().join('\n')).toContain('STATUS');
+      } finally {
+        tui.stop();
+      }
+    },
+  );
+});

+ 47 - 7
packages/tui/test/unit/tui-engine-local-deltas.test.ts

@@ -56,7 +56,7 @@ describe('MCode Pi Engine local deltas', () => {
     }
   });
 
-  it('preserves native scrollback when transient rows shrink above the viewport', async () => {
+  it('rebuilds when a transient collapse changes rows already in scrollback', async () => {
     const terminal = new RecordingVirtualTerminal(40, 5);
     const tui = new TuiMainScreen(terminal);
     const component = new MutableLines();
@@ -81,9 +81,9 @@ describe('MCode Pi Engine local deltas', () => {
 
     const writes = terminal.takeWrites();
     expect(writes).toContain('\x1b[2J\x1b[H');
-    expect(writes).not.toContain('\x1b[3J');
-    expect(terminal.getScrollBuffer()).toContain('activity-1');
-    expect(terminal.getViewport()).toEqual(['composer', '', '', '', '']);
+    expect(writes).toContain('\x1b[3J');
+    expect(terminal.getScrollBuffer()).not.toContain('activity-1');
+    expect(terminal.getViewport()).toEqual(['header', 'status', 'composer', '', '']);
     expect(terminal.getScrollBuffer().filter((line) => line === 'header')).toHaveLength(1);
     expect(tui.fullRedraws).toBe(2);
   });
@@ -99,17 +99,20 @@ describe('MCode Pi Engine local deltas', () => {
     await terminal.flush();
 
     // Settle the activity row, then repaint a historical line (for example Markdown styling).
+    terminal.takeWrites();
     component.lines = [...answer, `composer${CURSOR_MARKER}`, 'status'];
+    component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
     tui.renderNow();
     await terminal.flush();
-    terminal.takeWrites();
+    expect(terminal.takeWrites()).toContain('\x1b[3J');
     component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
     tui.renderNow();
     await terminal.flush();
 
     expect(terminal.takeWrites()).not.toContain('\x1b[3J');
-    expect(terminal.getScrollBuffer()).toEqual([...answer, 'composer', 'status', '']);
-    expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 41 });
+    expect(terminal.getScrollBuffer()).toEqual([...answer, 'composer', 'status']);
+    expect(terminal.getViewport().at(-1)).toBe('status');
+    expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 42 });
 
     // A later burst must continue from the same logical/physical boundary.
     component.lines.splice(80, 0, ...Array.from({ length: 50 }, (_, index) => `More ${index}`));
@@ -123,6 +126,43 @@ describe('MCode Pi Engine local deltas', () => {
     ]);
   });
 
+  it.each([1, 8, 30])(
+    'keeps the composer and status at the bottom as %i running rows settle and new output grows',
+    async (activityRows) => {
+      const terminal = new RecordingVirtualTerminal(60, 44);
+      const tui = new TuiMainScreen(terminal);
+      const component = new MutableLines();
+      const answer = Array.from({ length: 80 }, (_, index) => `Answer ${index}`);
+      component.lines = [
+        ...answer,
+        ...Array.from({ length: activityRows }, (_, index) => `Activity ${index}`),
+        `composer${CURSOR_MARKER}`,
+        'running',
+      ];
+      tui.addChild(component);
+      tui.renderNow();
+      await terminal.flush();
+      terminal.takeWrites();
+
+      component.lines = [...answer, `composer${CURSOR_MARKER}`, 'idle'];
+      for (let added = 0; added <= activityRows + 1; added++) {
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(
+          component.lines.slice(-terminal.rows).map((line) => line.replace(CURSOR_MARKER, '')),
+        );
+        expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 42 });
+        if (added === 0) expect(terminal.takeWrites()).toContain('\x1b[3J');
+        else expect(terminal.takeWrites()).not.toContain('\x1b[3J');
+        expect(terminal.getScrollBuffer()).toEqual(
+          component.lines.map((line) => line.replace(CURSOR_MARKER, '')),
+        );
+        if (added <= activityRows) component.lines.splice(-2, 0, `New answer ${added}`);
+      }
+      expect(terminal.getScrollBuffer()).not.toContain('');
+    },
+  );
+
   it('keeps every appended row when a historical row changes in the same frame', async () => {
     const terminal = new RecordingVirtualTerminal(67, 44);
     const tui = new TuiMainScreen(terminal);

+ 289 - 0
packages/tui/test/unit/tui-feature-viewport-contract.test.ts

@@ -0,0 +1,289 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { TuiSessionInputSummary } from '../../src/runtime/port.js';
+import { TuiAgentTeamPanel } from '../../src/tui/agent-team/panel.js';
+import type { TuiAgentTeamSnapshot } from '../../src/tui/agent-team/model.js';
+import { TuiBackgroundWorkPanel } from '../../src/tui/background-work/panel.js';
+import { TuiSessionMutationForkConfirmation } from '../../src/tui/controller/product/session-mutation-flow.js';
+import { TuiAltScreen } from '../../src/tui/engine/tui-alt-screen.js';
+import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
+import { TuiPluginManager } from '../../src/tui/features/plugin/manager.js';
+import { TuiSessionHistoryExplorer } from '../../src/tui/features/session-mutation/history-explorer.js';
+import { TuiSessionMutationHistoryPicker } from '../../src/tui/features/session-mutation/history-picker.js';
+import { TuiSessionMutationRewindPreviewPanel } from '../../src/tui/features/session-mutation/rewind-preview-panel.js';
+import { TuiSessionMutationScopePicker } from '../../src/tui/features/session-mutation/scope-picker.js';
+import { TuiTranscriptPanel } from '../../src/tui/features/transcript/panel.js';
+import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
+import { TuiSurfaceHost, type TuiFeatureScreen } from '../../src/tui/shell/surface-host.js';
+import { createTranscriptCell } from '../../src/tui/transcript/model.js';
+import { TranscriptStore } from '../../src/tui/transcript/store.js';
+import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
+
+type Factory = (count: number, onCancel: () => void, requestRender: () => void) => TuiFeatureScreen;
+const summaries = (count: number): TuiSessionInputSummary[] =>
+  Array.from({ length: count }, (_, index) => ({
+    userMessageId: `input-${index}`,
+    contentHead: `Prompt ${index}`,
+    timestamp: index + 1,
+    fileChangeCount: 0,
+  }));
+const team = (count: number): TuiAgentTeamSnapshot => ({
+  rootSessionId: 'root',
+  capturedAtMs: 1,
+  summary: { total: count, running: count, waiting: 0, queued: 0, done: 0, failed: 0, stopped: 0 },
+  members: Array.from({ length: count }, (_, index) => ({
+    sessionId: `agent-${index}`,
+    parentSessionId: 'root',
+    agentName: `Agent ${index}`,
+    task: 'Inspect rendering',
+    status: 'running',
+    phase: 'tool',
+    activity: 'Reading',
+    toolCount: 1,
+    startedAtMs: 1,
+    updatedAtMs: 1,
+  })),
+});
+const factories: Record<string, Factory> = {
+  tasks: (count, onCancel, requestRender) =>
+    new TuiBackgroundWorkPanel({
+      agentTeam: () => team(count),
+      backgroundTasks: () => [],
+      activeSessionId: () => 'root',
+      onOpenAgent: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  agents: (count, onCancel, requestRender) =>
+    new TuiAgentTeamPanel({
+      snapshot: () => team(count),
+      activeSessionId: () => 'root',
+      onSelect: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  plugins: (count, onCancel, requestRender) => {
+    const plugins = Array.from({ length: count }, (_, index) => ({
+      pluginId: `plugin-${index}`,
+      name: `Plugin ${index}`,
+      displayName: `Plugin ${index}`,
+      marketplace: 'official' as const,
+      installed: false,
+      enabled: false,
+      capabilities: { appCount: 0, mcpServerCount: 0, skillCount: 1 },
+    }));
+    return new TuiPluginManager({
+      plugins,
+      onInstall: async (plugin) => plugin,
+      onRemove: async (plugin) => plugin,
+      onSetEnabled: async (plugin) => plugin,
+      onRefresh: async () => plugins,
+      onCancel,
+      requestRender,
+    });
+  },
+  transcript: (count, onCancel, requestRender) =>
+    new TuiTranscriptPanel({
+      source: new TranscriptStore(
+        Array.from({ length: count }, (_, index) =>
+          createTranscriptCell({
+            id: `cell-${index}`,
+            turnId: `turn-${index}`,
+            kind: 'user',
+            status: 'succeeded',
+            content: `Inspect message ${index}`,
+            createdAtMs: index + 1,
+          }),
+        ),
+      ),
+      onCancel,
+      requestRender,
+    }),
+  history: (count, onCancel, requestRender) =>
+    new TuiSessionHistoryExplorer({
+      summaries: summaries(count),
+      mutationAvailable: true,
+      onAction: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  'history-picker': (count, onCancel, requestRender) =>
+    new TuiSessionMutationHistoryPicker({
+      summaries: summaries(count),
+      mode: 'rewind',
+      onSelect: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  'rewind-preview': (count, onCancel, requestRender) =>
+    new TuiSessionMutationRewindPreviewPanel({
+      preview: {
+        turns: [
+          {
+            turnId: 'turn',
+            files: Array.from({ length: count }, (_, index) => ({
+              filePath: `src/file-${index}.ts`,
+              action: 'modified' as const,
+              skipped: false,
+            })),
+          },
+        ],
+      },
+      onContinue: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  'rewind-scope': (_count, onCancel, requestRender) =>
+    new TuiSessionMutationScopePicker({
+      onSelect: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+  'fork-confirmation': (_count, onCancel, requestRender) =>
+    new TuiSessionMutationForkConfirmation({
+      summary: summaries(1)[0]!,
+      options: { canFork: true, worktreeEligible: false, worktreeVisible: false },
+      onConfirm: vi.fn(),
+      onCancel,
+      requestRender,
+    }),
+};
+
+describe.each(Object.entries(factories))('%s regular viewport lifecycle', (_name, factory) => {
+  it.each([
+    ...[0, 1, 30].flatMap((count) => [8, 24, 50].map((rows) => ({ count, rows, chatCount: 80 }))),
+    ...[0, 4].map((chatCount) => ({ count: 1, rows: 24, chatCount })),
+  ])(
+    'isolates $count entries over $chatCount chat rows at $rows rows through updates, resize, nesting and return',
+    async ({ count, rows, chatCount }) => {
+      const terminal = new VirtualTerminal(80, rows);
+      const tui = new TuiMainScreen(terminal);
+      const messages = Array.from({ length: chatCount }, (_, index) => `BACKGROUND-${index}`);
+      const chat = () => [...messages, 'COMPOSER', 'STATUS'];
+      const chatComponent = { render: chat, invalidate() {} };
+      const host = new TuiSurfaceHost({
+        chat: { component: chatComponent, focus: chatComponent },
+        chatMode: 'regular',
+        viewportRows: () => terminal.rows,
+        regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
+          tui.requestRender(),
+        ),
+        setFocus: (focus) => tui.setFocus(focus),
+        requestRender: () => tui.requestRender(),
+      });
+      tui.addChild(host);
+      const assertCovered = async () => {
+        tui.renderNow();
+        await terminal.flush();
+        const viewport = terminal.getViewport().join('\n');
+        expect(viewport.trim()).not.toBe('');
+        expect(viewport).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
+      };
+      tui.start();
+      try {
+        await terminal.waitForRender();
+        const handle = host.pushFeature({
+          screen: factory(
+            count,
+            () => handle.close(),
+            () => tui.requestRender(),
+          ),
+        });
+        await assertCovered();
+        messages.push('BACKGROUND-live');
+        await assertCovered();
+        messages.splice(-12);
+        await assertCovered();
+        for (const key of ['\x1b[B', '\x1b[6~', '\x1b[5~']) {
+          terminal.sendInput(key);
+          await assertCovered();
+        }
+        terminal.resize(40, rows === 8 ? 24 : 8);
+        await assertCovered();
+        terminal.resize(80, rows);
+        await assertCovered();
+        const nestedFactory =
+          _name === 'rewind-preview' ? factories['rewind-scope']! : factories['rewind-preview']!;
+        const nested = host.pushFeature({
+          screen: nestedFactory(
+            0,
+            () => nested.close(),
+            () => tui.requestRender(),
+          ),
+        });
+        await assertCovered();
+        terminal.sendInput('\x1b');
+        await assertCovered();
+        expect(handle.isActive()).toBe(true);
+        // Some panels first clear a search/filter on Esc; close their surface handle here.
+        handle.close();
+        tui.renderNow();
+        await vi.waitFor(async () => {
+          await terminal.flush();
+          const expected = [...chat(), ...Array(Math.max(0, rows - chat().length)).fill('')];
+          expect(terminal.getViewport()).toEqual(expected.slice(-rows));
+          expect(terminal.getScrollBuffer()).toEqual(expected);
+        });
+      } finally {
+        host.dispose();
+        tui.stop();
+      }
+    },
+  );
+});
+
+describe.each(Object.entries(factories))('%s fullscreen viewport lifecycle', (_name, factory) => {
+  it.each([
+    { rows: 8, count: 0 },
+    { rows: 24, count: 1 },
+    { rows: 50, count: 30 },
+  ])(
+    'isolates $count entries at $rows rows and restores the chat layout',
+    async ({ rows, count }) => {
+      const terminal = new VirtualTerminal(80, rows);
+      const tui = new TuiAltScreen(terminal);
+      const component = {
+        render: () => ['BACKGROUND-chat', 'COMPOSER', 'STATUS'],
+        invalidate() {},
+      };
+      const host = new TuiSurfaceHost({
+        chat: { component, focus: component },
+        chatMode: 'fullscreen',
+        viewportRows: () => terminal.rows,
+        regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
+          tui.requestRender(),
+        ),
+        setFocus: (focus) => tui.setFocus(focus),
+        requestRender: () => tui.requestRender(),
+      });
+      tui.setLayoutRoot(host);
+      tui.start();
+      try {
+        await terminal.waitForRender();
+        const original = terminal.getViewport();
+        const handle = host.pushFeature({
+          screen: factory(
+            count,
+            () => handle.close(),
+            () => tui.requestRender(),
+          ),
+        });
+        for (const width of [80, 24, 80]) {
+          terminal.resize(width, rows);
+          terminal.sendInput('\x1b[B');
+          terminal.sendInput('\x1b[6~');
+          tui.renderNow();
+          await terminal.flush();
+          expect(terminal.getViewport().join('\n').trim()).not.toBe('');
+          expect(terminal.getViewport().join('\n')).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
+        }
+        handle.close();
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(original);
+      } finally {
+        host.dispose();
+        tui.stop();
+      }
+    },
+  );
+});

+ 274 - 0
packages/tui/test/unit/tui-session-history-flow.test.ts

@@ -0,0 +1,274 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
+import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
+import { TuiSurfaceHost, type TuiFeatureScreen } from '../../src/tui/shell/surface-host.js';
+import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
+
+import type { TuiSessionInputSummary } from '../../src/runtime/port.js';
+import { TuiSessionMutationFlow } from '../../src/tui/controller/product/session-mutation-flow.js';
+import { stripAnsi } from '../../src/tui/rendering/text.js';
+
+const SESSION_ID = 'session-history';
+const SUMMARY: TuiSessionInputSummary = {
+  userMessageId: 'user-history-1',
+  assistantMessageId: 'assistant-history-1',
+  contentHead: 'Change the historical input',
+  timestamp: 1_700_000_000_000,
+  fileChangeCount: 1,
+};
+
+function createHarness(realHost?: TuiSurfaceHost) {
+  const listSessionInputSummaries = vi.fn(async () => [SUMMARY]);
+  const getSessionRewindPreview = vi.fn(async () => ({
+    turns: [
+      {
+        turnId: 'turn-history-1',
+        files: [{ filePath: 'src/history.ts', action: 'modified' as const, skipped: false }],
+      },
+    ],
+  }));
+  const rewindSession = vi.fn(async () => ({ rewound: true }));
+  const listMessagePage = vi.fn(async () => ({
+    messages: [
+      {
+        id: SUMMARY.userMessageId,
+        role: 'user' as const,
+        content: 'Full historical input',
+        timestamp: SUMMARY.timestamp,
+      },
+    ],
+    hasMore: false,
+  }));
+  const editSessionMessage = vi.fn();
+  const pushedScreens: Array<TuiFeatureScreen & {
+    id: string;
+    handleInput(data: string): void;
+    render(width: number): string[];
+  }> = [];
+  const closeHandles: Array<ReturnType<typeof vi.fn>> = [];
+  const surfaceHost = {
+    pushFeature: vi.fn(
+      ({
+        screen,
+      }: {
+        screen: TuiFeatureScreen & { handleInput(data: string): void };
+      }) => {
+        pushedScreens.push(screen);
+        const realHandle = realHost?.pushFeature({ screen });
+        const close = vi.fn(() => realHandle?.close() ?? true);
+        closeHandles.push(close);
+        return { id: screen.id, close, isActive: () => true };
+      },
+    ),
+    setChatFocus: vi.fn(),
+  };
+  const editor = { setText: vi.fn() };
+  const refreshProjection = vi.fn(async () => undefined);
+  const reloadSessionProjection = vi.fn(async () => undefined);
+  const setEditTranscriptBoundary = vi.fn();
+  const flow = new TuiSessionMutationFlow({
+    runtime: {
+      listSessionInputSummaries,
+      getSessionRewindPreview,
+      rewindSession,
+      listMessagePage,
+      editSessionMessage,
+    } as never,
+    controller: {
+      snapshot: () => ({
+        session: { sessionId: SESSION_ID, title: 'History test' },
+        sessions: [],
+      }),
+    } as never,
+    sessionFlow: { activateSessionById: vi.fn() } as never,
+    refreshProjection,
+    reloadSessionProjection,
+    surfaceHost: surfaceHost as never,
+    editor: editor as never,
+    setHint: vi.fn(),
+    append: vi.fn(),
+    setEditTranscriptBoundary,
+    onChanged: vi.fn(),
+    hasLiveRun: () => false,
+  });
+  return {
+    flow,
+    listSessionInputSummaries,
+    getSessionRewindPreview,
+    rewindSession,
+    listMessagePage,
+    editSessionMessage,
+    pushedScreens,
+    closeHandles,
+    surfaceHost,
+    editor,
+    refreshProjection,
+    reloadSessionProjection,
+    setEditTranscriptBoundary,
+  };
+}
+
+describe('TuiSessionMutationFlow history explorer', () => {
+  it.each([8, 24, 50])(
+    'restores chat after cancelling the real rewind confirmation at %i rows',
+    async (rows) => {
+      const terminal = new VirtualTerminal(80, rows);
+      const tui = new TuiMainScreen(terminal);
+      const chat = [
+        ...Array.from({ length: 80 }, (_, index) => `BACKGROUND-${index}`),
+        'COMPOSER',
+        'STATUS',
+      ];
+      const component = { render: () => chat, invalidate() {} };
+      const host = new TuiSurfaceHost({
+        chat: { component, focus: component },
+        chatMode: 'regular',
+        viewportRows: () => terminal.rows,
+        regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
+          tui.requestRender(),
+        ),
+        setFocus: (focus) => tui.setFocus(focus),
+        requestRender: () => tui.requestRender(),
+      });
+      const harness = createHarness(host);
+      tui.addChild(host);
+      tui.start();
+      try {
+        await terminal.waitForRender();
+        harness.flow.startHistory();
+        await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
+        // Choose conversation-only rewind through the actual history action menu.
+        for (const key of ['\r', '\x1b[B', '\x1b[B', '\r']) terminal.sendInput(key);
+        await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
+        tui.renderNow();
+        await terminal.flush();
+        expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-confirm');
+        expect(terminal.getViewport().join('\n')).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
+        terminal.sendInput('\x1b');
+        tui.renderNow();
+        await terminal.flush();
+        expect(host.getActiveSurface()).toEqual({
+          kind: 'feature',
+          id: 'session-history:explorer',
+        });
+        terminal.sendInput('\x1b');
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(chat.slice(-rows));
+        expect(terminal.getScrollBuffer()).toEqual(chat);
+        expect(harness.rewindSession).not.toHaveBeenCalled();
+      } finally {
+        host.dispose();
+        tui.stop();
+      }
+    },
+  );
+
+  it('confirms a conversation-only rewind without an irrelevant file preview', async () => {
+    const harness = createHarness();
+
+    harness.flow.startHistory();
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
+    expect(harness.pushedScreens[0]?.id).toBe('session-history:explorer');
+
+    harness.pushedScreens[0]?.handleInput('\r');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\r');
+
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
+    expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-confirm');
+    expect(harness.getSessionRewindPreview).not.toHaveBeenCalled();
+    expect(harness.rewindSession).not.toHaveBeenCalled();
+
+    harness.pushedScreens[1]?.handleInput('\r');
+    await vi.waitFor(() =>
+      expect(harness.rewindSession).toHaveBeenCalledWith({
+        sessionId: SESSION_ID,
+        userMessageId: SUMMARY.userMessageId,
+        clientRequestId: expect.stringMatching(/^tui-rewind_/u),
+      }),
+    );
+    await vi.waitFor(() =>
+      expect(harness.reloadSessionProjection).toHaveBeenCalledWith(SESSION_ID),
+    );
+    expect(harness.refreshProjection).not.toHaveBeenCalled();
+    expect(harness.flow.getInvocationCountForTesting()).toBe(0);
+  });
+
+  it('restores the history explorer after cancelling a conversation-only rewind', async () => {
+    const harness = createHarness();
+
+    harness.flow.startHistory();
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
+    const explorer = harness.pushedScreens[0];
+    explorer?.handleInput('\r');
+    explorer?.handleInput('\u001b[B');
+    explorer?.handleInput('\u001b[B');
+    explorer?.handleInput('\r');
+
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
+    harness.pushedScreens[1]?.handleInput('\u001b');
+
+    expect(harness.flow.getInvocationCountForTesting()).toBe(0);
+    expect(stripAnsi(explorer?.render(100).join('\n') ?? '')).toContain('Search:');
+    explorer?.handleInput('\r');
+    expect(stripAnsi(explorer?.render(100).join('\n') ?? '')).toContain('Choose history action');
+  });
+
+  it('previews a historical edit before loading it into the composer', async () => {
+    const harness = createHarness();
+
+    harness.flow.startHistory();
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
+    harness.pushedScreens[0]?.handleInput('\r');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\r');
+
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
+    expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-preview');
+    expect(harness.listMessagePage).not.toHaveBeenCalled();
+    expect(harness.editor.setText).not.toHaveBeenCalled();
+
+    harness.pushedScreens[1]?.handleInput('\r');
+    await vi.waitFor(() =>
+      expect(harness.listMessagePage).toHaveBeenCalledWith(SESSION_ID, {
+        limit: 100,
+      }),
+    );
+    await vi.waitFor(() =>
+      expect(harness.editor.setText).toHaveBeenCalledWith('Full historical input'),
+    );
+    expect(harness.setEditTranscriptBoundary).toHaveBeenCalledWith(SUMMARY.userMessageId);
+    expect(harness.surfaceHost.setChatFocus).toHaveBeenCalled();
+    expect(harness.editSessionMessage).not.toHaveBeenCalled();
+  });
+
+  it('uses the file preview as the final confirmation for a file rewind', async () => {
+    const harness = createHarness();
+
+    harness.flow.startHistory();
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
+    harness.pushedScreens[0]?.handleInput('\r');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\u001b[B');
+    harness.pushedScreens[0]?.handleInput('\r');
+
+    await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
+    expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-preview');
+    expect(harness.rewindSession).not.toHaveBeenCalled();
+
+    harness.pushedScreens[1]?.handleInput('\r');
+    await vi.waitFor(() =>
+      expect(harness.rewindSession).toHaveBeenCalledWith({
+        sessionId: SESSION_ID,
+        userMessageId: SUMMARY.userMessageId,
+        clientRequestId: expect.stringMatching(/^tui-rewind_/u),
+        rewindTurnDiff: true,
+      }),
+    );
+    expect(harness.pushedScreens).toHaveLength(2);
+  });
+});

+ 458 - 0
packages/tui/test/unit/tui-session-mutation-panels.test.ts

@@ -0,0 +1,458 @@
+import { describe, expect, it, vi } from 'vitest';
+import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
+import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
+import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
+
+import { TuiSessionMutationHistoryPicker } from '../../src/tui/features/session-mutation/history-picker.js';
+import { TuiSessionMutationRewindPreviewPanel } from '../../src/tui/features/session-mutation/rewind-preview-panel.js';
+import { TuiSessionMutationScopePicker } from '../../src/tui/features/session-mutation/scope-picker.js';
+import {
+  formatPromptHead,
+  formatRelativeTimestamp,
+  formatSessionInputSummaryLabel,
+} from '../../src/tui/features/session-mutation/format.js';
+import {
+  sessionHistoryText,
+  sessionMutationTemplate,
+  sessionMutationText,
+} from '../../src/tui/features/session-mutation/copy.js';
+import { stripAnsi } from '../../src/tui/rendering/text.js';
+import type {
+  TuiRewindPreview,
+  TuiSessionInputSummary,
+  TuiRewindScope,
+} from '../../src/runtime/port.js';
+
+const NOW_MS = 1_700_000_000_000;
+
+function makeSummary(overrides: Partial<TuiSessionInputSummary> = {}): TuiSessionInputSummary {
+  return {
+    userMessageId: 'msg-user-1',
+    assistantMessageId: 'msg-assistant-1',
+    contentHead: 'Investigate flaky login tests and capture the failure trace',
+    timestamp: NOW_MS - 5 * 60_000,
+    fileChangeCount: 2,
+    ...overrides,
+  };
+}
+
+describe('formatSessionInputSummaryLabel', () => {
+  it('formats a concise label with assistant-boundary, files, and relative time', () => {
+    const label = formatSessionInputSummaryLabel(
+      {
+        userMessageId: 'msg-user-1',
+        assistantMessageId: 'msg-assistant-1',
+        contentHead: 'Investigate flaky login tests and capture the failure trace',
+        timestamp: NOW_MS - 5 * 60_000,
+        fileChangeCount: 2,
+      },
+      { nowMs: NOW_MS },
+    );
+
+    expect(label.title).toContain('Investigate flaky login tests');
+    expect(label.title).toMatch(/\u2026$/u);
+    expect(label.subtitle).toMatch(/2 files/u);
+    expect(label.subtitle).toMatch(/5m/u);
+    expect(label.subtitle).toMatch(/assistant replied/u);
+  });
+
+  it('omits the assistant marker when no assistant message exists', () => {
+    const label = formatSessionInputSummaryLabel(
+      makeSummary({ assistantMessageId: undefined, fileChangeCount: 0 }),
+      { nowMs: NOW_MS },
+    );
+    expect(label.subtitle).not.toMatch(/assistant/u);
+    expect(label.subtitle).toMatch(/0 files/u);
+  });
+
+  it('uses Chinese Session history copy and formatting for a Chinese locale', () => {
+    const label = formatSessionInputSummaryLabel(makeSummary(), {
+      nowMs: NOW_MS,
+      locale: 'zh-CN',
+    });
+
+    expect(label.subtitle).toContain('2 个文件');
+    expect(label.subtitle).toContain('助手已回复');
+    expect(formatRelativeTimestamp(0, NOW_MS, 'zh-CN')).toBe('未知时间');
+    expect(sessionHistoryText('actions', 'zh_CN')).toBe('选择历史操作');
+    expect(sessionMutationText('sessionMutation.confirm.rewind.title', 'zh-Hans')).toBe(
+      '确认回退',
+    );
+    expect(
+      sessionMutationTemplate(
+        'sessionMutation.confirm.fileCounts',
+        { ready: 2, skipped: 1 },
+        'zh-CN',
+      ),
+    ).toBe('2 可回退 · 1 已跳过');
+  });
+});
+
+describe('TuiSessionMutationHistoryPicker', () => {
+  it('renders the picker header and lists every summary newest-first with full id retained', () => {
+    const older = makeSummary({
+      userMessageId: 'msg-user-older',
+      contentHead: 'Older prompt body',
+      timestamp: NOW_MS - 30 * 60_000,
+      fileChangeCount: 1,
+    });
+    const middle = makeSummary({
+      userMessageId: 'msg-user-middle',
+      contentHead: 'Middle prompt body',
+      timestamp: NOW_MS - 10 * 60_000,
+      fileChangeCount: 0,
+    });
+    const latest = makeSummary({
+      userMessageId: 'msg-user-latest',
+      contentHead: 'Latest prompt body',
+      timestamp: NOW_MS - 1 * 60_000,
+      fileChangeCount: 3,
+    });
+    const onSelect = vi.fn();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [older, middle, latest],
+      mode: 'rewind',
+      onSelect,
+      onCancel: vi.fn(),
+      nowMs: NOW_MS,
+    });
+
+    const rendered = stripAnsi(picker.render(80).join('\n'));
+
+    expect(rendered).toMatch(/Rewind to a previous message/);
+    expect(rendered).toContain('Latest prompt body');
+    expect(rendered).toContain('Middle prompt body');
+    expect(rendered).toContain('Older prompt body');
+    expect(rendered).toMatch(/1m/);
+    expect(rendered).toMatch(/3 files/);
+    expect(rendered.indexOf('Latest prompt body')).toBeLessThan(
+      rendered.indexOf('Middle prompt body'),
+    );
+    expect(rendered.indexOf('Middle prompt body')).toBeLessThan(
+      rendered.indexOf('Older prompt body'),
+    );
+    expect(rendered).toMatch(/1 turn affected/);
+    expect(rendered).toMatch(/2 turns affected/);
+    expect(rendered).toMatch(/3 turns affected/);
+
+    // Selection defaults to the latest summary.
+    picker.handleInput('\r');
+    expect(onSelect).toHaveBeenCalledTimes(1);
+    expect(onSelect).toHaveBeenCalledWith(latest);
+  });
+
+  it('does not offer incomplete inputs without an assistant boundary', () => {
+    const complete = makeSummary({ userMessageId: 'msg-user-complete' });
+    const incomplete = makeSummary({
+      userMessageId: 'msg-user-incomplete',
+      assistantMessageId: undefined,
+      contentHead: 'Still running',
+    });
+    const onSelect = vi.fn();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [complete, incomplete],
+      mode: 'fork',
+      onSelect,
+      onCancel: vi.fn(),
+      nowMs: NOW_MS,
+    });
+
+    const rendered = stripAnsi(picker.render(100).join('\n'));
+    expect(rendered).toContain('Investigate flaky login tests');
+    expect(rendered).not.toContain('Still running');
+    expect(rendered).toMatch(/1 incomplete message hidden/);
+
+    picker.handleInput('\r');
+    expect(onSelect).toHaveBeenCalledWith(complete);
+  });
+
+  it('truncates the displayed prompt head but keeps the full summary object on select', () => {
+    const longHead = 'word '.repeat(80).trim();
+    const summary = makeSummary({
+      userMessageId: 'msg-user-long',
+      contentHead: longHead,
+      fileChangeCount: 0,
+    });
+    const onSelect = vi.fn();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [summary],
+      mode: 'fork',
+      onSelect,
+      onCancel: vi.fn(),
+    });
+
+    const rendered = stripAnsi(picker.render(60).join('\n'));
+    expect(rendered).toContain('Fork from a previous message');
+    // Rendered line should not contain the full long head; it should be truncated with ellipsis.
+    expect(rendered).not.toContain(longHead);
+    expect(rendered).toMatch(/\u2026/);
+
+    picker.handleInput('\r');
+    expect(onSelect).toHaveBeenCalledWith(summary);
+  });
+
+  it('does not split an emoji at the prompt-head boundary', () => {
+    const head = `${'a'.repeat(46)}😀z`;
+
+    expect(formatPromptHead(head, 48)).toBe(head);
+    expect(formatPromptHead(`${head}tail`, 48)).not.toContain('\uFFFD');
+  });
+
+  it('renders a safe empty state when there are no summaries', () => {
+    const onSelect = vi.fn();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [],
+      mode: 'rewind',
+      onSelect,
+      onCancel: vi.fn(),
+    });
+
+    const rendered = stripAnsi(picker.render(80).join('\n'));
+    expect(rendered).toMatch(/No previous user messages/i);
+    expect(rendered).toMatch(/Esc cancel/);
+    // No summaries means there is nothing to select, so onSelect must not fire.
+    picker.handleInput('\r');
+    picker.handleInput('\u001b');
+    expect(onSelect).not.toHaveBeenCalled();
+  });
+
+  it('routes Escape to onCancel exactly once and never invokes the mutation callback', () => {
+    const summary = makeSummary();
+    const onSelect = vi.fn();
+    const onCancel = vi.fn();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [summary],
+      mode: 'rewind',
+      onSelect,
+      onCancel,
+    });
+
+    picker.handleInput('\u001b');
+    picker.handleInput('\u001b');
+
+    expect(onCancel).toHaveBeenCalledTimes(1);
+    expect(onSelect).not.toHaveBeenCalled();
+  });
+
+  it('exposes a stable surface id and pads renderViewport to the requested height', () => {
+    const summary = makeSummary();
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [summary],
+      mode: 'fork',
+      onSelect: vi.fn(),
+      onCancel: vi.fn(),
+    });
+
+    expect(picker.id).toBe('session-mutation:history');
+
+    const padded = picker.renderViewport(80, 24);
+    expect(padded.length).toBe(24);
+    expect(padded.some((line) => line.length > 0)).toBe(true);
+
+    const clipped = picker.renderViewport(80, 4);
+    expect(clipped.length).toBe(4);
+    expect(clipped.length).toBeLessThanOrEqual(picker.render(80).length);
+  });
+
+  it('returns an empty viewport for zero width without crashing', () => {
+    const picker = new TuiSessionMutationHistoryPicker({
+      summaries: [makeSummary()],
+      mode: 'fork',
+      onSelect: vi.fn(),
+      onCancel: vi.fn(),
+    });
+
+    expect(picker.renderViewport(0, 10)).toEqual([]);
+  });
+});
+
+describe('TuiSessionMutationRewindPreviewPanel', () => {
+  it.each([8, 24, 50])(
+    'owns the complete regular viewport at %i rows and restores chat on cancel',
+    async (rows) => {
+      const terminal = new VirtualTerminal(80, rows);
+      const tui = new TuiMainScreen(terminal);
+      const messages = Array.from({ length: 80 }, (_, index) => `chat-marker-${index}`);
+      const chat = () => [...messages, 'COMPOSER', 'STATUS'];
+      tui.addChild({ render: chat, invalidate() {} });
+      let close: () => void = () => undefined;
+      const panel = new TuiSessionMutationRewindPreviewPanel({
+        preview: { turns: [] },
+        target: 'Target /example-skill',
+        impact: '1 turn affected · 0 files',
+        onCancel: () => close(),
+        onContinue: vi.fn(),
+        requestRender: () => tui.requestRender(),
+      });
+      tui.start();
+      try {
+        await terminal.waitForRender();
+        const presenter = new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
+          tui.requestRender(),
+        );
+        const handle = presenter.show(panel, panel);
+        close = () => handle.close();
+        tui.setFocus(handle.focus);
+        for (let update = 0; update < 3; update++) {
+          tui.renderNow();
+          await terminal.flush();
+          const viewport = terminal.getViewport().join('\n');
+          expect(viewport).toContain('Rewind preview');
+          expect(viewport).not.toContain('chat-marker-');
+          expect(viewport).not.toContain('COMPOSER');
+          expect(viewport).not.toContain('STATUS');
+          if (update < 2) messages.push(`chat-marker-live-${update}`);
+        }
+        terminal.sendInput('\u001B');
+        tui.renderNow();
+        await terminal.flush();
+        expect(terminal.getViewport()).toEqual(chat().slice(-rows));
+        expect(terminal.getScrollBuffer()).toEqual(chat());
+      } finally {
+        tui.stop();
+      }
+    },
+  );
+
+  it('groups ready vs skipped files and shows modified/created/deleted actions', () => {
+    const preview: TuiRewindPreview = {
+      turns: [
+        {
+          turnId: 'turn-1',
+          files: [
+            { filePath: 'src/a.ts', action: 'modified', skipped: false },
+            { filePath: 'src/b.ts', action: 'created', skipped: false },
+            { filePath: 'src/c.ts', action: 'deleted', skipped: false },
+            { filePath: 'src/skipped.ts', action: 'modified', skipped: true },
+          ],
+        },
+      ],
+    };
+    const onCancel = vi.fn();
+    const panel = new TuiSessionMutationRewindPreviewPanel({
+      preview,
+      onCancel,
+    });
+
+    const rendered = stripAnsi(panel.render(80).join('\n'));
+
+    expect(rendered).toMatch(/Rewind preview/);
+    expect(rendered).toMatch(/Ready to rewind/);
+    expect(rendered).toMatch(/Skipped/);
+    expect(rendered).toContain('src/a.ts');
+    expect(rendered).toContain('src/b.ts');
+    expect(rendered).toContain('src/c.ts');
+    expect(rendered).toContain('src/skipped.ts');
+    expect(rendered).toMatch(/modified/);
+    expect(rendered).toMatch(/created/);
+    expect(rendered).toMatch(/deleted/);
+    expect(rendered).toMatch(/skipped/);
+  });
+
+  it('renders a no-diff message when no ready files remain', () => {
+    const preview: TuiRewindPreview = {
+      turns: [
+        {
+          turnId: 'turn-1',
+          files: [{ filePath: 'src/already-clean.ts', action: 'modified', skipped: true }],
+        },
+      ],
+    };
+    const onCancel = vi.fn();
+    const panel = new TuiSessionMutationRewindPreviewPanel({ preview, onCancel });
+
+    const rendered = stripAnsi(panel.render(80).join('\n'));
+    expect(rendered).toMatch(/no[- ]?diff/i);
+  });
+
+  it('treats repeated Escape presses as a single idempotent close', () => {
+    const panel = new TuiSessionMutationRewindPreviewPanel({
+      preview: { turns: [] },
+      onCancel: vi.fn(),
+    });
+
+    panel.handleInput('\u001b');
+    panel.handleInput('\u001b');
+
+    expect(panel.isClosed()).toBe(true);
+  });
+
+  it('keeps scroll and confirmation controls visible when the file preview overflows', () => {
+    const preview: TuiRewindPreview = {
+      turns: [
+        {
+          turnId: 'turn-many-files',
+          files: Array.from({ length: 20 }, (_, index) => ({
+            filePath: `src/file-${String(index)}.ts`,
+            action: 'modified',
+            skipped: false,
+          })),
+        },
+      ],
+    };
+    const onContinue = vi.fn();
+    const panel = new TuiSessionMutationRewindPreviewPanel({
+      preview,
+      onCancel: vi.fn(),
+      onContinue,
+      continueHint: 'Enter rewind · Esc back',
+      requestRender: vi.fn(),
+    });
+
+    const first = stripAnsi(panel.renderViewport(70, 10).join('\n'));
+    expect(first).toContain('PgUp/PgDn scroll');
+    expect(first).toContain('Enter rewind');
+    expect(first).toContain('Esc back');
+
+    panel.handleInput('\u001b[6~');
+    const scrolled = stripAnsi(panel.renderViewport(70, 10).join('\n'));
+    expect(scrolled).toContain('Enter rewind');
+    expect(scrolled).not.toBe(first);
+    panel.handleInput('\r');
+    expect(onContinue).toHaveBeenCalledOnce();
+  });
+});
+
+describe('TuiSessionMutationScopePicker', () => {
+  it('only exposes the two Desktop-compatible rewind scopes', () => {
+    const onSelect = vi.fn<(scope: TuiRewindScope) => void>();
+    const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel: vi.fn() });
+
+    const rendered = stripAnsi(picker.render(80).join('\n'));
+
+    expect(rendered).toMatch(/Choose what to rewind/);
+    expect(rendered).toContain('Conversation only');
+    expect(rendered).not.toContain('Files only');
+    expect(rendered).toContain('Conversation and files');
+    expect(rendered).not.toMatch(/partial/i);
+
+    const compact = stripAnsi(picker.renderViewport(60, 4).join('\n'));
+    expect(compact).toContain('Enter confirm');
+    expect(compact).toContain('Esc cancel');
+
+    picker.handleInput('\r');
+    expect(onSelect).toHaveBeenCalledWith('conversation');
+  });
+
+  it('returns the selected scope when navigating down then confirming', () => {
+    const onSelect = vi.fn<(scope: TuiRewindScope) => void>();
+    const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel: vi.fn() });
+
+    picker.handleInput('\u001b[B');
+    picker.handleInput('\r');
+
+    expect(onSelect).toHaveBeenCalledWith('conversation_and_files');
+  });
+
+  it('cancels idempotently and never fires onSelect', () => {
+    const onSelect = vi.fn();
+    const onCancel = vi.fn();
+    const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel });
+
+    picker.handleInput('\u001b');
+    picker.handleInput('\u001b');
+
+    expect(onCancel).toHaveBeenCalledTimes(1);
+    expect(onSelect).not.toHaveBeenCalled();
+  });
+});

+ 771 - 0
packages/tui/test/unit/tui-surface-host.test.ts

@@ -0,0 +1,771 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Terminal, TUI } from '../../src/tui/engine/public.js';
+import type { Component } from '../../src/tui/rendering/component.js';
+import {
+  TuiSurfaceHost,
+  type TuiFeatureScreen,
+  type TuiSurfaceHostOptions,
+} from '../../src/tui/shell/surface-host.js';
+import {
+  TuiOverlayRegularFeaturePresenter,
+  type TuiRegularFeaturePresenter,
+} from '../../src/tui/shell/regular-feature-presenter.js';
+import { TuiInteractionSurface } from '../../src/tui/shell/interaction-surface.js';
+import { TuiInlinePanelHost } from '../../src/tui/shell/inline-panel.js';
+import { TuiActivityLine } from '../../src/tui/shell/activity-line.js';
+
+function component(lines: readonly string[]): Component {
+  return {
+    render: () => lines,
+    invalidate: () => undefined,
+  };
+}
+
+function screen(id: string, render: (width: number) => readonly string[]): TuiFeatureScreen {
+  const layoutRoot: Component = { render, invalidate: () => undefined };
+  return {
+    id,
+    layoutRoot,
+    render: (width) => [...render(width)],
+    invalidate: () => undefined,
+  };
+}
+
+function createSurfaceHost(
+  options: Omit<TuiSurfaceHostOptions, 'regularFeaturePresenter'> & {
+    regularFeaturePresenter?: TuiRegularFeaturePresenter;
+  },
+): TuiSurfaceHost {
+  return new TuiSurfaceHost({
+    regularFeaturePresenter: {
+      show: (_screen, focus) => ({ focus, close: () => undefined }),
+    },
+    ...options,
+  });
+}
+
+function createRecordingPresenter(): {
+  presenter: TuiRegularFeaturePresenter;
+  presentations: Array<{
+    id: string;
+    focus: Component;
+    close: ReturnType<typeof vi.fn>;
+  }>;
+} {
+  const presentations: Array<{
+    id: string;
+    focus: Component;
+    close: ReturnType<typeof vi.fn>;
+  }> = [];
+  return {
+    presenter: {
+      show: (feature, focus) => {
+        const presentation = { id: feature.id, focus, close: vi.fn() };
+        presentations.push(presentation);
+        return presentation;
+      },
+    },
+    presentations,
+  };
+}
+
+describe('TuiSurfaceHost', () => {
+  it.each(['regular', 'fullscreen'] as const)(
+    'passes current terminal size to leaf features in %s',
+    (mode) => {
+      const terminal = { rows: 30 } as Terminal;
+      const overlays: Component[] = [];
+      const presenter = new TuiOverlayRegularFeaturePresenter(
+        terminal,
+        {
+          showOverlay: (overlay: Component) => {
+            overlays.push(overlay);
+            return { hide: vi.fn() };
+          },
+        } as unknown as TUI,
+        vi.fn(),
+      );
+      const renderViewport = vi.fn((width: number, height: number) => [`${width}x${height}`]);
+      const host = createSurfaceHost({
+        chat: { component: component(['chat']), focus: component([]) },
+        chatMode: mode,
+        mode: () => mode,
+        viewportRows: () => terminal.rows,
+        regularFeaturePresenter: presenter,
+        setFocus: vi.fn(),
+        requestRender: vi.fn(),
+      });
+      host.pushFeature({ screen: { ...screen('history', () => ['unbounded']), renderViewport } });
+      const render = () => (mode === 'regular' ? overlays[0]!.render(40) : host.render(40));
+      expect(render()).toEqual(
+        mode === 'regular' ? ['40x30', ...Array(29).fill('')] : ['40x30'],
+      );
+      terminal.rows = 8;
+      expect(render()).toEqual(mode === 'regular' ? ['40x8', ...Array(7).fill('')] : ['40x8']);
+      host.dispose();
+    },
+  );
+
+  it('invalidates only the mounted chat root in regular mode', () => {
+    const chatInvalidate = vi.fn();
+    const featureInvalidate = vi.fn();
+    const host = createSurfaceHost({
+      chat: {
+        component: { render: () => ['chat'], invalidate: chatInvalidate },
+        focus: component([]),
+      },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    const handle = host.pushFeature({
+      screen: {
+        ...screen('sessions', () => ['sessions']),
+        invalidate: featureInvalidate,
+      },
+    });
+    expect(chatInvalidate).not.toHaveBeenCalled();
+    expect(featureInvalidate).toHaveBeenCalledOnce();
+    chatInvalidate.mockClear();
+    featureInvalidate.mockClear();
+
+    host.invalidate();
+
+    expect(chatInvalidate).toHaveBeenCalledOnce();
+    expect(featureInvalidate).not.toHaveBeenCalled();
+
+    chatInvalidate.mockClear();
+    expect(handle.close()).toBe(true);
+    expect(chatInvalidate).not.toHaveBeenCalled();
+  });
+
+  it('invalidates only the active fullscreen feature', () => {
+    const chatInvalidate = vi.fn();
+    const firstInvalidate = vi.fn();
+    const secondInvalidate = vi.fn();
+    const host = createSurfaceHost({
+      chat: {
+        component: { render: () => ['chat'], invalidate: chatInvalidate },
+        focus: component([]),
+      },
+      chatMode: 'fullscreen',
+      mode: () => 'fullscreen',
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    host.pushFeature({
+      screen: { ...screen('first', () => ['first']), invalidate: firstInvalidate },
+    });
+    host.pushFeature({
+      screen: { ...screen('second', () => ['second']), invalidate: secondInvalidate },
+    });
+    chatInvalidate.mockClear();
+    firstInvalidate.mockClear();
+    secondInvalidate.mockClear();
+
+    host.invalidate();
+
+    expect(chatInvalidate).not.toHaveBeenCalled();
+    expect(firstInvalidate).not.toHaveBeenCalled();
+    expect(secondInvalidate).toHaveBeenCalledOnce();
+  });
+
+  it('lets a feature screen own invalidation of its Pi layout root', () => {
+    const overlays: Component[] = [];
+    const tui = {
+      showOverlay: vi.fn((overlay: Component) => {
+        overlays.push(overlay);
+        return { hide: vi.fn() };
+      }),
+    } as unknown as TUI;
+    const layoutInvalidate = vi.fn();
+    const screenInvalidate = vi.fn(() => layoutInvalidate());
+    const feature = {
+      id: 'sessions',
+      layoutRoot: { render: () => ['layout'], invalidate: layoutInvalidate },
+      render: () => ['sessions'],
+      invalidate: screenInvalidate,
+    };
+    const presenter = new TuiOverlayRegularFeaturePresenter({ rows: 24 } as Terminal, tui, vi.fn());
+
+    presenter.show(feature, feature);
+    overlays[0]?.invalidate();
+
+    expect(screenInvalidate).toHaveBeenCalledOnce();
+    expect(layoutInvalidate).toHaveBeenCalledOnce();
+  });
+
+  it('stops periodic terminal renders while an interaction owns the viewport', () => {
+    vi.useFakeTimers();
+    try {
+      const requestActivityRender = vi.fn();
+      const activity = new TuiActivityLine(
+        { phase: 'running', runId: 'turn-1' },
+        { requestRender: requestActivityRender },
+      );
+      const host = new TuiInlinePanelHost();
+      const surfaces = createSurfaceHost({
+        chat: { component: component(['chat']), focus: component([]) },
+        setFocus: vi.fn(),
+        requestRender: vi.fn(),
+      });
+      const interaction = new TuiInteractionSurface(host, surfaces, vi.fn(), (active) =>
+        activity.setAnimationPaused(active),
+      );
+      const panel = component(['question']);
+
+      vi.advanceTimersByTime(160);
+      expect(requestActivityRender).toHaveBeenCalledTimes(2);
+
+      interaction.show(panel);
+      requestActivityRender.mockClear();
+      vi.advanceTimersByTime(320);
+      expect(requestActivityRender).not.toHaveBeenCalled();
+
+      interaction.close(panel);
+      vi.advanceTimersByTime(80);
+      expect(requestActivityRender).toHaveBeenCalledOnce();
+
+      activity.dispose();
+    } finally {
+      vi.useRealTimers();
+    }
+  });
+
+  it('keeps the default chat surface inline and persistent', () => {
+    const chat = component(['chat']);
+    const focus = component([]);
+    const host = createSurfaceHost({
+      chat: { component: chat, focus },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(host.render(40)).toEqual(['chat']);
+  });
+
+  it('presents a regular feature over the persistent chat document and restores chat focus on close', () => {
+    const chat = component(['chat']);
+    const chatFocus = component([]);
+    const featureFocus = component([]);
+    const setFocus = vi.fn();
+    const requestRender = vi.fn();
+    const { presenter, presentations } = createRecordingPresenter();
+    const host = createSurfaceHost({
+      chat: { component: chat, focus: chatFocus },
+      regularFeaturePresenter: presenter,
+      setFocus,
+      requestRender,
+    });
+    const feature = screen('sessions', () => ['header', 'body', 'footer']);
+
+    const handle = host.pushFeature({ screen: feature, focus: featureFocus });
+
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'sessions' });
+    expect(host.render(40)).toEqual(['chat']);
+    expect(presentations.map(({ id }) => id)).toEqual(['sessions']);
+    expect(setFocus).toHaveBeenLastCalledWith(featureFocus);
+    expect(requestRender).toHaveBeenLastCalledWith();
+
+    expect(handle.close()).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(host.render(40)).toEqual(['chat']);
+    expect(presentations[0]?.close).toHaveBeenCalledOnce();
+    expect(setFocus).toHaveBeenLastCalledWith(chatFocus);
+    expect(requestRender).toHaveBeenLastCalledWith();
+  });
+
+  it('uses a central stack for nested feature screens', () => {
+    const chatFocus = component([]);
+    const firstFocus = component([]);
+    const secondFocus = component([]);
+    const setFocus = vi.fn();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: chatFocus },
+      setFocus,
+      requestRender: vi.fn(),
+    });
+    const first = host.pushFeature({
+      screen: screen('sessions', () => ['sessions']),
+      focus: firstFocus,
+    });
+    const second = host.pushFeature({
+      screen: screen('session-detail', () => ['detail']),
+      focus: secondFocus,
+    });
+
+    expect(first.close()).toBe(false);
+    expect(second.close()).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'sessions' });
+    expect(setFocus).toHaveBeenLastCalledWith(firstFocus);
+    expect(first.close()).toBe(true);
+    expect(setFocus).toHaveBeenLastCalledWith(chatFocus);
+  });
+
+  it('keeps a regular renderer stable while a feature stack opens and closes', () => {
+    let mode: 'regular' | 'fullscreen' = 'regular';
+    const switchMode = vi.fn((next: typeof mode) => {
+      mode = next;
+      return true;
+    });
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      mode: () => mode,
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+
+    const first = host.pushFeature({ screen: screen('first', () => ['first']) });
+    const second = host.pushFeature({ screen: screen('second', () => ['second']) });
+
+    expect(mode).toBe('regular');
+    expect(switchMode).not.toHaveBeenCalled();
+    second.close();
+    first.close();
+    expect(mode).toBe('regular');
+    expect(switchMode).not.toHaveBeenCalled();
+  });
+
+  it('keeps chat and feature screens fullscreen when fullscreen is the configured chat mode', () => {
+    const switchMode = vi.fn(() => true);
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => 'fullscreen',
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+
+    const feature = host.pushFeature({ screen: screen('sessions', () => ['sessions']) });
+
+    expect(host.getChatMode()).toBe('fullscreen');
+    expect(switchMode).not.toHaveBeenCalled();
+    expect(feature.close()).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(switchMode).not.toHaveBeenCalled();
+  });
+
+  it('switches the visible chat immediately when its configured mode changes', () => {
+    const switchMode = vi.fn(() => true);
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+
+    expect(host.setChatMode('fullscreen')).toBe(true);
+    expect(host.getChatMode()).toBe('fullscreen');
+    expect(switchMode).toHaveBeenCalledOnce();
+    expect(switchMode).toHaveBeenCalledWith('fullscreen');
+  });
+
+  it('changes the renderer immediately while keeping the active feature in the selected mode', () => {
+    let mode: 'regular' | 'fullscreen' = 'fullscreen';
+    const switchMode = vi.fn((next: typeof mode) => {
+      mode = next;
+      return true;
+    });
+    const { presenter, presentations } = createRecordingPresenter();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => mode,
+      regularFeaturePresenter: presenter,
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+    const feature = host.pushFeature({ screen: screen('sessions', () => ['sessions']) });
+
+    expect(host.setChatMode('regular')).toBe(true);
+    expect(host.getChatMode()).toBe('regular');
+    expect(switchMode).toHaveBeenCalledOnce();
+    expect(switchMode).toHaveBeenCalledWith('regular');
+    expect(presentations.map(({ id }) => id)).toEqual(['sessions']);
+
+    expect(feature.close()).toBe(true);
+    expect(switchMode).toHaveBeenCalledOnce();
+    expect(presentations[0]?.close).toHaveBeenCalledOnce();
+  });
+
+  it('rolls back the configured chat mode when Pi refuses the renderer switch', () => {
+    const switchMode = vi.fn(() => false);
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+
+    expect(host.setChatMode('fullscreen')).toBe(false);
+    expect(host.getChatMode()).toBe('regular');
+  });
+
+  it('rolls back the configured chat mode when the renderer switch throws', () => {
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode: () => {
+        throw new Error('terminal restart failed');
+      },
+    });
+
+    expect(() => host.setChatMode('fullscreen')).toThrow('terminal restart failed');
+    expect(host.getChatMode()).toBe('regular');
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+  });
+
+  it('restores fullscreen when a regular feature cannot be presented after a mode change', () => {
+    let mode: 'regular' | 'fullscreen' = 'fullscreen';
+    const switchMode = vi.fn((next: typeof mode) => {
+      mode = next;
+      return true;
+    });
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => mode,
+      regularFeaturePresenter: {
+        show: () => {
+          throw new Error('regular feature presentation failed');
+        },
+      },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+    host.pushFeature({ screen: screen('sessions', () => ['sessions']) });
+
+    expect(() => host.setChatMode('regular')).toThrow('regular feature presentation failed');
+    expect(host.getChatMode()).toBe('fullscreen');
+    expect(mode).toBe('fullscreen');
+    expect(switchMode.mock.calls.map(([next]) => next)).toEqual(['regular', 'fullscreen']);
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'sessions' });
+  });
+
+  it('does not mutate the feature stack when the regular presenter refuses a feature', () => {
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      regularFeaturePresenter: {
+        show: () => {
+          throw new Error('regular feature presentation failed');
+        },
+      },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    const feature = screen('sessions', () => ['sessions']);
+
+    expect(() => host.pushFeature({ screen: feature })).toThrow(
+      'regular feature presentation failed',
+    );
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(host.render(40)).toEqual(['chat']);
+  });
+
+  it('restores a nested feature stack when presenting the previous feature throws on close', () => {
+    let failNextPresentation = false;
+    const presentations: Array<{ id: string; close: ReturnType<typeof vi.fn> }> = [];
+    const presenter: TuiRegularFeaturePresenter = {
+      show: (feature, focus) => {
+        if (failNextPresentation) {
+          failNextPresentation = false;
+          throw new Error('regular feature presentation failed');
+        }
+        const presentation = { id: feature.id, focus, close: vi.fn() };
+        presentations.push(presentation);
+        return presentation;
+      },
+    };
+    const firstDispose = vi.fn();
+    const secondDispose = vi.fn();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      regularFeaturePresenter: presenter,
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+
+    const first = host.pushFeature({
+      screen: { ...screen('first', () => ['first']), dispose: firstDispose },
+    });
+    const second = host.pushFeature({
+      screen: { ...screen('second', () => ['second']), dispose: secondDispose },
+    });
+
+    failNextPresentation = true;
+    expect(() => second.close()).toThrow('regular feature presentation failed');
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'second' });
+    expect(secondDispose).not.toHaveBeenCalled();
+    expect(presentations.at(-1)?.id).toBe('second');
+
+    expect(second.close()).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'first' });
+    expect(secondDispose).toHaveBeenCalledOnce();
+    expect(first.close()).toBe(true);
+    expect(firstDispose).toHaveBeenCalledOnce();
+  });
+
+  it('defers chat focus changes until the feature stack closes', () => {
+    const initialChatFocus = component([]);
+    const pendingDecisionFocus = component([]);
+    const featureFocus = component([]);
+    const setFocus = vi.fn();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: initialChatFocus },
+      setFocus,
+      requestRender: vi.fn(),
+    });
+    const feature = host.pushFeature({
+      screen: screen('sessions', () => ['sessions']),
+      focus: featureFocus,
+    });
+
+    host.setChatFocus(pendingDecisionFocus);
+    expect(setFocus).toHaveBeenCalledTimes(1);
+    expect(setFocus).toHaveBeenLastCalledWith(featureFocus);
+
+    feature.close();
+    expect(setFocus).toHaveBeenLastCalledWith(pendingDecisionFocus);
+  });
+
+  it('restores the highest-priority chat layer around feature navigation', () => {
+    const composer = component([]);
+    const interactionFocus = component([]);
+    const modalFocus = component([]);
+    const featureFocus = component([]);
+    const setFocus = vi.fn();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: composer },
+      setFocus,
+      requestRender: vi.fn(),
+    });
+
+    const interaction = host.pushChatLayer({
+      id: 'interaction',
+      focus: interactionFocus,
+      priority: 100,
+    });
+    const modal = host.pushChatLayer({
+      id: 'modal',
+      focus: modalFocus,
+      priority: 200,
+    });
+    const feature = host.pushFeature({
+      screen: screen('sessions', () => ['sessions']),
+      focus: featureFocus,
+    });
+
+    expect(setFocus).toHaveBeenLastCalledWith(featureFocus);
+    feature.close();
+    expect(setFocus).toHaveBeenLastCalledWith(modalFocus);
+    modal.close();
+    expect(setFocus).toHaveBeenLastCalledWith(interactionFocus);
+    interaction.close();
+    expect(setFocus).toHaveBeenLastCalledWith(composer);
+  });
+
+  it('temporarily lets a blocking chat layer preempt a feature screen', () => {
+    const composer = component([]);
+    const featureFocus = component([]);
+    const decisionFocus = component([]);
+    const setFocus = vi.fn();
+    const switchMode = vi.fn(() => true);
+    const { presenter, presentations } = createRecordingPresenter();
+    const host = createSurfaceHost({
+      chat: { component: component(['chat decision']), focus: composer },
+      regularFeaturePresenter: presenter,
+      setFocus,
+      requestRender: vi.fn(),
+      switchMode,
+    });
+    host.pushFeature({
+      screen: screen('transcript', () => ['transcript inspector']),
+      focus: featureFocus,
+    });
+
+    const decision = host.pushChatLayer({
+      id: 'interaction',
+      focus: decisionFocus,
+      priority: 100,
+      preemptsFeatures: true,
+    });
+
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(host.render(40)[0]).toBe('chat decision');
+    expect(setFocus).toHaveBeenLastCalledWith(decisionFocus);
+    expect(presentations.map(({ id }) => id)).toEqual(['transcript']);
+    expect(presentations[0]?.close).toHaveBeenCalledOnce();
+    expect(switchMode).not.toHaveBeenCalled();
+
+    decision.close();
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'transcript' });
+    expect(host.render(40)[0]).toBe('chat decision');
+    expect(setFocus).toHaveBeenLastCalledWith(featureFocus);
+    expect(presentations.map(({ id }) => id)).toEqual(['transcript', 'transcript']);
+    expect(switchMode).not.toHaveBeenCalled();
+  });
+
+  it('replaces an active interaction without changing the configured fullscreen renderer', () => {
+    let mode: 'regular' | 'fullscreen' = 'fullscreen';
+    const switchMode = vi.fn((next: typeof mode) => {
+      mode = next;
+      return true;
+    });
+    const inline = new TuiInlinePanelHost();
+    const first = component(['first decision']);
+    const second = component(['second decision']);
+    const setFocus = vi.fn();
+    const followFullscreenBottom = vi.fn();
+    const host = createSurfaceHost({
+      chat: { component: inline, focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => mode,
+      setFocus,
+      requestRender: vi.fn(),
+      switchMode,
+    });
+    host.pushFeature({ screen: screen('transcript', () => ['transcript']) });
+    const interaction = new TuiInteractionSurface(
+      inline,
+      host,
+      vi.fn(),
+      undefined,
+      followFullscreenBottom,
+    );
+
+    interaction.show(first);
+    expect(followFullscreenBottom).toHaveBeenCalledOnce();
+    expect(mode).toBe('fullscreen');
+    expect(switchMode).not.toHaveBeenCalled();
+    interaction.show(second);
+    expect(followFullscreenBottom).toHaveBeenCalledTimes(2);
+
+    expect(switchMode).not.toHaveBeenCalled();
+    expect(inline.current()).toBe(second);
+    expect(setFocus).toHaveBeenLastCalledWith(second);
+  });
+
+  it('keeps an interaction mounted when restoring its preempted regular feature throws', () => {
+    let failNextPresentation = false;
+    const inline = new TuiInlinePanelHost();
+    const host = createSurfaceHost({
+      chat: { component: inline, focus: component([]) },
+      regularFeaturePresenter: {
+        show: (_feature, focus) => {
+          if (failNextPresentation) {
+            failNextPresentation = false;
+            throw new Error('feature restore failed');
+          }
+          return { focus, close: () => undefined };
+        },
+      },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    host.pushFeature({ screen: screen('transcript', () => ['transcript']) });
+    const interaction = new TuiInteractionSurface(inline, host, vi.fn());
+    const activePanel = component(['active decision']);
+    interaction.show(activePanel);
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    failNextPresentation = true;
+    expect(() => interaction.close(activePanel)).toThrow('feature restore failed');
+    expect(inline.isActive(activePanel)).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+
+    expect(interaction.close(activePanel)).toBe(true);
+    expect(inline.isActive()).toBe(false);
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'transcript' });
+  });
+
+  it('keeps a blocking chat layer in the configured fullscreen chat mode', () => {
+    const switchMode = vi.fn(() => true);
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => 'fullscreen',
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+      switchMode,
+    });
+    host.pushFeature({ screen: screen('transcript', () => ['transcript']) });
+
+    const interaction = host.pushChatLayer({
+      id: 'interaction',
+      focus: component([]),
+      priority: 100,
+      preemptsFeatures: true,
+    });
+
+    expect(host.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
+    expect(switchMode).not.toHaveBeenCalled();
+    expect(interaction.close()).toBe(true);
+    expect(host.getActiveSurface()).toEqual({ kind: 'feature', id: 'transcript' });
+    expect(switchMode).not.toHaveBeenCalled();
+  });
+
+  it('passes the complete feature document to the Pi layout tree', () => {
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      chatMode: 'fullscreen',
+      mode: () => 'fullscreen',
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    host.pushFeature({
+      screen: screen('diff', () => ['one', 'two', 'three', 'four']),
+      focus: component([]),
+    });
+
+    expect(host.render(40)).toEqual(['one', 'two', 'three', 'four']);
+  });
+
+  it('disposes feature screens and distinct focus owners exactly once', () => {
+    const screenDispose = vi.fn();
+    const focusDispose = vi.fn();
+    const feature = {
+      ...screen('sessions', () => ['sessions']),
+      dispose: screenDispose,
+    };
+    const focus = {
+      ...component([]),
+      dispose: focusDispose,
+    };
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+
+    const handle = host.pushFeature({ screen: feature, focus });
+
+    expect(handle.close()).toBe(true);
+    expect(handle.close()).toBe(false);
+    expect(screenDispose).toHaveBeenCalledOnce();
+    expect(focusDispose).toHaveBeenCalledOnce();
+  });
+
+  it('disposes every feature when clearing a nested stack', () => {
+    const disposals = [vi.fn(), vi.fn()];
+    const host = createSurfaceHost({
+      chat: { component: component(['chat']), focus: component([]) },
+      setFocus: vi.fn(),
+      requestRender: vi.fn(),
+    });
+    host.pushFeature({
+      screen: { ...screen('first', () => ['first']), dispose: disposals[0] },
+    });
+    host.pushFeature({
+      screen: { ...screen('second', () => ['second']), dispose: disposals[1] },
+    });
+
+    host.clearFeatures();
+
+    expect(disposals[0]).toHaveBeenCalledOnce();
+    expect(disposals[1]).toHaveBeenCalledOnce();
+  });
+});

+ 4 - 0
release/public-source.json

@@ -3241,6 +3241,7 @@
     "packages/tui/test/unit/tui-delegation-flow.test.ts",
     "packages/tui/test/unit/tui-duration.test.ts",
     "packages/tui/test/unit/tui-engine-local-deltas.test.ts",
+    "packages/tui/test/unit/tui-feature-viewport-contract.test.ts",
     "packages/tui/test/unit/tui-goal-banner.test.ts",
     "packages/tui/test/unit/tui-image-preview.test.ts",
     "packages/tui/test/unit/tui-keybindings.test.ts",
@@ -3251,9 +3252,12 @@
     "packages/tui/test/unit/tui-provider-onboarding.test.ts",
     "packages/tui/test/unit/tui-runtime-adapter.test.ts",
     "packages/tui/test/unit/tui-scrollbar-interaction.test.ts",
+    "packages/tui/test/unit/tui-session-history-flow.test.ts",
     "packages/tui/test/unit/tui-session-manager.test.ts",
+    "packages/tui/test/unit/tui-session-mutation-panels.test.ts",
     "packages/tui/test/unit/tui-shell-block.test.ts",
     "packages/tui/test/unit/tui-status-line-items.test.ts",
+    "packages/tui/test/unit/tui-surface-host.test.ts",
     "packages/tui/test/unit/tui-terminal-image-paste.test.ts",
     "packages/tui/test/unit/tui-thinking-preview.test.ts",
     "packages/tui/test/unit/tui-transcript-presentation.test.ts",

+ 5 - 1
test/vitest-suites.json

@@ -145,7 +145,11 @@
       "packages/config/test/config-update-preservation.test.ts",
       "packages/agent-modules/context-manager/test/compaction-usage.test.ts",
       "packages/local-runtime/test/unit/session-diff-fallback.test.ts",
-      "test/history-processing.test.ts"
+      "test/history-processing.test.ts",
+      "packages/tui/test/unit/tui-feature-viewport-contract.test.ts",
+      "packages/tui/test/unit/tui-session-history-flow.test.ts",
+      "packages/tui/test/unit/tui-session-mutation-panels.test.ts",
+      "packages/tui/test/unit/tui-surface-host.test.ts"
     ],
     "status-contract": [
       "packages/tui/test/unit/tui-build-mode-contract.test.ts"