Selaa lähdekoodia

fix: rebuild changed TUI scrollback after queued turns (#274)

DanielWalnut 2 kuukautta sitten
vanhempi
sitoutus
89c930a2df

+ 2 - 2
docs/tui-capabilities.md

@@ -86,8 +86,8 @@ and initial prompt are not applied.
 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;
+boundary, or history refresh changes text already in scrollback, 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.

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

@@ -163,11 +163,11 @@
     },
     {
       "path": "tui-main-screen.ts",
-      "currentSha256": "9fbbaf8b430423c80bd1abff87a4618a15dcc1253934dbf3b3fdab476e86e584",
+      "currentSha256": "f22abd4d0e88d818c9c923721047948c2a6d56df2d57f5bb633cccd5efd3c56d",
       "changeIds": ["L005", "L017", "L027", "L033", "L034", "L037"],
       "upstreamCommit": "6c4f360264397c59801f6da2bdac13e3b1fcbe91",
       "reason": "Keep strict TypeScript fixes and stream full and differential renders through Pi's bounded terminal writer. 缩放期间仅重绘可见尾部 常规模式在差分比较前剥离行首 OSC 133 zone 标记。 内容收缩或历史内容变化触发回退重绘时仅更新可见区域。",
-      "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."
+      "behaviorImpact": "Regular updates preserve native scrollback. When document shrink reveals previously scrolled rows or visible text in scrollback changes, replay the complete current session to fill the viewport and avoid stale or duplicate history. Style-only changes preserve native scrollback. Rebuilding clears pre-launch shell scrollback. Resize retains the existing delayed history replay."
     },
     {
       "path": "tui.ts",

+ 3 - 3
packages/tui/src/tui/engine/LOCAL_CHANGES.md

@@ -116,12 +116,12 @@ Remove `L024` when the selected Pi baseline natively matches legacy-terminal `Ct
 - 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
+## L034: Regular viewport reconstruction after document changes
 
 - 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.
+- Minimal difference: when a shorter document would move the viewport origin backwards, or changed visible text is already in scrollback, clear and replay the complete current projection. Compare changed historical rows without terminal sequences so style-only updates preserve scrollback. 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.
+- 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. Queue lifecycle tests replay bracketed CJK paste, Alt+Enter, auto-drain, and history refresh through Ghostty; equal-height and growing historical edits are also covered by xterm. Virtual terminals do not establish native Windows Terminal or iTerm2 touchpad acceptance.
 - Removal condition: the selected Pi baseline provides equivalent complete viewport and unique-history behavior.
 
 ## L036: Unframed multiline paste chunks

+ 12 - 4
packages/tui/src/tui/engine/tui-main-screen.ts

@@ -2,7 +2,7 @@ import * as fs from "node:fs";
 import * as path from "node:path";
 import { deleteKittyImage, isImageLine } from "./terminal-image.js";
 import { type TUI, TuiBase, type TuiStopOptions } from "./tui.js";
-import { visibleWidth } from "./utils.js";
+import { stripTerminalSequences, visibleWidth } from "./utils.js";
 
 const KITTY_SEQUENCE_PREFIX = "\x1b_G";
 const MAX_RENDER_WRITE_CHARS = 1024 * 1024;
@@ -503,11 +503,19 @@ export class TuiMainScreen extends TuiBase implements TUI {
 			return;
 		}
 
-		// Differential rendering can only touch what was actually visible. A historical row cannot
-		// be rewritten in native scrollback. Redraw only the visible viewport so a session-state
-		// update does not clear the user's native scrollback or move Windows Terminal to its start.
+		// Native scrollback is not addressable. If its text changed, retaining the old prefix
+		// would splice stale rows onto the new document, even when its total height grew.
+		// Style-only changes can still repaint the viewport without replaying history.
 		if (firstChanged < prevViewportTop) {
 			logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
+			for (let i = firstChanged; i < prevViewportTop; i++) {
+				const oldLine = this.previousLines[i] ?? "";
+				const newLine = newLines[i] ?? "";
+				if (oldLine !== newLine && stripTerminalSequences(oldLine) !== stripTerminalSequences(newLine)) {
+					fullRender(true);
+					return;
+				}
+			}
 			fullRender(true, true);
 			return;
 		}

+ 222 - 168
packages/tui/test/unit/tui-app.test.ts

@@ -12741,181 +12741,235 @@ describe("createTuiApp", () => {
     }
   });
 
-  it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
-    const terminal = new FakeTerminal();
-    const runtime = createRuntime();
-    const busEvents: TuiRuntimeEvent[] = [];
-    const queuedItems: TuiQueuedMessage[] = [];
-    let wakeBus: (() => void) | undefined;
-    let finishFirstTurn: (() => void) | undefined;
-    let finishQueuedStream: (() => void) | undefined;
-    const queuedStreamClosed = vi.fn();
-    let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
-    const waitForNextBusEvent = (signal: AbortSignal) =>
-      new Promise<void>((resolve) => {
-        wakeBus = resolve;
-        signal.addEventListener("abort", resolve, { once: true });
-      });
-    vi.mocked(runtime.sendMessage).mockImplementation(
-      async function* sendMessage() {
-        await new Promise<void>((resolve) => {
-          finishFirstTurn = resolve;
+  it.each([1, 100])(
+    "settles an auto-drained follow-up of %i lines with unique terminal history",
+    async (lineCount) => {
+      const queuedText = Array.from(
+        { length: lineCount },
+        (_, i) => `Queue line ${i}: 合成测试文字`,
+      ).join("\n");
+      const terminal = new FakeTerminal();
+      const runtime = createRuntime();
+      const busEvents: TuiRuntimeEvent[] = [];
+      const queuedItems: TuiQueuedMessage[] = [];
+      let wakeBus: (() => void) | undefined;
+      let finishFirstTurn: (() => void) | undefined;
+      let finishQueuedStream: (() => void) | undefined;
+      const queuedStreamClosed = vi.fn();
+      let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
+      const waitForNextBusEvent = (signal: AbortSignal) =>
+        new Promise<void>((resolve) => {
+          wakeBus = resolve;
+          signal.addEventListener("abort", resolve, { once: true });
         });
-        yield { type: "delta", content: "First answer" };
-        yield { type: "done" };
-      },
-    );
-    vi.mocked(runtime.watchSessionTurn).mockImplementation(
-      async function* watchSessionTurn() {
-        try {
+      vi.mocked(runtime.sendMessage).mockImplementation(
+        async function* sendMessage() {
           await new Promise<void>((resolve) => {
-            finishQueuedStream = resolve;
+            finishFirstTurn = resolve;
           });
-          yield { type: "delta", content: "Queued answer" };
+          yield { type: "delta", content: "First answer" };
           yield { type: "done" };
-        } finally {
-          queuedStreamClosed();
-        }
-      },
-    );
-    vi.mocked(runtime.enqueueMessage).mockImplementation(
-      async (sessionId, content) => {
-        const item: TuiQueuedMessage = {
-          itemId: "queue-b",
-          sessionId,
-          status: "queued",
-          content,
-        };
-        queuedItems.push(item);
-        return { itemId: item.itemId, status: item.status, position: 1 };
-      },
-    );
-    vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
-      ...queuedItems,
-    ]);
-    vi.mocked(runtime.getMessages).mockImplementation(
-      async () => durableMessages,
-    );
-    vi.mocked(runtime.watchEvents).mockImplementation(
-      async function* watchEvents(signal) {
-        while (!signal.aborted) {
-          if (busEvents.length === 0) await waitForNextBusEvent(signal);
-          if (signal.aborted) return;
-          const event = busEvents.shift();
-          if (event) yield event;
-        }
-      },
-    );
-    const emit = (event: RawTuiRuntimeEvent) => {
-      busEvents.push(runtimeEvent(event));
-      wakeBus?.();
-      wakeBus = undefined;
-    };
-    const app = createTuiApp({
-      runtime,
-      terminal,
-      version: "0.1.0",
-      workspaceDir: "/workspace",
-      productFeatures: { queue: true },
-    });
-
-    app.start();
-    await app.ready;
-    const first = app.submit("A");
-    await vi.waitFor(() =>
-      expect(app.controller.snapshot().activeTurnId).toBeDefined(),
-    );
-    await app.submit("B");
-    expect(app.tui.render(80).join("\n")).toContain(
-      "Next · after current response",
-    );
-    expect(app.tui.render(80).join("\n")).toContain("B");
+        },
+      );
+      vi.mocked(runtime.watchSessionTurn).mockImplementation(
+        async function* watchSessionTurn() {
+          try {
+            await new Promise<void>((resolve) => {
+              finishQueuedStream = resolve;
+            });
+            yield { type: "delta", content: "Queued answer" };
+            yield { type: "done" };
+          } finally {
+            queuedStreamClosed();
+          }
+        },
+      );
+      vi.mocked(runtime.enqueueMessage).mockImplementation(
+        async (sessionId, content) => {
+          const item: TuiQueuedMessage = {
+            itemId: "queue-b",
+            sessionId,
+            status: "queued",
+            content,
+          };
+          queuedItems.push(item);
+          return { itemId: item.itemId, status: item.status, position: 1 };
+        },
+      );
+      vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
+        ...queuedItems,
+      ]);
+      vi.mocked(runtime.getMessages).mockImplementation(
+        async () => durableMessages,
+      );
+      vi.mocked(runtime.watchEvents).mockImplementation(
+        async function* watchEvents(signal) {
+          while (!signal.aborted) {
+            if (busEvents.length === 0) await waitForNextBusEvent(signal);
+            if (signal.aborted) return;
+            const event = busEvents.shift();
+            if (event) yield event;
+          }
+        },
+      );
+      const emit = (event: RawTuiRuntimeEvent) => {
+        busEvents.push(runtimeEvent(event));
+        wakeBus?.();
+        wakeBus = undefined;
+      };
+      const app = createTuiApp({
+        runtime,
+        terminal,
+        version: "0.1.0",
+        workspaceDir: "/workspace",
+        productFeatures: { queue: true },
+      });
 
-    finishFirstTurn?.();
-    await first;
-    const queuedItem = queuedItems[0];
-    expect(queuedItem).toBeDefined();
-    if (!queuedItem) throw new Error("Expected B to be queued.");
-    queuedItems[0] = { ...queuedItem, status: "running" };
-    emit({
-      type: "session.queue.updated",
-      timestamp: 200,
-      source: "runtime",
-      payload: {
-        sessionId: "session-1",
-        itemId: "queue-b",
-        status: "running",
-        queuedCount: 0,
-      },
-    });
-    emit({
-      type: "session.start",
-      timestamp: 201,
-      source: "runtime",
-      payload: {
-        sessionId: "session-1",
-        turnId: "turn_queue_b",
-        source: "queued-drain",
-        queueItemIds: ["queue-b"],
-      },
-    });
-    await vi.waitFor(() =>
-      expect(app.tui.render(80).join("\n")).toContain("Loading"),
-    );
-    expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
+      const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
+      let writeIndex = 0;
+      const assertScreen = () => {
+        app.tui.renderNow();
+        for (; writeIndex < terminal.writes.length; writeIndex++)
+          screen.feed(terminal.writes[writeIndex]!);
+        const expected = stripAnsi(app.tui.render(terminal.columns).join("\n"))
+          .split("\n")
+          .map((line) => line.trimEnd())
+          .join("\n")
+          .trimEnd();
+        expect(screen.text()).toBe(expected);
+      };
+      app.start();
+      try {
+        await app.ready;
+        const first = app.submit("A");
+        await vi.waitFor(() =>
+          expect(app.controller.snapshot().activeTurnId).toBeDefined(),
+        );
+        terminal.input?.(`\x1b[200~${queuedText}\x1b[201~`);
+        assertScreen();
+        terminal.input?.("\x1b\r");
+        await vi.waitFor(() =>
+          expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
+        );
+        await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
+        expect(vi.mocked(runtime.enqueueMessage).mock.calls[0]?.[1]).toBe(queuedText);
+        expect(app.tui.render(80).join("\n")).toContain(
+          "Next · after current response",
+        );
+        expect(app.tui.render(80).join("\n")).toContain("Queue line 0:");
+
+        assertScreen();
+        finishFirstTurn?.();
+        await first;
+        const queuedItem = queuedItems[0];
+        expect(queuedItem).toBeDefined();
+        if (!queuedItem) throw new Error("Expected B to be queued.");
+        queuedItems[0] = { ...queuedItem, status: "running" };
+        emit({
+          type: "session.queue.updated",
+          timestamp: 200,
+          source: "runtime",
+          payload: {
+            sessionId: "session-1",
+            itemId: "queue-b",
+            status: "running",
+            queuedCount: 0,
+          },
+        });
+        emit({
+          type: "session.start",
+          timestamp: 201,
+          source: "runtime",
+          payload: {
+            sessionId: "session-1",
+            turnId: "turn_queue_b",
+            source: "queued-drain",
+            queueItemIds: ["queue-b"],
+          },
+        });
+        await vi.waitFor(() =>
+          expect(app.tui.render(80).join("\n")).toContain("Loading"),
+        );
+        expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
 
-    queuedItems.length = 0;
-    durableMessages = [
-      {
-        id: "history-user-b",
-        turnId: "turn_queue_b",
-        role: "user",
-        content: "B",
-        timestamp: 202,
-      },
-      {
-        id: "history-assistant-b",
-        turnId: "turn_queue_b",
-        role: "assistant",
-        content: "Queued answer",
-        timestamp: 203,
-      },
-    ];
-    finishQueuedStream?.();
-    await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
-    emit({
-      type: "session.finish",
-      timestamp: 3_201,
-      source: "runtime",
-      payload: {
-        sessionId: "session-1",
-        turnId: "turn_queue_b",
-        status: "finished",
-      },
-    });
+        assertScreen();
+        queuedItems.length = 0;
+        durableMessages = [
+          {
+            id: "history-user-a",
+            turnId: "turn_a",
+            role: "user",
+            content: "A",
+            timestamp: 100,
+          },
+          {
+            id: "history-assistant-a",
+            turnId: "turn_a",
+            role: "assistant",
+            content: "First answer",
+            timestamp: 101,
+          },
+          {
+            id: "history-user-b",
+            turnId: "turn_queue_b",
+            role: "user",
+            content: queuedText,
+            timestamp: 202,
+          },
+          {
+            id: "history-assistant-b",
+            turnId: "turn_queue_b",
+            role: "assistant",
+            content: "Queued answer",
+            timestamp: 203,
+          },
+        ];
+        finishQueuedStream?.();
+        await vi.waitFor(() =>
+          expect(queuedStreamClosed).toHaveBeenCalledOnce(),
+        );
+        emit({
+          type: "session.finish",
+          timestamp: 3_201,
+          source: "runtime",
+          payload: {
+            sessionId: "session-1",
+            turnId: "turn_queue_b",
+            status: "finished",
+          },
+        });
 
-    await vi.waitFor(() =>
-      expect(
-        app.transcript
-          .snapshot()
-          .filter((cell) => cell.content === "Queued answer"),
-      ).toHaveLength(1),
-    );
-    await vi.waitFor(() =>
-      expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
-        status: "succeeded",
-        durationMs: 3_000,
-      }),
-    );
-    const settledUi = app.tui.render(80).join("\n");
-    expect(settledUi).toContain("Completed in 3s");
-    expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
-      settledUi.indexOf("Queued answer"),
-    );
-    expect(settledUi).not.toContain("message waiting");
-    expect(settledUi).not.toContain("Next · after current response");
-    await app.stop();
-  });
+        await vi.waitFor(() =>
+          expect(
+            app.transcript
+              .snapshot()
+              .filter((cell) => cell.content === "Queued answer"),
+          ).toHaveLength(1),
+        );
+        await vi.waitFor(() =>
+          expect(
+            app.transcript.get("turn-duration:turn_queue_b"),
+          ).toMatchObject({
+            status: "succeeded",
+            durationMs: 3_000,
+          }),
+        );
+        const settledUi = app.tui.render(80).join("\n");
+        expect(settledUi).toContain("Completed in 3s");
+        expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
+          settledUi.indexOf("Queued answer"),
+        );
+        expect(settledUi).not.toContain("message waiting");
+        expect(settledUi).not.toContain("Next · after current response");
+        assertScreen();
+      } finally {
+        finishFirstTurn?.();
+        finishQueuedStream?.();
+        await app.stop();
+        screen.dispose();
+      }
+    },
+  );
 
   it("records submitted drafts in editor history", async () => {
     const terminal = new FakeTerminal();

+ 37 - 0
packages/tui/test/unit/tui-engine-local-deltas.test.ts

@@ -184,6 +184,43 @@ describe('MCode Pi Engine local deltas', () => {
     expect(terminal.getScrollBuffer()).toEqual([...answer, ...more, 'composer']);
   });
 
+  it.each([0, 30])('rebuilds changed scrollback text even when the document grows by %i rows', async (growth) => {
+    const terminal = new RecordingVirtualTerminal(67, 24);
+    const tui = new TuiMainScreen(terminal);
+    const component = new MutableLines();
+    const input = Array.from({ length: 80 }, (_, index) => `Queued input ${index}`);
+    component.lines = [...input, `composer${CURSOR_MARKER}`, 'status'];
+    tui.addChild(component);
+    tui.renderNow();
+    await terminal.flush();
+    terminal.takeWrites();
+
+    component.lines = [
+      'Recovered context',
+      ...Array.from({ length: growth }, (_, index) => `Recovered row ${index}`),
+      ...input.slice(1),
+      `composer${CURSOR_MARKER}`,
+      'status',
+    ];
+    tui.renderNow();
+    await terminal.flush();
+
+    const expected = component.lines.map((line) => line.replace(CURSOR_MARKER, ''));
+    expect(terminal.takeWrites()).toContain('\x1b[3J');
+    expect(terminal.getScrollBuffer()).toEqual(expected);
+    expect(terminal.getViewport()).toEqual(expected.slice(-terminal.rows));
+    expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 22 });
+
+    // Subsequent streaming must overwrite the current footer, not append a second one.
+    component.lines.splice(-2, 0, 'Next response');
+    tui.renderNow();
+    await terminal.flush();
+    expect(terminal.takeWrites()).not.toContain('\x1b[3J');
+    expect(terminal.getScrollBuffer()).toEqual([
+      ...expected.slice(0, -2), 'Next response', 'composer', 'status',
+    ]);
+  });
+
   it('rebuilds the document when shrinking leaves no rows in the previous viewport', async () => {
     const terminal = new RecordingVirtualTerminal(67, 44);
     const tui = new TuiMainScreen(terminal);