@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
210 lines • 9.7 kB
JavaScript
/**
* Collapsed widget for a pending async (waitForAnswer=false) question: it
* sits above the editor and shows the unanswered count with the idle
* countdown, the first unanswered question with its options, and every way
* into the full AskUserQuestionComponent. The response-building helpers here
* are pure so interactive-mode can turn ordinary composer text into the
* comment answer.
*/
import { sanitizeTerminalLabel, Text, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
import { theme } from "../theme/theme.js";
import { askUserAnswerKeyHint } from "./ask-user-answer-key.js";
import { AskUserCountdown } from "./ask-user-countdown.js";
import { formatCountdownLabel } from "./ask-user-question-state.js";
import { keyText } from "./keybinding-hints.js";
/** Host-owned widget slot displaying one request from the pending queue. */
export const ASK_USER_WIDGET_KEY = "ask-user";
const INDENT = " ";
function hasAnswer(answer) {
if (!answer)
return false;
if (answer.selected.length > 0)
return true;
return (answer.text ?? "").trim() !== "";
}
/** Question ids the draft has not answered yet. */
export function unansweredIds(request, draft) {
return request.questions.filter((question) => !hasAnswer(draft.answers?.[question.id])).map((q) => q.id);
}
/** Response for a draft that already answers every question, submitted from the collapsed widget. */
export function buildAnsweredResponse(request, draft) {
const comment = draft.comment?.trim();
return {
status: comment ? "comment-submitted" : "answered",
resolvedBy: "local_ui",
answers: draft.answers ?? {},
...(comment ? { comment: draft.comment } : {}),
unanswered: unansweredIds(request, draft),
};
}
/** Response for composer text typed while the question is pending: the text is the comment. */
export function buildCommentResponse(request, draft, comment) {
return {
status: "comment-submitted",
resolvedBy: "local_ui",
answers: draft.answers ?? {},
comment,
unanswered: unansweredIds(request, draft),
};
}
/** Response for an idle countdown that expired while the widget was collapsed. */
export function buildTimedOutResponse(request, draft, autoResolvedAfterMs) {
const comment = draft.comment?.trim();
return {
status: "timed_out",
answers: draft.answers ?? {},
...(comment ? { comment } : {}),
unanswered: unansweredIds(request, draft),
autoResolvedAfterMs,
};
}
export function renderStatusLine(unanswered, countdownLabel, pendingCount = 1) {
const countdown = countdownLabel === "" ? "" : theme.fg("muted", ` · ${countdownLabel}`);
return (theme.fg("accent", theme.bold("?")) +
theme.fg("text", pendingCount > 1 ? ` ${pendingCount} questions pending` : ` Question pending (${unanswered} unanswered)`) +
countdown);
}
export function renderQuestionLine(question) {
return (INDENT +
theme.fg("text", theme.bold(question.header)) +
theme.fg("muted", " - ") +
theme.fg("text", question.question));
}
export function renderOptionsLine(question, remaining) {
const parts = question.options.map((option, index) => theme.fg("dim", `${index + 1}`) + theme.fg("muted", ` ${option.label}`));
parts.push(theme.fg("muted", "own answer"));
if (remaining > 0)
parts.push(theme.fg("muted", `+${remaining} more question${remaining === 1 ? "" : "s"}`));
return INDENT + parts.join(theme.fg("muted", " · "));
}
/** Hint naming every way into the pending question; the shortcut segment follows the effective binding. */
export function renderAnswerHint() {
const shortcut = askUserAnswerKeyHint();
const keys = shortcut === "" ? "enter" : `enter or ${shortcut}`;
return [
theme.fg("dim", keys) + theme.fg("muted", " to answer"),
theme.fg("dim", "/answer"),
theme.fg("muted", "or just type your reply"),
].join(theme.fg("muted", " · "));
}
/**
* How to select text while the app owns the mouse: Option on iTerm2, Option on macOS VS Code only with
* `terminal.integrated.macOptionClickForcesSelection`, Shift elsewhere (Windows Terminal, Ghostty,
* WezTerm, kitty, VS Code on Windows/Linux). Terminal.app documents no drag bypass (Option-drag is its
* rectangular selection); its documented way out is Command-R, which toggles Allow Mouse Reporting.
* Inside tmux the outer terminal decides and cannot be detected.
*/
export function selectionBypassHint(termProgram = process.env.TERM_PROGRAM ?? "", platform = process.platform) {
if (termProgram === "iTerm.app")
return "option+drag";
if (termProgram === "Apple_Terminal")
return "cmd+r (toggle mouse reporting)";
if (termProgram === "vscode" && platform === "darwin")
return "option+drag (with terminal.integrated.macOptionClickForcesSelection)";
if (termProgram === "tmux")
return "shift+drag (option+drag on iTerm2)";
return "shift+drag";
}
export class AskUserAsyncWidget {
constructor(options) {
this.countdownLabel = "";
this.hits = [];
this.renderedWidth = 0;
this.options = options;
this.request = options.request;
this.draft = options.draft;
this.pendingCount = options.pendingCount ?? 1;
if (options.timeoutMs > 0 || options.getDeadlineAtMs) {
this.countdown = new AskUserCountdown(options.timeoutMs, options.tui, (remainingMs) => {
this.countdownLabel = formatCountdownLabel(remainingMs);
this.update();
}, options.onExpire, options.getDeadlineAtMs);
}
this.update();
}
dispose() {
this.countdown?.dispose();
}
invalidate() { }
update() {
this.options.tui?.requestRender();
}
render(width) {
this.hits = [];
this.renderedWidth = width;
if (width < 5)
return [truncateToWidth("Use keys to answer", width)];
const pending = unansweredIds(this.request, this.draft);
const shown = this.request.questions.find((question) => question.id === pending[0]);
const lines = [];
const addAction = (text, action) => {
const line = truncateToWidth(text, width);
this.hits.push({ action, row: lines.length, startColumn: 0, endColumn: visibleWidth(line) });
lines.push(line);
};
addAction(renderStatusLine(pending.length, this.countdownLabel, this.pendingCount), "expand");
if (shown) {
addAction(renderQuestionLine({
...shown,
header: sanitizeTerminalLabel(shown.header),
question: sanitizeTerminalLabel(shown.question),
}), "expand");
let line = "";
const labels = [...shown.options.map((option) => sanitizeTerminalLabel(option.label)), "own answer…"];
for (const [index, label] of labels.entries()) {
const button = `[ ${truncateToWidth(label, width - 4, "…")} ]`;
if (line !== "" && visibleWidth(line) + 2 + visibleWidth(button) > width) {
lines.push(line);
line = "";
}
if (line !== "")
line += " ";
const startColumn = visibleWidth(line);
line += theme.fg("muted", button);
this.hits.push({
action: index === shown.options.length ? "own-answer" : index,
row: lines.length,
startColumn,
endColumn: visibleWidth(line),
});
}
if (line !== "")
lines.push(line);
if (pending.length > 1)
lines.push(truncateToWidth(theme.fg("muted", `+${pending.length - 1} more question${pending.length === 2 ? "" : "s"}`), width));
}
if (this.pendingCount > 1)
addAction(theme.fg("muted", `▸ +${this.pendingCount - 1} more · ${keyText("app.question.next")} next question`), "next");
const capture = this.options.mouseCaptureActive ? (this.options.tui?.mouseCaptureState() ?? "armed") : "off";
if (capture === "armed")
lines.push(...new Text(theme.fg("muted", `click an option · ${selectionBypassHint()} to select text`), 0, 0).render(width));
else if (capture === "yielded")
lines.push(...new Text(theme.fg("muted", "wheel scrolls · press any key to click options again"), 0, 0).render(width));
lines.push(...new Text(renderAnswerHint(), 0, 0).render(width));
return lines;
}
handleMouse(event) {
if (event.width !== this.renderedWidth ||
event.button !== "left" ||
event.shift ||
event.alt ||
event.ctrl ||
(event.type !== "press" && (event.type !== "click" || event.clickCount !== 1)))
return undefined;
const hit = this.hits.find((span) => span.row === event.y && event.x >= span.startColumn && event.x < span.endColumn);
if (!hit)
return undefined;
if (event.type === "click") {
if (typeof hit.action === "number")
this.options.onOptionClick?.(hit.action);
else if (hit.action === "own-answer")
this.options.onOwnAnswerClick?.();
else if (hit.action === "expand")
this.options.onExpandClick?.();
else
this.options.onNextQuestion?.();
}
return { handled: true };
}
}
//# sourceMappingURL=ask-user-async-widget.js.map