小类随手记

pi 插件:浮动终端(float-term)——在 pi 内随时唤起 fish / lazygit / yazi等工具

基于 node-pty + overlay 实现浮动终端,支持 Ctrl+Alt+F/G/Y 快捷键在 pi 内直接唤起 fish、lazygit、yazi、gcp 等工具,内置完整 ANSI 终端模拟器,支持 alternate screen、CJK/emoji 宽字符。

背景

pi 写代码时,经常需要切出去看一眼文件(yazi)、提交代码(lazygit / gcp)、或者临时跑个命令(fish)。每次都 Ctrl+Z 挂起 pi 或者另开一个终端窗口很打断思路。

理想的状态是:按一个键,在 pi 上层弹出一个真正的终端小窗,用完即关——像 Neovim 的浮动终端(:term / :Floaterm),但更通用、更顺手。

之前写过 pi 的 CustomEditor 扩展把光标改成竖线,又写了 git-changes 扩展利用 overlay 查看文件变更。这次更进一步:利用 pi 的 overlay 框架,结合 node-pty 实现真正的 PTY 浮动终端,并且内置一个完整的 ANSI 终端模拟器(TermBuffer)来渲染输出。

需求

  1. 一键唤起——常用工具一个快捷键,无需输入命令,其他工具在通用终端fish中按需要唤起
  2. 真正的终端——不是 spawn + 抓 stdout,而是 PTY,支持交互式 TUI 程序(lazygit、yazi、vim、htop 等)
  3. 不占用主 UI——浮动 overlay,查看/操作完即关,pi 主界面不受影响
  4. 完整的终端渲染——支持颜色、光标定位、alternate screen(全屏 TUI 程序)、CJK/emoji 宽字符
  5. 快速关闭——Ctrl+Space 强制关闭,exit / Ctrl+D 正常退出
  6. 使用lazygit 在pi内部跟踪文件变动情况

快捷键与命令

快捷键命令功能
Ctrl+Alt+F/float-fish浮动终端:fish shell
Ctrl+Alt+G/float-lazygit浮动终端:lazygit
Ctrl+Alt+Y/float-yazi浮动终端:yazi 文件管理器
Ctrl+Shift+Alt+G浮动终端:gcp(conventional commits)

状态栏常驻显示快捷键提示:

1
C-a-f:fish  C-a-y:yazi  C-S-a-g:gcp  C-a-g:lazygit

实现方法

整体架构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
┌─ pi Extension API ──────────────────────────────────┐
│                                                      │
│  pi.registerShortcut("ctrl+alt+f", ...)  ──┐         │
│  pi.registerCommand("/float-fish", ...)  ──┤         │
│                                           │          │
│           ┌───────────────────────────────▼────────┐ │
│           │     ctx.ui.custom({ overlay })          │ │
│           │     FloatTermOverlay                    │ │
│           │                                         │ │
│           │  ┌─────────────────────────────────┐   │ │
│           │  │  node-pty (IPty)                 │   │ │
│           │  │  • ptySpawn(fish/lazygit/yazi)   │   │ │
│           │  │  • onData → TermBuffer.write()   │   │ │
│           │  │  • handleInput → pty.write()     │   │ │
│           │  │  • resize(cols, rows)            │   │ │
│           │  └─────────────────────────────────┘   │ │
│           │                                         │ │
│           │  ┌─────────────────────────────────┐   │ │
│           │  │  TermBuffer (ANSI 终端模拟器)     │   │ │
│           │  │  • CSI 解析(光标、擦除、模式)    │   │ │
│           │  │  • SGR 渲染(颜色、粗体、反视频)  │   │ │
│           │  │  • Alternate Screen(vim/lazygit)│   │ │
│           │  │  • 查询响应(DA/CPR/DSR)         │   │ │
│           │  │  • CJK/emoji 宽字符               │   │ │
│           │  └─────────────────────────────────┘   │ │
│           │                                         │ │
│           │  render() → ANSI-styled terminal lines  │ │
│           │  handleInput() → forward keystrokes     │ │
│           └─────────────────────────────────────────┘ │
│                                                      │
│  ctx.ui.setStatus() → footer shortcut hints          │
└──────────────────────────────────────────────────────┘

关键 API

API用途
pi.registerShortcut("ctrl+alt+f", ...)全局快捷键,一键唤起浮动终端
pi.registerCommand("float-fish", ...)命令入口,/float-fish 唤起
ctx.ui.custom(component, { overlay: true })浮动 overlay,叠加在主 UI 之上
ctx.ui.setStatus(key, text)footer 状态栏常驻快捷键提示
node-pty (ptySpawn)创建真正的 PTY 伪终端进程
matchesKey(data, Key.ctrl(" "))检测 Ctrl+Space 强制关闭

node-pty:真正的 PTY 终端

child_process.spawn 不同,node-pty 创建的是 伪终端(PTY)。区别在于:

spawnnode-pty
输出管道(pipe),无终端特性PTY,程序以为自己在真实终端里
TUI 程序❌ lazygit / vim / htop 无法运行✅ 完全支持
ANSI 转义程序通常不输出程序正常输出颜色、光标控制、alternate screen
resize不支持pty.resize(cols, rows)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { spawn as ptySpawn } from "node-pty";

this.ptyProcess = ptySpawn(shellCmd, shellArgs, {
  name: "xterm-256color",
  cols,
  rows,
  cwd: process.cwd(),
  env: process.env as Record<string, string>,
});

// 转发用户按键到 PTY
this.ptyProcess.write(data);

// 接收 PTY 输出 → 交给 TermBuffer 解析渲染
this.ptyProcess.onData((data: string) => {
  const responses = this.term.write(data);
  if (responses) this.ptyProcess.write(responses); // 响应终端查询
  this.tui.requestRender();
});

TermBuffer:ANSI 终端模拟器

因为 pi 的 overlay 渲染是基于行数组(render(): string[])的,无法直接使用终端的原生渲染。所以需要一个 ANSI 终端模拟器 把 PTY 输出的 ANSI 转义序列解析成 Cell 网格,再重新转成带颜色的 ANSI 字符串。

实现了一个精简但功能完备的终端模拟器,包含:

CSI 序列支持

序列功能
CSI n A/B/C/D光标上/下/右/左移动
CSI n;m H / CSI n;m f光标定位(CUP)
CSI n J擦除显示(0=光标后, 1=光标前, 2/3=全屏)
CSI n K擦除行(0=光标后, 1=光标前, 2=整行)
CSI s / CSI u保存/恢复光标位置和属性
CSI ?25 h/l光标显示/隐藏
CSI ?1049 h/l / CSI ?47 h/lAlternate Screen 切换

SGR 渲染(Select Graphic Rendition)

支持 ANSI 256 色、True Color(RGB→256 映射)、粗体、斜体、下划线、反视频等属性。

反视频(reverse video)的处理很关键:pi 的 overlay 背景是透明的,叠加在终端上。如果直接输出 \x1b[7m(让终端自己做反视频),可能和显式颜色冲突导致闪烁。TermBuffer 的做法是在渲染时手动交换 fg/bg 颜色,而不是输出 \x1b[7m

1
2
3
4
5
6
if (a.reverse) {
  // Swap; supply terminal-appropriate defaults.
  const tmp = fg;
  fg = bg ?? 0;  // default bg → dark
  bg = tmp ?? 7;  // default fg → light
}

Alternate Screen(全屏程序支持)

lazygit、vim、less 等程序会切换终端的 alternate screen buffer\x1b[?1049h),TermBuffer 完整实现了双缓冲切换:

1
2
3
4
5
6
7
8
9
private enterAltScreen(): void {
  this.useAltScreen = true;
  this.altGrid = this.grid;          // 保存主屏幕
  this.altCursorX = this.cursorX;
  this.altCursorY = this.cursorY;
  this.altAttrs = cloneAttrs(this.attrs);
  this.grid = newGrid(this.cols, this.rows);  // 全新空屏
  // ...
}

退出时恢复主屏幕(\x1b[?1049l),内容完整还原。

终端查询响应

有些程序启动时会查询终端能力,如果不响应会导致卡死或显示异常:

查询序列含义响应
CSI cPrimary DA(设备属性)CSI ?1;2c(VT100 + AVO)
CSI > cSecondary DACSI >0;0;0c
CSI 6 nCPR(光标位置报告)CSI row;col R
CSI 5 nDSR(设备状态报告)CSI 0n

CJK / Emoji 宽字符

中日韩字符和 emoji 占 2 个终端列宽。TermBuffer 用 Unicode 码点范围判断宽度,渲染时宽字符占一个 Cell 并标记下一个 Cell 为空占位符:

1
2
// 宽字符第二列为空占位,跳过渲染
if (cell.char === "") continue;

浮动框渲染

浮动框使用 Unicode box-drawing 字符绘制边框(╭╮╰╯│─),紫色(mauve)边框:

  • 内容区域:TermBuffer 渲染的行数组,每行的 ANSI 颜色被保留
  • 底部提示栏:居中显示 Ctrl+Space: close | exit / Ctrl+D: quit shell
  • 尺寸:宽 85%,高 75%,居中锚定
1
2
3
4
5
6
7
{ overlay: true,
  overlayOptions: {
    width: "85%",
    maxHeight: "75%",
    anchor: "center",
  }
}

叠加层支持终端 resize:当 pi 窗口大小变化时,overlay 重新计算内部行列数,同步调用 pty.resize(cols, rows) 通知 PTY 进程。

完整代码

放到 ~/.pi/agent/extensions/float-term.ts,需要先在该目录 npm/bun install node-pty,pi 会自动发现并加载。

float-term.ts (519 行)
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/**
 * Float Term — 浮动终端 (floating terminal overlay for pi)
 *
 * 用法:
 *   Ctrl+Shift+H  — 弹出一个浮动的 fish 终端小窗(居中,85% 宽 x 75% 高)
 *   /float-term   — 同上
 *
 * 交互:
 *   正常输入 → 发送到终端
 *   exit / Ctrl+D → 退出 shell,自动关闭
 *   Ctrl+Space → 强制关闭浮动终端
 *
 * 类似 Neovim 的 <leader>ft 浮动终端。
 * 基于 node-pty 实现真正的 PTY 终端模拟。
 *
 * 可通过 FLOAT_TERM_SHELL 环境变量自定义 shell(默认 fish)。
 *
 * 自动发现路径: ~/.pi/agent/extensions/float-term.ts
 *
 * 依赖: node-pty (需在 extensions/ 下 npm install node-pty)
 */

import type { IPty } from "node-pty";
import { spawn as ptySpawn } from "node-pty";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import {
  Key,
  matchesKey,
  truncateToWidth,
  visibleWidth,
} from "@earendil-works/pi-tui";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface CellAttrs {
  fg?: number;
  bg?: number;
  bold?: boolean;
  dim?: boolean;
  italic?: boolean;
  underline?: boolean;
  reverse?: boolean;
}

interface Cell {
  char: string;
  attrs: CellAttrs;
}

const EMPTY_ATTRS: CellAttrs = {};

function cloneAttrs(a: CellAttrs): CellAttrs {
  if (a === EMPTY_ATTRS) return {};
  if (
    !a.fg &&
    !a.bg &&
    !a.bold &&
    !a.dim &&
    !a.italic &&
    !a.underline &&
    !a.reverse
  )
    return {};
  return {
    fg: a.fg,
    bg: a.bg,
    bold: a.bold,
    dim: a.dim,
    italic: a.italic,
    underline: a.underline,
    reverse: a.reverse,
  };
}

function attrsEqual(a: CellAttrs, b: CellAttrs): boolean {
  return (
    a.fg === b.fg &&
    a.bg === b.bg &&
    a.bold === b.bold &&
    a.dim === b.dim &&
    a.italic === b.italic &&
    a.underline === b.underline &&
    a.reverse === b.reverse
  );
}

// ---------------------------------------------------------------------------
// Cell → ANSI SGR styled string
// ---------------------------------------------------------------------------

function cellToSGR(cell: Cell): string {
  const a = cell.attrs;
  const codes: number[] = [];

  if (a.bold) codes.push(1);
  if (a.dim) codes.push(2);
  if (a.italic) codes.push(3);
  if (a.underline) codes.push(4);

  // Resolve reverse at render-time: swap fg/bg with sensible defaults.
  let fg = a.fg;
  let bg = a.bg;
  if (a.reverse) {
    const tmp = fg;
    fg = bg ?? 0;
    bg = tmp ?? 7;
  }

  if (fg !== undefined) {
    if (fg < 8) codes.push(30 + fg);
    else if (fg < 16) codes.push(90 + (fg - 8));
    else codes.push(38, 5, fg);
  }
  if (bg !== undefined) {
    if (bg < 8) codes.push(40 + bg);
    else if (bg < 16) codes.push(100 + (bg - 8));
    else codes.push(48, 5, bg);
  }

  if (codes.length === 0) return cell.char;
  return `\x1b[${codes.join(";")}m${cell.char}`;
}

// ---------------------------------------------------------------------------
// Unicode width & colour helpers
// ---------------------------------------------------------------------------

/** Map 24-bit RGB to the closest entry in the 256-colour palette. */
function rgbTo256(r: number, g: number, b: number): number {
  if (r === g && g === b) {
    if (r <= 7) return 16;
    if (r >= 248) return 231;
    return Math.round((r - 8) / 10) + 232;
  }
  const ri = Math.max(0, Math.min(5, Math.round(r / 51)));
  const gi = Math.max(0, Math.min(5, Math.round(g / 51)));
  const bi = Math.max(0, Math.min(5, Math.round(b / 51)));
  return 16 + 36 * ri + 6 * gi + bi;
}

/** Rough East-Asian width check. Returns 2 for CJK / fullwidth / emoji, 1 otherwise. */
function charWidth(cp: number): number {
  if (cp >= 0x2e80 && cp <= 0x303e) return 2;
  if (cp >= 0x3040 && cp <= 0x3247) return 2;
  if (cp >= 0x3200 && cp <= 0x33bf) return 2;
  if (cp >= 0x3400 && cp <= 0xa4cf) return 2;
  if (cp >= 0xa960 && cp <= 0xd7af) return 2;
  if (cp >= 0xf900 && cp <= 0xfaff) return 2;
  if (cp >= 0xfe10 && cp <= 0xfe6f) return 2;
  if (cp >= 0xff01 && cp <= 0xff60) return 2;
  if (cp >= 0xffe0 && cp <= 0xffe6) return 2;
  if (cp >= 0x1f000 && cp <= 0x1f9ff) return 2;
  if (cp >= 0x20000 && cp <= 0x3134f) return 2;
  return 1;
}

// ---------------------------------------------------------------------------
// Terminal Buffer — minimal ANSI terminal emulator
// ---------------------------------------------------------------------------

class TermBuffer {
  cols: number;
  rows: number;
  private grid: Cell[][];
  private cursorX = 0;
  private cursorY = 0;
  private attrs: CellAttrs = { ...EMPTY_ATTRS };
  private savedX = 0;
  private savedY = 0;
  private savedAttrs: CellAttrs = { ...EMPTY_ATTRS };

  // Alternate screen buffer (for lazygit, vim, etc.)
  private altGrid: Cell[][] | null = null;
  private altCursorX = 0;
  private altCursorY = 0;
  private altAttrs: CellAttrs = { ...EMPTY_ATTRS };
  private useAltScreen = false;

  private escState: "normal" | "esc" | "escNext" | "csi" | "osc" | "oscEsc" =
    "normal";
  private csiParams = "";
  private queryBuf = "";
  private cachedLines: string[] | null = null;
  dirty = true;

  constructor(cols: number, rows: number) {
    this.cols = cols;
    this.rows = rows;
    this.grid = newGrid(cols, rows);
  }

  resize(cols: number, rows: number): void {
    const oldGrid = this.grid;
    const oldRows = this.rows;
    const oldCols = this.cols;
    this.cols = cols;
    this.rows = rows;
    this.grid = newGrid(cols, rows);
    const copyRows = Math.min(oldRows, rows);
    const copyCols = Math.min(oldCols, cols);
    for (let r = 0; r < copyRows; r++) {
      for (let c = 0; c < copyCols; c++) {
        this.grid[r]![c] = oldGrid[r]![c]!;
      }
    }
    this.cursorX = Math.min(this.cursorX, cols - 1);
    this.cursorY = Math.min(this.cursorY, rows - 1);
    this.dirty = true;
  }

  private enterAltScreen(): void {
    if (this.useAltScreen) return;
    this.useAltScreen = true;
    this.altGrid = this.grid;
    this.altCursorX = this.cursorX;
    this.altCursorY = this.cursorY;
    this.altAttrs = cloneAttrs(this.attrs);
    this.grid = newGrid(this.cols, this.rows);
    this.cursorX = 0;
    this.cursorY = 0;
    this.attrs = { ...EMPTY_ATTRS };
    this.dirty = true;
  }

  private leaveAltScreen(): void {
    if (!this.useAltScreen) return;
    this.useAltScreen = false;
    if (this.altGrid) {
      this.grid = this.altGrid;
      this.cursorX = this.altCursorX;
      this.cursorY = this.altCursorY;
      this.attrs = cloneAttrs(this.altAttrs);
      this.altGrid = null;
    }
    this.dirty = true;
  }

  write(data: string): string {
    const responses = this.handleQueries(data);
    for (let i = 0; i < this.queryBuf.length; ) {
      const cp = this.queryBuf.codePointAt(i)!;
      const ch = String.fromCodePoint(cp);
      this.processChar(cp, ch);
      i += cp > 0xffff ? 2 : 1;
    }
    this.queryBuf = "";
    this.dirty = true;
    return responses;
  }

  private handleQueries(data: string): string {
    this.queryBuf += data;
    let responses = "";
    const re = /\x1b\[([?>]?)(\d*(?:;\d+)*)([cn])/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(this.queryBuf)) !== null) {
      const prefix = m[1] || "";
      const finalByte = m[3]!;
      if (finalByte === "c") {
        if (prefix === ">") responses += "\x1b[>0;0;0c";
        else responses += "\x1b[?1;2c";
      } else if (finalByte === "n") {
        const p = parseInt(m[2] || "0", 10) || 0;
        if (p === 6)
          responses += `\x1b[${this.cursorY + 1};${this.cursorX + 1}R`;
        else if (p === 5) responses += "\x1b[0n";
      }
    }
    if (responses) {
      this.queryBuf = this.queryBuf.replace(/\x1b\[[?>]?\d*(?:;\d+)*[cn]/g, "");
    }
    return responses;
  }

  private processChar(code: number, ch: string): void {
    if (this.escState === "normal") {
      if (code === 0x1b) { this.escState = "esc"; }
      else if (code === 0x0d) { this.cursorX = 0; }
      else if (code === 0x0a) { this.lineFeed(); }
      else if (code === 0x08) { if (this.cursorX > 0) this.cursorX--; }
      else if (code === 0x09) {
        this.cursorX = Math.min(this.cols - 1, (Math.floor(this.cursorX / 8) + 1) * 8);
      } else if (code >= 0x20) { this.putChar(ch, charWidth(code)); }
    } else if (this.escState === "esc") {
      if (ch === "[") { this.escState = "csi"; this.csiParams = ""; }
      else if (ch === "]") { this.escState = "osc"; }
      else if (ch === "_" || ch === "P" || ch === "^") { this.escState = "osc"; }
      else if (ch === "(" || ch === ")" || ch === "*" || ch === "+") { this.escState = "escNext"; }
      else { this.escState = "normal"; }
    } else if (this.escState === "csi") {
      if ((code >= 0x30 && code <= 0x39) || ch === ";" || ch === "?" || ch === " " || ch === ">") {
        this.csiParams += ch;
      } else {
        this.handleCSI(ch, this.csiParams);
        this.escState = "normal";
      }
    } else if (this.escState === "osc") {
      if (code === 0x07) { this.escState = "normal"; }
      else if (code === 0x1b) { this.escState = "oscEsc"; }
      else if (code === 0x9c) { this.escState = "normal"; }
    } else if (this.escState === "escNext") {
      this.escState = "normal";
    } else if (this.escState === "oscEsc") {
      if (ch === "\\") { this.escState = "normal"; }
      else { this.escState = "osc"; }
    }
  }

  private handleCSI(finalByte: string, params: string): void {
    const nums = params.replace(/^\?/, "").split(";").map((s) => (s === "" ? 0 : parseInt(s, 10)));
    switch (finalByte) {
      case "m": return this.handleSGR(nums);
      case "A": this.cursorY = Math.max(0, this.cursorY - (nums[0] || 1)); break;
      case "B": this.cursorY = Math.min(this.rows - 1, this.cursorY + (nums[0] || 1)); break;
      case "C": this.cursorX = Math.min(this.cols - 1, this.cursorX + (nums[0] || 1)); break;
      case "D": this.cursorX = Math.max(0, this.cursorX - (nums[0] || 1)); break;
      case "H": case "f": {
        const row = Math.max(1, nums[0] || 1) - 1;
        const col = Math.max(1, nums[1] || 1) - 1;
        this.cursorY = Math.min(this.rows - 1, row);
        this.cursorX = Math.min(this.cols - 1, col);
        break;
      }
      case "J": this.eraseDisplay(nums[0] || 0); break;
      case "K": this.eraseLine(nums[0] || 0); break;
      case "s":
        this.savedX = this.cursorX; this.savedY = this.cursorY;
        this.savedAttrs = cloneAttrs(this.attrs); break;
      case "u":
        this.cursorX = this.savedX; this.cursorY = this.savedY;
        this.attrs = cloneAttrs(this.savedAttrs); break;
      case "h": case "l":
        if (params.startsWith("?")) {
          const modeNum = nums[0] || 0;
          if (modeNum === 1049 || modeNum === 47) {
            if (finalByte === "h") this.enterAltScreen();
            else this.leaveAltScreen();
          }
        }
        break;
    }
  }

  private handleSGR(nums: number[]): void {
    if (nums.length === 0 || (nums.length === 1 && nums[0] === 0)) {
      this.attrs = { ...EMPTY_ATTRS }; return;
    }
    let i = 0;
    while (i < nums.length) {
      const n = nums[i]!;
      if (n === 0) this.attrs = { ...EMPTY_ATTRS };
      else if (n === 1) this.attrs.bold = true;
      else if (n === 2) this.attrs.dim = true;
      else if (n === 3) this.attrs.italic = true;
      else if (n === 4) this.attrs.underline = true;
      else if (n === 7) this.attrs.reverse = true;
      else if (n >= 30 && n <= 37) this.attrs.fg = n - 30;
      else if (n >= 40 && n <= 47) this.attrs.bg = n - 40;
      else if (n >= 90 && n <= 97) this.attrs.fg = n - 90 + 8;
      else if (n >= 100 && n <= 107) this.attrs.bg = n - 100 + 8;
      else if (n === 38 && i + 2 < nums.length && nums[i + 1] === 5) {
        this.attrs.fg = nums[i + 2]!; i += 2;
      } else if (n === 48 && i + 2 < nums.length && nums[i + 1] === 5) {
        this.attrs.bg = nums[i + 2]!; i += 2;
      } else if (n === 38 && i + 4 < nums.length && nums[i + 1] === 2) {
        this.attrs.fg = rgbTo256(nums[i + 2]!, nums[i + 3]!, nums[i + 4]!); i += 4;
      } else if (n === 48 && i + 4 < nums.length && nums[i + 1] === 2) {
        this.attrs.bg = rgbTo256(nums[i + 2]!, nums[i + 3]!, nums[i + 4]!); i += 4;
      } else if (n === 39) this.attrs.fg = undefined;
      else if (n === 49) this.attrs.bg = undefined;
      else if (n === 22) { this.attrs.bold = false; this.attrs.dim = false; }
      else if (n === 23) this.attrs.italic = false;
      else if (n === 24) this.attrs.underline = false;
      else if (n === 27) this.attrs.reverse = false;
      i++;
    }
  }

  private eraseDisplay(n: number): void {
    if (n === 0) {
      for (let r = this.cursorY; r < this.rows; r++) {
        const start = r === this.cursorY ? this.cursorX : 0;
        for (let c = start; c < this.cols; c++)
          this.grid[r]![c] = { char: " ", attrs: { ...EMPTY_ATTRS } };
      }
    } else if (n === 1) {
      for (let r = 0; r <= this.cursorY; r++) {
        const end = r === this.cursorY ? this.cursorX : this.cols - 1;
        for (let c = 0; c <= end; c++)
          this.grid[r]![c] = { char: " ", attrs: { ...EMPTY_ATTRS } };
      }
    } else if (n === 2 || n === 3) {
      this.grid = newGrid(this.cols, this.rows);
      this.cursorX = 0; this.cursorY = 0;
    }
  }

  private eraseLine(n: number): void {
    if (n === 0) {
      for (let c = this.cursorX; c < this.cols; c++)
        this.grid[this.cursorY]![c] = { char: " ", attrs: { ...EMPTY_ATTRS } };
    } else if (n === 1) {
      for (let c = 0; c <= this.cursorX; c++)
        this.grid[this.cursorY]![c] = { char: " ", attrs: { ...EMPTY_ATTRS } };
    } else if (n === 2) {
      for (let c = 0; c < this.cols; c++)
        this.grid[this.cursorY]![c] = { char: " ", attrs: { ...EMPTY_ATTRS } };
    }
  }

  private putChar(ch: string, width: number = 1): void {
    if (this.cursorX + width > this.cols) {
      this.cursorX = 0;
      this.lineFeed();
    }
    this.grid[this.cursorY]![this.cursorX] = { char: ch, attrs: cloneAttrs(this.attrs) };
    if (width === 2 && this.cursorX + 1 < this.cols) {
      this.grid[this.cursorY]![this.cursorX + 1] = { char: "", attrs: cloneAttrs(this.attrs) };
    }
    this.cursorX += width;
  }

  private lineFeed(): void {
    if (this.cursorY < this.rows - 1) {
      this.cursorY++;
    } else {
      for (let r = 0; r < this.rows - 1; r++) this.grid[r] = this.grid[r + 1]!;
      this.grid[this.rows - 1] = new Array(this.cols).fill(null).map(() => ({ char: " ", attrs: { ...EMPTY_ATTRS } as CellAttrs }));
    }
  }

  render(): string[] {
    if (!this.dirty && this.cachedLines) return this.cachedLines;
    const bgReset = "\x1b[0;40m";
    const lines: string[] = [];
    for (let r = 0; r < this.rows; r++) {
      const row = this.grid[r]!;
      let line = bgReset;
      let lastAttrs: CellAttrs = { bg: 0 };
      for (let c = 0; c < this.cols; c++) {
        const cell = row[c]!;
        if (cell.char === "") continue;
        if (attrsEqual(cell.attrs, lastAttrs)) {
          line += cell.char;
        } else {
          line += cellToSGR(cell);
          lastAttrs = cell.attrs;
        }
      }
      line += "\x1b[0m";
      lines.push(line.replace(/(\s+)(\x1b\[0m)$/, "$2"));
    }
    this.cachedLines = lines;
    this.dirty = false;
    return lines;
  }
}

function newGrid(cols: number, rows: number): Cell[][] {
  const g: Cell[][] = [];
  for (let r = 0; r < rows; r++) {
    const row: Cell[] = [];
    for (let c = 0; c < cols; c++) {
      row.push({ char: " ", attrs: { ...EMPTY_ATTRS } });
    }
    g.push(row);
  }
  return g;
}

// ---------------------------------------------------------------------------
// Overlay Component
// ---------------------------------------------------------------------------

const BORDER_COLOUR = "\x1b[38;5;133m";
const BORDER_RESET = "\x1b[0m";

class FloatTermOverlay {
  private term: TermBuffer;
  private ptyProcess: IPty;
  private done: (v: null) => void;
  private tui: any;
  private closed = false;
  private innerRows: number;
  private innerCols: number;

  constructor(
    shellCmd: string,
    shellArgs: string[],
    cols: number,
    rows: number,
    tui: any,
    done: (v: null) => void,
  ) {
    this.tui = tui;
    this.done = done;
    this.innerCols = cols;
    this.innerRows = rows;
    this.term = new TermBuffer(cols, rows);
    this.ptyProcess = ptySpawn(shellCmd, shellArgs, {
      name: "xterm-256color",
      cols, rows,
      cwd: process.cwd(),
      env: process.env as Record<string, string>,
    });
    this.ptyProcess.onData((data: string) => {
      if (this.closed) return;
      const responses = this.term.write(data);
      if (responses) this.ptyProcess.write(responses);
      this.tui.requestRender();
    });
    this.ptyProcess.onExit(() => {
      this.closed = true;
      done(null);
    });
  }

  handleInput(data: string): void {
    if (this.closed) return;
    if (matchesKey(data, Key.ctrl(" ")) || matchesKey(data, "ctrl+space")) {
      this.close(); return;
    }
    this.ptyProcess.write(data);
  }

  render(width: number): string[] {
    if (this.closed) return [];
    const termLines = this.term.render();
    const lines: string[] = [];
    const topBar = "╭" + "─".repeat(this.innerCols) + "╮";
    lines.push(padAnsi(BORDER_COLOUR + topBar + BORDER_RESET, width));
    for (const raw of termLines) {
      const content = truncateToWidth(raw, this.innerCols);
      const vis = visibleWidth(content);
      const padded = vis < this.innerCols ? content + " ".repeat(this.innerCols - vis) : content;
      lines.push(padAnsi(
        BORDER_COLOUR + "│" + BORDER_RESET + padded + BORDER_COLOUR + "│" + BORDER_RESET,
        width,
      ));
    }
    const hint = " Ctrl+Space: close | exit / Ctrl+D: quit shell ";
    const hintLen = visibleWidth(hint);
    const barLen = this.innerCols;
    if (hintLen <= barLen) {
      const leftPad = Math.floor((barLen - hintLen) / 2);
      const rightPad = barLen - hintLen - leftPad;
      const bottomBar = "╰" + "─".repeat(leftPad) + hint + "─".repeat(rightPad) + "╯";
      lines.push(padAnsi(BORDER_COLOUR + bottomBar + BORDER_RESET, width));
    } else {
      lines.push(padAnsi(BORDER_COLOUR + "╰" + "─".repeat(barLen) + "╯" + BORDER_RESET, width));
    }
    return lines;
  }

  invalidate(): void {}

  close(): void {
    if (this.closed) return;
    this.closed = true;
    try { this.ptyProcess.kill(); } catch (_) { /* ignore */ }
    this.done(null);
  }

  resize(cols: number, rows: number): void {
    this.innerCols = cols;
    this.innerRows = rows;
    this.term.resize(cols, rows);
    try { this.ptyProcess.resize(cols, rows); } catch (_) { /* ignore */ }
  }
}

function padAnsi(styled: string, width: number): string {
  const vis = visibleWidth(styled);
  if (vis >= width) return truncateToWidth(styled, width);
  return styled + " ".repeat(width - vis);
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

async function openFloatTerm(ctx: any, shellCmd: string, shellArgs: string[]) {
  if (ctx.mode !== "tui") {
    ctx.ui.notify("浮动终端需要 TUI 模式", "warning");
    return;
  }
  let termHeight = 40;
  await ctx.ui.custom<null>(
    (tui: any, _theme: any, _kb: any, done: any) => {
      let overlay: FloatTermOverlay | null = null;
      let lastWidth = 0;
      const wrapper = {
        render(width: number): string[] {
          const innerCols = Math.max(20, width - 2);
          const maxContentRows = Math.max(4, Math.floor(termHeight * 0.75) - 2);
          const rows = Math.min(Math.max(4, Math.floor(innerCols * 0.45)), maxContentRows);
          if (!overlay) {
            overlay = new FloatTermOverlay(shellCmd, shellArgs, innerCols, rows, tui, done);
            lastWidth = width;
          } else if (width !== lastWidth) {
            overlay.resize(innerCols, rows);
            lastWidth = width;
          }
          return overlay!.render(width);
        },
        invalidate(): void {},
        handleInput(data: string): void {
          if (overlay) { overlay.handleInput(data); }
          else if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
            done(null);
          }
        },
      };
      return wrapper;
    },
    {
      overlay: true,
      overlayOptions: {
        width: "85%",
        maxHeight: "75%",
        anchor: "center",
        margin: { top: 0, bottom: 0, left: 0, right: 0 },
        visible: (_tw: number, th: number) => { termHeight = th; return true; },
      },
    },
  );
}

export default function (pi: ExtensionAPI) {
  const STATUS_KEY = "float-term";

  function refreshStatus(ctx: any) {
    if (!ctx.hasUI) return;
    const t = ctx.ui.theme;
    const hint = [
      t.fg("accent", "C-a-f") + t.fg("dim", ":fish"),
      t.fg("accent", "C-a-y") + t.fg("dim", ":yazi"),
      t.fg("accent", "C-S-a-g") + t.fg("dim", ":gcp"),
      t.fg("accent", "C-a-g") + t.fg("dim", ":lazygit"),
    ].join("  ");
    ctx.ui.setStatus(STATUS_KEY, hint);
  }

  pi.on("session_start", async (_e, ctx) => { refreshStatus(ctx); });

  pi.registerShortcut("ctrl+alt+f", {
    description: "浮动终端: fish",
    handler: async (ctx: any) => { await openFloatTerm(ctx, "fish", []); },
  });
  pi.registerShortcut("ctrl+alt+g", {
    description: "浮动终端: lazygit",
    handler: async (ctx: any) => { await openFloatTerm(ctx, "lazygit", []); },
  });
  pi.registerShortcut("ctrl+alt+y", {
    description: "浮动终端: yazi",
    handler: async (ctx: any) => { await openFloatTerm(ctx, "yazi", []); },
  });
  pi.registerShortcut("ctrl+shift+alt+g", {
    description: "浮动终端: gcp (git conventional commits)",
    handler: async (ctx: any) => { await openFloatTerm(ctx, "fish", ["-c", "gcp; exec fish"]); },
  });

  pi.registerCommand("float-fish", {
    description: "打开浮动终端 (fish)",
    handler: async (_args: any, ctx: any) => { await openFloatTerm(ctx, "fish", []); },
  });
  pi.registerCommand("float-lazygit", {
    description: "打开浮动终端 (lazygit)",
    handler: async (_args: any, ctx: any) => { await openFloatTerm(ctx, "lazygit", []); },
  });
  pi.registerCommand("float-yazi", {
    description: "打开浮动终端 (yazi)",
    handler: async (_args: any, ctx: any) => { await openFloatTerm(ctx, "yazi", []); },
  });
}

效果

浮动终端界面

1
2
3
4
5
6
7
8
9
╭──────────────────────────────────────────────────╮
│  Welcome to fish, the friendly interactive shell  │
│  /home/y/myws/os-config >                         │
│                                                   │
│                                                   │
│                                                   │
│                                                   │
│  Ctrl+Space: close | exit / Ctrl+D: quit shell    │
╰──────────────────────────────────────────────────╯

状态栏提示

1
C-a-f:fish  C-a-y:yazi  C-S-a-g:gcp  C-a-g:lazygit

操作速查

按键效果
Ctrl+Alt+F唤起 fish 浮动终端
Ctrl+Alt+G唤起 lazygit
Ctrl+Alt+Y唤起 yazi 文件管理器
Ctrl+Shift+Alt+G唤起 gcp(conventional commits)
/float-fish命令方式唤起 fish
/float-lazygit命令方式唤起 lazygit
/float-yazi命令方式唤起 yazi
Ctrl+Space强制关闭浮动终端
exit / Ctrl+D正常退出

总结

这次扩展是 pi 插件体系中最复杂的之一,核心挑战在于:

  1. PTY vs Pipe——只有 PTY 才能让交互式 TUI 程序(lazygit、yazi、vim)正常工作,child_process.spawn 的 pipe 模式不行
  2. ANSI 终端模拟器——因为 pi 的 overlay 渲染框架是行数组接口,必须把 PTY 输出重新解析成 Cell 网格再渲染。自己实现一个精简的终端模拟器虽然工作量大,但规避了对 xterm.js 等重型库的依赖
  3. Alternate Screen——全屏 TUI 程序依赖 alternate screen buffer,TermBuffer 的双缓冲机制完整支持了切换和恢复
  4. 反视频渲染——\x1b[7m 在 overlay 叠加场景下有特殊处理,通过手动交换 fg/bg 颜色避免闪烁

结合 bar-cursor 扩展git-changes 扩展,pi 的三个扩展覆盖了光标美化工作区状态终端集成三个维度,全部通过 ~/.pi/agent/extensions/ 目录热加载,配合 NixOS home-manager 管理软链接,配置可追溯、可复现。

TypeScript 扩展的开发体验很好——放到目录就自动加载,/reload 热更新,调试迭代很快。

comments powered by Disqus
Theme Stack