@criogaid/pi-hashline-edit 0.3.1 → 0.5.0

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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -4,103 +4,138 @@ import { initTheme } from "@earendil-works/pi-coding-agent";
4
4
  import { registerFusionCards } from "./fusion-card.ts";
5
5
  import type { ActionFusionProgress } from "./action-fusion.ts";
6
6
 
7
- const theme = { fg: (_color: string, text: string) => text, bg: (_color: string, text: string) => text, bold: (text: string) => text };
8
- const themeKeys = [Symbol.for("@earendil-works/pi-coding-agent:theme"), Symbol.for("@mariozechner/pi-coding-agent:theme")];
7
+ const theme = {
8
+ fg: (_color: string, text: string) => text,
9
+ bg: (_color: string, text: string) => text,
10
+ bold: (text: string) => text,
11
+ };
12
+ const themeKeys = [
13
+ Symbol.for("@earendil-works/pi-coding-agent:theme"),
14
+ Symbol.for("@mariozechner/pi-coding-agent:theme"),
15
+ ];
9
16
  const originalThemes = themeKeys.map((key) => Object.getOwnPropertyDescriptor(globalThis, key));
10
17
  before(() => initTheme("dark"));
11
- after(() => themeKeys.forEach((key, index) => {
12
- const original = originalThemes[index];
13
- if (original) Object.defineProperty(globalThis, key, original);
14
- else Reflect.deleteProperty(globalThis, key);
15
- }));
18
+ after(() =>
19
+ themeKeys.forEach((key, index) => {
20
+ const original = originalThemes[index];
21
+ if (original) Object.defineProperty(globalThis, key, original);
22
+ else Reflect.deleteProperty(globalThis, key);
23
+ }),
24
+ );
16
25
 
17
26
  function harness(entries: any[] = []) {
18
- const renderers = new Map<string, any>();
19
- const handlers = new Map<string, any>();
20
- const backgrounds: string[] = [];
21
- const report = registerFusionCards({
22
- on(event: string, handler: any) { handlers.set(event, handler); },
23
- registerEntryRenderer(type: string, renderer: any) { renderers.set(type, renderer); },
24
- appendEntry(customType: string, data: unknown) { entries.push({ type: "custom", customType, data: structuredClone(data) }); },
25
- } as any);
26
- const restore = (event = "session_start", branch = entries) => handlers.get(event)({}, { sessionManager: { getBranch: () => branch } });
27
- const card = (entry: any, expanded = false) => renderers.get(entry.customType)(entry, { expanded }, {
28
- ...theme, bg: (color: string, text: string) => { backgrounds.push(color); return text; },
29
- });
30
- return { entries, report, restore, card, backgrounds };
27
+ const renderers = new Map<string, any>();
28
+ const handlers = new Map<string, any>();
29
+ const backgrounds: string[] = [];
30
+ const report = registerFusionCards({
31
+ on(event: string, handler: any) {
32
+ handlers.set(event, handler);
33
+ },
34
+ registerEntryRenderer(type: string, renderer: any) {
35
+ renderers.set(type, renderer);
36
+ },
37
+ appendEntry(customType: string, data: unknown) {
38
+ entries.push({ type: "custom", customType, data: structuredClone(data) });
39
+ },
40
+ } as any);
41
+ const restore = (event = "session_start", branch = entries, extra = {}) =>
42
+ handlers.get(event)({}, { sessionManager: { getBranch: () => branch }, ...extra });
43
+ const card = (entry: any, expanded = false) =>
44
+ renderers.get(entry.customType)(
45
+ entry,
46
+ { expanded },
47
+ {
48
+ ...theme,
49
+ bg: (color: string, text: string) => {
50
+ backgrounds.push(color);
51
+ return text;
52
+ },
53
+ },
54
+ );
55
+ return { entries, report, restore, card, backgrounds };
31
56
  }
32
57
 
33
58
  const waiting: ActionFusionProgress = {
34
- toolCallId: "call-1", path: "file.ts", commandText: "npm test", command: "waiting",
35
- publication: "NOT_PUBLISHED", freshness: "unknown", output: "", mutationCompleted: false,
59
+ toolCallId: "call-1",
60
+ path: "file.ts",
61
+ commandText: "npm test",
62
+ command: "waiting",
63
+ publication: "NOT_PUBLISHED",
64
+ freshness: "unknown",
65
+ output: "",
66
+ mutationCompleted: false,
36
67
  };
37
68
 
38
69
  test("one independent card updates live and only persists its endpoints", () => {
39
- const h = harness();
40
- h.report(waiting);
41
- const card = h.card(h.entries[0]);
42
- assert.match(card.render(100).join("\n"), /waiting/);
43
- assert.equal(h.backgrounds.at(-1), "toolPendingBg");
44
- h.report({ ...waiting, command: "running", publication: "PUBLISHED", output: "first test passed" });
45
- assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
46
- assert.equal(h.entries.length, 1);
47
- const output = Array.from({ length: 20 }, (_, i) => `output line ${i}`).join("\n");
48
- h.report({ ...waiting, command: "succeeded", publication: "PUBLISHED", freshness: "changed", output });
49
- assert.equal(h.entries.length, 2);
50
- assert.equal(h.entries[0].data.command, "waiting");
51
- const collapsed = card.render(100).join("\n");
52
- assert.match(collapsed, /succeeded/);
53
- assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
54
- assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
55
- assert.match(collapsed, /output line 19/);
56
- assert.doesNotMatch(collapsed, /output line 0\b/);
57
- assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
70
+ const h = harness();
71
+ h.report(waiting);
72
+ const card = h.card(h.entries[0]);
73
+ assert.match(card.render(100).join("\n"), /waiting/);
74
+ assert.equal(h.backgrounds.at(-1), "toolPendingBg");
75
+ h.report({
76
+ ...waiting,
77
+ command: "running",
78
+ publication: "PUBLISHED",
79
+ output: "first test passed",
80
+ });
81
+ assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
82
+ assert.equal(h.entries.length, 1);
83
+ const output = Array.from({ length: 20 }, (_, i) => `output line ${i}`).join("\n");
84
+ h.report({
85
+ ...waiting,
86
+ command: "succeeded",
87
+ publication: "PUBLISHED",
88
+ freshness: "changed",
89
+ output,
90
+ });
91
+ assert.equal(h.entries.length, 2);
92
+ assert.equal(h.entries[0].data.command, "waiting");
93
+ const collapsed = card.render(100).join("\n");
94
+ assert.match(collapsed, /succeeded/);
95
+ assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
96
+ assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
97
+ assert.match(collapsed, /output line 19/);
98
+ assert.doesNotMatch(collapsed, /output line 0\b/);
99
+ assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
58
100
  });
59
101
 
60
102
  test("session restore uses final snapshots and marks unfinished calls unknown", () => {
61
- const h = harness();
62
- h.report(waiting);
63
- h.report({ ...waiting, command: "failed", publication: "PUBLISHED", output: "Command exited with code 7" });
64
- const resumed = harness(h.entries);
65
- resumed.restore();
66
- assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /failed[\s\S]*Command exited with code 7/);
67
- assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
68
- resumed.restore("session_tree", [h.entries[0]]);
69
- assert.match(resumed.card(h.entries[0]).render(100).join("\n"), /interrupted \(final status unknown\)/);
103
+ const h = harness();
104
+ h.report(waiting);
105
+ h.report({
106
+ ...waiting,
107
+ command: "failed",
108
+ publication: "PUBLISHED",
109
+ output: "Command exited with code 7",
110
+ });
111
+ const resumed = harness(h.entries);
112
+ resumed.restore();
113
+ assert.match(
114
+ resumed.card(h.entries[0]).render(100).join("\n"),
115
+ /failed[\s\S]*Command exited with code 7/,
116
+ );
117
+ assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
118
+ resumed.restore("session_tree", [h.entries[0]]);
119
+ assert.match(
120
+ resumed.card(h.entries[0]).render(100).join("\n"),
121
+ /interrupted \(final status unknown\)/,
122
+ );
70
123
  });
71
124
 
72
125
  test("skips and cancellations stay neutral and restore their own reason", () => {
73
- for (const command of ["skipped", "cancelled"] as const) {
74
- const h = harness();
75
- h.report(waiting);
76
- h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
77
- for (const restored of [false, true]) {
78
- const view = restored ? harness(h.entries) : h;
79
- if (restored) view.restore();
80
- const output = view.card(h.entries[0], true).render(160).join("\n");
81
- assert.match(output, /Not run because the mutation did not complete/);
82
- assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
83
- assert.ok(!view.backgrounds.includes("toolErrorBg"));
84
- assert.ok(!view.backgrounds.includes("toolSuccessBg"));
85
- assert.equal(view.backgrounds.at(-1), "customMessageBg");
86
- }
87
- }
88
- });
89
-
90
- test("legacy snapshots separate known command failures and suppress mutation diagnostics", () => {
91
- for (const command of ["skipped", "failed", "cancelled"] as const) {
92
- const output = command === "skipped"
93
- ? "mutation failed; the command was not run [then_run:skipped]\nNo file changes were published. Command skipped.\nAnchor mismatch: 1 shifted.\nInput-anchor checks"
94
- : `mutation completed; then_run did not complete successfully [then_run:${command === "cancelled" ? "skipped" : "failed"}]\nFile changes are saved. Command ${command}.\nactual command diagnostic`;
95
- const entries = [
96
- { type: "custom", customType: "hashline-then-run", data: waiting },
97
- { type: "custom", customType: "hashline-then-run-result", data: { ...waiting, command, publication: "PUBLISHED", output } },
98
- ];
99
- const h = harness(entries);
100
- h.restore();
101
- const text = h.card(entries[0], true).render(160).join("\n");
102
- assert.doesNotMatch(text, /Anchor mismatch|Input-anchor|publication=|freshness=|File changes are saved|mutation completed/);
103
- assert.match(text, command === "skipped" ? /Command was not run/ : /actual command diagnostic/);
104
- assert.equal(entries[1].data.output, output, "restoring must not rewrite persisted evidence");
105
- }
126
+ for (const command of ["skipped", "cancelled"] as const) {
127
+ const h = harness();
128
+ h.report(waiting);
129
+ h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
130
+ for (const restored of [false, true]) {
131
+ const view = restored ? harness(h.entries) : h;
132
+ if (restored) view.restore();
133
+ const output = view.card(h.entries[0], true).render(160).join("\n");
134
+ assert.match(output, /Not run because the mutation did not complete/);
135
+ assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
136
+ assert.ok(!view.backgrounds.includes("toolErrorBg"));
137
+ assert.ok(!view.backgrounds.includes("toolSuccessBg"));
138
+ assert.equal(view.backgrounds.at(-1), "customMessageBg");
139
+ }
140
+ }
106
141
  });
@@ -1,102 +1,218 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ /**
2
+ * Action Fusion presentation: the mutation card shell that keeps the file
3
+ * result's status independent of the fused command, and the separate
4
+ * transcript card for each then_run command.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
8
+
9
+ import type {
10
+ ExtensionAPI,
11
+ ExtensionContext,
12
+ ToolDefinition,
13
+ } from "@earendil-works/pi-coding-agent";
2
14
  import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
3
- import { Box, Text, type Component } from "@earendil-works/pi-tui";
15
+ import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
16
+ import type { TSchema } from "typebox";
4
17
  import type { ActionFusionProgress } from "./action-fusion.ts";
18
+ import { renderToolError, type MutationRenderState } from "./render.ts";
5
19
 
6
20
  const CARD_TYPE = "hashline-then-run";
7
21
  const RESULT_TYPE = "hashline-then-run-result";
8
22
 
9
- type CommandCardData = Pick<ActionFusionProgress, "toolCallId" | "commandText" | "command" | "output" | "reason"> & { version: 1 };
23
+ type CommandCardData = Pick<
24
+ ActionFusionProgress,
25
+ "toolCallId" | "commandText" | "command" | "output" | "reason"
26
+ >;
10
27
 
11
- function commandCardData({ toolCallId, commandText, command, output, reason }: ActionFusionProgress): CommandCardData {
12
- return { version: 1, toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
28
+ function commandCardData({
29
+ toolCallId,
30
+ commandText,
31
+ command,
32
+ output,
33
+ reason,
34
+ }: ActionFusionProgress): CommandCardData {
35
+ return { toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
13
36
  }
14
37
 
15
38
  /** Render one durable transcript card per fused command without adding model context. */
16
39
  export function registerFusionCards(pi: ExtensionAPI) {
17
- const bash = createBashToolDefinition(process.cwd());
18
- const states = new Map<string, CommandCardData>();
19
- const active = new Set<string>();
40
+ let currentCwd = process.cwd();
41
+ const bash = createBashToolDefinition(process.cwd());
42
+ const states = new Map<string, CommandCardData>();
43
+ const active = new Set<string>();
44
+
45
+ const restore = (ctx: ExtensionContext) => {
46
+ if (ctx.cwd) currentCwd = ctx.cwd;
47
+ states.clear();
48
+ active.clear();
49
+ for (const entry of ctx.sessionManager.getBranch()) {
50
+ if (
51
+ entry.type !== "custom" ||
52
+ (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)
53
+ )
54
+ continue;
55
+ const data = entry.data as ActionFusionProgress | undefined;
56
+ if (
57
+ data &&
58
+ typeof data.toolCallId === "string" &&
59
+ typeof data.commandText === "string" &&
60
+ typeof data.output === "string"
61
+ ) {
62
+ states.set(data.toolCallId, commandCardData(data));
63
+ }
64
+ }
65
+ };
66
+ pi.on("session_start", (_event, ctx) => restore(ctx));
67
+ pi.on("session_tree", (_event, ctx) => restore(ctx));
20
68
 
21
- const restore = (ctx: ExtensionContext) => {
22
- states.clear();
23
- active.clear();
24
- for (const entry of ctx.sessionManager.getBranch()) {
25
- if (entry.type !== "custom" || (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)) continue;
26
- const data = entry.data as (ActionFusionProgress & { version?: number }) | undefined;
27
- if (data && typeof data.toolCallId === "string" && typeof data.commandText === "string" && typeof data.output === "string") {
28
- const restored = commandCardData(data);
29
- // Older snapshots stored the compound error in output. Recover only a known command wrapper.
30
- if (data.version !== 1 && ["skipped", "cancelled", "failed", "timeout"].includes(data.command)) {
31
- const marker = data.command === "cancelled" ? "[then_run:skipped]" : "[then_run:failed]";
32
- const fileState = data.publication === "PUBLISHED" ? "File changes are saved."
33
- : data.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
34
- const prefix = `mutation completed; then_run did not complete successfully ${marker}\n${fileState} Command ${data.command}.\n`;
35
- if (data.command !== "skipped" && data.output.startsWith(prefix)) restored.output = data.output.slice(prefix.length);
36
- else {
37
- restored.output = "";
38
- restored.reason = data.command === "skipped" ? "Command was not run." : "Legacy failure details are available in the original tool result.";
39
- }
40
- }
41
- states.set(data.toolCallId, restored);
42
- }
43
- }
44
- };
45
- pi.on("session_start", (_event, ctx) => restore(ctx));
46
- pi.on("session_tree", (_event, ctx) => restore(ctx));
69
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
70
+ const initial = entry.data;
71
+ if (!initial) return undefined;
72
+ const statusText = new Text("", 0, 0);
73
+ const box = new Box(1, 1);
74
+ let call: Component | undefined;
75
+ let result: Component | undefined;
76
+ const rendererState = { startedAt: undefined, endedAt: undefined, interval: undefined };
77
+ return {
78
+ invalidate: () => box.invalidate(),
79
+ render(width) {
80
+ // Read live state during rendering; native tool updates schedule the repaint.
81
+ const current = states.get(initial.toolCallId) ?? initial;
82
+ const pending = current.command === "waiting" || current.command === "running";
83
+ const interrupted = pending && !active.has(current.toolCallId);
84
+ const status = interrupted ? "interrupted (final status unknown)" : current.command;
85
+ const failed = current.command === "failed" || current.command === "timeout";
86
+ const color =
87
+ pending || current.command === "cancelled"
88
+ ? "warning"
89
+ : failed
90
+ ? "error"
91
+ : current.command === "succeeded"
92
+ ? "success"
93
+ : "dim";
94
+ const background =
95
+ pending && !interrupted
96
+ ? "toolPendingBg"
97
+ : failed
98
+ ? "toolErrorBg"
99
+ : current.command === "succeeded"
100
+ ? "toolSuccessBg"
101
+ : "customMessageBg";
102
+ box.setBgFn((line) => theme.bg(background, line));
103
+ statusText.setText(
104
+ `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`,
105
+ );
106
+ const context = {
107
+ args: { command: current.commandText },
108
+ toolCallId: current.toolCallId,
109
+ cwd: currentCwd,
110
+ state: rendererState,
111
+ invalidate: () => box.invalidate(),
112
+ // Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
113
+ executionStarted: false,
114
+ argsComplete: true,
115
+ isPartial: pending && !interrupted,
116
+ expanded,
117
+ showImages: false,
118
+ isError: failed,
119
+ };
120
+ call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
121
+ box.clear();
122
+ box.addChild(statusText);
123
+ box.addChild(call);
124
+ if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
125
+ if (current.output || current.command === "succeeded" || failed) {
126
+ result = bash.renderResult!(
127
+ { content: [{ type: "text", text: current.output }], details: undefined },
128
+ { expanded, isPartial: context.isPartial },
129
+ theme,
130
+ { ...context, lastComponent: result },
131
+ );
132
+ box.addChild(result);
133
+ }
134
+ return box.render(width);
135
+ },
136
+ };
137
+ });
47
138
 
48
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
49
- const initial = entry.data;
50
- if (!initial) return undefined;
51
- const statusText = new Text("", 0, 0);
52
- const box = new Box(1, 1);
53
- let call: Component | undefined;
54
- let result: Component | undefined;
55
- const rendererState = { startedAt: undefined, endedAt: undefined, interval: undefined };
56
- return {
57
- invalidate: () => box.invalidate(),
58
- render(width) {
59
- // Read live state during rendering; native tool updates schedule the repaint.
60
- const current = states.get(initial.toolCallId) ?? initial;
61
- const pending = current.command === "waiting" || current.command === "running";
62
- const interrupted = pending && !active.has(current.toolCallId);
63
- const status = interrupted ? "interrupted (final status unknown)" : current.command;
64
- const failed = current.command === "failed" || current.command === "timeout";
65
- const color = pending || current.command === "cancelled" ? "warning" : failed ? "error" : current.command === "succeeded" ? "success" : "dim";
66
- const background = pending && !interrupted ? "toolPendingBg" : failed ? "toolErrorBg" : current.command === "succeeded" ? "toolSuccessBg" : "customMessageBg";
67
- box.setBgFn((line) => theme.bg(background, line));
68
- statusText.setText(`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`);
69
- const context = {
70
- args: { command: current.commandText }, toolCallId: current.toolCallId, cwd: process.cwd(),
71
- state: rendererState, invalidate: () => box.invalidate(),
72
- // Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
73
- executionStarted: false, argsComplete: true, isPartial: pending && !interrupted, expanded, showImages: false,
74
- isError: failed,
75
- };
76
- call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
77
- box.clear();
78
- box.addChild(statusText);
79
- box.addChild(call);
80
- if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
81
- if (current.output || current.command === "succeeded" || failed) {
82
- result = bash.renderResult!({ content: [{ type: "text", text: current.output }], details: undefined },
83
- { expanded, isPartial: context.isPartial }, theme, { ...context, lastComponent: result });
84
- box.addChild(result);
85
- }
86
- return box.render(width);
87
- },
88
- };
89
- });
139
+ return (progress: ActionFusionProgress, ctx?: ExtensionContext) => {
140
+ if (ctx?.cwd) currentCwd = ctx.cwd;
141
+ const first = !states.has(progress.toolCallId);
142
+ const data = commandCardData(progress);
143
+ states.set(progress.toolCallId, data);
144
+ const pending = progress.command === "waiting" || progress.command === "running";
145
+ if (pending) active.add(progress.toolCallId);
146
+ else active.delete(progress.toolCallId);
147
+ // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
148
+ if (first) pi.appendEntry(CARD_TYPE, data);
149
+ if (!pending) pi.appendEntry(RESULT_TYPE, data);
150
+ };
151
+ }
152
+
153
+ /** Mutation render state plus the shell that keeps the card status independent of then_run. */
154
+ interface FusedMutationRenderState extends MutationRenderState {
155
+ mutationShell?: {
156
+ box: Box;
157
+ call?: Component;
158
+ result?: Component;
159
+ fileState?: { freshness?: string };
160
+ };
161
+ }
90
162
 
91
- return (progress: ActionFusionProgress) => {
92
- const first = !states.has(progress.toolCallId);
93
- const data = commandCardData(progress);
94
- states.set(progress.toolCallId, data);
95
- const pending = progress.command === "waiting" || progress.command === "running";
96
- if (pending) active.add(progress.toolCallId);
97
- else active.delete(progress.toolCallId);
98
- // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
99
- if (first) pi.appendEntry(CARD_TYPE, data);
100
- if (!pending) pi.appendEntry(RESULT_TYPE, data);
101
- };
163
+ /** Keep the mutation card's background independent of the fused command's lifetime. */
164
+ export function withMutationStatus<TParams extends TSchema, TDetails>(
165
+ tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
166
+ ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
167
+ return {
168
+ ...tool,
169
+ renderShell: "self",
170
+ renderCall(args, theme, context) {
171
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
172
+ shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
173
+ shell.box.clear();
174
+ shell.box.addChild(shell.call);
175
+ shell.box.setBgFn((line: string) =>
176
+ theme.bg(
177
+ context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
178
+ line,
179
+ ),
180
+ );
181
+ return shell.box;
182
+ },
183
+ renderResult(result, options, theme, context) {
184
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
185
+ const details = result.details as
186
+ | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
187
+ | undefined;
188
+ const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
189
+ // Fused errors retain combined details for the model; show the mutation's summary here.
190
+ const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
191
+ shell.result = fusedError
192
+ ? renderToolError(result, theme)
193
+ : tool.renderResult!(result, { ...options, isPartial }, theme, {
194
+ ...context,
195
+ isPartial,
196
+ lastComponent: shell.result,
197
+ });
198
+ // Pi runs renderCall first; update its box in place without invalidating the tool row.
199
+ shell.box.addChild(shell.result);
200
+ const file = details?.actionFusion ?? shell.fileState;
201
+ if (file) {
202
+ shell.fileState = { freshness: file.freshness };
203
+ if (file.freshness === "changed" || file.freshness === "missing") {
204
+ shell.box.addChild(
205
+ new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
206
+ );
207
+ }
208
+ }
209
+ shell.box.setBgFn((line: string) =>
210
+ theme.bg(
211
+ isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
212
+ line,
213
+ ),
214
+ );
215
+ return new Container();
216
+ },
217
+ };
102
218
  }