Browse Source

fix: preserve the IME cursor across Windows terminal rendering (#271)

DanielWalnut 2 tháng trước cách đây
mục cha
commit
ff415b1711

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

@@ -163,8 +163,8 @@
     },
     {
       "path": "tui-main-screen.ts",
-      "currentSha256": "daf48c4d9a594abd282d4d4fd855373d17cb1033d0b5bdc2396e1727c2186153",
-      "changeIds": ["L005", "L017", "L027", "L033", "L034"],
+      "currentSha256": "9fbbaf8b430423c80bd1abff87a4618a15dcc1253934dbf3b3fdab476e86e584",
+      "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."

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

@@ -131,3 +131,10 @@ Remove `L024` when the selected Pi baseline natively matches legacy-terminal `Ct
 - Boundary: this is a conservative fallback, not a replacement for bracketed paste. A standalone Enter and text followed only by a final Enter retain key semantics. Unframed pastes split into line-sized or character-sized chunks cannot be distinguished from typing and are not inferred using timing. Conversely, multiple typed lines delivered in a single chunk are indistinguishable from an unframed paste and use this fallback. Control sequences retain their existing parser.
 - Evidence: `test/unit/tui-terminal-text-paste.test.ts` replays ProcessTerminal input into the product Editor, including CR, LF, CRLF, Unicode, large pastes, every bracketed chunk split, Enter/shortcuts, and stop/start mode lifecycle. The CR and CRLF cases submitted three separate messages before the fix. These are synthetic input replays, not real WSL terminal acceptance.
 - Removal condition: the selected Pi baseline provides equivalent unframed multiline input handling.
+
+## L037: Commit the IME cursor with the regular-screen frame
+
+- Product contract: a presented frame exposes the focused input's cursor position and visibility, including full redraws, differential updates, and deletion-only frames.
+- Minimal difference: append cursor restoration to the bounded frame writer before ending synchronized output. Cursor-only updates retain the existing path. The product renderer separately defaults to a visible hardware cursor on Windows, where older ConPTY renderers can omit hidden cursor positions; explicit options and `PI_HARDWARE_CURSOR` remain authoritative.
+- Evidence: `test/unit/tui-ime-cursor.test.ts` replays terminal sequences at each synchronized-output boundary and exercises the product renderer, Composer, Editor, focus, mode switches, CJK wrapping, resize and shrink. Native Windows IME and ConPTY transport require separate acceptance.
+- Removal condition: the selected Pi baseline commits cursor restoration within the same synchronized frame.

+ 22 - 16
packages/tui/src/tui/engine/tui-main-screen.ts

@@ -341,8 +341,6 @@ export class TuiMainScreen extends TuiBase implements TUI {
 				}
 				output.append(line);
 			}
-			output.append("\x1b[?2026l"); // End synchronized output
-			output.flush();
 			this.cursorRow = Math.max(0, newLines.length - 1);
 			this.hardwareCursorRow = this.cursorRow;
 			// Reset max lines when clearing, otherwise track growth
@@ -352,7 +350,9 @@ export class TuiMainScreen extends TuiBase implements TUI {
 				this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
 			}
 			this.previousViewportTop = Math.max(start, newLines.length - height);
-			this.positionHardwareCursor(cursorPos, newLines.length);
+			this.positionHardwareCursor(cursorPos, newLines.length, output);
+			output.append("\x1b[?2026l"); // Present only after restoring the input cursor.
+			output.flush();
 			this.previousLines = newLines;
 			this.previousKittyImageIds = this.collectKittyImageIds(newLines);
 			this.previousWidth = width;
@@ -489,12 +489,12 @@ export class TuiMainScreen extends TuiBase implements TUI {
 				if (moveBack > 0) {
 					output.append(`\x1b[${moveBack}A`);
 				}
-				output.append("\x1b[?2026l");
-				output.flush();
 				this.cursorRow = targetRow;
 				this.hardwareCursorRow = targetRow;
+				this.positionHardwareCursor(cursorPos, newLines.length, output);
+				output.append("\x1b[?2026l");
+				output.flush();
 			}
-			this.positionHardwareCursor(cursorPos, newLines.length);
 			this.previousLines = newLines;
 			this.previousKittyImageIds = this.collectKittyImageIds(newLines);
 			this.previousWidth = width;
@@ -620,8 +620,6 @@ export class TuiMainScreen extends TuiBase implements TUI {
 			output.append(`\x1b[${extraLines}A`);
 		}
 
-		output.append("\x1b[?2026l"); // End synchronized output
-
 		if (process.env.PI_TUI_DEBUG === "1") {
 			const debugDir = "/tmp/tui";
 			fs.mkdirSync(debugDir, { recursive: true });
@@ -651,8 +649,6 @@ export class TuiMainScreen extends TuiBase implements TUI {
 			fs.writeFileSync(debugPath, debugData);
 		}
 
-		output.flush();
-
 		// Track cursor position for next render
 		// cursorRow tracks end of content (for viewport calculation)
 		// hardwareCursorRow tracks actual terminal cursor position (for movement)
@@ -662,8 +658,10 @@ export class TuiMainScreen extends TuiBase implements TUI {
 		this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
 		this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
 
-		// Position hardware cursor for IME
-		this.positionHardwareCursor(cursorPos, newLines.length);
+		// Restore the IME anchor before presenting the frame, including cursor visibility.
+		this.positionHardwareCursor(cursorPos, newLines.length, output);
+		output.append("\x1b[?2026l");
+		output.flush();
 
 		this.previousLines = newLines;
 		this.previousKittyImageIds = this.collectKittyImageIds(newLines);
@@ -676,9 +674,14 @@ export class TuiMainScreen extends TuiBase implements TUI {
 	 * @param cursorPos The cursor position extracted from rendered output, or null
 	 * @param totalLines Total number of rendered lines
 	 */
-	private positionHardwareCursor(cursorPos: { row: number; col: number } | null, totalLines: number): void {
+	private positionHardwareCursor(
+		cursorPos: { row: number; col: number } | null,
+		totalLines: number,
+		output?: BoundedTerminalWriter,
+	): void {
 		if (!cursorPos || totalLines <= 0) {
-			this.terminal.hideCursor();
+			if (output) output.append("\x1b[?25l");
+			else this.terminal.hideCursor();
 			return;
 		}
 
@@ -698,11 +701,14 @@ export class TuiMainScreen extends TuiBase implements TUI {
 		buffer += `\x1b[${targetCol + 1}G`;
 
 		if (buffer) {
-			this.terminal.write(buffer);
+			if (output) output.append(buffer);
+			else this.terminal.write(buffer);
 		}
 
 		this.hardwareCursorRow = targetRow;
-		if (this.getShowHardwareCursor()) {
+		if (output) {
+			output.append(this.getShowHardwareCursor() ? "\x1b[?25h" : "\x1b[?25l");
+		} else if (this.getShowHardwareCursor()) {
 			this.terminal.showCursor();
 		} else {
 			this.terminal.hideCursor();

+ 7 - 1
packages/tui/src/tui/renderer/interactive-renderer.ts

@@ -275,7 +275,13 @@ export class McodeInteractiveRenderer {
 
   private createRenderer(
     mode: TuiMode,
-    showHardwareCursor = this.options.showHardwareCursor,
+    // Older ConPTY renderers omit hidden cursor positions from their output,
+    // leaving browser-terminal IME composition at the last painted cell.
+    // Keep explicit options and PI_HARDWARE_CURSOR authoritative.
+    showHardwareCursor = this.options.showHardwareCursor ??
+      (process.platform === 'win32' && process.env.PI_HARDWARE_CURSOR === undefined
+        ? true
+        : undefined),
   ): TuiMainScreen | TuiAltScreen {
     if (mode === 'fullscreen') {
       return new TuiAltScreen(

+ 200 - 0
packages/tui/test/unit/tui-ime-cursor.test.ts

@@ -0,0 +1,200 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { McodeInteractiveRenderer } from "../../src/tui/renderer/interactive-renderer.js";
+import { TuiComposer } from "../../src/tui/shell/composer.js";
+import { Editor } from "../../src/tui/widgets/editor/editor.js";
+import { type Component } from "../../src/tui/engine/public.js";
+import { VirtualTerminal } from "../pi-084-upstream/virtual-terminal.js";
+
+const platformDescriptor = Object.getOwnPropertyDescriptor(
+  process,
+  "platform",
+)!;
+const identity = (text: string) => text;
+const theme = {
+  borderColor: identity,
+  selectList: {
+    selectedPrefix: identity,
+    selectedText: identity,
+    description: identity,
+    scrollInfo: identity,
+    noMatch: identity,
+  },
+};
+
+class RecordingTerminal extends VirtualTerminal {
+  writes: string[] = [];
+  override write(data: string): void {
+    this.writes.push(data);
+    super.write(data);
+  }
+  override hideCursor(): void {
+    this.write("\x1b[?25l");
+  }
+  override showCursor(): void {
+    this.write("\x1b[?25h");
+  }
+}
+
+function setup(
+  mode: "regular" | "fullscreen",
+  showHardwareCursor?: boolean,
+  columns = 40,
+) {
+  const terminal = new RecordingTerminal(columns, 16);
+  const renderer = new McodeInteractiveRenderer({
+    terminal,
+    initialMode: mode,
+    showHardwareCursor,
+  });
+  const editor = new Editor(renderer.ui, theme, { paddingX: 1 });
+  const composer = new TuiComposer(
+    editor,
+    {
+      mode: "message",
+      surface: "conversation",
+      placeholder: "Ask a side question…",
+    },
+    { showTips: false },
+  );
+  const trailing: Component & { lines: string[] } = {
+    lines: ["status", "extra"],
+    render() {
+      return this.lines;
+    },
+    invalidate() {},
+  };
+  renderer.ui.addChild(composer);
+  renderer.ui.addChild(trailing);
+  renderer.ui.setFocus(editor);
+  return { terminal, renderer, editor, trailing };
+}
+
+afterEach(() => {
+  Object.defineProperty(process, "platform", platformDescriptor);
+  vi.unstubAllEnvs();
+});
+
+describe("IME cursor through the product renderer", () => {
+  it.each([
+    ["regular", 8],
+    ["regular", 40],
+    ["regular", 80],
+    ["fullscreen", 8],
+    ["fullscreen", 40],
+    ["fullscreen", 80],
+  ] as const)(
+    "publishes a visible Windows input cursor in %s mode at width %s and after switching",
+    async (mode, columns) => {
+      Object.defineProperty(process, "platform", { value: "win32" });
+      vi.stubEnv("PI_HARDWARE_CURSOR", undefined);
+      const { terminal, renderer, editor } = setup(mode, undefined, columns);
+      try {
+        renderer.start();
+        await terminal.waitForRender();
+        expect(renderer.ui.getShowHardwareCursor()).toBe(true);
+        expect(terminal.writes.join("")).toContain("\x1b[?25h");
+        expect(terminal.getCursorPosition()).toEqual({ x: 3, y: 2 });
+        editor.setText("中文abc");
+        renderer.ui.renderNow();
+        await terminal.flush();
+        expect(terminal.getCursorPosition()).toEqual(
+          columns === 8 ? { x: 6, y: 3 } : { x: 10, y: 2 },
+        );
+        renderer.switchMode(mode === "regular" ? "fullscreen" : "regular");
+        renderer.ui.renderNow();
+        await terminal.flush();
+        expect(renderer.ui.getShowHardwareCursor()).toBe(true);
+        expect(terminal.getCursorPosition()).toEqual(
+          columns === 8 ? { x: 6, y: 3 } : { x: 10, y: 2 },
+        );
+        renderer.ui.setFocus(null);
+        terminal.writes = [];
+        renderer.ui.renderNow();
+        await terminal.flush();
+        expect(terminal.writes.join("")).toContain("\x1b[?25l");
+        expect(terminal.writes.join("")).not.toContain("\x1b[?25h");
+      } finally {
+        renderer.dispose();
+      }
+    },
+  );
+
+  it.each([
+    ["win32", undefined, undefined, true],
+    ["win32", "0", undefined, false],
+    ["win32", "1", undefined, true],
+    ["win32", undefined, false, false],
+    ["darwin", undefined, undefined, false],
+    ["linux", undefined, undefined, false],
+    ["linux", "1", undefined, true],
+    ["linux", "0", true, true],
+  ] as const)(
+    "respects cursor policy on %s, env=%s, option=%s",
+    (platform, env, option, expected) => {
+      Object.defineProperty(process, "platform", { value: platform });
+      vi.stubEnv("PI_HARDWARE_CURSOR", env);
+      const { renderer } = setup("regular", option);
+      try {
+        expect(renderer.ui.getShowHardwareCursor()).toBe(expected);
+      } finally {
+        renderer.dispose();
+      }
+    },
+  );
+
+  it.each([false, true])(
+    "settles the cursor before each regular-mode frame is presented (visible=%s)",
+    async (visible) => {
+      const { terminal, renderer, editor, trailing } = setup(
+        "regular",
+        visible,
+      );
+      const replay = new VirtualTerminal(40, 16);
+      let cursorVisible = false;
+      const assertFrame = async (expected: { x: number; y: number }) => {
+        renderer.ui.renderNow();
+        await terminal.flush();
+        const output = terminal.writes.splice(0).join("");
+        let boundaries = 0;
+        // Replay at synchronized-output boundaries, not just after the final write:
+        // the latter would miss the old frame presenting the last painted column.
+        for (const part of output.split(/(\x1b\[\?2026l)/u)) {
+          replay.write(part);
+          for (const match of part.matchAll(/\x1b\[\?25([hl])/gu))
+            cursorVisible = match[1] === "h";
+          if (part === "\x1b[?2026l") {
+            await replay.flush();
+            expect(replay.getCursorPosition()).toEqual(expected);
+            expect(cursorVisible).toBe(visible);
+            boundaries++;
+          }
+        }
+        await replay.flush();
+        expect(replay.getCursorPosition()).toEqual(expected);
+        return boundaries;
+      };
+      try {
+        renderer.start();
+        expect(await assertFrame({ x: 3, y: 2 })).toBeGreaterThan(0);
+        editor.setText("中文abc");
+        expect(await assertFrame({ x: 10, y: 2 })).toBeGreaterThan(0);
+        editor.handleInput("\x1b[D");
+        await assertFrame({ x: 9, y: 2 });
+        trailing.lines = ["status"]; // deleted-lines-only branch
+        expect(await assertFrame({ x: 9, y: 2 })).toBeGreaterThan(0);
+        editor.setText("中文\nabc");
+        expect(await assertFrame({ x: 6, y: 3 })).toBeGreaterThan(0);
+        editor.setText(""); // differential shrink and placeholder restoration
+        expect(await assertFrame({ x: 3, y: 2 })).toBeGreaterThan(0);
+        await assertFrame({ x: 3, y: 2 }); // unchanged frame
+        terminal.resize(32, 16);
+        replay.resize(32, 16);
+        expect(await assertFrame({ x: 3, y: 2 })).toBeGreaterThan(0);
+        renderer.ui.requestRender(true); // forced full repaint
+        expect(await assertFrame({ x: 3, y: 2 })).toBeGreaterThan(0);
+      } finally {
+        renderer.dispose();
+      }
+    },
+  );
+});

+ 1 - 0
release/public-source.json

@@ -3247,6 +3247,7 @@
     "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-ime-cursor.test.ts",
     "packages/tui/test/unit/tui-keybindings.test.ts",
     "packages/tui/test/unit/tui-model-picker.test.ts",
     "packages/tui/test/unit/tui-plugin-manager.test.ts",

+ 1 - 0
test/vitest-suites.json

@@ -78,6 +78,7 @@
       "packages/tui/test/unit/tui-chat-controller.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-ime-cursor.test.ts",
       "packages/tui/test/unit/tui-scrollbar-interaction.test.ts",
       "packages/tui/test/unit/tui-image-preview.test.ts",
       "packages/tui/test/unit/tui-session-manager.test.ts",