小类随手记

pi 插件:随时查看工作区文件变更(git-changes)

基于 pi 的 overlay + shortcut + 状态栏扩展机制,实现随时按 ctrl+shift+g 浮动查看 git 变更文件列表,支持 Enter 填入路径、e 键 nvim 编辑、y 键复制到剪贴板。

背景

pi 写代码时,AI 经常批量修改文件。时间久了容易忘了改过哪些文件、是否有遗漏。我希望能随时一键查看工作区文件的变更状态——像 git status 但不用切出去、不用手指离开键盘。

之前写过 pi 的 CustomEditor 扩展把光标改成竖线。这次更进一步:利用 pi 的 overlay(浮动框) + shortcut(快捷键) + status bar(状态栏) 三项能力,做了一个完整的 Git 变更查看器。

需求

  1. 随时可看——一键唤起浮动面板,列出所有变更文件
  2. 分类清晰——区分 Staged / Unstaged / Untracked / Conflict
  3. 快速操作——
    • Enter:文件路径填入输入框(交给 AI 处理)
    • e:用 nvim 打开编辑/查看
    • y:复制完整文件路径到系统剪贴板
  4. 无感提示——状态栏常驻显示变更计数,提醒有未提交的改动

实现方法

整体架构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
┌─ pi Extension API ──────────────────────────────────┐
                                                      
  pi.registerCommand("/changes")  ──┐                 
  pi.registerShortcut("ctrl+shift+g") ─┤              
                                                     
               ┌─────────────────────▼──────────────┐ 
                    ctx.ui.custom({ overlay })       
                    GitChangesOverlay                
                                                     
                  render()  带边框的浮动面板        
                  handleInput()  ↑↓ e y Enter Esc  
                  done()  返回 action + file       
               └─────────────────────────────────────┘ 
                                                      
  pi.on("tool_result")    refreshStatus()            
  ctx.ui.setStatus()      footer "git:📝3"           
└──────────────────────────────────────────────────────┘

关键 API

API用途
pi.registerShortcut("ctrl+shift+g", ...)全局快捷键,任何位置一键唤起
ctx.ui.custom(component, { overlay: true })渲染浮动框,叠加在当前 UI 之上
ctx.ui.setStatus(key, text)footer 状态栏常驻显示
ctx.ui.setEditorText(text)将文本放入输入框
pi.exec("git", ["status", "--porcelain"])获取 git 变更(异步,复用 pi 进程管理)
matchesKey(data, Key.escape)TUI 键盘事件匹配(兼容各种终端协议)
truncateToWidth() / visibleWidth()ANSI-aware 字符串截断/宽度计算

浮动框渲染

浮动框使用 Unicode box-drawing 字符绘制边框(╭╮╰╯│─),内部按分类分组渲染:

  • 文件行padToWidth() 补齐到统一宽度,保证右边框对齐
  • 选中行高亮显示( 前缀 + accent 色)
  • 状态标签按类别着色:绿 [+]=staged、黄 [*]=modified、红 [-]=deleted、灰 [?]=untracked
  • 底部提示栏显示全部快捷键

剪贴板:OSC 52

y 键复制文件路径到系统剪贴板不依赖 xclip / wl-copy 等外部工具,而是通过 OSC 52(Operating System Command 52)终端转义序列:

1
2
3
4
function osc52Copy(text: string): void {
  const b64 = Buffer.from(text).toString("base64");
  process.stdout.write(`\x1b]52;c;${b64}\x1b\\`);
}

现代终端(Kitty、Ghostty、WezTerm、Alacritty、Foot、iTerm2)均支持,零依赖、跨平台。

nvim 编辑:spawnSync

e 键通过 Node.js spawnSyncstdio: "inherit" 方式启动 nvim,让 nvim 直接接管终端:

1
2
import { spawnSync } from "node:child_process";
spawnSync("nvim", [file], { stdio: "inherit" });

退出 nvim 后控制权自动回到 pi,TUI 会重绘恢复。

完整代码

放到 ~/.pi/agent/extensions/git-changes.ts,pi 会自动发现并加载。

git-changes.ts (271 行)
  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
/**
 * Git Changes Viewer — 查看工作区修改/新增/删除文件列表
 *
 * 三种访问方式:
 *   /changes          — 浮动 overlay,分类展示 git 变更
 *   ctrl+shift+g      — 快捷键拉起 overlay
 *   footer 状态栏      — 常驻显示变更文件计数
 *
 * 自动发现路径: ~/.pi/agent/extensions/git-changes.ts
 */

import { spawnSync } from "node:child_process";
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
import { Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";

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

type ThemeColor = "success" | "warning" | "error" | "dim" | "muted" | "text" | "accent" | "border";

interface OverlayResult {
  action: "copy" | "edit" | "yank";
  file: string;
}

/** Write text to system clipboard via OSC 52 escape sequence. */
function osc52Copy(text: string): void {
  const b64 = Buffer.from(text).toString("base64");
  process.stdout.write(`\x1b]52;c;${b64}\x1b\\`);
}

interface GitChange {
  status: string; // XY from "git status --porcelain"
  file: string;
  category: "staged" | "unstaged" | "untracked" | "conflict";
}

interface NavItem {
  type: "header" | "file" | "gap";
  tag?: string; // e.g. "[+]" for staged add
  file?: string;
  catLabel?: string; // e.g. "📦 Staged (3)"
  catColor?: ThemeColor;
}

const CATEGORY_META: Record<GitChange["category"], { emoji: string; label: string; color: ThemeColor }> = {
  staged: { emoji: "📦", label: "Staged", color: "success" },
  unstaged: { emoji: "📝", label: "Unstaged", color: "warning" },
  untracked: { emoji: "❓", label: "Untracked", color: "dim" },
  conflict: { emoji: "⚠️", label: "Conflicts", color: "error" },
};

// Map git porcelain XY to display tag
function statusTag(status: string): string {
  const m: Record<string, string> = {
    "M ": "[+]", "A ": "[+]", "D ": "[-]", "R ": "[~]", "C ": "[+]",
    " M": "[*]", " D": "[-]", "??": "[?]", "!!": "[!]",
    AM: "[+]", MM: "[*]", AD: "[!]", UA: "[!]", UU: "[!]",
  };
  if (m[status]) return m[status];
  if (status.includes("U")) return "[!]";
  return `[${status.trim() || " "}]`;
}

// ---------------------------------------------------------------------------
// Git helpers
// ---------------------------------------------------------------------------

function parseGitStatus(output: string): GitChange[] {
  const changes: GitChange[] = [];
  for (const line of output.trim().split("\n")) {
    if (!line) continue;
    const status = line.substring(0, 2);
    const rest = line.substring(3).trim();
    const file = rest.includes(" -> ") ? rest.split(" -> ")[1]! : rest;
    const X = status[0]!;
    const Y = status[1]!;

    let category: GitChange["category"];
    if (X === "?" && Y === "?") category = "untracked";
    else if (X === "U" || Y === "U" || status === "AA" || status === "DD") category = "conflict";
    else if (X !== " " && X !== "?") category = "staged";
    else category = "unstaged";

    changes.push({ status, file, category });
  }
  return changes;
}

async function getGitChanges(pi: ExtensionAPI): Promise<GitChange[] | null> {
  try {
    const result = await pi.exec("git", ["status", "--porcelain"]);
    if (result.code !== 0) return null;
    return parseGitStatus(result.stdout);
  } catch {
    return null;
  }
}

function groupByCategory(changes: GitChange[]): Map<GitChange["category"], GitChange[]> {
  const order: GitChange["category"][] = ["staged", "unstaged", "untracked", "conflict"];
  const map = new Map<GitChange["category"], GitChange[]>();
  for (const cat of order) {
    const group = changes.filter((c) => c.category === cat);
    if (group.length > 0) map.set(cat, group);
  }
  return map;
}

// ---------------------------------------------------------------------------
// Overlay
// ---------------------------------------------------------------------------

/** Pad or truncate a styled string to exactly `width` display columns. */
function padToWidth(styled: string, width: number): string {
  const vis = visibleWidth(styled);
  if (vis >= width) return truncateToWidth(styled, width);
  return styled + " ".repeat(width - vis);
}

class GitChangesOverlay {
  private theme: Theme;
  private done: (v: OverlayResult | null) => void;
  private items: NavItem[];
  private sel = 0;

  private cacheW = -1;
  private cacheLines: string[] | null = null;

  constructor(changes: GitChange[], theme: Theme, done: (v: OverlayResult | null) => void) {
    this.theme = theme;
    this.done = done;

    const grouped = groupByCategory(changes);
    this.items = [];

    for (const [cat, group] of grouped) {
      const meta = CATEGORY_META[cat];
      this.items.push({
        type: "header",
        catLabel: `${meta.emoji} ${meta.label} (${group.length})`,
        catColor: meta.color,
      });
      for (const c of group) {
        this.items.push({
          type: "file",
          tag: statusTag(c.status),
          file: c.file,
          catColor: meta.color,
        });
      }
      this.items.push({ type: "gap" });
    }

    // Start on first file
    this.sel = this.items.findIndex((i) => i.type === "file");
    if (this.sel < 0) this.sel = 0;
  }

  handleInput(data: string): void {
    if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
      this.done(null);
      return;
    }
    const item = this.items[this.sel];
    if (matchesKey(data, Key.enter) || matchesKey(data, Key.return)) {
      if (item?.type === "file" && item.file) this.done({ action: "copy", file: item.file });
      return;
    }
    if (data === "e") {
      if (item?.type === "file" && item.file) this.done({ action: "edit", file: item.file });
      return;
    }
    if (data === "y") {
      if (item?.type === "file" && item.file) this.done({ action: "yank", file: item.file });
      return;
    }
    if (matchesKey(data, Key.up)) {
      for (let i = this.sel - 1; i >= 0; i--) {
        if (this.items[i]!.type === "file") { this.sel = i; this.invalidate(); return; }
      }
    } else if (matchesKey(data, Key.down)) {
      for (let i = this.sel + 1; i < this.items.length; i++) {
        if (this.items[i]!.type === "file") { this.sel = i; this.invalidate(); return; }
      }
    }
  }

  render(width: number): string[] {
    if (this.cacheW === width && this.cacheLines) return this.cacheLines;

    const th = this.theme;
    const w = width;
    const inner = w - 2; // content inside │...│

    const B = (s: string): string => th.fg("border", s);

    const lines: string[] = [];
    lines.push(padToWidth(B(`╭${"─".repeat(inner)}╮`), w));

    for (let i = 0; i < this.items.length; i++) {
      const item = this.items[i]!;
      const sel = i === this.sel;

      if (item.type === "gap") {
        lines.push(padToWidth(B("│") + " ".repeat(inner) + B("│"), w));
        continue;
      }

      if (item.type === "header") {
        const color = item.catColor || "accent";
        const label = item.catLabel || "";
        const body = padToWidth(th.fg(color, th.bold ? th.bold(label) : label), inner);
        lines.push(padToWidth(B("│") + body + B("│"), w));
        continue;
      }

      // File entry
      const marker = sel ? th.fg("accent", "▶ ") : "  ";
      const tag = item.tag || "";
      const fname = item.file || "";
      const tagColor: ThemeColor = item.catColor || "text";
      const fnameColor: ThemeColor = sel ? "accent" : "text";

      const body = marker + th.fg(tagColor, tag) + " " + th.fg(fnameColor, fname);
      lines.push(padToWidth(B("│") + padToWidth(body, inner) + B("│"), w));
    }

    // Footer hint
    const hint = th.fg("dim", "↑↓ move  Enter→editor  e=edit(nvim)  y=yank  Esc=close");
    lines.push(padToWidth(B("│") + padToWidth(hint, inner) + B("│"), w));

    lines.push(padToWidth(B(`╰${"─".repeat(inner)}╯`), w));

    this.cacheW = width;
    this.cacheLines = lines;
    return lines;
  }

  invalidate(): void { this.cacheW = -1; this.cacheLines = null; }
}

// ---------------------------------------------------------------------------
// Status badge
// ---------------------------------------------------------------------------

function buildStatusText(changes: GitChange[]): string {
  if (changes.length === 0) return "";
  const counts: Record<string, number> = {};
  for (const c of changes) counts[c.category] = (counts[c.category] || 0) + 1;

  const parts: string[] = [];
  if (counts.staged) parts.push(`📦${counts.staged}`);
  if (counts.unstaged) parts.push(`📝${counts.unstaged}`);
  if (counts.untracked) parts.push(`❓${counts.untracked}`);
  if (counts.conflict) parts.push(`⚠️${counts.conflict}`);
  return `git:${parts.join("")}`;
}

// ---------------------------------------------------------------------------
// Extension entry point
// ---------------------------------------------------------------------------

export default function (pi: ExtensionAPI) {
  const STATUS_KEY = "git-changes";

  async function refreshStatus(ctx: ExtensionContext) {
    if (!ctx.hasUI) return;
    const changes = await getGitChanges(pi);
    if (changes === null) {
      ctx.ui.setStatus(STATUS_KEY, undefined);
      return;
    }
    const text = buildStatusText(changes);
    if (text) {
      ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme.fg("warning", text + " | ctrl+shift+g"));
    } else {
      ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme.fg("success", "git:✓ | ctrl+shift+g"));
    }
  }

  async function showOverlay(ctx: ExtensionContext) {
    if (!ctx.hasUI) {
      ctx.ui.notify("Git changes viewer requires TUI mode", "warning");
      return;
    }

    const changes = await getGitChanges(pi);
    if (changes === null) {
      ctx.ui.notify("Not a git repository (or git not available)", "warning");
      return;
    }
    if (changes.length === 0) {
      ctx.ui.notify("Working tree clean — no changes", "info");
      return;
    }

    const result = await ctx.ui.custom<OverlayResult | null>((_tui, theme, _kb, done) => {
      const ov = new GitChangesOverlay(changes, theme, done);
      return {
        render: (w: number) => ov.render(w),
        invalidate: () => ov.invalidate(),
        handleInput: (d: string) => ov.handleInput(d),
      };
    }, { overlay: true, overlayOptions: { minWidth: 44, maxHeight: "80%" } });

    if (result) {
      switch (result.action) {
        case "copy":
          ctx.ui.setEditorText(result.file);
          ctx.ui.notify(`→ editor: ${result.file}`, "info");
          break;
        case "edit":
          ctx.ui.notify(`nvim ${result.file}`, "info");
          spawnSync("nvim", [result.file], { stdio: "inherit" });
          break;
        case "yank":
          osc52Copy(result.file);
          ctx.ui.notify(`📋 yanked: ${result.file}`, "info");
          break;
      }
    }
  }

  // /changes command
  pi.registerCommand("changes", {
    description: "Show git working tree changes (modified/added/deleted files)",
    handler: async (_args, ctx) => { await showOverlay(ctx); },
  });

  // ctrl+shift+g shortcut
  pi.registerShortcut("ctrl+shift+g", {
    description: "Show git changes overlay",
    handler: async (ctx) => { await showOverlay(ctx); },
  });

  // Auto-refresh status after file-modifying operations
  pi.on("session_start", async (_e, ctx) => { await refreshStatus(ctx); });
  pi.on("tool_result", async (e, ctx) => {
    if (e.toolName === "bash" || e.toolName === "write" || e.toolName === "edit") {
      await refreshStatus(ctx);
    }
  });
  pi.on("user_bash", async (_e, ctx) => { await refreshStatus(ctx); });
}

效果

浮动框

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
╭───────────────────────────────────────────────╮
│  📦 Staged (2)                                │
│     [+] modules/ai/cfg_pi/extensions/git-c... │
│  ▶ [+] modules/ai/cfg_pi/settings.json        │ ← 当前选中
│                                               │
│  📝 Unstaged (1)                              │
│     [*] flake.nix                             │
│                                               │
│  ❓ Untracked (1)                              │
│     [?] new-script.sh                         │
│                                               │
│  ↑↓ move  Enter→editor  e=edit(nvim)  y=yank  Esc=close
╰───────────────────────────────────────────────╯

状态栏

1
2
git:📦2📝1❓1 | ctrl+shift+g          ← 有变更时(warning 色)
git:✓ | ctrl+shift+g                  ← 干净时(success 色)

操作速查

按键效果
ctrl+shift+g全局唤起浮动框
Enter文件路径填入输入框,交给 AI
envim 打开文件编辑/查看
y复制完整路径到系统剪贴板(OSC 52)
Esc关闭浮动框

总结

这次扩展利用了 pi 的三个扩展能力:

  1. Overlayctx.ui.custom + overlay: true)——浮动框不破坏主 UI 状态,查看完即关
  2. Shortcutpi.registerShortcut)——ctrl+shift+g 与全局键位不冲突(比 ctrl+shift+u preset、ctrl+shift+p plan mode 等默认未占用)
  3. Status barctx.ui.setStatus)——变更计数无感常驻,配合 tool_result 事件自动刷新

结合 bar-cursor 扩展 和 NixOS home-manager 的 activation 脚本软链接管理,pi 的整个配置都是声明式、可追溯的。TypeScript 扩展放到 ~/.pi/agent/extensions/ 目录就自动加载,/reload 热更新,开发体验很流畅。

comments powered by Disqus
Theme Stack