Skip to content

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

Rust

add inline side questions (#370)

kt82e0b1e0a0d9
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 14e2fc9ae2..6f1d26bc2e 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Added `/btw` and `/side` for one-turn inline side questions that use the current context without changing the main session ([ENG-4509](https://linear.app/primeintellect/issue/ENG-4509/add-btw-and-side-side-question-flows)).
- Changed the new-chat splash to show only version, model, and cwd metadata and rotate among five example prompts.
## [0.2.8] - 2026-07-09
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 69669d679d..87ea5a9486 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -155,6 +155,7 @@ Type `/` in the editor to trigger commands. [Extensions](#extensions) can regist
| `/clone` | Duplicate the current active branch into a new session |
| `/compact [prompt]` | Manually compact context, optional custom instructions |
| `/copy` | Copy last assistant message to clipboard |
+| `/btw <question>`, `/side <question>` | Ask one inline side question without adding it to the session |
| `/export [file]` | Export session to HTML file |
| `/share` | Upload as private GitHub gist with shareable HTML link |
| `/reload` | Reload keybindings, extensions, skills, prompts, and context files (themes hot-reload automatically) |
diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.md
index c700eb81f5..27bb949e46 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -50,6 +50,7 @@ Type `/` in the editor to open command completion. Extensions can register custo
| `/clone` | Duplicate the current active branch into a new session |
| `/compact [prompt]` | Manually compact context, optionally with custom instructions |
| `/copy` | Copy last assistant message to clipboard |
+| `/btw <question>`, `/side <question>` | Ask one inline side question without adding it to the session |
| `/export [file]` | Export session to HTML |
| `/share` | Upload as private GitHub gist with shareable HTML link |
| `/reload` | Reload keybindings, extensions, skills, prompts, and context files |
diff --git a/packages/coding-agent/src/core/side-question.ts b/packages/coding-agent/src/core/side-question.ts
new file mode 100644
index 0000000000..a619ce6600
--- /dev/null
+++ b/packages/coding-agent/src/core/side-question.ts
@@ -0,0 +1,119 @@
+import { Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
+
+export type SideQuestionStatus = "running" | "complete" | "cancelled" | "error";
+
+export interface SideQuestionEvent {
+ id: string;
+ question: string;
+ answer: string;
+ status: SideQuestionStatus;
+ errorMessage?: string;
+}
+
+export interface SideQuestionRun {
+ done: Promise<void>;
+ abort(): void;
+}
+
+const SIDE_QUESTION_INSTRUCTION =
+ "Answer this one side question using only the conversation context above. Do not use tools and do not ask a follow-up question.";
+
+function readAssistantText(message: AgentMessage): string {
+ if (message.role !== "assistant") {
+ return "";
+ }
+ return message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+}
+
+export function startSideQuestion(
+ parent: Agent,
+ id: string,
+ question: string,
+ onEvent: (event: SideQuestionEvent) => void | Promise<void>,
+): SideQuestionRun {
+ const model = parent.state.model;
+ if (!model) {
+ throw new Error("Select a model before asking a side question");
+ }
+
+ const sideAgent = new Agent({
+ initialState: {
+ model,
+ systemPrompt: parent.state.systemPrompt,
+ messages: structuredClone(parent.state.messages),
+ thinkingLevel: "off",
+ tools: [],
+ },
+ convertToLlm: parent.convertToLlm,
+ transformContext: parent.transformContext,
+ streamFn: parent.streamFn,
+ getApiKey: parent.getApiKey,
+ onPayload: parent.onPayload,
+ onResponse: parent.onResponse,
+ shouldStopAfterTurn: () => true,
+ sessionId: parent.sessionId,
+ thinkingBudgets: parent.thinkingBudgets,
+ transport: "sse",
+ maxRetryDelayMs: parent.maxRetryDelayMs,
+ toolExecution: parent.toolExecution,
+ });
+
+ let answer = "";
+ let abortRequested = false;
+ let started = false;
+ const emit = (status: SideQuestionStatus, errorMessage?: string) =>
+ onEvent({ id, question, answer, status, ...(errorMessage ? { errorMessage } : {}) });
+
+ const unsubscribe = sideAgent.subscribe(async (event) => {
+ if (event.type !== "message_update" && event.type !== "message_end") {
+ return;
+ }
+ const nextAnswer = readAssistantText(event.message);
+ if (nextAnswer === answer) {
+ return;
+ }
+ answer = nextAnswer;
+ await emit("running");
+ });
+
+ const prompt = `<side_question>\n${SIDE_QUESTION_INSTRUCTION}\n\n${question}\n</side_question>`;
+ const done = Promise.resolve()
+ .then(() => emit("running"))
+ .then(async () => {
+ if (abortRequested) {
+ await emit("cancelled");
+ return;
+ }
+ started = true;
+ await sideAgent.prompt(prompt);
+ if (abortRequested) {
+ await emit("cancelled");
+ return;
+ }
+ if (sideAgent.state.errorMessage) {
+ await emit("error", sideAgent.state.errorMessage);
+ return;
+ }
+ await emit("complete");
+ })
+ .catch(async (error) => {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ await Promise.resolve(
+ emit(abortRequested ? "cancelled" : "error", abortRequested ? undefined : errorMessage),
+ ).catch(() => undefined);
+ })
+ .finally(unsubscribe);
+
+ return {
+ done,
+ abort() {
+ abortRequested = true;
+ if (started) {
+ sideAgent.abort();
+ }
+ },
+ };
+}
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index 400bbc169b..69b84f5fca 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -44,6 +44,12 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
{ name: "import", description: "Import and resume a session from a JSONL file" },
{ name: "share", description: "Share session as a secret GitHub gist" },
{ name: "copy", description: "Copy last agent message to clipboard" },
+ {
+ name: "btw",
+ description: "Ask one side question without adding it to the session",
+ argumentHint: "<question>",
+ takesArgument: true,
+ },
{ name: "name", description: "Set session display name" },
{ name: "session", description: "Show session info" },
{ name: "system-prompt", description: "Show the exact system prompt sent to the model" },
@@ -103,6 +109,7 @@ const BUILTIN_SLASH_COMMAND_ALIASES: ReadonlyArray<BuiltinSlashCommandAlias> = [
{ name: "usage", aliasFor: "context" },
{ name: "thinking", aliasFor: "effort" },
{ name: "rename", aliasFor: "name" },
+ { name: "side", aliasFor: "btw" },
];
function buildBuiltinSlashCommands(): ReadonlyArray<BuiltinSlashCommand> {
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 450ed9c697..c471da5b26 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -48,6 +48,7 @@ import type {
AgentConnectionSessionListCallbacks,
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
+ AgentConnectionSideQuestionEvent,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionState,
@@ -86,6 +87,7 @@ export class DaemonAgentConnection implements AgentConnection {
private lastEventSequence: number | undefined;
private latestSnapshot: AgentConnectionSnapshot | undefined;
private latestSnapshotIsFresh = false;
+ private readonly activeSideQuestionIds = new Set<string>();
constructor(
private readonly client: DaemonClient,
@@ -421,6 +423,34 @@ export class DaemonAgentConnection implements AgentConnection {
});
}
+ async startSideQuestion(id: string, question: string): Promise<void> {
+ this.activeSideQuestionIds.add(id);
+ try {
+ await this.requestOk({
+ type: "start_side_question",
+ activeSessionId: this.activeSessionId,
+ sideQuestionId: id,
+ question,
+ });
+ } catch (error) {
+ this.activeSideQuestionIds.delete(id);
+ if (isUnknownDaemonCommandError(error, "start_side_question")) {
+ throw new Error("the daemon is running an older build; restart the daemon and try again");
+ }
+ throw error;
+ }
+ }
+
+ async abortSideQuestion(id: string): Promise<boolean> {
+ const data = await this.requestData<{ aborted: boolean }>({
+ type: "abort_side_question",
+ activeSessionId: this.activeSessionId,
+ sideQuestionId: id,
+ });
+ this.activeSideQuestionIds.delete(id);
+ return data.aborted;
+ }
+
async steer(message: string, images?: ImageContent[]): Promise<void> {
await this.requestOk({ type: "steer", activeSessionId: this.activeSessionId, message, images });
}
@@ -683,6 +713,7 @@ export class DaemonAgentConnection implements AgentConnection {
}
async dispose(): Promise<void> {
+ await Promise.allSettled([...this.activeSideQuestionIds].map((id) => this.abortSideQuestion(id)));
this.unsubscribeDaemonMessages();
this.unsubscribeDaemonClose();
await this.requestOk({ type: "detach", activeSessionId: this.activeSessionId }).catch(() => undefined);
@@ -720,6 +751,11 @@ export class DaemonAgentConnection implements AgentConnection {
await this.emit({ type: "session_event", event: message.event });
return;
}
+ if (message.type === "side_question_event") {
+ this.observeSideQuestionEvent(message.event);
+ await this.emit({ type: "side_question_event", event: message.event });
+ return;
+ }
if (message.type === "session_status") {
// Keep a cached snapshot's recap current so a later re-attach seeds it.
if (this.latestSnapshot) {
@@ -786,6 +822,12 @@ export class DaemonAgentConnection implements AgentConnection {
await listener(event);
}
}
+
+ private observeSideQuestionEvent(event: AgentConnectionSideQuestionEvent): void {
+ if (event.status !== "running") {
+ this.activeSideQuestionIds.delete(event.id);
+ }
+ }
}
function getAttachActiveSessionId(result: SessionSummary | DaemonAttachResult): string {
@@ -869,6 +911,8 @@ function invalidatesCachedSnapshot(commandType: DaemonCommandBody["type"]): bool
case "get_last_assistant_text":
case "get_system_prompt":
case "get_tool_definition":
+ case "start_side_question":
+ case "abort_side_question":
case "export_html":
case "export_jsonl":
return false;
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index 359629db47..7649d6cb98 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -9,6 +9,7 @@ import type { RefinementResult } from "../../core/refinement/index.js";
import { type DeleteSessionFileResult, deleteSessionFile } from "../../core/session-file-actions.js";
import { SessionManager } from "../../core/session-manager.js";
import type { SessionStats } from "../../core/session-stats.js";
+import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";
import {
createAgentConnectionCommands,
createAgentConnectionResourceSnapshot,
@@ -51,11 +52,13 @@ import type {
export class InProcessAgentConnection implements AgentConnection {
private readonly listeners = new Set<AgentConnectionEventListener>();
private readonly beforeSessionInvalidateListeners = new Set<AgentConnectionBeforeSessionInvalidateListener>();
+ private readonly sideQuestionRuns = new Map<string, SideQuestionRun>();
private unsubscribeSessionEvents: (() => void) | undefined;
constructor(private readonly runtimeHost: AgentSessionRuntime) {
this.bindCurrentSessionEvents();
this.runtimeHost.setBeforeSessionInvalidate(() => {
+ this.abortAllSideQuestions();
for (const listener of [...this.beforeSessionInvalidateListeners]) {
listener();
}
@@ -214,6 +217,29 @@ export class InProcessAgentConnection implements AgentConnection {
});
}
+ async startSideQuestion(id: string, question: string): Promise<void> {
+ if (this.sideQuestionRuns.has(id)) {
+ throw new Error(`Side question already exists: ${id}`);
+ }
+ const run = startSideQuestion(this.session.agent, id, question, (event) =>
+ this.emit({ type: "side_question_event", event }),
+ );
+ this.sideQuestionRuns.set(id, run);
+ const removeRun = () => {
+ this.sideQuestionRuns.delete(id);
+ };
+ void run.done.then(removeRun, removeRun);
+ }
+
+ async abortSideQuestion(id: string): Promise<boolean> {
+ const run = this.sideQuestionRuns.get(id);
+ if (!run) {
+ return false;
+ }
+ run.abort();
+ return true;
+ }
+
async steer(message: string, images?: ImageContent[]): Promise<void> {
await this.session.steer(message, images);
}
@@ -404,6 +430,7 @@ export class InProcessAgentConnection implements AgentConnection {
}
async dispose(): Promise<void> {
+ this.abortAllSideQuestions();
this.unsubscribeSessionEvents?.();
this.unsubscribeSessionEvents = undefined;
this.runtimeHost.setBeforeSessionInvalidate(undefined);
@@ -422,6 +449,13 @@ export class InProcessAgentConnection implements AgentConnection {
});
}
+ private abortAllSideQuestions(): void {
+ for (const run of this.sideQuestionRuns.values()) {
+ run.abort();
+ }
+ this.sideQuestionRuns.clear();
+ }
+
private async emit(event: AgentConnectionEvent): Promise<void> {
for (const listener of [...this.listeners]) {
await listener(event);
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index 30263c4383..d795959603 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -58,6 +58,7 @@ export type {
AgentConnectionSessionStateEntry,
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
+ AgentConnectionSideQuestionEvent,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionSourceInfo,
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 6cca8be419..2af19911f1 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -379,6 +379,14 @@ export interface AgentConnectionPromptOptions {
streamingBehavior?: "steer" | "followUp";
}
+export interface AgentConnectionSideQuestionEvent {
+ id: string;
+ question: string;
+ answer: string;
+ status: "running" | "complete" | "cancelled" | "error";
+ errorMessage?: string;
+}
+
export interface AgentConnectionExecuteBashOptions {
excludeFromContext?: boolean;
}
@@ -499,6 +507,7 @@ export type AgentConnectionSessionEvent =
export type AgentConnectionEvent =
| { type: "session_event"; event: AgentConnectionSessionEvent }
+ | { type: "side_question_event"; event: AgentConnectionSideQuestionEvent }
| { type: "session_replaced"; state: AgentConnectionState; messages: AgentMessage[] }
| { type: "session_status"; recap?: string }
| { type: "extension_ui_request"; request: AgentConnectionExtensionUiRequest }
@@ -543,6 +552,8 @@ export interface AgentConnection {
respondToExtensionUiRequest(requestId: string, response: AgentConnectionExtensionUiResponse): Promise<void>;
prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void>;
+ startSideQuestion(id: string, question: string): Promise<void>;
+ abortSideQuestion(id: string): Promise<boolean>;
steer(message: string, images?: ImageContent[]): Promise<void>;
followUp(message: string, images?: ImageContent[]): Promise<void>;
/** Request cancellation of the active turn and return once the request is accepted. */
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 150b25c443..aac19cbb04 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -79,6 +79,7 @@ import type {
import { deleteSessionFile } from "../../core/session-file-actions.js";
import { type SessionInfo, SessionManager } from "../../core/session-manager.js";
import type { SessionStats } from "../../core/session-stats.js";
+import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";
import { killTrackedDetachedChildren } from "../../utils/shell.js";
import {
createAgentConnectionCommands,
@@ -160,6 +161,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"agent_messages_resume",
"agent_messages_clear",
"abort",
+ "start_side_question",
+ "abort_side_question",
"execute_bash",
"abort_bash",
"cancel_rlm_child",
@@ -252,6 +255,10 @@ export class AgentDaemon {
private readonly sessions = new Map<string, ActiveSessionState>();
private readonly openingSessions = new Map<string, Promise<ActiveSessionState>>();
private readonly closingSessions = new Map<string, Promise<void>>();
+ private readonly sideQuestionRuns = new Map<
+ string,
+ { run: SideQuestionRun; client: DaemonSocketClient; activeSessionId: string }
+ >();
private readonly signalCleanupHandlers: Array<() => void> = [];
private readonly cronStore: AgentCronJobStore;
private readonly cronScheduler: AgentCronScheduler;
@@ -447,6 +454,9 @@ export class AgentDaemon {
}
private refreshReplacedSessionState(state: ActiveSessionState): void {
+ for (const client of state.clients) {
+ this.abortSideQuestionsFor(client, state.activeSessionId);
+ }
this.summarizer.forget(state.activeSessionId);
state.summaryState = undefined;
state.runtime.session.setCurrentRecap(undefined);
@@ -1551,6 +1561,53 @@ export class AgentDaemon {
return success(command.id, "abort");
}
+ case "start_side_question": {
+ const state = this.getSessionState(command.activeSessionId);
+ if (this.sideQuestionRuns.has(command.sideQuestionId)) {
+ throw new Error(`Side question already exists: ${command.sideQuestionId}`);
+ }
+ if (this.hasActiveSideQuestionFor(client, state.activeSessionId)) {
+ throw new Error("A side question is already running for this client and session");
+ }
+ const run = startSideQuestion(
+ state.runtime.session.agent,
+ command.sideQuestionId,
+ command.question,
+ (event) => {
+ this.write(client, {
+ type: "side_question_event",
+ activeSessionId: state.activeSessionId,
+ event,
+ });
+ if (event.status !== "running") {
+ this.sideQuestionRuns.delete(event.id);
+ }
+ },
+ );
+ this.sideQuestionRuns.set(command.sideQuestionId, {
+ run,
+ client,
+ activeSessionId: state.activeSessionId,
+ });
+ void run.done.catch((error) => {
+ this.sideQuestionRuns.delete(command.sideQuestionId);
+ this.log(
+ `side question ${command.sideQuestionId} failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
+ return success(command.id, "start_side_question");
+ }
+
+ case "abort_side_question": {
+ this.getSessionState(command.activeSessionId);
+ const entry = this.sideQuestionRuns.get(command.sideQuestionId);
+ if (!entry || entry.client !== client || entry.activeSessionId !== command.activeSessionId) {
+ return success(command.id, "abort_side_question", { aborted: false });
+ }
+ entry.run.abort();
+ return success(command.id, "abort_side_question", { aborted: true });
+ }
+
case "execute_bash": {
const state = this.getSessionState(command.activeSessionId);
if (state.runtime.session.isBashRunning) {
@@ -2275,6 +2332,7 @@ export class AgentDaemon {
}
private detachClientFromSession(client: DaemonSocketClient, state: ActiveSessionState): void {
+ this.abortSideQuestionsFor(client, state.activeSessionId);
detachClientFromActiveSession(client, state);
this.write(client, { type: "session_detached", activeSessionId: state.activeSessionId });
// Abandoned new-chat: discard it so it doesn't linger in memory or leave an
@@ -2528,6 +2586,9 @@ export class AgentDaemon {
}
private async closeSession(state: ActiveSessionState, reason: DaemonSessionClosedReason): Promise<void> {
+ for (const client of state.clients) {
+ this.abortSideQuestionsFor(client, state.activeSessionId);
+ }
const existingClose = this.closingSessions.get(state.activeSessionId);
if (existingClose) {
await existingClose;
@@ -2688,6 +2749,25 @@ export class AgentDaemon {
client.socket.write(serializeJsonLine(message));
}
+ private abortSideQuestionsFor(client: DaemonSocketClient, activeSessionId: string): void {
+ for (const [id, entry] of this.sideQuestionRuns) {
+ if (entry.client !== client || entry.activeSessionId !== activeSessionId) {
+ continue;
+ }
+ entry.run.abort();
+ this.sideQuestionRuns.delete(id);
+ }
+ }
+
+ private hasActiveSideQuestionFor(client: DaemonSocketClient, activeSessionId: string): boolean {
+ for (const entry of this.sideQuestionRuns.values()) {
+ if (entry.client === client && entry.activeSessionId === activeSessionId) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private registerSignalHandlers(): void {
const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM"];
if (process.platform !== "win32") {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 352df4aa22..8682a85291 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -22,6 +22,7 @@ import type {
AgentConnectionSessionContext,
AgentConnectionSessionEvent,
AgentConnectionSessionTreeNode,
+ AgentConnectionSideQuestionEvent,
AgentConnectionState,
} from "../agent-connection/types.js";
import type { SessionSummary } from "./daemon-session-list.js";
@@ -315,6 +316,14 @@ export type DaemonCommand =
| { id?: string; type: "agent_messages_resume" }
| { id?: string; type: "agent_messages_clear"; activeSessionId: string }
| { id?: string; type: "abort"; activeSessionId: string }
+ | {
+ id?: string;
+ type: "start_side_question";
+ activeSessionId: string;
+ sideQuestionId: string;
+ question: string;
+ }
+ | { id?: string; type: "abort_side_question"; activeSessionId: string; sideQuestionId: string }
| {
id?: string;
type: "execute_bash";
@@ -486,6 +495,7 @@ export type DaemonOutbound =
serverCapabilities: readonly DaemonClientCapability[];
}
| { type: "session_event"; activeSessionId: string; event: AgentConnectionSessionEvent; meta?: DaemonEventMeta }
+ | { type: "side_question_event"; activeSessionId: string; event: AgentConnectionSideQuestionEvent }
| { type: "session_status"; activeSessionId: string; recap?: string; meta?: DaemonEventMeta }
| {
type: "session_replaced";
diff --git a/packages/coding-agent/src/modes/interactive/components/side-question.ts b/packages/coding-agent/src/modes/interactive/components/side-question.ts
new file mode 100644
index 0000000000..e835794e00
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/side-question.ts
@@ -0,0 +1,70 @@
+import { type Component, Markdown, Text, visibleWidth } from "@earendil-works/pi-tui";
+import type { AgentConnectionSideQuestionEvent } from "../../agent-connection/types.js";
+import { getMarkdownTheme, theme } from "../theme/theme.js";
+
+export class SideQuestionComponent implements Component {
+ private readonly paddingX: number;
+ private readonly answer: Markdown;
+ private event: AgentConnectionSideQuestionEvent;
+
+ constructor(
+ event: AgentConnectionSideQuestionEvent,
+ private readonly getMaxLines: () => number,
+ paddingX = 2,
+ ) {
+ this.event = event;
+ this.paddingX = Math.max(2, paddingX);
+ this.answer = new Markdown("", this.paddingX, 0, getMarkdownTheme(), {
+ color: (content: string) => theme.fg("userMessageText", content),
+ });
+ this.answer.setText(event.answer);
+ }
+
+ update(event: AgentConnectionSideQuestionEvent): void {
+ this.event = event;
+ this.answer.setText(event.answer);
+ }
+
+ invalidate(): void {
+ this.answer.invalidate();
+ }
+
+ render(width: number): string[] {
+ const blank = " ".repeat(Math.max(1, width));
+ const question = new Text(
+ `${theme.fg("accent", "/btw")} ${theme.bold(theme.fg("userMessageText", this.event.question))}`,
+ this.paddingX,
+ 0,
+ ).render(width);
+ const lines = [blank, ...question, blank, ...this.renderAnswer(width), blank];
+ const maxLines = Math.max(6, this.getMaxLines());
+ if (lines.length <= maxLines) {
+ return lines.map((line) => this.applySurface(line, width));
+ }
+ const ellipsis = new Text(theme.fg("dim", "…"), this.paddingX, 0).render(width)[0] ?? blank;
+ return [...lines.slice(0, maxLines - 1), ellipsis].map((line) => this.applySurface(line, width));
+ }
+
+ private renderAnswer(width: number): string[] {
+ if (this.event.answer) {
+ return this.answer.render(width);
+ }
+ if (this.event.errorMessage) {
+ return new Text(theme.fg("error", this.event.errorMessage), this.paddingX, 0).render(width);
+ }
+ if (this.event.status === "cancelled") {
+ return new Text(theme.fg("userMessageText", "Cancelled"), this.paddingX, 0).render(width);
+ }
+ const message = this.event.status === "complete" ? "No response" : "Thinking…";
+ return new Text(theme.fg("userMessageText", message), this.paddingX, 0).render(width);
+ }
+
+ private applySurface(line: string, width: number): string {
+ const padded = line + " ".repeat(Math.max(0, width - visibleWidth(line)));
+ const background = theme.getUserMessageBackgroundColor();
+ return padded
+ .split("\x1b[0m")
+ .map((segment) => background(segment))
+ .join("\x1b[0m");
+ }
+}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 33712fa2fb..7d8563af69 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -3,6 +3,7 @@
* Handles TUI rendering and user interaction, delegating agent execution to AgentConnection.
*/
+import { randomUUID } from "node:crypto";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
@@ -124,6 +125,7 @@ import type {
AgentConnectionSessionEvent,
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
+ AgentConnectionSideQuestionEvent,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionSourceInfo,
@@ -170,6 +172,7 @@ import { ScopedModelsSelectorComponent } from "./components/scoped-models-select
import { SessionPickerScreen } from "./components/session-picker-screen.js";
import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
+import { SideQuestionComponent } from "./components/side-question.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
import { SubagentTreeView } from "./components/subagent-tree-view.js";
import { ToolExecutionComponent, type ToolExecutionDefinition } from "./components/tool-execution.js";
@@ -598,6 +601,7 @@ export class InteractiveMode {
private pendingMessagesContainer: Container;
private statusContainer: Container;
private queuedMessagesContainer: Container;
+ private sideQuestionContainer: Container;
private defaultEditor: CustomEditor;
private editor: EditorComponent;
private promptStash: PromptStash | undefined;
@@ -654,6 +658,9 @@ export class InteractiveMode {
// Streaming message tracking
private streamingComponent: AssistantMessageComponent | undefined = undefined;
private streamingMessage: AssistantMessage | undefined = undefined;
+ private sideQuestionComponent: SideQuestionComponent | undefined;
+ private sideQuestionEvent: AgentConnectionSideQuestionEvent | undefined;
+ private activeSideQuestionId: string | undefined;
// User bash execution tracking (! / !! prefix), driven by bash_* session events
private activeBashComponent: BashExecutionComponent | undefined = undefined;
@@ -789,6 +796,7 @@ export class InteractiveMode {
}
this.agentConnection.onBeforeSessionInvalidate(() => {
this.resetExtensionUI();
+ this.resetSideQuestion();
});
this.version = VERSION;
this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
@@ -802,6 +810,7 @@ export class InteractiveMode {
this.pendingMessagesContainer = new Container();
this.statusContainer = new Container();
this.queuedMessagesContainer = new Container();
+ this.sideQuestionContainer = new Container();
this.childAgentDetail = new ChildAgentDetailComponent(() => this.getChildAgentPanelRows(), {
ui: this.ui,
});
@@ -1095,11 +1104,13 @@ export class InteractiveMode {
this.renderRecap();
this.mainContainer.addChild(this.recapContainer);
this.mainContainer.addChild(this.queuedMessagesContainer);
+ this.mainContainer.addChild(this.sideQuestionContainer);
this.mainContainer.addChild(this.editorContainer);
this.mainContainer.addChild(this.childAgentSummary);
this.mainContainer.addChild(this.widgetContainerBelow);
this.footerSlot.addChild(this.footer);
this.mainContainer.addChild(this.footerSlot);
+ this.promptDock.addChild(this.sideQuestionContainer);
this.promptDock.addChild(this.editorContainer);
this.promptDock.addChild(this.childAgentSummary);
this.promptDock.addChild(this.footerSlot);
@@ -2124,13 +2135,7 @@ export class InteractiveMode {
return { cancelled: true };
}
- this.chatContainer.clear();
- await this.renderInitialMessages();
- if (result.editorText && !this.editor.getText().trim()) {
- this.editor.setText(result.editorText);
- }
- this.showStatus("Navigated to selected point");
- void this.flushCompactionQueue({ willRetry: false });
+ await this.renderTreeNavigation(result);
return { cancelled: false };
},
switchSession: async (sessionPath, options) => {
@@ -2336,7 +2341,13 @@ export class InteractiveMode {
}
private hasInterruptibleWork(): boolean {
- return this.isAgentStreaming() || this.isAgentCompacting() || this.isBashRunning() || this.getRetryAttempt() > 0;
+ return (
+ this.isAgentStreaming() ||
+ this.isAgentCompacting() ||
+ this.isBashRunning() ||
+ this.getRetryAttempt() > 0 ||
+ this.sideQuestionEvent?.status === "running"
+ );
}
private getRetryAttempt(): number {
@@ -3689,6 +3700,105 @@ export class InteractiveMode {
return images.length > 0 ? images : undefined;
}
+ private async handleSideQuestion(question: string): Promise<void> {
+ if (!question) {
+ this.showWarning("Usage: /btw <question>");
+ return;
+ }
+ if (this.activeSideQuestionId) {
+ this.showWarning("Wait for the current side question to finish or cancel it first.");
+ return;
+ }
+
+ this.clearSideQuestion();
+ const event: AgentConnectionSideQuestionEvent = {
+ id: randomUUID(),
+ question,
+ answer: "",
+ status: "running",
+ };
+ this.activeSideQuestionId = event.id;
+ this.sideQuestionEvent = event;
+ this.sideQuestionComponent = new SideQuestionComponent(
+ event,
+ () => this.getSideQuestionMaxLines(),
+ this.settingsManager.getEditorPaddingX(),
+ );
+ this.sideQuestionContainer.addChild(new Spacer(1));
+ this.sideQuestionContainer.addChild(this.sideQuestionComponent);
+ this.ui.requestRender();
+
+ try {
+ await this.agentConnection.startSideQuestion(event.id, question);
+ } catch (error) {
+ this.handleSideQuestionEvent({
+ ...event,
+ status: "error",
+ errorMessage: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ private handleSideQuestionEvent(event: AgentConnectionSideQuestionEvent): void {
+ if (event.id === this.activeSideQuestionId && event.status !== "running") {
+ this.activeSideQuestionId = undefined;
+ }
+ if (event.id !== this.sideQuestionEvent?.id || !this.sideQuestionComponent) {
+ return;
+ }
+ this.sideQuestionEvent = event;
+ this.sideQuestionComponent.update(event);
+ this.ui.requestRender();
+ }
+
+ private clearSideQuestion(options: { abort?: boolean } = {}): void {
+ const event = this.sideQuestionEvent;
+ if (options.abort && event?.status === "running") {
+ this.abortSideQuestion(event.id);
+ }
+ this.sideQuestionEvent = undefined;
+ this.sideQuestionComponent = undefined;
+ this.sideQuestionContainer.clear();
+ if (this.isInitialized) {
+ this.ui.requestRender();
+ }
+ }
+
+ private resetSideQuestion(): void {
+ this.clearSideQuestion({ abort: true });
+ this.activeSideQuestionId = undefined;
+ }
+
+ private abortSideQuestion(id: string, reportError = false): void {
+ void this.agentConnection
+ .abortSideQuestion(id)
+ .then((aborted) => {
+ if (!aborted && this.activeSideQuestionId === id) {
+ this.activeSideQuestionId = undefined;
+ }
+ })
+ .catch((error) => {
+ if (reportError) {
+ this.showError(error instanceof Error ? error.message : String(error));
+ }
+ });
+ }
+
+ private async renderTreeNavigation(result: { editorText?: string }): Promise<void> {
+ this.clearSideQuestion({ abort: true });
+ this.chatContainer.clear();
+ await this.renderInitialMessages();
+ if (result.editorText && !this.editor.getText().trim()) {
+ this.editor.setText(result.editorText);
+ }
+ this.showStatus("Navigated to selected point");
+ void this.flushCompactionQueue({ willRetry: false });
+ }
+
+ private getSideQuestionMaxLines(): number {
+ return Math.max(6, Math.min(12, Math.floor(this.ui.terminal.rows * 0.3)));
+ }
+
private setupEditorSubmitHandler(): void {
this.defaultEditor.onSubmit = async (text: string) => {
text = text.trim();
@@ -3704,6 +3814,11 @@ export class InteractiveMode {
const canonicalCommandText = commandName ? `/${commandName}${commandArgs ? ` ${commandArgs}` : ""}` : text;
// Handle commands
+ if (commandName === "btw") {
+ this.editor.setText("");
+ await this.handleSideQuestion(commandArgs);
+ return;
+ }
if (commandName === "settings" && !commandArgs) {
await this.showSettingsSelector();
this.editor.setText("");
@@ -3919,6 +4034,7 @@ export class InteractiveMode {
);
return;
}
+ this.clearSideQuestion({ abort: true });
this.editor.addToHistory?.(text);
this.editor.setText("");
// Optimistic: bash_start only fires after extension dispatch, and the
@@ -3940,6 +4056,8 @@ export class InteractiveMode {
return;
}
+ this.clearSideQuestion({ abort: true });
+
// Queue input during compaction (extension commands execute immediately)
if (this.isAgentCompacting()) {
if (this.isExtensionCommand(text)) {
@@ -3991,6 +4109,7 @@ export class InteractiveMode {
this.sessionEventQueue = run.catch(() => {});
await run;
} else if (event.type === "session_replaced") {
+ this.resetSideQuestion();
this.resetExtensionUI();
this.applyConnectionStateSnapshot(event.state);
this.resetCurrentSessionRenderState({ clearPromptStash: true });
@@ -4001,6 +4120,8 @@ export class InteractiveMode {
this.sessionRecap = event.recap;
this.patchConnectionState({ recap: event.recap });
this.renderRecap();
+ } else if (event.type === "side_question_event") {
+ this.handleSideQuestionEvent(event.event);
} else if (event.type === "extension_ui_request") {
await this.handleConnectionExtensionUiRequest(event.request);
} else if (event.type === "closed") {
@@ -5559,6 +5680,11 @@ export class InteractiveMode {
private handleEscape(): void {
this.clearCtrlCExitHint();
+ if (this.sideQuestionEvent) {
+ this.clearEscapeRepeat();
+ this.clearSideQuestion({ abort: true });
+ return;
+ }
const action = this.takeEscapeRepeatAction();
if (action === "tree") {
void this.showTreeSelector();
@@ -5618,6 +5744,9 @@ export class InteractiveMode {
}
private interruptOrClearInput(): void {
+ if (this.sideQuestionEvent?.status === "running") {
+ this.abortSideQuestion(this.sideQuestionEvent.id, true);
+ }
if (this.getRetryAttempt() > 0) {
void this.agentConnection.abortRetry();
}
@@ -7109,14 +7238,7 @@ export class InteractiveMode {
return;
}
- // Update UI
- this.chatContainer.clear();
- await this.renderInitialMessages();
- if (result.editorText && !this.editor.getText().trim()) {
- this.editor.setText(result.editorText);
- }
- this.showStatus("Navigated to selected point");
- void this.flushCompactionQueue({ willRetry: false });
+ await this.renderTreeNavigation(result);
} catch (error) {
this.showError(error instanceof Error ? error.message : String(error));
} finally {
diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
index 5672581910..0085294032 100644
--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -64,6 +64,7 @@ type ResetHarness = PromptStashLiveMarkerHarness & {
type SubmitHarness = PromptStashHarness & {
defaultEditor: { onSubmit?: (text: string) => void | Promise<void> };
+ sideQuestionContainer: { clear: Mock };
isAgentCompacting: () => boolean;
isAgentStreaming: () => boolean;
flushPendingBashComponents: Mock;
@@ -227,6 +228,7 @@ describe("InteractiveMode prompt stash", () => {
const mode: SubmitHarness = {
...createPromptStashHarness({ stash: "half-written draft" }),
defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
isAgentCompacting: () => false,
isAgentStreaming: () => false,
flushPendingBashComponents: vi.fn(),
@@ -248,6 +250,7 @@ describe("InteractiveMode prompt stash", () => {
mode = {
...createPromptStashHarness({ stash: "half-written draft" }),
defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
isAgentCompacting: () => false,
isAgentStreaming: () => false,
flushPendingBashComponents: vi.fn(),
@@ -275,6 +278,7 @@ describe("InteractiveMode prompt stash", () => {
mode = {
...createPromptStashHarness({ stash: "half-written draft" }),
defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
isAgentCompacting: () => false,
isAgentStreaming: () => false,
flushPendingBashComponents: vi.fn(),
@@ -305,6 +309,7 @@ describe("InteractiveMode prompt stash", () => {
const mode: SubmitHarness & { showSettingsSelector: Mock<() => Promise<void>> } = {
...createPromptStashHarness({ text: "/settings", stash: "half-written draft" }),
defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
isAgentCompacting: () => false,
isAgentStreaming: () => false,
flushPendingBashComponents: vi.fn(),
@@ -398,6 +403,7 @@ describe("InteractiveMode prompt stash", () => {
} = {
...createPromptStashHarness({ text: "quick follow-up", stash: "half-written draft" }),
defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
isAgentCompacting: () => false,
isAgentStreaming: () => true,
flushPendingBashComponents: vi.fn(),
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index e0197c6f6f..a9e2b9e323 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -302,6 +302,7 @@ describe("InteractiveMode.renderSessionContext", () => {
type SubmitHandlerHarness = {
defaultEditor: { onSubmit?: (text: string) => Promise<void> };
editor: { setText: (text: string) => void; addToHistory?: (text: string) => void };
+ clearSideQuestion: () => void;
clearShortcutGuide: () => void;
showWarning: (message: string) => void;
showError: (message: string) => void;
@@ -318,6 +319,7 @@ function createSubmitHandlerHarness(overrides: Partial<SubmitHandlerHarness> = {
const fakeThis: SubmitHandlerHarness = {
defaultEditor: {},
editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ clearSideQuestion: vi.fn(),
clearShortcutGuide: vi.fn(),
showWarning: vi.fn(),
showError: vi.fn(),
@@ -573,6 +575,7 @@ describe("InteractiveMode connection events", () => {
return vi.fn();
}),
},
+ resetSideQuestion: vi.fn(),
resetExtensionUI: vi.fn(),
applyConnectionStateSnapshot: vi.fn(),
resetCurrentSessionRenderState: vi.fn(),
diff --git a/packages/coding-agent/test/slash-commands.test.ts b/packages/coding-agent/test/slash-commands.test.ts
index 0b40523d99..c707b63010 100644
--- a/packages/coding-agent/test/slash-commands.test.ts
+++ b/packages/coding-agent/test/slash-commands.test.ts
@@ -32,6 +32,16 @@ describe("built-in slash commands", () => {
});
});
+ test("exposes /btw as an argument command with /side as an alias", () => {
+ expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "btw")).toMatchObject({
+ argumentHint: "<question>",
+ aliases: ["side"],
+ takesArgument: true,
+ });
+ expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "side")).toBeUndefined();
+ expect(builtinSlashCommandTakesArgument("side")).toBe(true);
+ });
+
test("marks argument commands as taking a free-form argument", () => {
expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "goal")).toMatchObject({
takesArgument: true,
@@ -117,4 +127,15 @@ describe("slash command aliases", () => {
isAlias: true,
});
});
+
+ test("resolves /side to /btw", () => {
+ const parsed = parseSlashCommand("/side Is this cached?");
+
+ expect(resolveSlashCommand(parsed!)).toEqual({
+ name: "btw",
+ args: "Is this cached?",
+ originalName: "side",
+ isAlias: true,
+ });
+ });
});
diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
new file mode 100644
index 0000000000..cd0d77932a
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -0,0 +1,377 @@
+import { fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { Container } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { type SideQuestionEvent, startSideQuestion } from "../../../src/core/side-question.js";
+import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";
+import { SideQuestionComponent } from "../../../src/modes/interactive/components/side-question.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, getMessageText } from "../harness.js";
+
+function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve = () => {};
+ const promise = new Promise<void>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+describe("ENG-4509 side questions", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ it("uses the current context without tools or session persistence", async () => {
+ const harness = await createHarness({ systemPrompt: "Remember relevant project context." });
+ try {
+ harness.setResponses([fauxAssistantMessage("The codename is kestrel.")]);
+ await harness.session.prompt("The project codename is kestrel.");
+ harness.session.agent.sessionId = "cache-session";
+ const systemPromptBefore = harness.session.agent.state.systemPrompt;
+ const messagesBefore = structuredClone(harness.session.messages);
+ const entriesBefore = structuredClone(harness.sessionManager.getEntries());
+ const events: SideQuestionEvent[] = [];
+ let observedTransport: string | undefined;
+ let observedSessionId: string | undefined;
+
+ harness.setResponses([
+ (context, options) => {
+ expect(context.systemPrompt).toBe(systemPromptBefore);
+ expect(context.tools).toEqual([]);
+ expect(context.messages.map(getMessageText)).toEqual([
+ "The project codename is kestrel.",
+ "The codename is kestrel.",
+ expect.stringContaining("What is the project codename?"),
+ ]);
+ observedTransport = options?.transport;
+ observedSessionId = options?.sessionId;
+ return fauxAssistantMessage("kestrel");
+ },
+ ]);
+
+ const run = startSideQuestion(
+ harness.session.agent,
+ "question-1",
+ "What is the project codename?",
+ (event) => {
+ events.push(event);
+ },
+ );
+ await run.done;
+
+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "kestrel" });
+ expect(observedTransport).toBe("sse");
+ expect(observedSessionId).toBe("cache-session");
+ expect(harness.session.messages).toEqual(messagesBefore);
+ expect(harness.sessionManager.getEntries()).toEqual(entriesBefore);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("can finish while the main agent is still working", async () => {
+ const harness = await createHarness();
+ const mainStarted = deferred();
+ const releaseMain = deferred();
+ try {
+ harness.setResponses([
+ async () => {
+ mainStarted.resolve();
+ await releaseMain.promise;
+ return fauxAssistantMessage("main complete");
+ },
+ (context) => {
+ expect(context.tools).toEqual([]);
+ expect(context.messages.map(getMessageText)).toEqual([
+ "Run the main task.",
+ expect.stringContaining("Can I ask this concurrently?"),
+ ]);
+ return fauxAssistantMessage("yes");
+ },
+ ]);
+
+ const mainRun = harness.session.prompt("Run the main task.");
+ await mainStarted.promise;
+ const events: SideQuestionEvent[] = [];
+ const sideRun = startSideQuestion(
+ harness.session.agent,
+ "question-2",
+ "Can I ask this concurrently?",
+ (event) => {
+ events.push(event);
+ },
+ );
+ await sideRun.done;
+
+ expect(harness.session.isStreaming).toBe(true);
+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "yes" });
+ releaseMain.resolve();
+ await mainRun;
+ } finally {
+ releaseMain.resolve();
+ await harness.session.agent.waitForIdle();
+ harness.cleanup();
+ }
+ });
+
+ it("cancels independently of the main agent", async () => {
+ const harness = await createHarness();
+ const sideStarted = deferred();
+ try {
+ harness.setResponses([
+ async (_context, options) => {
+ sideStarted.resolve();
+ await new Promise<void>((resolve) => {
+ options?.signal?.addEventListener("abort", () => resolve(), { once: true });
+ });
+ return fauxAssistantMessage("");
+ },
+ ]);
+ const events: SideQuestionEvent[] = [];
+ const run = startSideQuestion(harness.session.agent, "question-3", "Wait here", (event) => {
+ events.push(event);
+ });
+ await sideStarted.promise;
+ run.abort();
+ await run.done;
+
+ expect(events.at(-1)).toMatchObject({ status: "cancelled" });
+ expect(harness.session.isStreaming).toBe(false);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("emits a terminal event after a transient event delivery failure", async () => {
+ const harness = await createHarness();
+ try {
+ const events: SideQuestionEvent[] = [];
+ let shouldFail = true;
+ const run = startSideQuestion(harness.session.agent, "question-4", "Can this recover?", (event) => {
+ if (shouldFail) {
+ shouldFail = false;
+ throw new Error("event delivery failed");
+ }
+ events.push(event);
+ });
+
+ await run.done;
+
+ expect(events).toEqual([expect.objectContaining({ status: "error", errorMessage: "event delivery failed" })]);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("aborts daemon side questions when the session runtime is replaced", () => {
+ const clients = [{ id: "client-1" }, { id: "client-2" }];
+ const sessionState = {
+ activeSessionId: "session-1",
+ clients: new Set(clients),
+ summaryState: undefined,
+ runtime: {
+ metadata: { kind: "primary" },
+ session: { setCurrentRecap: vi.fn() },
+ },
+ };
+ const abortSideQuestionsFor = vi.fn();
+ const fakeThis = Object.assign(Object.create(AgentDaemon.prototype), {
+ abortSideQuestionsFor,
+ summarizer: { forget: vi.fn(), seed: vi.fn() },
+ rebindCronJobsToState: vi.fn(),
+ });
+ const refreshReplacedSessionState = (
+ AgentDaemon.prototype as unknown as {
+ refreshReplacedSessionState(this: typeof fakeThis, state: typeof sessionState): void;
+ }
+ ).refreshReplacedSessionState;
+
+ refreshReplacedSessionState.call(fakeThis, sessionState);
+
+ expect(abortSideQuestionsFor).toHaveBeenCalledTimes(2);
+ expect(abortSideQuestionsFor).toHaveBeenNthCalledWith(1, clients[0], "session-1");
+ expect(abortSideQuestionsFor).toHaveBeenNthCalledWith(2, clients[1], "session-1");
+ });
+
+ it("limits daemon side questions to one run per client and session", () => {
+ const client = { id: "client-1" };
+ const otherClient = { id: "client-2" };
+ const fakeThis = Object.assign(Object.create(AgentDaemon.prototype), {
+ sideQuestionRuns: new Map([
+ ["question-1", { client, activeSessionId: "session-1", run: { abort: vi.fn(), done: Promise.resolve() } }],
+ ]),
+ });
+ const hasActiveSideQuestionFor = (
+ AgentDaemon.prototype as unknown as {
+ hasActiveSideQuestionFor(this: typeof fakeThis, candidate: typeof client, activeSessionId: string): boolean;
+ }
+ ).hasActiveSideQuestionFor;
+
+ expect(hasActiveSideQuestionFor.call(fakeThis, client, "session-1")).toBe(true);
+ expect(hasActiveSideQuestionFor.call(fakeThis, client, "session-2")).toBe(false);
+ expect(hasActiveSideQuestionFor.call(fakeThis, otherClient, "session-1")).toBe(false);
+ });
+
+ it("renders a bounded one-turn panel above the prompt", () => {
+ const component = new SideQuestionComponent(
+ {
+ id: "question-4",
+ question: "What changed?",
+ answer: "First line\n\nSecond line\n\nThird line\n\nFourth line",
+ status: "complete",
+ },
+ () => 8,
+ );
+ const lines = component.render(40);
+ const rendered = stripAnsi(lines.join("\n"));
+
+ expect(lines).toHaveLength(8);
+ expect(lines.every((line) => line.includes("\x1b[48"))).toBe(true);
+ expect(rendered).toContain(" /btw What changed?");
+ expect(rendered).not.toContain(" answer");
+ expect(rendered).toContain("First line");
+ expect(rendered).toContain("…");
+ });
+
+ it("aligns the thinking placeholder with the streamed response", () => {
+ const running = new SideQuestionComponent(
+ { id: "question-5", question: "Still running?", answer: "", status: "running" },
+ () => 8,
+ 4,
+ );
+ const complete = new SideQuestionComponent(
+ { id: "question-5", question: "Still running?", answer: "Aligned response", status: "complete" },
+ () => 8,
+ 4,
+ );
+ const runningLines = running.render(40).map(stripAnsi);
+ const completeLines = complete.render(40).map(stripAnsi);
+ const thinkingLine = runningLines.find((line) => line.includes("Thinking…"));
+ const responseLine = completeLines.find((line) => line.includes("Aligned response"));
+ const rawThinkingLine = running.render(40).find((line) => line.includes("Thinking…"));
+
+ expect(thinkingLine?.indexOf("Thinking…")).toBe(responseLine?.indexOf("Aligned response"));
+ expect(rawThinkingLine).toContain("\x1b[39mThinking…");
+ });
+
+ it("uses the user-message foreground for pane content", () => {
+ const component = new SideQuestionComponent(
+ { id: "question-5", question: "Readable question", answer: "Readable response", status: "complete" },
+ () => 8,
+ );
+ const rendered = component.render(40).join("\n");
+
+ expect(rendered).toContain("\x1b[39mReadable question\x1b[39m");
+ expect(rendered).toContain("\x1b[39mReadable response");
+ });
+
+ it("keeps streamed text when a side question is cancelled", () => {
+ const component = new SideQuestionComponent(
+ { id: "question-5", question: "Partial?", answer: "Useful partial response", status: "cancelled" },
+ () => 8,
+ );
+ const rendered = stripAnsi(component.render(40).join("\n"));
+
+ expect(rendered).toContain("Useful partial response");
+ expect(rendered).not.toContain("Cancelled");
+ });
+
+ it("closes and cancels a running pane before handling other Escape actions", () => {
+ const abortSideQuestion = vi.fn(async () => true);
+ const takeEscapeRepeatAction = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ activeSideQuestionId: "question-5",
+ sideQuestionEvent: {
+ id: "question-5",
+ question: "Still running?",
+ answer: "",
+ status: "running",
+ },
+ sideQuestionComponent: {},
+ sideQuestionContainer: new Container(),
+ agentConnection: { abortSideQuestion },
+ isInitialized: false,
+ clearCtrlCExitHint: vi.fn(),
+ clearEscapeRepeat: vi.fn(),
+ takeEscapeRepeatAction,
+ armEscapeRepeat: vi.fn(),
+ interruptOrClearInput: vi.fn(),
+ });
+ const handleEscape = (InteractiveMode.prototype as unknown as { handleEscape(this: typeof fakeThis): void })
+ .handleEscape;
+
+ handleEscape.call(fakeThis);
+
+ expect(abortSideQuestion).toHaveBeenCalledWith("question-5");
+ expect(fakeThis.sideQuestionEvent).toBeUndefined();
+ expect(fakeThis.activeSideQuestionId).toBe("question-5");
+ expect(takeEscapeRepeatAction).not.toHaveBeenCalled();
+ });
+
+ it("waits for a cancelled run to settle before starting another side question", async () => {
+ const showWarning = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ activeSideQuestionId: "question-5",
+ showWarning,
+ });
+ const handleSideQuestion = (
+ InteractiveMode.prototype as unknown as {
+ handleSideQuestion(this: typeof fakeThis, question: string): Promise<void>;
+ }
+ ).handleSideQuestion;
+
+ await handleSideQuestion.call(fakeThis, "Can this overlap?");
+
+ expect(showWarning).toHaveBeenCalledWith("Wait for the current side question to finish or cancel it first.");
+ });
+
+ it("reports side-question abort failures without rejecting the interrupt path", async () => {
+ const showError = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ activeSideQuestionId: "question-6",
+ sideQuestionEvent: {
+ id: "question-6",
+ question: "Still running?",
+ answer: "",
+ status: "running",
+ },
+ agentConnection: { abortSideQuestion: vi.fn(async () => Promise.reject(new Error("daemon unavailable"))) },
+ showError,
+ getRetryAttempt: () => 0,
+ isAgentCompacting: () => false,
+ isBashRunning: () => false,
+ isAgentStreaming: () => false,
+ });
+ const interruptOrClearInput = (
+ InteractiveMode.prototype as unknown as { interruptOrClearInput(this: typeof fakeThis): void }
+ ).interruptOrClearInput;
+
+ interruptOrClearInput.call(fakeThis);
+
+ await vi.waitFor(() => expect(showError).toHaveBeenCalledWith("daemon unavailable"));
+ });
+
+ it("dismisses the side-question pane after successful tree navigation", async () => {
+ const clearSideQuestion = vi.fn();
+ const setText = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ clearSideQuestion,
+ chatContainer: new Container(),
+ renderInitialMessages: vi.fn(async () => undefined),
+ editor: { getText: () => "", setText },
+ showStatus: vi.fn(),
+ flushCompactionQueue: vi.fn(async () => undefined),
+ });
+ const renderTreeNavigation = (
+ InteractiveMode.prototype as unknown as {
+ renderTreeNavigation(this: typeof fakeThis, result: { editorText?: string }): Promise<void>;
+ }
+ ).renderTreeNavigation;
+
+ await renderTreeNavigation.call(fakeThis, { editorText: "restored draft" });
+
+ expect(clearSideQuestion).toHaveBeenCalledWith({ abort: true });
+ expect(setText).toHaveBeenCalledWith("restored draft");
+ });
+});