pi-chassis 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +21 -0
  3. package/README.md +51 -2
  4. package/THIRD_PARTY_NOTICES +30 -0
  5. package/dist/chassis/alert.d.ts +50 -0
  6. package/dist/chassis/alert.js +107 -0
  7. package/dist/chassis/api.d.ts +411 -0
  8. package/dist/chassis/api.js +676 -0
  9. package/dist/chassis/bash-output.d.ts +89 -0
  10. package/dist/chassis/bash-output.js +157 -0
  11. package/dist/chassis/brand.d.ts +99 -0
  12. package/dist/chassis/brand.js +79 -0
  13. package/dist/chassis/client.d.ts +87 -0
  14. package/dist/chassis/client.js +271 -0
  15. package/dist/chassis/commands.d.ts +60 -0
  16. package/dist/chassis/commands.js +211 -0
  17. package/dist/chassis/editor.d.ts +70 -0
  18. package/dist/chassis/editor.js +213 -0
  19. package/dist/chassis/footer.d.ts +14 -0
  20. package/dist/chassis/footer.js +136 -0
  21. package/dist/chassis/header.d.ts +12 -0
  22. package/dist/chassis/header.js +38 -0
  23. package/dist/chassis/home.d.ts +48 -0
  24. package/dist/chassis/home.js +184 -0
  25. package/dist/chassis/icons.d.ts +203 -0
  26. package/dist/chassis/icons.js +190 -0
  27. package/dist/chassis/index.d.ts +21 -0
  28. package/dist/chassis/index.js +582 -0
  29. package/dist/chassis/layout.d.ts +40 -0
  30. package/dist/chassis/layout.js +264 -0
  31. package/dist/chassis/message-modes.d.ts +21 -0
  32. package/dist/chassis/message-modes.js +49 -0
  33. package/dist/chassis/messages.d.ts +75 -0
  34. package/dist/chassis/messages.js +392 -0
  35. package/dist/chassis/modes.d.ts +21 -0
  36. package/dist/chassis/modes.js +99 -0
  37. package/dist/chassis/palette.d.ts +84 -0
  38. package/dist/chassis/palette.js +235 -0
  39. package/dist/chassis/peek.d.ts +61 -0
  40. package/dist/chassis/peek.js +156 -0
  41. package/dist/chassis/prompt-row.d.ts +42 -0
  42. package/dist/chassis/prompt-row.js +68 -0
  43. package/dist/chassis/provider-view.d.ts +34 -0
  44. package/dist/chassis/provider-view.js +107 -0
  45. package/dist/chassis/provider.d.ts +69 -0
  46. package/dist/chassis/provider.js +73 -0
  47. package/dist/chassis/readonly-command.d.ts +19 -0
  48. package/dist/chassis/readonly-command.js +454 -0
  49. package/dist/chassis/sanitize.d.ts +42 -0
  50. package/dist/chassis/sanitize.js +103 -0
  51. package/dist/chassis/session-info.d.ts +39 -0
  52. package/dist/chassis/session-info.js +107 -0
  53. package/dist/chassis/sidebar.d.ts +48 -0
  54. package/dist/chassis/sidebar.js +273 -0
  55. package/dist/chassis/state.d.ts +38 -0
  56. package/dist/chassis/state.js +19 -0
  57. package/dist/chassis/telemetry.d.ts +60 -0
  58. package/dist/chassis/telemetry.js +191 -0
  59. package/dist/chassis/tools.d.ts +112 -0
  60. package/dist/chassis/tools.js +588 -0
  61. package/dist/chassis/version.d.ts +2 -0
  62. package/dist/chassis/version.js +20 -0
  63. package/dist/diff/git-diff.d.ts +71 -0
  64. package/dist/diff/git-diff.js +325 -0
  65. package/dist/diff/host.d.ts +34 -0
  66. package/dist/diff/host.js +50 -0
  67. package/dist/diff/index.d.ts +13 -0
  68. package/dist/diff/index.js +86 -0
  69. package/dist/diff/render.d.ts +67 -0
  70. package/dist/diff/render.js +196 -0
  71. package/dist/diff/types.d.ts +60 -0
  72. package/dist/diff/types.js +4 -0
  73. package/dist/diff/view.d.ts +118 -0
  74. package/dist/diff/view.js +528 -0
  75. package/dist/git/flows.d.ts +92 -0
  76. package/dist/git/flows.js +415 -0
  77. package/dist/git/forge.d.ts +26 -0
  78. package/dist/git/forge.js +41 -0
  79. package/dist/git/index.d.ts +20 -0
  80. package/dist/git/index.js +121 -0
  81. package/dist/git/repo.d.ts +64 -0
  82. package/dist/git/repo.js +186 -0
  83. package/dist/git/run.d.ts +38 -0
  84. package/dist/git/run.js +127 -0
  85. package/dist/git/settings.d.ts +8 -0
  86. package/dist/git/settings.js +38 -0
  87. package/dist/git/text.d.ts +51 -0
  88. package/dist/git/text.js +109 -0
  89. package/dist/widgets/container/detect.d.ts +23 -0
  90. package/dist/widgets/container/detect.js +67 -0
  91. package/dist/widgets/container/index.d.ts +9 -0
  92. package/dist/widgets/container/index.js +26 -0
  93. package/dist/widgets/mcp/index.d.ts +13 -0
  94. package/dist/widgets/mcp/index.js +50 -0
  95. package/dist/widgets/mcp/status.d.ts +50 -0
  96. package/dist/widgets/mcp/status.js +70 -0
  97. package/dist/widgets/session-todos/index.d.ts +12 -0
  98. package/dist/widgets/session-todos/index.js +52 -0
  99. package/dist/widgets/subagents/index.d.ts +16 -0
  100. package/dist/widgets/subagents/index.js +173 -0
  101. package/dist/widgets/subagents/status.d.ts +61 -0
  102. package/dist/widgets/subagents/status.js +198 -0
  103. package/dist/widgets/todo/index.d.ts +13 -0
  104. package/dist/widgets/todo/index.js +65 -0
  105. package/dist/widgets/todo/parse.d.ts +29 -0
  106. package/dist/widgets/todo/parse.js +122 -0
  107. package/docs/branding.md +25 -0
  108. package/docs/development.md +22 -0
  109. package/docs/diff-api.md +18 -0
  110. package/docs/git.md +23 -0
  111. package/docs/internals.md +13 -0
  112. package/docs/provider-status.md +23 -0
  113. package/docs/status-widgets.md +157 -0
  114. package/docs/tool-rows.md +50 -0
  115. package/docs/usage.md +62 -0
  116. package/docs/widgets.md +113 -0
  117. package/extensions/chassis/alert.ts +127 -0
  118. package/extensions/chassis/api.ts +967 -0
  119. package/extensions/chassis/bash-output.ts +186 -0
  120. package/extensions/chassis/brand.ts +151 -0
  121. package/extensions/chassis/client.ts +284 -0
  122. package/extensions/chassis/commands.ts +244 -0
  123. package/extensions/chassis/editor.ts +253 -0
  124. package/extensions/chassis/footer.ts +131 -0
  125. package/extensions/chassis/header.ts +43 -0
  126. package/extensions/chassis/home.ts +186 -0
  127. package/extensions/chassis/icons.ts +220 -0
  128. package/extensions/chassis/index.ts +605 -0
  129. package/extensions/chassis/layout.ts +298 -0
  130. package/extensions/chassis/message-modes.ts +48 -0
  131. package/extensions/chassis/messages.ts +403 -0
  132. package/extensions/chassis/modes.ts +108 -0
  133. package/extensions/chassis/palette.ts +258 -0
  134. package/extensions/chassis/peek.ts +167 -0
  135. package/extensions/chassis/prompt-row.ts +86 -0
  136. package/extensions/chassis/provider-view.ts +118 -0
  137. package/extensions/chassis/provider.ts +115 -0
  138. package/extensions/chassis/readonly-command.ts +440 -0
  139. package/extensions/chassis/sanitize.ts +108 -0
  140. package/extensions/chassis/session-info.ts +127 -0
  141. package/extensions/chassis/sidebar.ts +285 -0
  142. package/extensions/chassis/state.ts +50 -0
  143. package/extensions/chassis/telemetry.ts +222 -0
  144. package/extensions/chassis/tools.ts +618 -0
  145. package/extensions/chassis/version.ts +20 -0
  146. package/extensions/diff/git-diff.ts +365 -0
  147. package/extensions/diff/host.ts +58 -0
  148. package/extensions/diff/index.ts +101 -0
  149. package/extensions/diff/render.ts +217 -0
  150. package/extensions/diff/types.ts +67 -0
  151. package/extensions/diff/view.ts +523 -0
  152. package/extensions/git/flows.ts +485 -0
  153. package/extensions/git/forge.ts +54 -0
  154. package/extensions/git/index.ts +117 -0
  155. package/extensions/git/repo.ts +200 -0
  156. package/extensions/git/run.ts +143 -0
  157. package/extensions/git/settings.ts +38 -0
  158. package/extensions/git/text.ts +133 -0
  159. package/extensions/widgets/container/detect.ts +81 -0
  160. package/extensions/widgets/container/index.ts +29 -0
  161. package/extensions/widgets/mcp/index.ts +53 -0
  162. package/extensions/widgets/mcp/status.ts +94 -0
  163. package/extensions/widgets/session-todos/index.ts +55 -0
  164. package/extensions/widgets/subagents/index.ts +170 -0
  165. package/extensions/widgets/subagents/status.ts +237 -0
  166. package/extensions/widgets/todo/index.ts +66 -0
  167. package/extensions/widgets/todo/parse.ts +119 -0
  168. package/package.json +91 -4
  169. package/scripts/link-pi.mjs +76 -0
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Git side of the diff view: parsing unified diff text, and loading the two things the panel can
3
+ * show from a repository.
4
+ *
5
+ * changes everything not yet committed: staged, unstaged and untracked files in one list, with
6
+ * git status's two-letter code for each (`M `, ` M`, `MM`, `??`)
7
+ * branch what the current branch changed since it left its base branch (`main...HEAD`; the
8
+ * base is the remote's default branch, as /pr finds it)
9
+ *
10
+ * All git commands are run with execFile and an argument array, never through a shell, and with
11
+ * --no-optional-locks so looking never blocks the user's own git.
12
+ */
13
+
14
+ import { execFile } from "node:child_process";
15
+ import { lstat, readFile } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ import { compareRef, defaultBranch, remoteName } from "../git/repo.ts";
18
+ import { PLAIN_DIFF } from "../git/run.ts";
19
+
20
+ export interface DiffLine {
21
+ kind: "add" | "del" | "ctx" | "note";
22
+ text: string;
23
+ oldNo?: number;
24
+ newNo?: number;
25
+ }
26
+
27
+ export interface Hunk {
28
+ /** The `@@ -a,b +c,d @@ context` line. */
29
+ header: string;
30
+ lines: DiffLine[];
31
+ /** The hunk's lines exactly as git wrote them, header first. */
32
+ raw: string[];
33
+ }
34
+
35
+ export interface FileDiff {
36
+ path: string;
37
+ oldPath?: string;
38
+ /** Two characters for the file list: git status's XY for changes, "M " style for a branch. */
39
+ code: string;
40
+ status: "A" | "M" | "D" | "R";
41
+ binary: boolean;
42
+ added: number;
43
+ removed: number;
44
+ /** The lines before the first hunk (`diff --git`, `index`, `---`, `+++`). */
45
+ header: string[];
46
+ hunks: Hunk[];
47
+ /** Why there is no text to show (too large, a symlink, unreadable). */
48
+ note?: string;
49
+ }
50
+
51
+ export interface Loaded {
52
+ files: FileDiff[];
53
+ /** A message to show in place of an empty list, or under a full one. */
54
+ note?: string;
55
+ /** A failure to show instead of the list. */
56
+ error?: string;
57
+ /** Dim text next to the source tabs, e.g. "main...HEAD · 3 commits". */
58
+ meta?: string;
59
+ /** What the branch source compares against ("origin/develop"); the Branch tab names it. */
60
+ base?: string;
61
+ }
62
+
63
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;
64
+
65
+ const cleanPath = (p: string): string => p.replace(/\t.*$/, "").replace(/^[ab]\//, "");
66
+
67
+ /**
68
+ * Parse unified diff text (`git diff`, or `diff -u` with `---`/`+++` headers) into files and hunks.
69
+ * A hunk ends when its line counts from the `@@` header are used up, so a blank context line that
70
+ * lost its leading space does not end it early. A line that starts with `@@ ` or `diff --git `
71
+ * ends it too, whatever the counts say: a body line always starts with a space, `+`, `-` or `\`,
72
+ * so this makes a diff with wrong counts (from a hand-built or model-written patch) still split
73
+ * into the right hunks and files.
74
+ */
75
+ export function parseUnifiedDiff(text: string): FileDiff[] {
76
+ const files: FileDiff[] = [];
77
+ const all = text.split("\n");
78
+ if (all[all.length - 1] === "") all.pop();
79
+ let f: FileDiff | undefined;
80
+ let h: Hunk | undefined;
81
+ let oldLeft = 0;
82
+ let newLeft = 0;
83
+ let oldNo = 0;
84
+ let newNo = 0;
85
+ let pendingOld: { path: string; raw: string } | undefined;
86
+ const start = (path: string): FileDiff => {
87
+ const n: FileDiff = { path, code: "M ", status: "M", binary: false, added: 0, removed: 0, header: [], hunks: [] };
88
+ files.push(n);
89
+ return n;
90
+ };
91
+
92
+ for (const line of all) {
93
+ const startsNew = line.startsWith("@@ ") || line.startsWith("diff --git ");
94
+ if (h && f && !startsNew && (oldLeft > 0 || newLeft > 0 || line.startsWith("\\"))) {
95
+ h.raw.push(line);
96
+ if (line.startsWith("\\")) {
97
+ h.lines.push({ kind: "note", text: line.slice(2) });
98
+ continue;
99
+ }
100
+ const c = line[0] ?? " ";
101
+ const body = line.slice(1);
102
+ if (c === "+") {
103
+ h.lines.push({ kind: "add", text: body, newNo: newNo++ });
104
+ newLeft--;
105
+ f.added++;
106
+ } else if (c === "-") {
107
+ h.lines.push({ kind: "del", text: body, oldNo: oldNo++ });
108
+ oldLeft--;
109
+ f.removed++;
110
+ } else {
111
+ h.lines.push({ kind: "ctx", text: body, oldNo: oldNo++, newNo: newNo++ });
112
+ oldLeft--;
113
+ newLeft--;
114
+ }
115
+ continue;
116
+ }
117
+ h = undefined;
118
+
119
+ if (line.startsWith("diff --git ")) {
120
+ const rest = line.slice(11);
121
+ const same = /^a\/(.+) b\/\1$/.exec(rest);
122
+ f = start(same ? same[1]! : (rest.split(" b/").pop() ?? rest));
123
+ f.header.push(line);
124
+ pendingOld = undefined;
125
+ continue;
126
+ }
127
+ const m = HUNK.exec(line);
128
+ if (m) {
129
+ f ??= start("(diff)");
130
+ h = { header: line, lines: [], raw: [line] };
131
+ f.hunks.push(h);
132
+ oldNo = Number(m[1]);
133
+ newNo = Number(m[3]);
134
+ oldLeft = m[2] === undefined ? 1 : Number(m[2]);
135
+ newLeft = m[4] === undefined ? 1 : Number(m[4]);
136
+ continue;
137
+ }
138
+ const inGitHeader = f !== undefined && f.hunks.length === 0 && f.header.length > 0;
139
+ if (line.startsWith("--- ")) {
140
+ if (inGitHeader) f!.header.push(line);
141
+ else pendingOld = { path: cleanPath(line.slice(4)), raw: line };
142
+ continue;
143
+ }
144
+ if (line.startsWith("+++ ")) {
145
+ if (inGitHeader) {
146
+ f!.header.push(line);
147
+ } else {
148
+ const p = cleanPath(line.slice(4));
149
+ f = start(p === "/dev/null" ? (pendingOld?.path ?? "(diff)") : p);
150
+ if (pendingOld) f.header.push(pendingOld.raw);
151
+ f.header.push(line);
152
+ pendingOld = undefined;
153
+ }
154
+ continue;
155
+ }
156
+ if (!f || f.hunks.length > 0) continue;
157
+ f.header.push(line);
158
+ if (line.startsWith("new file mode")) f.status = "A";
159
+ else if (line.startsWith("deleted file mode")) f.status = "D";
160
+ else if (line.startsWith("rename from ")) {
161
+ f.oldPath = line.slice(12);
162
+ f.status = "R";
163
+ } else if (line.startsWith("rename to ")) f.path = line.slice(10);
164
+ else if (line.startsWith("Binary files ") || line.startsWith("GIT binary patch")) f.binary = true;
165
+ }
166
+ for (const file of files) file.code = `${file.status} `;
167
+ return files;
168
+ }
169
+
170
+ // ---- running git -------------------------------------------------------------------------------
171
+
172
+ const TIMEOUT_MS = 10_000;
173
+ const MAX_BUFFER = 32 << 20;
174
+ // PLAIN_DIFF forces the a/ b/ prefixes the parser expects, whatever diff.noprefix or
175
+ // diff.mnemonicPrefix say in the user's config.
176
+ const DIFF_FLAGS = [...PLAIN_DIFF, "-M", "--unified=3"];
177
+
178
+ interface GitResult {
179
+ ok: boolean;
180
+ out: string;
181
+ err: string;
182
+ }
183
+
184
+ function git(args: string[], cwd: string): Promise<GitResult> {
185
+ return new Promise((resolve) => {
186
+ execFile(
187
+ "git",
188
+ ["--no-optional-locks", "-c", "core.quotepath=off", ...args],
189
+ { cwd, timeout: TIMEOUT_MS, maxBuffer: MAX_BUFFER, encoding: "utf8" },
190
+ (err, out, errOut) => {
191
+ const message = err ? (String(errOut ?? "").trim().split("\n")[0] || err.message).slice(0, 200) : "";
192
+ resolve({ ok: !err, out: String(out ?? ""), err: message });
193
+ },
194
+ );
195
+ });
196
+ }
197
+
198
+ async function repoRoot(cwd: string): Promise<{ root: string } | { error: string }> {
199
+ const top = await git(["rev-parse", "--show-toplevel"], cwd);
200
+ if (top.ok) return { root: top.out.trim() };
201
+ return { error: /not a git repository/i.test(top.err) ? "Not a git repository" : top.err || "git failed" };
202
+ }
203
+
204
+ export interface StatusEntry {
205
+ xy: string;
206
+ path: string;
207
+ orig?: string;
208
+ }
209
+
210
+ /** Parse `git status --porcelain=v1 -z`. A rename or copy is followed by its origin as its own entry. */
211
+ export function parseStatus(out: string): StatusEntry[] {
212
+ const parts = out.split("\0");
213
+ const entries: StatusEntry[] = [];
214
+ for (let i = 0; i < parts.length; i++) {
215
+ const p = parts[i]!;
216
+ if (p.length < 4) continue;
217
+ const xy = p.slice(0, 2);
218
+ const entry: StatusEntry = { xy, path: p.slice(3) };
219
+ if (xy[0] === "R" || xy[0] === "C" || xy[1] === "R" || xy[1] === "C") entry.orig = parts[++i];
220
+ entries.push(entry);
221
+ }
222
+ return entries;
223
+ }
224
+
225
+ const statusLetter = (xy: string): FileDiff["status"] => {
226
+ if (xy.includes("R")) return "R";
227
+ if (xy.includes("D")) return "D";
228
+ if (xy.includes("A") || xy === "??") return "A";
229
+ return "M";
230
+ };
231
+
232
+ const MAX_UNTRACKED_FILES = 200;
233
+ const MAX_UNTRACKED_BYTES = 256 * 1024;
234
+
235
+ /** A new file as the diff git would show if it were added: every line an addition. */
236
+ async function untrackedDiff(root: string, path: string): Promise<FileDiff> {
237
+ const header = [`diff --git a/${path} b/${path}`, "new file mode 100644", "--- /dev/null", `+++ b/${path}`];
238
+ const empty = (): FileDiff => {
239
+ const f = parseUnifiedDiff(header.join("\n"))[0]!;
240
+ f.code = "??";
241
+ return f;
242
+ };
243
+ const full = join(root, path);
244
+ try {
245
+ const st = await lstat(full);
246
+ if (!st.isFile()) {
247
+ const f = empty();
248
+ f.note = st.isSymbolicLink() ? "symlink" : "not a regular file";
249
+ return f;
250
+ }
251
+ if (st.size > MAX_UNTRACKED_BYTES) {
252
+ const f = empty();
253
+ f.note = `${Math.round(st.size / 1024)} KB, too large to show`;
254
+ return f;
255
+ }
256
+ const buf = await readFile(full);
257
+ if (buf.subarray(0, 8000).includes(0)) {
258
+ const f = empty();
259
+ f.binary = true;
260
+ return f;
261
+ }
262
+ const text = buf.toString("utf8");
263
+ const lines = text.split("\n");
264
+ const endsWithNewline = text.endsWith("\n");
265
+ if (endsWithNewline) lines.pop();
266
+ if (lines.length === 0) return empty();
267
+ const body = [`@@ -0,0 +1,${lines.length} @@`, ...lines.map((l) => `+${l}`)];
268
+ if (!endsWithNewline) body.push("\");
269
+ const f = parseUnifiedDiff([...header, ...body].join("\n"))[0]!;
270
+ f.code = "??";
271
+ return f;
272
+ } catch {
273
+ const f = empty();
274
+ f.note = "unreadable";
275
+ return f;
276
+ }
277
+ }
278
+
279
+ /** Staged, unstaged and untracked changes in one list, like `git status` with the diffs attached. */
280
+ export async function loadChanges(cwd: string): Promise<Loaded> {
281
+ const repo = await repoRoot(cwd);
282
+ if ("error" in repo) return { files: [], error: repo.error };
283
+ const { root } = repo;
284
+ const [status, head] = await Promise.all([
285
+ git(["status", "--porcelain=v1", "-z", "-uall"], root),
286
+ git(["rev-parse", "--verify", "--quiet", "HEAD"], root),
287
+ ]);
288
+ if (!status.ok) return { files: [], error: status.err || "git status failed" };
289
+
290
+ const byPath = new Map<string, FileDiff>();
291
+ if (head.ok) {
292
+ const d = await git(["diff", "HEAD", ...DIFF_FLAGS], root);
293
+ if (!d.ok) return { files: [], error: d.err || "git diff failed" };
294
+ for (const f of parseUnifiedDiff(d.out)) byPath.set(f.path, f);
295
+ } else {
296
+ // No commits yet: there is no HEAD to compare with, so take the index and the working tree
297
+ // separately. A file in both shows what is staged.
298
+ const [cached, worktree] = await Promise.all([git(["diff", "--cached", ...DIFF_FLAGS], root), git(["diff", ...DIFF_FLAGS], root)]);
299
+ for (const f of parseUnifiedDiff(worktree.out)) byPath.set(f.path, f);
300
+ for (const f of parseUnifiedDiff(cached.out)) byPath.set(f.path, f);
301
+ }
302
+
303
+ const files: FileDiff[] = [];
304
+ const untracked: string[] = [];
305
+ for (const e of parseStatus(status.out)) {
306
+ if (e.xy === "??") {
307
+ untracked.push(e.path);
308
+ continue;
309
+ }
310
+ const f: FileDiff = byPath.get(e.path) ?? {
311
+ path: e.path,
312
+ oldPath: e.orig,
313
+ code: e.xy,
314
+ status: statusLetter(e.xy),
315
+ binary: false,
316
+ added: 0,
317
+ removed: 0,
318
+ header: [],
319
+ hunks: [],
320
+ };
321
+ f.code = e.xy;
322
+ if (e.orig) f.oldPath ??= e.orig;
323
+ files.push(f);
324
+ byPath.delete(e.path);
325
+ }
326
+ for (const f of byPath.values()) {
327
+ f.code = " M";
328
+ files.push(f);
329
+ }
330
+ for (const path of untracked.slice(0, MAX_UNTRACKED_FILES)) files.push(await untrackedDiff(root, path));
331
+ files.sort((a, b) => a.path.localeCompare(b.path));
332
+ const skipped = untracked.length - MAX_UNTRACKED_FILES;
333
+ return { files, note: skipped > 0 ? `${skipped} more untracked files not shown` : undefined };
334
+ }
335
+
336
+ /**
337
+ * The branch to compare against and the ref to compare with, found the way /pr finds its base: the
338
+ * remote's default branch, else main or master on the remote, else main or master here. The
339
+ * remote's copy is preferred over a local one, which may be stale.
340
+ */
341
+ async function findBase(root: string): Promise<{ branch: string; ref: string } | undefined> {
342
+ const remote = (await remoteName(root)) ?? "origin";
343
+ const branch = await defaultBranch(root, remote);
344
+ if (!branch) return undefined;
345
+ const ref = await compareRef(root, remote, branch);
346
+ return ref ? { branch, ref } : undefined;
347
+ }
348
+
349
+ /** What the current branch changed since it left its base: `git diff <base>...HEAD`. */
350
+ export async function loadBranch(cwd: string): Promise<Loaded> {
351
+ const repo = await repoRoot(cwd);
352
+ if ("error" in repo) return { files: [], error: repo.error };
353
+ const { root } = repo;
354
+ if (!(await git(["rev-parse", "--verify", "--quiet", "HEAD"], root)).ok) return { files: [], note: "No commits yet." };
355
+ const base = await findBase(root);
356
+ if (!base) return { files: [], note: "Could not find a base branch to compare against: the remote names no default branch, and there is no main or master." };
357
+ const current = await git(["symbolic-ref", "--short", "-q", "HEAD"], root);
358
+ if (current.ok && current.out.trim() === base.branch) return { files: [], meta: base.ref, base: base.ref, note: `You are on ${base.branch}. Switch to a branch to see how it differs.` };
359
+ const [d, count] = await Promise.all([git(["diff", ...DIFF_FLAGS, `${base.ref}...HEAD`], root), git(["rev-list", "--count", `${base.ref}..HEAD`], root)]);
360
+ if (!d.ok) return { files: [], error: d.err || "git diff failed" };
361
+ const files = parseUnifiedDiff(d.out);
362
+ files.sort((a, b) => a.path.localeCompare(b.path));
363
+ const n = Number(count.out.trim()) || 0;
364
+ return { files, base: base.ref, meta: `${base.ref}...HEAD · ${n} commit${n === 1 ? "" : "s"}`, note: files.length ? undefined : `No changes against ${base.ref}.` };
365
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The diff view's shared store, for other extensions and packages.
3
+ *
4
+ * It lives on globalThis under a registered symbol (pi loads each extension in its own module
5
+ * scope, so a plain module variable would be a separate copy in each). Actions added before the
6
+ * diff view loads are kept and shown once it does; a diff opened while it is not loaded, or is
7
+ * switched off in /widgets, reports that by returning false. So does one that could not be shown:
8
+ * there is no interactive UI, or the view is already open.
9
+ *
10
+ * This file imports only types, so it has no files to bring along; the chassis client re-exports it.
11
+ */
12
+
13
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import type { DiffAction, DiffHost, OpenDiffRequest } from "./types.ts";
15
+
16
+ export const DIFF_API_VERSION = 1;
17
+ const KEY = Symbol.for("pi-chassis/diff");
18
+
19
+ export function diffHost(): DiffHost {
20
+ const g = globalThis as unknown as Record<symbol, DiffHost | undefined>;
21
+ const host = (g[KEY] ??= { apiVersion: DIFF_API_VERSION, actions: [] });
22
+ host.apiVersion = Math.max(host.apiVersion, DIFF_API_VERSION);
23
+ return host;
24
+ }
25
+
26
+ /**
27
+ * Add an entry to the diff view's action menu (`a`). It is run with the file and hunk under the
28
+ * cursor, after the panel has closed. Adding the same id again replaces it. The returned function
29
+ * removes it.
30
+ */
31
+ export function addDiffAction(action: DiffAction): () => void {
32
+ const host = diffHost();
33
+ host.actions = [...host.actions.filter((a) => a.id !== action.id), action];
34
+ return () => {
35
+ host.actions = host.actions.filter((a) => a !== action);
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Open the diff view on the uncommitted git changes (as `/diff` does), with `file` selected when it
41
+ * is among them (a path relative to the session's directory, or absolute). Resolves true once it was
42
+ * shown and closed, and false, without showing anything, when the diff view is not loaded, has been
43
+ * switched off, is already open, or there is no interactive UI.
44
+ */
45
+ export async function openChanges(ctx: ExtensionContext, file?: string): Promise<boolean> {
46
+ const open = diffHost().openChanges;
47
+ return open ? open(ctx, file) : false;
48
+ }
49
+
50
+ /**
51
+ * Show a unified diff in the diff view and resolve true when it closes. Resolves false, without
52
+ * showing anything, when the diff view is not loaded, has been switched off, is already open, or
53
+ * there is no interactive UI.
54
+ */
55
+ export async function openDiff(ctx: ExtensionContext, req: OpenDiffRequest): Promise<boolean> {
56
+ const open = diffHost().open;
57
+ return open ? open(ctx, req) : false;
58
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Git diff view: `/diff` (or ctrl+x d) opens a full-size panel with the changed files on the left
3
+ * and the selected file's diff on the right.
4
+ *
5
+ * /diff everything not yet committed: staged, unstaged and untracked files, one list
6
+ * /diff branch what this branch changed since it left its base branch (main...HEAD)
7
+ *
8
+ * It reads git on open and on `r`, never on a timer. Other extensions can open it with their own
9
+ * diff and add actions to it: see host.ts and client.ts (openDiff, addDiffAction).
10
+ * It is registered as a widget with no slot so `/widgets disable diff` switches it off.
11
+ */
12
+
13
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import { getRegistry, registerWidget } from "../chassis/api.ts";
15
+ import { loadBranch, loadChanges, parseUnifiedDiff } from "./git-diff.ts";
16
+ import { diffHost } from "./host.ts";
17
+ import type { OpenDiffRequest } from "./types.ts";
18
+ import { DiffView, type ViewDeps } from "./view.ts";
19
+
20
+ const ID = "diff";
21
+
22
+ const load: ViewDeps["load"] = (source, cwd) => (source === "branch" ? loadBranch(cwd) : loadChanges(cwd));
23
+
24
+ export default function (pi: ExtensionAPI) {
25
+ const host = diffHost();
26
+ let openNow = false;
27
+
28
+ /** Show the panel and resolve true when it closes; false, with nothing shown, when it is already open or there is no terminal UI. */
29
+ const show = async (ctx: ExtensionContext, opts: { initial?: "changes" | "branch"; file?: string; external?: OpenDiffRequest }): Promise<boolean> => {
30
+ if (openNow) return false;
31
+ if (!ctx.hasUI || ctx.mode !== "tui") return false; // the panel is a custom component: only the terminal UI can draw it
32
+ openNow = true;
33
+ try {
34
+ await ctx.ui.custom<void>(
35
+ (tui, theme, _kb, done) =>
36
+ new DiffView({
37
+ tui,
38
+ theme,
39
+ ctx,
40
+ cwd: opts.external?.cwd ?? ctx.cwd,
41
+ actions: () => diffHost().actions,
42
+ done: () => done(),
43
+ load,
44
+ initial: opts.initial,
45
+ file: opts.file,
46
+ external: opts.external ? { title: opts.external.title, files: parseUnifiedDiff(opts.external.diff) } : undefined,
47
+ }),
48
+ { overlay: true, overlayOptions: { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 } },
49
+ );
50
+ return true;
51
+ } finally {
52
+ openNow = false;
53
+ }
54
+ };
55
+
56
+ const disabled = (): boolean => getRegistry().disabled.has(ID);
57
+
58
+ const open = async (ctx: ExtensionContext, initial?: "changes" | "branch", file?: string): Promise<boolean> => {
59
+ if (disabled()) {
60
+ ctx.ui.notify("The diff view is switched off. /widgets enable diff turns it back on.", "info");
61
+ return false;
62
+ }
63
+ return show(ctx, { initial, file });
64
+ };
65
+
66
+ host.openChanges = (ctx, file) => open(ctx, "changes", file);
67
+
68
+ host.open = async (ctx, req) => (disabled() ? false : show(ctx, { external: req }));
69
+
70
+ registerWidget(pi, {
71
+ id: ID,
72
+ title: "Diff view",
73
+ slots: [], // no sidebar row or footer segment: it exists so /widgets can switch it off
74
+ render: () => undefined,
75
+ actions: [
76
+ { id: "open", label: "Open the diff view", description: "Staged, unstaged and untracked changes", run: async (ctx) => void (await open(ctx)) },
77
+ { id: "branch", label: "Diff this branch against its base", description: "What the branch changed since it left main (or the remote's default branch)", run: async (ctx) => void (await open(ctx, "branch")) },
78
+ ],
79
+ });
80
+
81
+ pi.registerCommand("diff", {
82
+ description: "Git diff view: /diff [branch]",
83
+ getArgumentCompletions: (prefix) => {
84
+ const opts = ["changes", "branch"].filter((o) => o.startsWith(prefix.trim()));
85
+ return opts.length ? opts.map((o) => ({ value: o, label: o })) : null;
86
+ },
87
+ handler: async (args, ctx) => {
88
+ const a = args.trim().toLowerCase();
89
+ if (a && a !== "changes" && a !== "branch") {
90
+ ctx.ui.notify("Usage: /diff [changes|branch]", "warning");
91
+ return;
92
+ }
93
+ await open(ctx, a === "branch" ? "branch" : "changes");
94
+ },
95
+ });
96
+
97
+ pi.on("session_shutdown", async () => {
98
+ host.open = undefined;
99
+ host.openChanges = undefined;
100
+ });
101
+ }