@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
257 lines • 11.3 kB
JavaScript
import { Container, copyLineSources, Markdown, nextRenderRevision, Spacer, Text, truncateToWidth, } from "@earendil-works/pi-tui";
import { sharedMarkdownTheme, theme } from "../theme/theme.js";
import { createAssistantRenderDescriptors } from "./assistant-render-descriptors.js";
import { createMarkdownTransform } from "./markdown-transform.js";
import { createBoundedRenderSignature } from "./render-signature.js";
const OSC133_ZONE_START = "\x1b]133;A\x07";
const OSC133_ZONE_END = "\x1b]133;B\x07";
const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
function assertNever(value) {
throw new TypeError(`Unexpected assistant render variant: ${String(value)}`);
}
/** The folded handoff line: always one row, cut to the width instead of wrapping (senpi#3323). */
class SingleLine {
constructor(text, pad) {
this.revision = nextRenderRevision();
this.text = text;
this.pad = pad;
}
render(width) {
const room = Math.max(1, width - this.pad);
return [`${" ".repeat(this.pad)}${truncateToWidth(this.text, room)}`];
}
invalidate() { }
getRenderRevision() {
return this.revision;
}
}
export class AssistantMessageComponent extends Container {
constructor(message, hideThinkingBlock = false, markdownTheme = sharedMarkdownTheme(), hiddenThinkingLabel = "Thinking...", outputPad = 1, markdownTransformers = []) {
super();
this.renderDescriptors = [];
this.hasToolCalls = false;
this.expanded = false;
this.providerErrorOwned = false;
this.ownsTurnNotice = false;
this.isStreaming = false;
this.thinkingVisibilityOverrides = new Map();
this.handoffOpenOverrides = new Map();
/** Moves whenever the cached render is dropped; output is a function of the state `updateContent` records. */
this.revision = nextRenderRevision();
this.hideThinkingBlock = hideThinkingBlock;
this.markdownTheme = markdownTheme;
this.hiddenThinkingLabel = hiddenThinkingLabel;
this.outputPad = outputPad;
this.markdownTransformers = markdownTransformers;
// Container for text/thinking content
this.contentContainer = new Container();
this.addChild(this.contentContainer);
if (message)
this.updateContent(message);
}
invalidate() {
this.renderCache = undefined;
this.revision = nextRenderRevision();
super.invalidate();
this.renderDescriptors = [];
this.refreshContent();
}
setHideThinkingBlock(hide) {
if (this.hideThinkingBlock === hide)
return;
this.hideThinkingBlock = hide;
this.thinkingVisibilityOverrides.clear();
this.refreshContent();
}
setHiddenThinkingLabel(label) {
if (this.hiddenThinkingLabel === label)
return;
this.hiddenThinkingLabel = label;
this.refreshContent();
}
setExpanded(expanded) {
if (this.expanded === expanded)
return;
this.expanded = expanded;
this.handoffOpenOverrides.clear();
this.refreshContent();
}
/** A replayed turn draws in one component, so it shows its own turn-ending notice (senpi#4958). */
setOwnsTurnNotice(owned) {
if (this.ownsTurnNotice === owned)
return;
this.ownsTurnNotice = owned;
this.refreshContent();
}
setProviderErrorOwned(owned) {
if (this.providerErrorOwned === owned)
return;
this.providerErrorOwned = owned;
this.refreshContent();
}
/** Transcript-only reasoning/empty streaming heads may sit inside a compact exploration group. */
get isExplorationDetail() {
return this.renderDescriptors.every((part) => part.kind === "spacer" || part.kind === "thinking-label");
}
setOutputPad(padding) {
this.outputPad = padding;
this.renderDescriptors = [];
this.refreshContent();
}
getRenderRevision() {
return this.revision;
}
render(width) {
const signature = this.lastMessageSignature ?? "";
if (this.renderCache?.width === width && this.renderCache.signature === signature) {
return copyLineSources(this.renderCache.lines, [...this.renderCache.lines]);
}
const lines = super.render(width);
if (this.hasToolCalls || lines.length === 0) {
this.cacheRender(width, signature, lines);
return lines;
}
lines[0] = OSC133_ZONE_START + lines[0];
lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];
this.cacheRender(width, signature, lines);
return lines;
}
updateContent(message, isStreaming = this.isStreaming) {
const previousMessage = this.lastMessage;
const streamingChanged = this.isStreaming !== isStreaming;
this.isStreaming = isStreaming;
this.lastMessage = message;
const messageSignature = this.createMessageSignature(message);
if (!streamingChanged && previousMessage === message && this.lastMessageSignature === messageSignature) {
return;
}
this.lastMessageSignature = messageSignature;
this.renderCache = undefined;
this.revision = nextRenderRevision();
if (streamingChanged)
this.renderDescriptors = [];
this.hasToolCalls = message.content.some((content) => content.type === "toolCall");
const descriptors = createAssistantRenderDescriptors(message, {
expanded: this.expanded,
providerErrorOwned: this.providerErrorOwned,
hiddenThinkingLabel: this.hiddenThinkingLabel,
hideThinkingBlock: this.hideThinkingBlock,
thinkingVisibilityOverrides: this.thinkingVisibilityOverrides,
handoffOpenOverrides: this.handoffOpenOverrides,
hasToolCalls: this.hasToolCalls,
ownsTurnNotice: this.ownsTurnNotice,
});
this.reconcileRenderDescriptors(descriptors);
}
reconcileRenderDescriptors(descriptors) {
let divergentIndex = 0;
const sharedLength = Math.min(this.renderDescriptors.length, descriptors.length);
while (divergentIndex < sharedLength) {
const previous = this.renderDescriptors[divergentIndex];
const next = descriptors[divergentIndex];
const child = this.contentContainer.children[divergentIndex];
if (!previous || !next || !child || previous.kind !== next.kind)
break;
if (previous.text !== next.text) {
if ((next.kind === "text-md" || next.kind === "thinking-md") && child instanceof Markdown) {
child.setText(next.text);
}
else
break;
}
divergentIndex++;
}
for (const child of this.contentContainer.children.splice(divergentIndex))
child.dispose?.();
for (const descriptor of descriptors.slice(divergentIndex))
this.contentContainer.addChild(this.createRenderChild(descriptor));
this.renderDescriptors = descriptors;
}
createRenderChild(descriptor) {
switch (descriptor.kind) {
case "spacer":
return new Spacer(1);
case "text-md":
return new Markdown(descriptor.text, this.outputPad, 0, this.markdownTheme, undefined, {
transform: createMarkdownTransform("assistant", this.isStreaming, this.markdownTransformers),
});
case "thinking-md":
return this.withThinkingToggle(new Markdown(descriptor.text, this.outputPad, 0, this.markdownTheme, {
color: (text) => theme.fg("thinkingText", text),
italic: true,
}, {
transform: createMarkdownTransform("assistant-thinking", this.isStreaming, this.markdownTransformers),
}), descriptor);
case "thinking-label":
return this.withThinkingToggle(new Text(descriptor.text, this.outputPad, 0), descriptor);
case "error-text":
return new Text(descriptor.text, this.outputPad, 0);
case "provider-native-summary":
return new Text(descriptor.text, 1, 0);
case "provider-native-body":
return new Text(descriptor.text, 3, 0);
case "handoff-line":
return this.withHandoffToggle(new SingleLine(descriptor.text, this.outputPad), descriptor);
case "handoff-body":
return this.withHandoffToggle(new Text(descriptor.text, this.outputPad, 0), descriptor);
default:
return assertNever(descriptor.kind);
}
}
/**
* Left-clicking a thinking run toggles that run between its label and its body (upstream
* 71026970a). The mouse handler is attached to the Markdown/Text child itself so the
* incremental reconciler still sees the same child types it updates in place.
*/
withThinkingToggle(component, descriptor) {
const runIndex = descriptor.thinkingRun;
if (runIndex === undefined)
return component;
component.handleMouse = (event) => {
if (event.type !== "click" || event.button !== "left")
return undefined;
const hidden = this.thinkingVisibilityOverrides.get(runIndex) ?? this.hideThinkingBlock;
this.thinkingVisibilityOverrides.set(runIndex, !hidden);
this.refreshContent();
return { handled: true };
};
return component;
}
/** Left-clicking a handoff fold line or its open body toggles that block, like a thinking run. */
withHandoffToggle(component, descriptor) {
const block = descriptor.handoffBlock;
if (block === undefined)
return component;
component.handleMouse = (event) => {
if (event.type !== "click" || event.button !== "left")
return undefined;
const open = this.handoffOpenOverrides.get(block) ?? this.expanded;
this.handoffOpenOverrides.set(block, !open);
this.refreshContent();
return { handled: true };
};
return component;
}
createMessageSignature(message) {
return createBoundedRenderSignature({
content: message.content,
hiddenThinkingLabel: this.hiddenThinkingLabel,
hideThinkingBlock: this.hideThinkingBlock,
thinkingVisibilityOverrides: [...this.thinkingVisibilityOverrides],
handoffOpenOverrides: [...this.handoffOpenOverrides],
expanded: this.expanded,
errorState: [message.diagnostics, message.errorMessage],
stopReason: message.stopReason,
});
}
cacheRender(width, signature, lines) {
this.renderCache = { lines: copyLineSources(lines, [...lines]), signature, width };
}
refreshContent() {
if (!this.lastMessage)
return;
this.lastMessageSignature = undefined;
this.updateContent(this.lastMessage);
}
}
//# sourceMappingURL=assistant-message.js.map