Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

simplify refinement and compaction notices (#2179)

ktfc782b8a4318
diff --git a/packages/coding-agent/.changes/compact-refinement-compaction.md b/packages/coding-agent/.changes/compact-refinement-compaction.md
new file mode 100644
index 0000000000..87c3e138b4
--- /dev/null
+++ b/packages/coding-agent/.changes/compact-refinement-compaction.md
@@ -0,0 +1,4 @@
+- Changed refinement notices to show a spaced purple status line and softer semantic summary in overview and details, with full change counts and diffs in all output.
+- Added expandable Title and Description diffs with the same red and green backgrounds as file edits, preserving other fields and failure details.
+- Changed successful compaction notices to show a purple Context compacted header and softer summary preview, with the full summary and token/focus metadata in all output.
+- Fixed refinement notices to stay purple across themes and avoid extra blank lines before following prose.
diff --git a/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts b/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts
index 8772901833..1f2885df80 100644
--- a/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts
@@ -1,4 +1,4 @@
-import { Box, Container, Text } from "@earendil-works/pi-tui";
+import { Container, Spacer, Text } from "@earendil-works/pi-tui";
import type { CompactionOutcomeMessage } from "../../../core/messages.js";
import { theme } from "../theme/theme.js";
@@ -7,9 +7,8 @@ export class CompactionOutcomeMessageComponent extends Container {
constructor(message: CompactionOutcomeMessage) {
super();
const color = message.details.outcome === "skipped" ? "warning" : "error";
- const contentBox = new Box(2, 1, (text: string) => theme.getUserMessageBackgroundColor()(text));
- contentBox.addChild(new Text(theme.fg(color, message.content), 0, 0));
- this.addChild(contentBox);
+ this.addChild(new Spacer(1));
+ this.addChild(new Text(theme.fg(color, message.content), 1, 0));
}
setExpanded(_expanded: boolean): void {}
@@ -18,9 +17,8 @@ export class CompactionOutcomeMessageComponent extends Container {
export class MalformedCompactionOutcomeMessageComponent extends Container {
constructor() {
super();
- const contentBox = new Box(2, 1, (text: string) => theme.getUserMessageBackgroundColor()(text));
- contentBox.addChild(new Text(theme.fg("error", "[Malformed compaction outcome message]"), 0, 0));
- this.addChild(contentBox);
+ this.addChild(new Spacer(1));
+ this.addChild(new Text(theme.fg("error", "[Malformed compaction outcome message]"), 1, 0));
}
setExpanded(_expanded: boolean): void {}
diff --git a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts
index 653dbfa22b..cdeb3bf9d0 100644
--- a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts
@@ -1,11 +1,10 @@
import { Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";
import type { CompactionSummaryMessage } from "../../../core/messages.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
-import { customMessageLabel, ExpandableCustomMessageBox } from "./expandable-custom-message.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
+import { ExpandableEventMessage } from "./expandable-event-message.js";
-/** Compaction summary card: full markdown summary when expanded. */
-export class CompactionSummaryMessageComponent extends ExpandableCustomMessageBox {
+/** Compact context outcome with the full markdown summary available on demand. */
+export class CompactionSummaryMessageComponent extends ExpandableEventMessage {
constructor(
private readonly message: CompactionSummaryMessage,
private readonly markdownTheme: MarkdownTheme = getMarkdownTheme(),
@@ -16,32 +15,25 @@ export class CompactionSummaryMessageComponent extends ExpandableCustomMessageBo
protected updateDisplay(): void {
this.clear();
+ this.addChild(new Text(theme.fg("refinementHeader", "◆ Context compacted"), 1, 0));
+ const summary = this.message.summary.trim()
+ ? this.message.summary
+ : "No summary was recorded for this compaction.";
+ if (!this.expanded) {
+ this.addSummary(summary, undefined, "refinementSummary");
+ return;
+ }
- const tokenStr = this.message.tokensBefore.toLocaleString();
- const label = customMessageLabel("compaction");
- this.addChild(new Text(label, 0, 0));
- this.addChild(new Spacer(1));
+ this.addChild(
+ new Markdown(summary, 1, 0, this.markdownTheme, {
+ color: (text: string) => theme.fg("refinementSummary", text),
+ }),
+ );
+ const tokenStr = this.message.tokensBefore.toLocaleString();
const instructions = this.message.customInstructions;
- if (this.expanded) {
- let header = `**Compacted from ${tokenStr} tokens**\n\n`;
- if (instructions) {
- header += `**Focus:** ${instructions}\n\n`;
- }
- this.addChild(
- new Markdown(header + this.message.summary, 0, 0, this.markdownTheme, {
- color: (text: string) => theme.fg("customMessageText", text),
- }),
- );
- } else {
- const focus = instructions ? ` · focus: ${instructions}` : "";
- this.addChild(
- new Text(
- `${theme.fg("customMessageText", `Compacted from ${tokenStr} tokens${focus}`)} ${expandCollapseHint("app.tools.expand", false)}`,
- 0,
- 0,
- ),
- );
- }
+ const focus = instructions ? ` · focus: ${instructions}` : "";
+ this.addChild(new Spacer(1));
+ this.addChild(new Text(theme.fg("dim", `Compacted from ${tokenStr} tokens${focus}`), 1, 0));
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
index 26e7008825..e4075bb4be 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -155,6 +155,7 @@ export function buildConversationComponents(
? new RefinementOutcomeMessageComponent(message)
: new MalformedRefinementOutcomeMessageComponent();
component.setExpanded(expanded);
+ if (component instanceof RefinementOutcomeMessageComponent) component.setEditDiffsExpanded(editDiffsExpanded);
components.push(component);
} else if (isAgentSessionMessage(message) && message.display) {
const component = new AgentMessageComponent(message, options.markdownTheme, {
diff --git a/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts b/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts
new file mode 100644
index 0000000000..e632a4eed8
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts
@@ -0,0 +1,48 @@
+import { type Component, Container, Text, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
+import { type ThemeColor, theme } from "../theme/theme.js";
+
+class EventSummary implements Component {
+ constructor(
+ private readonly summary: string,
+ private readonly expanded: boolean,
+ private readonly color: ThemeColor,
+ ) {}
+
+ render(width: number): string[] {
+ if (width < 1) return [];
+ const text = this.expanded ? this.summary : this.summary.replace(/\s+/g, " ").trim();
+ // Keep the standard one-column chat inset on every summary line.
+ const contentWidth = Math.max(1, width - 1);
+ const lines = wrapTextWithAnsi(text, contentWidth);
+ if (!this.expanded && lines.length > 2) {
+ lines.splice(2);
+ lines[1] = truncateToWidth(`${lines[1]} …`, contentWidth, "…");
+ }
+ return lines.map((line) => theme.fg(this.color, ` ${line}`));
+ }
+
+ invalidate(): void {}
+}
+
+/** Compact outcome first, with quiet metadata and the existing details toggle. */
+export abstract class ExpandableEventMessage extends Container {
+ protected expanded = false;
+
+ setExpanded(expanded: boolean): void {
+ if (this.expanded === expanded) return;
+ this.expanded = expanded;
+ this.updateDisplay();
+ }
+
+ override invalidate(): void {
+ super.invalidate();
+ this.updateDisplay();
+ }
+
+ protected addSummary(summary: string, metadata?: string, color: ThemeColor = "customMessageText"): void {
+ this.addChild(new EventSummary(summary, this.expanded, color));
+ if (metadata) this.addChild(new Text(theme.fg("dim", metadata), 1, 0));
+ }
+
+ protected abstract updateDisplay(): void;
+}
diff --git a/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts b/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts
index 8b65e1bf02..350df9b0f1 100644
--- a/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts
@@ -1,42 +1,29 @@
-import { type Component, Spacer, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
+import { type Component, Spacer, Text } from "@earendil-works/pi-tui";
import type { RefinementOutcomeMessage } from "../../../core/messages.js";
import type { AppliedRefinementEdit, HarnessEntry } from "../../../core/refinement/refinement.js";
import { generateDiffString } from "../../../core/tools/edit-diff.js";
import { theme } from "../theme/theme.js";
-import { renderDiff } from "./diff.js";
-import { customMessageLabel, ExpandableCustomMessageBox } from "./expandable-custom-message.js";
-import { expandCollapseHint } from "./keybinding-hints.js";
-
-function editableEntry(entry: HarnessEntry): Record<string, unknown> {
- return {
- title: entry.title,
- content: entry.content,
- path: entry.path,
- reference: entry.reference,
- arguments: entry.arguments,
- metadata: entry.metadata,
- };
-}
-
-function proposedEntry(edit: AppliedRefinementEdit): Record<string, unknown> {
- return {
- ...(edit.title === undefined ? {} : { title: edit.title }),
- ...(edit.content === undefined ? {} : { content: edit.content }),
- ...(edit.path === undefined ? {} : { path: edit.path }),
- ...(edit.reference === undefined ? {} : { reference: edit.reference }),
- ...(edit.arguments === undefined ? {} : { arguments: edit.arguments }),
- ...(edit.metadata === undefined ? {} : { metadata: edit.metadata }),
- };
-}
-
-function entryText(entry: Record<string, unknown> | undefined): string {
- return entry === undefined ? "" : `${JSON.stringify(entry, null, 2)}\n`;
-}
-
-function editDiff(edit: AppliedRefinementEdit): string {
- const before = edit.before ? editableEntry(edit.before) : undefined;
- const after = edit.after ? editableEntry(edit.after) : edit.action === "delete" ? undefined : proposedEntry(edit);
- return generateDiffString(entryText(before), entryText(after), 4).diff;
+import { renderRichDiff } from "./diff.js";
+import { ExpandableEventMessage } from "./expandable-event-message.js";
+
+type EditFieldKey = (typeof EDIT_FIELDS)[number]["key"];
+
+/** Editable harness entry fields shown per edit, in display order. */
+const EDIT_FIELDS = [
+ { key: "title", label: "Title" },
+ { key: "content", label: "Description" },
+ { key: "path", label: "Path" },
+ { key: "reference", label: "Reference" },
+ { key: "arguments", label: "Arguments" },
+ { key: "metadata", label: "Metadata" },
+] as const;
+
+interface EditFieldRows {
+ label: string;
+ /** Rendered value lines; empty values produce no rows. */
+ value: string[];
+ /** Changed fields render -/+ rows instead of a plain value. */
+ change?: { removed: string[]; added: string[] };
}
function editScope(edit: AppliedRefinementEdit, fallback: "local" | "global"): "local" | "global" {
@@ -53,58 +40,190 @@ function editLabel(edit: AppliedRefinementEdit, fallbackScope: "local" | "global
return `${theme.fg("success", verb)} ${scope} ${edit.kind} \`${edit.id}\``;
}
-function editCount(edits: AppliedRefinementEdit[]): string {
- const applied = edits.filter((edit) => edit.applied).length;
- return edits.length === applied
- ? `${applied} edit${applied === 1 ? "" : "s"} applied`
- : `${applied}/${edits.length} edits applied`;
+function refinementHeader(message: RefinementOutcomeMessage): string {
+ const { edits, rollbackOf } = message.details;
+ const applied = edits.filter((edit) => edit.applied);
+ const operation = rollbackOf ? "Harness rollback" : "Harness refinement";
+ if (edits.length === 0)
+ return `${rollbackOf ? "Harness rollback unchanged" : "Harness unchanged"} · no edits applied`;
+ if (applied.length === 0) return `${operation} failed · 0/${edits.length} edits applied`;
+ if (applied.length < edits.length) {
+ return `${rollbackOf ? "Harness partially rolled back" : "Harness partially refined"} · ${applied.length}/${edits.length} edits applied`;
+ }
+ if (rollbackOf)
+ return `Harness rollback completed · ${applied.length} edit${applied.length === 1 ? "" : "s"} applied`;
+ const first = applied[0]!;
+ if (applied.every((edit) => edit.kind === first.kind)) {
+ const kind =
+ first.kind === "memory"
+ ? applied.length === 1
+ ? "memory"
+ : "memories"
+ : `${first.kind}${applied.length === 1 ? "" : "s"}`;
+ const action = applied.every((edit) => edit.action === first.action)
+ ? { create: "created", update: "updated", delete: "deleted" }[first.action]
+ : "changed";
+ return `Harness refined · ${applied.length} ${kind} ${action}`;
+ }
+ return `Harness refined · ${applied.length} edits applied`;
+}
+
+function fieldValueLines(value: unknown): string[] {
+ if (typeof value === "string") {
+ return value.length === 0 ? [] : value.split("\n");
+ }
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ return [];
+ }
+ return Object.keys(value).length === 0 ? [] : [JSON.stringify(value)];
+}
+
+function proposedRecord(edit: AppliedRefinementEdit): Record<string, unknown> {
+ const proposed: Record<string, unknown> = {};
+ for (const { key } of EDIT_FIELDS) {
+ if (edit[key] !== undefined) {
+ proposed[key] = edit[key];
+ }
+ }
+ return proposed;
+}
+
+function entryFieldRows(entry: Partial<Record<EditFieldKey, unknown>> | undefined): EditFieldRows[] {
+ if (!entry) {
+ return [];
+ }
+ const rows: EditFieldRows[] = [];
+ for (const { key, label } of EDIT_FIELDS) {
+ const value = fieldValueLines(entry[key]);
+ if (value.length > 0) {
+ rows.push({ label, value });
+ }
+ }
+ return rows;
+}
+
+/** Update edits show one plain row per unchanged field and -/+ rows for changed ones. */
+function updateFieldRows(before: HarnessEntry, after: HarnessEntry): EditFieldRows[] {
+ const rows: EditFieldRows[] = [];
+ for (const { key, label } of EDIT_FIELDS) {
+ const removed = fieldValueLines(before[key]);
+ const added = fieldValueLines(after[key]);
+ if (removed.length === 0 && added.length === 0) {
+ continue;
+ }
+ if (removed.join("\n") === added.join("\n")) {
+ rows.push({ label, value: added });
+ continue;
+ }
+ rows.push({ label, value: [], change: { removed, added } });
+ }
+ return rows;
}
-/** Width-aware collapsed line: truncates the summary so the line never wraps. */
-class CollapsedOutcomeLine implements Component {
+function editFieldRows(edit: AppliedRefinementEdit): EditFieldRows[] {
+ if (!edit.applied) {
+ const proposed = entryFieldRows(edit.after ?? proposedRecord(edit));
+ if (!edit.before) return proposed;
+ return [
+ ...entryFieldRows(edit.before).map((field) => ({ ...field, label: `Before ${field.label}` })),
+ ...proposed.map((field) => ({ ...field, label: `Proposed ${field.label}` })),
+ ];
+ }
+ if (edit.before && edit.after) {
+ return updateFieldRows(edit.before, edit.after);
+ }
+ const fields = entryFieldRows(edit.after ?? edit.before ?? proposedRecord(edit));
+ if (edit.action === "update") return fields;
+ return fields.map((field) => ({
+ label: field.label,
+ value: [],
+ change: {
+ removed: edit.action === "delete" ? field.value : [],
+ added: edit.action === "create" ? field.value : [],
+ },
+ }));
+}
+
+/** Expanded fields share the same line gutters and background blocks as file edits. */
+class RefinementEditSection implements Component {
constructor(
- private readonly summary: string,
- private readonly suffix: string,
+ private readonly label: string,
+ private readonly fields: EditFieldRows[] = [],
) {}
+ invalidate(): void {}
+
render(width: number): string[] {
- const room = Math.max(20, width - visibleWidth(this.suffix) - 1);
- const line = `${theme.fg("customMessageText", truncateToWidth(this.summary, room, "…"))} ${this.suffix}`;
- return [truncateToWidth(line, Math.max(1, width), "")];
+ if (width < 1) return [];
+ const lines = new Text(this.label, 1, 0).render(width);
+ for (const field of this.fields) {
+ lines.push(...new Text(theme.fg("muted", field.label), 1, 0).render(width));
+ if (field.change) {
+ const { diff } = generateDiffString(
+ field.change.removed.join("\n"),
+ field.change.added.join("\n"),
+ Number.MAX_SAFE_INTEGER,
+ );
+ const inset = width > 1 ? " " : "";
+ for (const row of renderRichDiff(diff, width - inset.length)) lines.push(`${inset}${row}`);
+ } else {
+ for (const row of new Text(field.value.join("\n"), 1, 0).render(width)) lines.push(row);
+ }
+ }
+ return lines;
}
-
- invalidate(): void {}
}
-/** Durable refinement outcome card: per-edit rows with before/after diffs when expanded. */
-export class RefinementOutcomeMessageComponent extends ExpandableCustomMessageBox {
+/** Durable refinement outcome with per-edit details available on demand. */
+export class RefinementOutcomeMessageComponent extends ExpandableEventMessage {
+ private summaryExpanded = false;
constructor(private readonly message: RefinementOutcomeMessage) {
super();
this.updateDisplay();
}
+ setEditDiffsExpanded(expanded: boolean): void {
+ if (this.summaryExpanded === expanded) return;
+ this.summaryExpanded = expanded;
+ this.updateDisplay();
+ }
+
protected updateDisplay(): void {
this.clear();
- const { summary, edits, scope } = this.message.details;
- this.addChild(new Text(customMessageLabel("refinement"), 0, 0));
+ const { summary, edits, scope, rollbackOf, refinementId } = this.message.details;
this.addChild(new Spacer(1));
- if (!this.expanded) {
- const suffix = `${theme.fg("customMessageText", `· ${editCount(edits)}`)} ${expandCollapseHint("app.tools.expand", false)}`;
- this.addChild(new CollapsedOutcomeLine(summary, suffix));
- return;
- }
-
- this.addChild(new Text(theme.fg("customMessageText", `${summary} · ${editCount(edits)}`), 0, 0));
- for (const edit of edits) {
- this.addChild(new Text(`${theme.fg("dim", " ╰─ ")}${editLabel(edit, scope)}`, 0, 0));
- const diff = editDiff(edit);
- if (diff) this.addChild(new Text(renderDiff(diff), 4, 0));
+ const outcome = refinementHeader(this.message);
+ const header = outcome.startsWith("Harness refined ·") ? "Harness refined" : outcome;
+ this.addChild(new Text(theme.fg("refinementHeader", `◆ ${header}`), 1, 0));
+ this.addSummary(
+ summary.trim() || "No summary was recorded for this harness change.",
+ undefined,
+ "refinementSummary",
+ );
+ if (this.expanded) {
+ this.addChild(new Spacer(1));
+ this.addChild(
+ new Text(
+ theme.fg(
+ "dim",
+ `${outcome} · Refinement ${refinementId} · ${scope}${rollbackOf ? ` · rollback of ${rollbackOf}` : ""}`,
+ ),
+ 1,
+ 0,
+ ),
+ );
+
+ for (const edit of edits) {
+ this.addChild(new Spacer(1));
+ this.addChild(new RefinementEditSection(editLabel(edit, scope), editFieldRows(edit)));
+ if (edit.reason) this.addChild(new Text(theme.fg("muted", `Reason: ${edit.reason}`), 1, 0));
+ }
}
}
}
-export class MalformedRefinementOutcomeMessageComponent extends ExpandableCustomMessageBox {
+export class MalformedRefinementOutcomeMessageComponent extends ExpandableEventMessage {
constructor() {
super();
this.updateDisplay();
@@ -112,6 +231,7 @@ export class MalformedRefinementOutcomeMessageComponent extends ExpandableCustom
protected updateDisplay(): void {
this.clear();
- this.addChild(new Text(theme.fg("error", "[Malformed refinement outcome message]"), 0, 0));
+ this.addChild(new Spacer(1));
+ this.addChild(new Text(theme.fg("error", "[Malformed refinement outcome message]"), 1, 0));
}
}
diff --git a/packages/coding-agent/src/modes/interactive/theme/dark.json b/packages/coding-agent/src/modes/interactive/theme/dark.json
index 342efc81b7..06b4788d0f 100644
--- a/packages/coding-agent/src/modes/interactive/theme/dark.json
+++ b/packages/coding-agent/src/modes/interactive/theme/dark.json
@@ -39,6 +39,8 @@
"customMessageBg": "customMsgBg",
"customMessageText": "",
"customMessageLabel": "#9575cd",
+ "refinementHeader": "#9575cd",
+ "refinementSummary": "#b7a1d6",
"toolPendingBg": "toolPendingBg",
"toolSuccessBg": "toolSuccessBg",
"toolErrorBg": "toolErrorBg",
diff --git a/packages/coding-agent/src/modes/interactive/theme/light.json b/packages/coding-agent/src/modes/interactive/theme/light.json
index fa75668844..16479d2b2a 100644
--- a/packages/coding-agent/src/modes/interactive/theme/light.json
+++ b/packages/coding-agent/src/modes/interactive/theme/light.json
@@ -38,6 +38,8 @@
"customMessageBg": "customMsgBg",
"customMessageText": "",
"customMessageLabel": "#7e57c2",
+ "refinementHeader": "#7146ab",
+ "refinementSummary": "#8a70ad",
"toolPendingBg": "toolPendingBg",
"toolSuccessBg": "toolSuccessBg",
"toolErrorBg": "toolErrorBg",
diff --git a/packages/coding-agent/src/modes/interactive/theme/prime.json b/packages/coding-agent/src/modes/interactive/theme/prime.json
index 9234278279..843597d49f 100644
--- a/packages/coding-agent/src/modes/interactive/theme/prime.json
+++ b/packages/coding-agent/src/modes/interactive/theme/prime.json
@@ -45,6 +45,8 @@
"customMessageBg": "customMsgBg",
"customMessageText": "",
"customMessageLabel": "warning",
+ "refinementHeader": "#9575cd",
+ "refinementSummary": "#b7a1d6",
"toolPendingBg": "toolPendingBg",
"toolSuccessBg": "toolSuccessBg",
"toolErrorBg": "toolErrorBg",
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme-schema.json b/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
index 93931797f6..46b1e8f7ac 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
+++ b/packages/coding-agent/src/modes/interactive/theme/theme-schema.json
@@ -33,7 +33,7 @@
},
"colors": {
"type": "object",
- "description": "Theme color definitions (all required)",
+ "description": "Theme color definitions (refinement colors have purple defaults)",
"required": [
"accent",
"border",
@@ -160,6 +160,14 @@
"$ref": "#/$defs/colorValue",
"description": "Custom message type label color"
},
+ "refinementHeader": {
+ "$ref": "#/$defs/colorValue",
+ "description": "Harness refinement status (defaults to purple)"
+ },
+ "refinementSummary": {
+ "$ref": "#/$defs/colorValue",
+ "description": "Harness refinement semantic summary (defaults to softer purple)"
+ },
"toolPendingBg": {
"$ref": "#/$defs/colorValue",
"description": "Tool execution box (pending state)"
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme.ts b/packages/coding-agent/src/modes/interactive/theme/theme.ts
index dd4a48f7f7..10a9c6f257 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme.ts
+++ b/packages/coding-agent/src/modes/interactive/theme/theme.ts
@@ -55,6 +55,8 @@ const ThemeJsonSchema = Type.Object({
customMessageBg: ColorValueSchema,
customMessageText: ColorValueSchema,
customMessageLabel: ColorValueSchema,
+ refinementHeader: Type.Optional(ColorValueSchema),
+ refinementSummary: Type.Optional(ColorValueSchema),
toolPendingBg: ColorValueSchema,
toolSuccessBg: ColorValueSchema,
toolErrorBg: ColorValueSchema,
@@ -139,6 +141,8 @@ export type ThemeColor =
| "userMessageText"
| "customMessageText"
| "customMessageLabel"
+ | "refinementHeader"
+ | "refinementSummary"
| "toolTitle"
| "toolOutput"
| "mdHeading"
@@ -184,6 +188,13 @@ export type ThemeBg =
| "toolPanelBg";
type ColorMode = "truecolor" | "256color";
+type RefinementColor = "refinementHeader" | "refinementSummary";
+
+function refinementColors(light: boolean): Record<RefinementColor, string> {
+ return light
+ ? { refinementHeader: "#7146ab", refinementSummary: "#8a70ad" }
+ : { refinementHeader: "#9575cd", refinementSummary: "#b7a1d6" };
+}
const ADAPTIVE_LIGHT_BG_ACCENT: Rgb = { r: 0, g: 95, b: 135 };
const SURFACE_MIN_LUMINANCE_DELTA = 12;
@@ -375,7 +386,8 @@ export class Theme {
private mode: ColorMode;
constructor(
- fgColors: Record<ThemeColor, string | number>,
+ fgColors: Record<Exclude<ThemeColor, RefinementColor>, string | number> &
+ Partial<Record<RefinementColor, string | number>>,
bgColors: Record<ThemeBg, string | number>,
mode: ColorMode,
options: { name?: string; sourcePath?: string; sourceInfo?: SourceInfo } = {},
@@ -385,6 +397,9 @@ export class Theme {
this.sourceInfo = options.sourceInfo;
this.mode = mode;
this.fgColors = new Map();
+ for (const [key, value] of Object.entries(refinementColors(options.name === "light"))) {
+ this.fgColors.set(key as RefinementColor, fgAnsi(value, mode));
+ }
for (const [key, value] of Object.entries(fgColors) as [ThemeColor, string | number][]) {
this.fgColors.set(key, fgAnsi(value, mode));
}
@@ -757,7 +772,10 @@ function loadThemeJson(name: string): ThemeJson {
function createTheme(themeJson: ThemeJson, mode?: ColorMode, sourcePath?: string): Theme {
const colorMode = mode ?? detectColorMode();
- const resolvedColors = resolveThemeColors(themeJson.colors, themeJson.vars);
+ const resolvedColors = resolveThemeColors(
+ { ...refinementColors(themeJson.name === "light"), ...themeJson.colors },
+ themeJson.vars,
+ );
const fgColors: Record<ThemeColor, string | number> = {} as Record<ThemeColor, string | number>;
const bgColors: Record<ThemeBg, string | number> = {} as Record<ThemeBg, string | number>;
const bgColorKeys: Set<string> = new Set([
@@ -1093,7 +1111,10 @@ export function getResolvedThemeColors(themeName?: string): Record<string, strin
const name = themeName ?? currentThemeName ?? getDefaultTheme();
const isLight = name === "light";
const themeJson = loadThemeJson(name);
- const resolved = resolveThemeColors(themeJson.colors, themeJson.vars);
+ const resolved = resolveThemeColors(
+ { ...refinementColors(themeJson.name === "light"), ...themeJson.colors },
+ themeJson.vars,
+ );
// Default text color for empty values (terminal uses default fg color)
const defaultText = isLight ? "#000000" : "#e5e5e7";
diff --git a/packages/coding-agent/test/compaction-message-components.test.ts b/packages/coding-agent/test/compaction-message-components.test.ts
new file mode 100644
index 0000000000..5a3103ff98
--- /dev/null
+++ b/packages/coding-agent/test/compaction-message-components.test.ts
@@ -0,0 +1,140 @@
+import { Container, setKeybindings, Text, visibleWidth } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { KeybindingsManager } from "../src/core/keybindings.js";
+import { convertToLlm, createCompactionOutcomeMessage, createCompactionSummaryMessage } from "../src/core/messages.js";
+import { CompactionOutcomeMessageComponent } from "../src/modes/interactive/components/compaction-outcome-message.js";
+import { CompactionSummaryMessageComponent } from "../src/modes/interactive/components/compaction-summary-message.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import { getMarkdownTheme, initTheme, theme } from "../src/modes/interactive/theme/theme.js";
+
+describe("compact compaction messages", () => {
+ beforeEach(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ test.each(["prime", "dark", "light"])("matches the refinement header and softer summary in the %s theme", (name) => {
+ initTheme(name);
+ const summary = "Finish the authentication fixes.";
+ const component = new CompactionSummaryMessageComponent(
+ createCompactionSummaryMessage(summary, 120480, "2026-09-09"),
+ );
+ const collapsed = component.render(80);
+ expect(collapsed.map((line) => stripAnsi(line).trimEnd())).toEqual([
+ " ◆ Context compacted",
+ " Finish the authentication fixes.",
+ ]);
+ expect(collapsed[0]).toContain(theme.fg("refinementHeader", "◆ Context compacted"));
+ expect(collapsed[1]).toBe(theme.fg("refinementSummary", ` ${summary}`));
+ expect(theme.getFgAnsi("refinementHeader")).not.toBe(theme.getFgAnsi("refinementSummary"));
+
+ component.setExpanded(true);
+ const expanded = stripAnsi(component.render(80).join("\n"));
+ expect(expanded).toContain(summary);
+ expect(expanded).toContain("Compacted from 120,480 tokens");
+ expect(expanded).not.toContain("Ctrl+O");
+ component.setExpanded(false);
+ expect(component.render(80)).toEqual(collapsed);
+ });
+
+ test("previews the stored summary instead of focus instructions and reveals all metadata on expansion", () => {
+ const focus =
+ "Keep the exact reproduction steps.\nPreserve the failing command and the environment details for the next turn.";
+ const summary = `${"Retained the authentication investigation and rollout decisions. ".repeat(8)}Final retained detail.`;
+ const message = createCompactionSummaryMessage(summary, 12345, "2026-09-09", focus);
+ const before = JSON.stringify(message);
+ const modelBefore = JSON.stringify(convertToLlm([message]));
+ const component = new CompactionSummaryMessageComponent(message);
+ const lines = component.render(80).map((line) => stripAnsi(line).trimEnd());
+ expect(lines).toHaveLength(3);
+ expect(lines[0]).toBe(" ◆ Context compacted");
+ expect(lines[1]).toContain("Retained the authentication investigation");
+ expect(lines[2]).toContain("…");
+ expect(lines.join("\n")).not.toMatch(/focus:|12,345|Final retained detail/);
+
+ for (const width of [12, 24, 40, 80]) {
+ for (const line of component.render(width)) expect(visibleWidth(line)).toBeLessThanOrEqual(width);
+ }
+ component.setExpanded(true);
+ const expanded = stripAnsi(component.render(80).join("\n")).replace(/\s+/g, " ");
+ expect(expanded).toContain(summary);
+ expect(expanded).toContain(focus.replace(/\s+/g, " "));
+ expect(expanded).toContain("Compacted from 12,345 tokens");
+ expect(JSON.stringify(message)).toBe(before);
+ expect(JSON.stringify(convertToLlm([message]))).toBe(modelBefore);
+ });
+
+ test("preserves full Markdown and the supplied Markdown theme in all output", () => {
+ const heading = vi.fn((text: string) => `heading:${text}`);
+ const component = new CompactionSummaryMessageComponent(
+ createCompactionSummaryMessage("## Next steps\n\nFinish the authentication fixes.", 100, "2026-09-09"),
+ { ...getMarkdownTheme(), heading },
+ );
+ component.setExpanded(true);
+ expect(stripAnsi(component.render(80).join("\n"))).toContain("heading:Next steps");
+ expect(heading).toHaveBeenCalled();
+ });
+
+ test("retains one leading gap in live and reopened chats through every display stage", () => {
+ const message = createCompactionSummaryMessage("Retained the next task.", 100, "2026-09-09");
+ const createMode = (expanded: boolean) =>
+ Object.assign(Object.create(InteractiveMode.prototype), {
+ chatContainer: new Container(),
+ pendingBashComponents: [],
+ toolOutputExpanded: expanded,
+ editDiffsExpanded: false,
+ getMarkdownThemeWithSettings: getMarkdownTheme,
+ ui: { isFullscreen: () => true, requestRender: vi.fn() },
+ });
+ const append = (mode: ReturnType<typeof createMode>) => {
+ mode.chatContainer.addChild(new Text("Before compaction", 1, 0));
+ Reflect.get(InteractiveMode.prototype, "addMessageToChat").call(mode, message);
+ };
+ const live = createMode(false);
+ append(live);
+ for (const [expanded, details] of [
+ [false, false],
+ [false, true],
+ [true, true],
+ [false, false],
+ ]) {
+ Object.assign(live, { toolOutputExpanded: expanded, editDiffsExpanded: details });
+ Reflect.get(InteractiveMode.prototype, "applyChatExpansion").call(live);
+ const reopened = createMode(expanded!);
+ append(reopened);
+ expect(live.chatContainer.render(80)).toEqual(reopened.chatContainer.render(80));
+ const lines = live.chatContainer.render(80).map((line: string) => stripAnsi(line).trimEnd());
+ expect(lines.slice(0, 3)).toEqual([" Before compaction", "", " ◆ Context compacted"]);
+ expect(lines.at(-1)).not.toBe("");
+ expect(lines.join("\n").includes("Compacted from")).toBe(expanded);
+ expect(lines.join("\n")).toContain("Retained the next task.");
+ }
+ });
+
+ test("labels missing summaries without inventing a result", () => {
+ const component = new CompactionSummaryMessageComponent(createCompactionSummaryMessage(" ", 100, "2026-09-09"));
+ for (const expanded of [false, true]) {
+ component.setExpanded(expanded);
+ expect(stripAnsi(component.render(80).join("\n"))).toContain("No summary was recorded for this compaction.");
+ }
+ });
+
+ test.each(["skipped", "cancelled", "failed"] as const)("keeps the full %s explanation visible", (outcome) => {
+ const content = `Auto-compaction ${outcome}: the context could not be compacted because the summary request did not complete. The original conversation remains available.`;
+ const component = new CompactionOutcomeMessageComponent(
+ createCompactionOutcomeMessage(content, { outcome, reason: "threshold" }),
+ );
+ const lines = component.render(80).map((line) => stripAnsi(line).trimEnd());
+ expect(
+ lines
+ .map((line) => line.trim())
+ .join(" ")
+ .trim(),
+ ).toBe(content);
+ expect(lines.filter((line) => line === "")).toHaveLength(1);
+ for (const line of lines) {
+ if (line.length > 0) expect(line.startsWith(" ")).toBe(true);
+ }
+ });
+});
diff --git a/packages/coding-agent/test/refinement-outcome-message.test.ts b/packages/coding-agent/test/refinement-outcome-message.test.ts
index 8c8b206175..ab8418389c 100644
--- a/packages/coding-agent/test/refinement-outcome-message.test.ts
+++ b/packages/coding-agent/test/refinement-outcome-message.test.ts
@@ -1,6 +1,12 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AssistantMessage } from "@earendil-works/pi-ai";
import { setKeybindings, type TUI, visibleWidth } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
-import { beforeAll, describe, expect, test } from "vitest";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
+import { getThemesDir } from "../src/config.js";
+import type { AgentSessionMessage } from "../src/core/agent-messages.js";
import { KeybindingsManager } from "../src/core/keybindings.js";
import {
convertToLlm,
@@ -11,7 +17,14 @@ import {
import type { HarnessEntry, RefinementResult } from "../src/core/refinement/refinement.js";
import { buildConversationComponents } from "../src/modes/interactive/components/conversation-components.js";
import { RefinementOutcomeMessageComponent } from "../src/modes/interactive/components/refinement-outcome-message.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import {
+ initTheme,
+ loadThemeFromPath,
+ preloadThemeValidator,
+ setThemeInstance,
+ theme,
+} from "../src/modes/interactive/theme/theme.js";
function entry(overrides: Partial<HarnessEntry> = {}): HarnessEntry {
return {
@@ -68,43 +81,93 @@ function rendered(component: RefinementOutcomeMessageComponent): string {
return stripAnsi(component.render(120).join("\n"));
}
+function expectChatInset(lines: string[]): void {
+ for (const line of lines) {
+ if (line.trim().length > 0) {
+ expect(line.startsWith(" "), `missing left inset: ${JSON.stringify(line)}`).toBe(true);
+ }
+ }
+}
+
describe("RefinementOutcomeMessageComponent", () => {
beforeAll(() => {
+ vi.stubEnv("COLORTERM", "truecolor");
initTheme("dark");
setKeybindings(new KeybindingsManager());
});
- test("collapses to a labeled one-liner and expands through the shared tool toggle", () => {
+ afterAll(() => vi.unstubAllEnvs());
+
+ test("shows the purple harness status and softer summary in overview and details, then full diffs", () => {
const message = createRefinementOutcomeMessage(result());
const component = new RefinementOutcomeMessageComponent(message);
const collapsed = rendered(component);
- expect(collapsed).toContain("[refinement]");
- expect(collapsed).toContain("Added local guidance to make conversational responses rhyme.");
- expect(collapsed).toContain("1 edit applied");
- expect(collapsed).toContain("Ctrl+O to expand");
- expect(collapsed).not.toContain("Created local prompt");
- expect(collapsed).not.toContain('Make conversational responses rhyme."');
+ const content = collapsed.split("\n").filter((line) => line.trim());
+ expect(content.map((line) => line.trimEnd())).toEqual([" ◆ Harness refined", ` ${result().summary}`]);
+ expect(component.render(120).join("\n")).toContain(theme.fg("refinementSummary", ` ${result().summary}`));
+ expect(component.render(120)[1]).toContain(theme.fg("refinementHeader", "◆ Harness refined"));
+ expect(collapsed.split("\n")[0].trim()).toBe("");
+ expect(collapsed.split("\n").at(-1)?.trim()).toBe(result().summary);
+ expect(collapsed).not.toContain("Ctrl+O");
+ expect(collapsed).not.toContain("[refinement]");
+ expect(collapsed).not.toContain("rhyme-response-guidance");
+ expectChatInset(collapsed.split("\n"));
+ // Collapsed rows stay compact: entry details only render when expanded.
+ expect(collapsed).not.toContain("Rhyme response guidance");
+ expect(collapsed).not.toContain("prompts/rhyme-response-guidance.md");
+ expect(collapsed).not.toContain('"content"');
+
+ component.setEditDiffsExpanded(true);
+ const details = rendered(component);
+ expect(details).toBe(collapsed);
+ expect(details).toContain("Added local guidance to make conversational responses rhyme.");
+ expect(component.render(120).join("\n")).toContain(
+ theme.fg("refinementSummary", " Added local guidance to make conversational responses rhyme."),
+ );
+ expect(details).not.toContain("rhyme-response-guidance");
+ expect(details).not.toContain(" Description");
+ expect(details).not.toContain("1 prompt created");
component.setExpanded(true);
const expanded = rendered(component);
expect(expanded).toContain("Created local prompt `rhyme-response-guidance`");
- expect(expanded).toContain('"content": "Make conversational responses rhyme."');
- expect(expanded).toContain('"path": "prompts/rhyme-response-guidance.md"');
+ expect(expanded).toContain(" Title");
+ expect(expanded).toContain("+ Rhyme response guidance");
+ expect(expanded).toContain(" Description");
+ expect(expanded).toContain("+ Make conversational responses rhyme.");
+ expect(expanded).toContain(" Path");
+ expect(expanded).toContain("prompts/rhyme-response-guidance.md");
+ expect(expanded).not.toContain("Ctrl+O");
+ expectChatInset(expanded.split("\n"));
+ // Structured rows, not a JSON dump.
+ expect(expanded).not.toContain('"content":');
+ expect(expanded).not.toContain('"title":');
+ expect(expanded).not.toContain('"path":');
+ expect(expanded).not.toContain("+1 {");
+
+ component.setExpanded(false);
+ expect(rendered(component)).toBe(details);
+ component.setEditDiffsExpanded(false);
+ expect(rendered(component)).toBe(collapsed);
});
- test("truncates the collapsed summary so the line never wraps", () => {
+ test("gives long semantic summaries two preview lines beneath the harness header", () => {
const long = result();
long.summary =
"Created local memory entries for the verifiers project context and running subagent tracking, plus a reusable subagent spec for parallel codebase exploration.";
const component = new RefinementOutcomeMessageComponent(createRefinementOutcomeMessage(long));
- const lines = component.render(80).map((line) => stripAnsi(line));
+ const overview = component.render(80);
+ component.setEditDiffsExpanded(true);
+ expect(component.render(80)).toEqual(overview);
+ const lines = overview.map((line) => stripAnsi(line));
const content = lines.filter((line) => line.trim().length > 0);
- expect(content).toHaveLength(2);
- expect(content[1]).toContain("…");
- expect(content[1]).toContain("1 edit applied");
- expect(content[1]).toContain("Ctrl+O to expand");
+ expect(content).toHaveLength(3);
+ expect(content[0].trim()).toBe("◆ Harness refined");
+ expect(content[1]).toContain("Created local memory entries for the verifiers project context");
+ expect(content[2]).toContain("…");
+ expectChatInset(lines);
for (const line of lines) {
expect(visibleWidth(line)).toBeLessThanOrEqual(80);
}
@@ -114,13 +177,16 @@ describe("RefinementOutcomeMessageComponent", () => {
expect(visibleWidth(stripAnsi(line))).toBeLessThanOrEqual(width);
}
}
+
+ component.setExpanded(true);
+ expect(rendered(component).replace(/\s+/g, " ")).toContain(long.summary);
});
- test("renders exact before and after payloads for updates and deletes", () => {
+ test("renders structured before and after rows for updates and deletes", () => {
const base = result();
- const before = entry({ id: "tone-guidance", content: "Respond plainly." });
- const after = entry({ id: "tone-guidance", content: "Respond in rhyme.", version: 2 });
- const deleted = entry({ id: "obsolete-guidance", content: "Use prose." });
+ const before = entry({ id: "tone-guidance", title: "Tone guidance", content: "Respond plainly." });
+ const after = entry({ id: "tone-guidance", title: "Tone guidance", content: "Respond in rhyme.", version: 2 });
+ const deleted = entry({ id: "obsolete-guidance", title: "Obsolete guidance", content: "Use prose." });
const message = createRefinementOutcomeMessage({
...base,
appliedEdits: [
@@ -131,28 +197,305 @@ describe("RefinementOutcomeMessageComponent", () => {
const component = new RefinementOutcomeMessageComponent(message);
component.setExpanded(true);
const output = rendered(component);
+ expectChatInset(output.split("\n"));
expect(output).toContain("Updated local prompt `tone-guidance`");
+ expect(output).toContain(" Description");
+ expect(output).toContain(" 1 - Respond plainly.");
+ expect(output).toContain(" 1 + Respond in rhyme.");
+ expect(output).toContain(" Tone guidance");
expect(output).toContain("Deleted local prompt `obsolete-guidance`");
- expect(output).toContain('"content": "Respond plainly."');
- expect(output).toContain('"content": "Respond in rhyme."');
- expect(output).toContain('"content": "Use prose."');
+ expect(output).toContain(" 1 - Use prose.");
+ expect(output).not.toContain('"content":');
+ });
+
+ test("renders create, update, and failed edits as structured sections with the chat inset", () => {
+ const created = entry({
+ id: "linear",
+ kind: "skill",
+ title: "Linear issues",
+ content: "Read and write Linear issues via MCP.",
+ path: "skills/linear/SKILL.md",
+ reference: { type: "python", import: "linear", callable: "run" },
+ arguments: { name: { type: "string", required: true } },
+ });
+ const before = entry({ id: "osint-tips", kind: "memory", title: "OSINT tips", content: "Use blogs." });
+ const after = entry({
+ id: "osint-tips",
+ kind: "memory",
+ title: "OSINT tips",
+ content: "Use blogs and acknowledgements.",
+ });
+ const message = createRefinementOutcomeMessage({
+ ...result(),
+ appliedEdits: [
+ {
+ action: "create",
+ kind: "skill",
+ id: created.id,
+ title: created.title,
+ content: created.content,
+ path: created.path,
+ after: created,
+ applied: true,
+ },
+ { action: "update", kind: "memory", id: before.id, before, after, applied: true },
+ {
+ action: "delete",
+ kind: "prompt",
+ id: "stale-note",
+ title: "Stale note",
+ content: "Old session note.",
+ applied: false,
+ error: "entry not found",
+ },
+ ],
+ });
+ const component = new RefinementOutcomeMessageComponent(message);
+
+ const collapsed = rendered(component);
+ expect(collapsed).toContain("Harness partially refined · 2/3 edits applied");
+ expect(collapsed).not.toContain("`linear`");
+ expect(collapsed).not.toContain("`osint-tips`");
+ expect(collapsed).not.toContain("`stale-note`");
+ expectChatInset(collapsed.split("\n"));
+
+ component.setExpanded(true);
+ const expanded = rendered(component);
+ expectChatInset(expanded.split("\n"));
+ expect(expanded).toContain("+ Linear issues");
+ expect(expanded).toContain("+ Read and write Linear issues via MCP.");
+ expect(expanded).toContain('+ {"type":"python","import":"linear","callable":"run"}');
+ expect(expanded).toContain('+ {"name":{"type":"string","required":true}}');
+ expect(expanded).toContain(" 1 - Use blogs.");
+ expect(expanded).toContain(" 1 + Use blogs and acknowledgements.");
+ expect(expanded).toContain("Failed to delete local prompt `stale-note`: entry not found");
+ expect(expanded).toContain(" Stale note");
+ // The raw JSON-diff blob is gone.
+ expect(expanded).not.toContain('"content":');
+ expect(expanded).not.toContain('"title":');
+ expect(expanded).not.toContain("+1 {");
+
+ for (const width of [80, 40, 24, 12]) {
+ for (const line of component.render(width)) {
+ expect(visibleWidth(stripAnsi(line))).toBeLessThanOrEqual(width);
+ }
+ }
});
- test("replays the durable outcome with the saved tool expansion state", () => {
+ test("shows memory action counts and file-style Title and Description backgrounds without changing the message", () => {
+ const before = entry({ kind: "memory", title: "Old title", content: " preserve indentation\nOld guidance" });
+ const after = entry({ ...before, title: "New title", content: " preserve indentation\nNew guidance" });
+ const message = createRefinementOutcomeMessage({
+ ...result(),
+ summary: "Remembered the project's authentication conventions.",
+ appliedEdits: [
+ {
+ action: "update",
+ kind: "memory",
+ id: before.id,
+ before,
+ after,
+ applied: true,
+ reason: "Repeated user preference",
+ },
+ ],
+ });
+ const original = JSON.stringify(message);
+ const component = new RefinementOutcomeMessageComponent(message);
+ expect(rendered(component)).toContain(message.details.summary);
+ component.setExpanded(true);
+ expect(rendered(component)).toContain("1 memory updated");
+ const rows = component.render(80);
+ const output = rows.map(stripAnsi).join("\n");
+ expect(output).toMatch(/ Title +\n/);
+ expect(output).toMatch(/ Description +\n/);
+ expect(output).toContain(" preserve indentation");
+ expect(output).toContain("Reason: Repeated user preference");
+ const removed = rows.find((row) => stripAnsi(row).includes("- Old guidance"))!;
+ const added = rows.find((row) => stripAnsi(row).includes("+ New guidance"))!;
+ expect(removed.startsWith(` ${theme.bg("toolDiffRemovedBg", "").slice(0, -5)}`)).toBe(true);
+ expect(added.startsWith(` ${theme.bg("toolDiffAddedBg", "").slice(0, -5)}`)).toBe(true);
+ expect(visibleWidth(removed)).toBe(80);
+ expect(visibleWidth(added)).toBe(80);
+ expect(output).not.toContain("Content");
+ for (const width of [12, 24, 40, 80]) {
+ for (const row of component.render(width)) expect(visibleWidth(row)).toBeLessThanOrEqual(width);
+ }
+ expect(JSON.stringify(message)).toBe(original);
+ });
+
+ test("labels no-change, failed, partial, and rollback outcomes honestly and preserves failure details", () => {
+ const failed = { ...result().appliedEdits[0]!, applied: false, error: "Permission denied" };
+ for (const [edits, rollbackOf, expected] of [
+ [[], undefined, "Harness unchanged · no edits applied"],
+ [[failed], undefined, "Harness refinement failed · 0/1 edits applied"],
+ [[failed], "old-refinement", "Harness rollback failed · 0/1 edits applied"],
+ [[...result().appliedEdits, failed], "old-refinement", "Harness partially rolled back · 1/2 edits applied"],
+ [result().appliedEdits, "old-refinement", "Harness rollback completed · 1 edit applied"],
+ ] as const) {
+ const component = new RefinementOutcomeMessageComponent(
+ createRefinementOutcomeMessage({
+ ...result(),
+ summary: "",
+ appliedEdits: [...edits],
+ rollbackOf,
+ }),
+ );
+ expect(rendered(component)).toContain(expected);
+ expect(rendered(component)).toContain("No summary was recorded");
+ component.setEditDiffsExpanded(true);
+ expect(rendered(component)).toContain("No summary was recorded");
+ component.setExpanded(true);
+ if (rollbackOf) expect(rendered(component)).toContain(`rollback of ${rollbackOf}`);
+ if (edits.some((edit) => !edit.applied)) expect(rendered(component)).toContain("Permission denied");
+ if (edits.every((edit) => !edit.applied)) {
+ expect(component.render(120).join("\n")).not.toContain(theme.bg("toolDiffAddedBg", "").slice(0, -5));
+ }
+ }
+ });
+
+ test("matches live and replay refinement stages without changing saved messages", () => {
const message = createRefinementOutcomeMessage(result());
- const [component] = buildConversationComponents([message], {
- ui: {} as TUI,
- cwd: "/tmp",
- toolOptions: {},
- getToolDefinition: () => undefined,
- toolsExpanded: true,
+ const original = JSON.stringify(message);
+ const live = new RefinementOutcomeMessageComponent(message);
+ const mode = Object.assign(Object.create(InteractiveMode.prototype), {
+ chatContainer: { children: [live] },
+ ui: { isFullscreen: () => true, requestRender: vi.fn() },
});
+ for (const [toolsExpanded, editDiffsExpanded] of [
+ [false, false],
+ [false, true],
+ [true, true],
+ [false, false],
+ ]) {
+ const [replay] = buildConversationComponents([message], {
+ ui: {} as TUI,
+ cwd: "/tmp",
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ toolsExpanded,
+ editDiffsExpanded,
+ });
+ Object.assign(mode, { toolOutputExpanded: toolsExpanded, editDiffsExpanded });
+ Reflect.get(InteractiveMode.prototype, "applyChatExpansion").call(mode);
+ expect(replay).toBeInstanceOf(RefinementOutcomeMessageComponent);
+ expect(live.render(120)).toEqual(replay!.render(120));
+ const output = rendered(live);
+ expect(output).toContain(result().summary);
+ expect(output.includes("+ Make conversational responses rhyme.")).toBe(toolsExpanded);
+ }
+ expect(JSON.stringify(message)).toBe(original);
+ });
- expect(component).toBeInstanceOf(RefinementOutcomeMessageComponent);
- expect(stripAnsi(component!.render(120).join("\n"))).toContain(
- '"content": "Make conversational responses rhyme."',
- );
+ test("uses purple refinement colors in every built-in theme and both terminal color modes", () => {
+ try {
+ for (const name of ["prime", "dark", "light"]) {
+ for (const mode of ["truecolor", "256color"] as const) {
+ setThemeInstance(loadThemeFromPath(join(getThemesDir(), `${name}.json`), mode));
+ const component = new RefinementOutcomeMessageComponent(createRefinementOutcomeMessage(result()));
+ const expectedHeader = name === "light" ? "113;70;171" : "149;117;205";
+ const expectedSummary = name === "light" ? "138;112;173" : "183;161;214";
+ if (mode === "truecolor") {
+ expect(component.render(120).join("\n")).toContain(`\x1b[38;2;${expectedHeader}m◆ Harness refined`);
+ } else {
+ expect(theme.getFgAnsi("refinementHeader")).toMatch(/^\x1b\[38;5;\d+m$/);
+ }
+ expect(theme.getFgAnsi("refinementHeader")).not.toBe(theme.getFgAnsi("warning"));
+ expect(theme.getFgAnsi("refinementSummary")).not.toBe(theme.getFgAnsi("refinementHeader"));
+ component.setEditDiffsExpanded(true);
+ if (mode === "truecolor")
+ expect(component.render(120).join("\n")).toContain(
+ `\x1b[38;2;${expectedSummary}m Added local guidance`,
+ );
+ }
+ }
+ } finally {
+ initTheme("dark");
+ }
+ });
+
+ test("gives existing custom themes purple defaults rather than inheriting their warning label", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "refinement-theme-"));
+ try {
+ await preloadThemeValidator();
+ const json = JSON.parse(readFileSync(join(getThemesDir(), "prime.json"), "utf8"));
+ delete json.colors.refinementHeader;
+ delete json.colors.refinementSummary;
+ json.name = "existing-custom";
+ const path = join(directory, "custom.json");
+ writeFileSync(path, JSON.stringify(json));
+ const custom = loadThemeFromPath(path, "truecolor");
+ expect(custom.getFgAnsi("refinementHeader")).toBe("\x1b[38;2;149;117;205m");
+ expect(custom.getFgAnsi("refinementSummary")).toBe("\x1b[38;2;183;161;214m");
+ expect(custom.getFgAnsi("customMessageLabel")).toBe(custom.getFgAnsi("warning"));
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
+ test("leaves one blank row before following prose through empty and agent-message neighbors in every stage", () => {
+ const assistant = (text: string): AssistantMessage => ({
+ role: "assistant",
+ content: [{ type: "text", text }],
+ api: "openai-responses",
+ provider: "openai",
+ model: "test",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 0,
+ });
+ const agent: AgentSessionMessage = {
+ role: "custom",
+ customType: "agent_message",
+ content: "Worker finished",
+ display: true,
+ timestamp: 0,
+ details: {
+ id: "worker",
+ message: "Worker finished",
+ from: { sessionId: "worker" },
+ fromRelationship: "child",
+ },
+ };
+ for (const neighbor of [[], [assistant("")], [agent], [agent, assistant("")]]) {
+ for (const [toolsExpanded, editDiffsExpanded] of [
+ [false, false],
+ [false, true],
+ [true, true],
+ ]) {
+ const components = buildConversationComponents(
+ [
+ assistant("Before notice"),
+ createRefinementOutcomeMessage(result()),
+ ...neighbor,
+ assistant("Following prose"),
+ ],
+ {
+ ui: {} as TUI,
+ cwd: "/tmp",
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ toolsExpanded,
+ editDiffsExpanded,
+ },
+ );
+ const rows = components.flatMap((component) => component.render(120)).map((row) => stripAnsi(row).trim());
+ const following = rows.indexOf("Following prose");
+ expect(rows[following - 1]).toBe("");
+ expect(rows[following - 2]).not.toBe("");
+ const header = rows.indexOf("◆ Harness refined");
+ expect(rows[header - 1]).toBe("");
+ expect(rows[header - 2]).toBe("Before notice");
+ }
+ }
});
test("uses a typed, presentation-only custom message", () => {