Skip to content

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

Rust

feat: multi-turn /btw side conversations (#512)

Ilija Lichkovski5b808362d810
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 555e2dcb10..75be1cb967 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -20,6 +20,7 @@
- Changed long live session opens to render a bounded recent transcript tail while preserving full prompt history ([#343](https://github.com/PrimeIntellect-ai/prime-agent/pull/343) by [@sethkarten](https://github.com/sethkarten)).
- Changed `/refine` to run planning in the background so the conversation is not blocked during the LLM pass ([#497](https://github.com/PrimeIntellect-ai/prime-agent/pull/497) by [@sethkarten](https://github.com/sethkarten)).
- Added serialized headless refinement and `--goal` / `--goal-token-budget` for seeding durable session goals ([#514](https://github.com/PrimeIntellect-ai/prime-agent/pull/514) by [@sethkarten](https://github.com/sethkarten)).
+- Added multi-turn `/btw` side conversations with transient in-pane bash commands ([#512](https://github.com/PrimeIntellect-ai/prime-agent/pull/512) by [@ilijalichkovski](https://github.com/ilijalichkovski)).
## [0.3.2] - 2026-07-20
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 0f016a6d4a..23d28bf3fe 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -161,7 +161,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 |
+| `/btw <question>`, `/side <question>` | Ask an inline side question without adding it to the session; replies continue the side conversation, esc returns |
| `/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 6d5c276107..6e783d9f79 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -54,7 +54,7 @@ Type `/` in the editor to open command completion. Extensions can register custo
| `/compact [prompt]` | Manually compact context, optionally with custom instructions |
| `/refine [instructions]` | Refine or roll back session-backed harness state |
| `/copy` | Copy last assistant message to clipboard |
-| `/btw <question>`, `/side <question>` | Ask one inline side question without adding it to the session |
+| `/btw <question>`, `/side <question>` | Ask an inline side question without adding it to the session; replies continue the side conversation, esc returns |
| `/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/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 6ef741659a..df5df6749b 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -309,7 +309,7 @@ export type AgentSessionEvent =
| { type: "rlm_child_update"; child: RlmChildAgentSnapshot }
| { type: "recap_update"; recap: string | undefined }
| { type: "goal_update"; goal: GoalState }
- | { type: "bash_start"; command: string; excludeFromContext: boolean }
+ | { type: "bash_start"; command: string; excludeFromContext: boolean; transient?: boolean; runId?: string }
| { type: "bash_output"; chunk: string }
| {
type: "bash_end";
@@ -319,6 +319,10 @@ export type AgentSessionEvent =
fullOutputPath?: string;
/** Set when execution failed before producing a result (e.g. spawn failure) */
errorMessage?: string;
+ /** Set for transient (side-conversation) runs so other attached clients suppress them. */
+ transient?: boolean;
+ /** Echo of the caller-supplied run id, so clients correlate runs by identity. */
+ runId?: string;
}
| { type: "refine_complete"; result: RefinementResult }
| { type: "refine_failed"; error: string };
@@ -8531,7 +8535,7 @@ export class AgentSession {
async executeBash(
command: string,
onChunk?: (chunk: string) => void,
- options?: { excludeFromContext?: boolean; operations?: BashOperations },
+ options?: { excludeFromContext?: boolean; operations?: BashOperations; transient?: boolean },
): Promise<BashResult> {
this._bashAbortController = new AbortController();
@@ -8551,7 +8555,9 @@ export class AgentSession {
},
);
- this.recordBashResult(command, result, options);
+ if (!options?.transient) {
+ this.recordBashResult(command, result, options);
+ }
return result;
} finally {
this._bashAbortController = undefined;
@@ -8567,7 +8573,10 @@ export class AgentSession {
* @param command The bash command to execute
* @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
*/
- async runUserBash(command: string, options?: { excludeFromContext?: boolean }): Promise<void> {
+ async runUserBash(
+ command: string,
+ options?: { excludeFromContext?: boolean; transient?: boolean; runId?: string },
+ ): Promise<void> {
if (this.isBashRunning) {
throw new Error("A bash command is already running");
}
@@ -8576,15 +8585,26 @@ export class AgentSession {
// slip through during the user_bash extension dispatch below.
this._userBashRunning = true;
this._userBashAbortRequested = false;
+ // Echoed on bash_start/bash_end so the requesting client can tell its own
+ // run apart from other clients' runs broadcast on the same session.
+ const identity = {
+ ...(options?.transient ? { transient: true } : {}),
+ ...(options?.runId !== undefined ? { runId: options.runId } : {}),
+ };
let end: UserBashEndDetails;
try {
- end = await this.runUserBashLocked(command, options?.excludeFromContext ?? false);
+ end = await this.runUserBashLocked(
+ command,
+ options?.excludeFromContext ?? false,
+ options?.transient ?? false,
+ identity,
+ );
} finally {
this._userBashRunning = false;
}
// Emitted after the slot is released so clients never observe a bash_end
// while the session still rejects new commands as already running.
- this._emit({ type: "bash_end", ...end });
+ this._emit({ type: "bash_end", ...end, ...identity });
void this._drainQueuedMessagesAfterBash().catch(() => undefined);
}
@@ -8645,7 +8665,12 @@ export class AgentSession {
}
}
- private async runUserBashLocked(command: string, excludeFromContext: boolean): Promise<UserBashEndDetails> {
+ private async runUserBashLocked(
+ command: string,
+ excludeFromContext: boolean,
+ transient: boolean,
+ identity: { transient?: boolean; runId?: string },
+ ): Promise<UserBashEndDetails> {
const eventResult = await this._extensionRunner.emitUserBash({
type: "user_bash",
command,
@@ -8653,7 +8678,13 @@ export class AgentSession {
cwd: this.sessionManager.getCwd(),
});
- this._emit({ type: "bash_start", command, excludeFromContext });
+ // Transient runs (side-conversation bash) live only in their pane: they
+ // are never recorded, so reloads and rebuilds cannot resurface them.
+ const record = transient
+ ? () => {}
+ : (result: BashResult) => this.recordBashResult(command, result, { excludeFromContext });
+
+ this._emit({ type: "bash_start", command, excludeFromContext, ...identity });
try {
// If an extension returned a full result, surface it without executing
if (eventResult?.result) {
@@ -8661,7 +8692,7 @@ export class AgentSession {
if (result.output) {
this._emit({ type: "bash_output", chunk: result.output });
}
- this.recordBashResult(command, result, { excludeFromContext });
+ record(result);
return {
exitCode: result.exitCode,
cancelled: result.cancelled,
@@ -8673,17 +8704,14 @@ export class AgentSession {
// An abort that arrived before the process spawned (during extension
// dispatch) has no abort controller to act on; honor it here instead.
if (this._userBashAbortRequested) {
- this.recordBashResult(
- command,
- { output: "", exitCode: undefined, cancelled: true, truncated: false },
- { excludeFromContext },
- );
+ record({ output: "", exitCode: undefined, cancelled: true, truncated: false });
return { exitCode: undefined, cancelled: true, truncated: false };
}
const result = await this.executeBash(command, (chunk) => this._emit({ type: "bash_output", chunk }), {
excludeFromContext,
operations: eventResult?.operations,
+ transient,
});
return {
exitCode: result.exitCode,
@@ -8695,11 +8723,7 @@ export class AgentSession {
const errorMessage = error instanceof Error ? error.message : String(error);
// Persist the failure like every other outcome so replayed transcripts
// and the LLM context reflect that the command did not run.
- this.recordBashResult(
- command,
- { output: `bash failed: ${errorMessage}`, exitCode: undefined, cancelled: false, truncated: false },
- { excludeFromContext },
- );
+ record({ output: `bash failed: ${errorMessage}`, exitCode: undefined, cancelled: false, truncated: false });
return {
exitCode: undefined,
cancelled: false,
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index a538593d67..63f0695358 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -97,12 +97,20 @@ declare module "@earendil-works/pi-agent-core" {
}
/**
- * Convert a BashExecutionMessage to user message text for LLM context.
+ * Format bash output for LLM context. The fence must be longer than any
+ * backtick run in the output so command output cannot terminate it early.
*/
-export function bashExecutionToText(msg: BashExecutionMessage): string {
- let text = `Ran \`${msg.command}\`\n`;
+export function bashOutputToText(
+ msg: Pick<BashExecutionMessage, "output" | "exitCode" | "cancelled" | "truncated" | "fullOutputPath">,
+): string {
+ let text = "";
if (msg.output) {
- text += `\`\`\`\n${msg.output}\n\`\`\``;
+ let longestBacktickRun = 0;
+ for (const match of msg.output.matchAll(/`+/g)) {
+ longestBacktickRun = Math.max(longestBacktickRun, match[0].length);
+ }
+ const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
+ text += `${fence}\n${msg.output}\n${fence}`;
} else {
text += "(no output)";
}
@@ -111,12 +119,21 @@ export function bashExecutionToText(msg: BashExecutionMessage): string {
} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {
text += `\n\nCommand exited with code ${msg.exitCode}`;
}
- if (msg.truncated && msg.fullOutputPath) {
- text += `\n\n[Output truncated. Full output: ${msg.fullOutputPath}]`;
+ if (msg.truncated) {
+ text += msg.fullOutputPath
+ ? `\n\n[Output truncated. Full output: ${msg.fullOutputPath}]`
+ : "\n\n[Output truncated.]";
}
return text;
}
+/**
+ * Convert a BashExecutionMessage to user message text for LLM context.
+ */
+export function bashExecutionToText(msg: BashExecutionMessage): string {
+ return `Ran \`${msg.command}\`\n${bashOutputToText(msg)}`;
+}
+
export function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {
return {
role: "branchSummary",
diff --git a/packages/coding-agent/src/core/side-question.ts b/packages/coding-agent/src/core/side-question.ts
index d90765aa69..02d970cd8c 100644
--- a/packages/coding-agent/src/core/side-question.ts
+++ b/packages/coding-agent/src/core/side-question.ts
@@ -1,4 +1,5 @@
import { Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
+import type { AssistantMessage, UserMessage } from "@earendil-works/pi-ai";
export type SideQuestionStatus = "running" | "complete" | "cancelled" | "error";
@@ -10,13 +11,23 @@ export interface SideQuestionEvent {
errorMessage?: string;
}
+export interface SideQuestionTurn {
+ question: string;
+ answer: 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.";
+ "Answer this side question using only the conversation context above. Do not use tools. The user may send follow-up side questions; none of this side conversation is added to the main session.";
+
+function sideQuestionPrompt(question: string, isFirstTurn: boolean): string {
+ const body = isFirstTurn ? `${SIDE_QUESTION_INSTRUCTION}\n\n${question}` : question;
+ return `<side_question>\n${body}\n</side_question>`;
+}
function readAssistantText(message: AgentMessage): string {
if (message.role !== "assistant") {
@@ -33,17 +44,45 @@ export function startSideQuestion(
id: string,
question: string,
onEvent: (event: SideQuestionEvent) => void | Promise<void>,
+ previousTurns: SideQuestionTurn[] = [],
): SideQuestionRun {
const model = parent.state.model;
if (!model) {
throw new Error("Select a model before asking a side question");
}
+ // Each turn re-clones the live main conversation, so follow-ups always see
+ // the newest main-thread context; earlier side turns are replayed after it.
+ const previousTurnMessages: AgentMessage[] = previousTurns.flatMap((turn, index) => [
+ {
+ role: "user",
+ content: [{ type: "text", text: sideQuestionPrompt(turn.question, index === 0) }],
+ timestamp: Date.now(),
+ } satisfies UserMessage,
+ {
+ role: "assistant",
+ content: [{ type: "text", text: turn.answer }],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ 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: Date.now(),
+ } satisfies AssistantMessage,
+ ]);
+
const sideAgent = new Agent({
initialState: {
model,
systemPrompt: parent.state.systemPrompt,
- messages: structuredClone(parent.state.messages),
+ messages: [...structuredClone(parent.state.messages), ...previousTurnMessages],
thinkingLevel: "off",
serviceTier: parent.state.serviceTier,
tools: [],
@@ -80,7 +119,7 @@ export function startSideQuestion(
await emit("running");
});
- const prompt = `<side_question>\n${SIDE_QUESTION_INSTRUCTION}\n\n${question}\n</side_question>`;
+ const prompt = sideQuestionPrompt(question, previousTurns.length === 0);
const done = Promise.resolve()
.then(() => emit("running"))
.then(async () => {
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index ade16ac5fa..bd21280f00 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -47,7 +47,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
{ name: "copy", description: "Copy last agent message to clipboard" },
{
name: "btw",
- description: "Ask one side question without adding it to the session",
+ description: "Ask a side question without adding it to the session; replies follow up, esc returns",
argumentHint: "<question>",
takesArgument: true,
},
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 f9b831f2a3..54aba961c8 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
@@ -70,6 +70,7 @@ import type {
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
AgentConnectionSideQuestionEvent,
+ AgentConnectionSideQuestionTurn,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionState,
@@ -746,7 +747,18 @@ export class DaemonAgentConnection implements AgentConnection {
);
}
- async startSideQuestion(id: string, question: string): Promise<void> {
+ async startSideQuestion(
+ id: string,
+ question: string,
+ previousTurns?: AgentConnectionSideQuestionTurn[],
+ ): Promise<void> {
+ if (previousTurns?.length && !this.client.supportsServerCapability("side_question_transcript")) {
+ // An older daemon would silently ignore previousTurns and answer the
+ // follow-up without the side-conversation context; fail loudly instead.
+ throw new Error(
+ "the daemon is running an older build without side-conversation follow-ups; restart the daemon and try again",
+ );
+ }
this.activeSideQuestionIds.add(id);
try {
await this.requestOk({
@@ -754,6 +766,7 @@ export class DaemonAgentConnection implements AgentConnection {
activeSessionId: this.activeSessionId,
sideQuestionId: id,
question,
+ previousTurns,
});
} catch (error) {
this.activeSideQuestionIds.delete(id);
@@ -820,12 +833,21 @@ export class DaemonAgentConnection implements AgentConnection {
}
async executeBash(command: string, options?: AgentConnectionExecuteBashOptions): Promise<void> {
+ if (options?.transient && !this.client.supportsServerCapability("transient_bash")) {
+ // An older daemon would record the run into the session, leaking the
+ // side conversation into the main transcript; fail loudly instead.
+ throw new Error(
+ "the daemon is running an older build without side-conversation bash; restart the daemon and try again",
+ );
+ }
try {
await this.requestOk({
type: "execute_bash",
activeSessionId: this.activeSessionId,
command,
excludeFromContext: options?.excludeFromContext,
+ transient: options?.transient,
+ runId: options?.runId,
});
} catch (error) {
if (isUnknownDaemonCommandError(error, "execute_bash")) {
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 c6644ff46e..10684b7c6d 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
@@ -58,6 +58,7 @@ import type {
AgentConnectionSessionListCallbacks,
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
+ AgentConnectionSideQuestionTurn,
AgentConnectionSlashCommand,
AgentConnectionSnapshot,
AgentConnectionState,
@@ -327,12 +328,20 @@ export class InProcessAgentConnection implements AgentConnection {
});
}
- async startSideQuestion(id: string, question: string): Promise<void> {
+ async startSideQuestion(
+ id: string,
+ question: string,
+ previousTurns?: AgentConnectionSideQuestionTurn[],
+ ): 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 }),
+ const run = startSideQuestion(
+ this.session.agent,
+ id,
+ question,
+ (event) => this.emit({ type: "side_question_event", event }),
+ previousTurns,
);
this.sideQuestionRuns.set(id, run);
const removeRun = () => {
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index ee620b5465..f89e1a30eb 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -61,6 +61,7 @@ export type {
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
AgentConnectionSideQuestionEvent,
+ AgentConnectionSideQuestionTurn,
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 6c32824610..9ee61958fc 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -439,8 +439,21 @@ export interface AgentConnectionSideQuestionEvent {
errorMessage?: string;
}
+export interface AgentConnectionSideQuestionTurn {
+ question: string;
+ answer: string;
+}
+
export interface AgentConnectionExecuteBashOptions {
excludeFromContext?: boolean;
+ /** Run without recording into the session (side-conversation bash). */
+ transient?: boolean;
+ /**
+ * Caller-generated id echoed on the run's bash_start/bash_end events, so the
+ * requesting client can tell its own run apart from other clients' runs
+ * broadcast on the same session.
+ */
+ runId?: string;
}
export interface AgentConnectionNewSessionOptions {
@@ -557,7 +570,7 @@ export type AgentConnectionSessionEvent =
| { type: "rlm_child_update"; child: AgentConnectionRlmChildAgentSnapshot }
| { type: "recap_update"; recap: string | undefined }
| { type: "goal_update"; goal: GoalState }
- | { type: "bash_start"; command: string; excludeFromContext: boolean }
+ | { type: "bash_start"; command: string; excludeFromContext: boolean; transient?: boolean; runId?: string }
| { type: "bash_output"; chunk: string }
| {
type: "bash_end";
@@ -567,6 +580,10 @@ export type AgentConnectionSessionEvent =
fullOutputPath?: string;
/** Set when execution failed before producing a result (e.g. spawn failure) */
errorMessage?: string;
+ /** Set for transient (side-conversation) runs so other attached clients suppress them. */
+ transient?: boolean;
+ /** Echo of the caller-supplied run id, so clients correlate runs by identity. */
+ runId?: string;
}
| { type: "refine_complete"; result: RefinementResult }
| { type: "refine_failed"; error: string };
@@ -644,7 +661,7 @@ export interface AgentConnection {
prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void>;
promptAndWait(message: string, options?: AgentConnectionPromptOptions): Promise<void>;
- startSideQuestion(id: string, question: string): Promise<void>;
+ startSideQuestion(id: string, question: string, previousTurns?: AgentConnectionSideQuestionTurn[]): Promise<void>;
abortSideQuestion(id: string): Promise<boolean>;
steer(message: string, images?: ImageContent[]): Promise<void>;
followUp(message: string, images?: ImageContent[]): Promise<void>;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 0aef897a9d..b67f1162d5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -3033,6 +3033,7 @@ export class AgentDaemon {
this.sideQuestionRuns.delete(event.id);
}
},
+ command.previousTurns,
);
this.sideQuestionRuns.set(command.sideQuestionId, {
run,
@@ -3066,7 +3067,11 @@ export class AgentDaemon {
// Respond before completion (bash can outlive the client request
// timeout); output and completion stream via bash_* session events.
void state.runtime.session
- .runUserBash(command.command, { excludeFromContext: command.excludeFromContext })
+ .runUserBash(command.command, {
+ excludeFromContext: command.excludeFromContext,
+ transient: command.transient,
+ runId: command.runId,
+ })
.catch((error) => {
this.broadcastToSession(
state,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 7ad382c46b..7639b44388 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -33,6 +33,7 @@ import type {
AgentConnectionSessionHeader,
AgentConnectionSessionTreeNode,
AgentConnectionSideQuestionEvent,
+ AgentConnectionSideQuestionTurn,
AgentConnectionState,
} from "../agent-connection/types.js";
import type { SessionSummary } from "./daemon-session-list.js";
@@ -49,8 +50,15 @@ import type { SessionSummary } from "./daemon-session-list.js";
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
export const DAEMON_PROTOCOL_VERSION = 4;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
-export const DAEMON_SCHEMA_REVISION = 3;
-export const DAEMON_SCHEMA_ID = "protocol-4-schema-3-cbdbe20e7ce4";
+// Revision 5: transient + runId on execute_bash (echoed with a transient
+// marker on the run's bash_start/bash_end session events) + transient_bash
+// capability.
+// Revision 4: side_question_transcript capability. The digest only covers the
+// command/outbound type source, so capability-list and session-event changes
+// must bump this revision by hand — otherwise a retained older daemon passes
+// the staleness probe and clients gate features against it forever.
+export const DAEMON_SCHEMA_REVISION = 5;
+export const DAEMON_SCHEMA_ID = "protocol-4-schema-5-4c17c4fb3f00";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -73,7 +81,15 @@ export type DaemonServerCapability =
| DaemonClientCapability
| "heartbeat_catalog"
| "heartbeat_management"
- | "model_catalog";
+ | "model_catalog"
+ // The daemon honors previousTurns on start_side_question (multi-turn side
+ // conversations). Clients must check before sending follow-up transcripts.
+ | "side_question_transcript"
+ // The daemon honors transient and runId on execute_bash (side-conversation
+ // bash: never recorded into the session, and its bash_start/bash_end events
+ // carry the transient marker and echoed runId so clients correlate runs by
+ // identity). Clients must check before sending.
+ | "transient_bash";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
export interface DaemonProtocolInfo {
@@ -105,6 +121,8 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
"heartbeat_catalog",
"heartbeat_management",
"model_catalog",
+ "side_question_transcript",
+ "transient_bash",
];
export interface DaemonRuntimeIdentity {
@@ -446,6 +464,7 @@ export type DaemonCommand =
activeSessionId: string;
sideQuestionId: string;
question: string;
+ previousTurns?: AgentConnectionSideQuestionTurn[];
}
| { id?: string; type: "abort_side_question"; activeSessionId: string; sideQuestionId: string }
| {
@@ -454,6 +473,8 @@ export type DaemonCommand =
activeSessionId: string;
command: string;
excludeFromContext?: boolean;
+ transient?: boolean;
+ runId?: string;
}
| { id?: string; type: "abort_bash"; activeSessionId: string }
| { id?: string; type: "cancel_rlm_child"; activeSessionId: string; childId: string }
diff --git a/packages/coding-agent/src/modes/interactive/components/side-question.ts b/packages/coding-agent/src/modes/interactive/components/side-question.ts
index 519456a82b..3cf901cb57 100644
--- a/packages/coding-agent/src/modes/interactive/components/side-question.ts
+++ b/packages/coding-agent/src/modes/interactive/components/side-question.ts
@@ -1,55 +1,146 @@
-import { type Component, Markdown, Text, visibleWidth } from "@earendil-works/pi-tui";
+import { Box, 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";
+interface SideQuestionTurnState {
+ kind: "turn";
+ event: AgentConnectionSideQuestionEvent;
+ /** Follow-up questions render as a standard user-message bubble; the first turn keeps the /btw header. */
+ questionBubble: Box | undefined;
+ answer: Markdown;
+}
+
+/** A ! / !! run inside the pane, rendered by the same component the main thread uses. */
+interface SideQuestionBashState {
+ kind: "bash";
+ component: Component;
+ running: boolean;
+}
+
export class SideQuestionComponent implements Component {
private readonly paddingX: number;
- private readonly answer: Markdown;
- private event: AgentConnectionSideQuestionEvent;
+ private readonly entries: (SideQuestionTurnState | SideQuestionBashState)[] = [];
constructor(event: AgentConnectionSideQuestionEvent, paddingX = 2) {
- this.event = event;
this.paddingX = Math.max(2, paddingX);
- this.answer = new Markdown("", this.paddingX, 0, getMarkdownTheme(), {
+ this.addTurn(event);
+ }
+
+ addTurn(event: AgentConnectionSideQuestionEvent): void {
+ let questionBubble: Box | undefined;
+ if (this.entries.length > 0) {
+ questionBubble = new Box(this.paddingX, 1, (content: string) =>
+ theme.getUserMessageBackgroundColor()(content),
+ );
+ questionBubble.addChild(
+ new Markdown(event.question, 0, 0, getMarkdownTheme(), {
+ color: (content: string) => theme.fg("userMessageText", content),
+ }),
+ );
+ }
+ const answer = new Markdown("", this.paddingX, 0, getMarkdownTheme(), {
color: (content: string) => theme.fg("userMessageText", content),
});
- this.answer.setText(event.answer);
+ answer.setText(event.answer);
+ this.entries.push({ kind: "turn", event, questionBubble, answer });
+ }
+
+ addBash(component: Component): void {
+ this.entries.push({ kind: "bash", component, running: true });
+ }
+
+ finishBash(): void {
+ for (const entry of this.entries) {
+ if (entry.kind === "bash") {
+ entry.running = false;
+ }
+ }
}
update(event: AgentConnectionSideQuestionEvent): void {
- this.event = event;
- this.answer.setText(event.answer);
+ const turn = this.entries.find(
+ (candidate): candidate is SideQuestionTurnState =>
+ candidate.kind === "turn" && candidate.event.id === event.id,
+ );
+ if (!turn) {
+ return;
+ }
+ turn.event = event;
+ turn.answer.setText(event.answer);
}
invalidate(): void {
- this.answer.invalidate();
+ for (const entry of this.entries) {
+ if (entry.kind === "bash") {
+ entry.component.invalidate();
+ } else {
+ entry.questionBubble?.invalidate();
+ entry.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];
- return lines.map((line) => this.applySurface(line, width));
+ const lines: string[] = [];
+ const pushSurfaced = (raw: string[]) => {
+ for (const line of raw) {
+ lines.push(this.applySurface(line, width));
+ }
+ };
+
+ pushSurfaced([blank]);
+ for (const entry of this.entries) {
+ if (entry.kind === "bash") {
+ pushSurfaced([...entry.component.render(width), blank]);
+ continue;
+ }
+ if (entry.questionBubble) {
+ // Bubble lines are already fully painted with the user-message background.
+ lines.push(...entry.questionBubble.render(width));
+ } else {
+ const question = new Text(
+ `${theme.fg("accent", "/btw")} ${theme.bold(theme.fg("userMessageText", entry.event.question))}`,
+ this.paddingX,
+ 0,
+ ).render(width);
+ pushSurfaced(question);
+ }
+ pushSurfaced([blank, ...this.renderAnswer(entry, width), blank]);
+ }
+ pushSurfaced([...this.renderHint(width), blank]);
+ return lines;
}
- private renderAnswer(width: number): string[] {
- if (this.event.answer) {
- return this.answer.render(width);
+ private renderAnswer(turn: SideQuestionTurnState, width: number): string[] {
+ const lines: string[] = [];
+ if (turn.event.answer) {
+ lines.push(...turn.answer.render(width));
+ }
+ if (turn.event.errorMessage) {
+ // A turn can fail after streaming partial output; show both.
+ lines.push(...new Text(theme.fg("error", turn.event.errorMessage), this.paddingX, 0).render(width));
}
- if (this.event.errorMessage) {
- return new Text(theme.fg("error", this.event.errorMessage), this.paddingX, 0).render(width);
+ if (lines.length > 0) {
+ return lines;
}
- if (this.event.status === "cancelled") {
+ if (turn.event.status === "cancelled") {
return new Text(theme.fg("userMessageText", "Cancelled"), this.paddingX, 0).render(width);
}
- const message = this.event.status === "complete" ? "No response" : "Thinking…";
+ const message = turn.event.status === "complete" ? "No response" : "Thinking…";
return new Text(theme.fg("userMessageText", message), this.paddingX, 0).render(width);
}
+ private renderHint(width: number): string[] {
+ // Any running turn blocks follow-ups (a completed notice can be the last
+ // turn while an earlier question still streams), so check them all.
+ const running = this.entries.some((entry) =>
+ entry.kind === "bash" ? entry.running : entry.event.status === "running",
+ );
+ const hint = running ? "esc to cancel and return to session" : "reply to follow up · esc to return to session";
+ return new Text(theme.fg("dim", hint), 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.getPopupBackgroundColor();
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 5e467fb54b..3b629608ad 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -98,6 +98,7 @@ import { emptyGoalState, formatGoalUsage, GOAL_CONTEXT_PREVIEW_LABEL, type GoalS
import type { KernelSentAgentMessage } from "../../core/kernel/index.js";
import { type AppKeybinding, KeybindingsManager } from "../../core/keybindings.js";
import {
+ bashOutputToText,
createCompactionSummaryMessage,
createHeartbeatPromptMessage,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
@@ -117,7 +118,7 @@ import {
parseSlashCommand,
resolveBuiltinSlashCommandName,
} from "../../core/slash-commands.js";
-import type { TruncationResult } from "../../core/tools/truncate.js";
+import { type TruncationResult, truncateTail } from "../../core/tools/truncate.js";
import { PRIME_BUTTERFLY_LOGO } from "../../themes/prime-logo.js";
import { getChangelogPath, parseChangelog } from "../../utils/changelog.js";
import { copyToClipboard } from "../../utils/clipboard.js";
@@ -871,7 +872,20 @@ export class InteractiveMode {
private streamingMessage: AssistantMessage | undefined = undefined;
private sideQuestionComponent: SideQuestionComponent | undefined;
private sideQuestionEvent: AgentConnectionSideQuestionEvent | undefined;
+ private sideQuestionTurns: AgentConnectionSideQuestionEvent[] = [];
private activeSideQuestionId: string | undefined;
+ // Set while a ! bash command runs inside the side conversation: its
+ // BashExecutionComponent renders inside the pane instead of the main chat.
+ // bash_* events broadcast to every attached client, so runs correlate by
+ // runId — the runId we generate here is echoed on our run's events.
+ private sideQuestionBash: { runId: string; input: string; seedTranscript: boolean } | undefined;
+ // The pane-mounted component of our own side run; bash_end seeds the side
+ // transcript only when it ends this exact component.
+ private sideQuestionBashComponent: BashExecutionComponent | undefined;
+ // Holds the runId of a side bash abandoned at pane close: that run's
+ // remaining bash_* events are swallowed (until its bash_end) instead of
+ // leaking into the main transcript.
+ private sideQuestionBashDiscarded: string | undefined;
// User bash execution tracking (! / !! prefix), driven by bash_* session events
private activeBashComponent: BashExecutionComponent | undefined = undefined;
@@ -2752,12 +2766,23 @@ export class InteractiveMode {
if (compactionFinished) {
await this.flushCompactionQueue({ willRetry: false });
}
- if (bashFinished && this.activeBashComponent) {
- this.activeBashComponent.setComplete(undefined, false);
- this.activeBashComponent = undefined;
- if (!snapshot.state.isStreaming) {
- this.flushPendingBashComponents();
+ if (bashFinished) {
+ if (this.activeBashComponent) {
+ this.activeBashComponent.setComplete(undefined, false);
+ this.activeBashComponent = undefined;
+ if (!snapshot.state.isStreaming) {
+ this.flushPendingBashComponents();
+ }
}
+ // A transient side bash is not persisted in the session snapshot, so a
+ // reconnect cannot replay its missed bash_end event. Release the pane's
+ // local running state when the authoritative snapshot says bash ended.
+ if (this.sideQuestionBash) {
+ this.sideQuestionComponent?.finishBash();
+ this.sideQuestionBash = undefined;
+ this.sideQuestionBashComponent = undefined;
+ }
+ this.sideQuestionBashDiscarded = undefined;
}
this.updateTerminalTitle();
this.setGoalAnnouncementBaseline(this.getGoalState());
@@ -4132,6 +4157,10 @@ export class InteractiveMode {
return images.length > 0 ? images : undefined;
}
+ private hasPastedImagesFor(text: string): boolean {
+ return imageMarkerIds(text).some((id) => this.pastedImages.has(id));
+ }
+
private async handleSideQuestion(question: string): Promise<void> {
if (!question) {
this.showWarning("Usage: /btw <question>");
@@ -4142,7 +4171,10 @@ export class InteractiveMode {
return;
}
- this.clearSideQuestion();
+ // Turns already answered in the open pane seed the follow-up's context.
+ const previousTurns = this.sideQuestionTurns
+ .filter((turn) => turn.answer)
+ .map((turn) => ({ question: turn.question, answer: turn.answer }));
const event: AgentConnectionSideQuestionEvent = {
id: randomUUID(),
question,
@@ -4151,13 +4183,22 @@ export class InteractiveMode {
};
this.activeSideQuestionId = event.id;
this.sideQuestionEvent = event;
- this.sideQuestionComponent = new SideQuestionComponent(event, this.settingsManager.getEditorPaddingX());
- this.sideQuestionContainer.addChild(new Spacer(1));
- this.sideQuestionContainer.addChild(this.sideQuestionComponent);
+ this.sideQuestionTurns.push(event);
+ if (this.sideQuestionComponent) {
+ this.sideQuestionComponent.addTurn(event);
+ } else {
+ this.sideQuestionComponent = new SideQuestionComponent(event, 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);
+ await this.agentConnection.startSideQuestion(
+ event.id,
+ question,
+ previousTurns.length > 0 ? previousTurns : undefined,
+ );
} catch (error) {
this.handleSideQuestionEvent({
...event,
@@ -4175,16 +4216,66 @@ export class InteractiveMode {
return;
}
this.sideQuestionEvent = event;
+ const turnIndex = this.sideQuestionTurns.findIndex((turn) => turn.id === event.id);
+ if (turnIndex !== -1) {
+ this.sideQuestionTurns[turnIndex] = event;
+ }
this.sideQuestionComponent.update(event);
this.ui.requestRender();
}
+ private finishSideQuestionBash(
+ event: Extract<AgentConnectionSessionEvent, { type: "bash_end" }>,
+ rawOutput: string,
+ ): void {
+ // Release the pane's running state before any early return so the cancel
+ // hint cannot stay stuck if the pending state was already cleared.
+ this.sideQuestionComponent?.finishBash();
+ const bash = this.sideQuestionBash;
+ if (!bash) {
+ return;
+ }
+ this.sideQuestionBash = undefined;
+ // The pane already rendered the run; this only seeds follow-up turns.
+ if (!bash.seedTranscript || event.cancelled || event.errorMessage) {
+ return;
+ }
+ const truncation = truncateTail(rawOutput);
+ const output = truncation.content.replace(/\n+$/, "");
+ this.sideQuestionTurns.push({
+ id: `side-bash-${randomUUID()}`,
+ question: bash.input,
+ answer: bashOutputToText({
+ output,
+ exitCode: event.exitCode,
+ cancelled: false,
+ truncated: event.truncated || truncation.truncated,
+ fullOutputPath: event.fullOutputPath,
+ }),
+ status: "complete",
+ });
+ }
+
private clearSideQuestion(options: { abort?: boolean } = {}): void {
const event = this.sideQuestionEvent;
if (options.abort && event?.status === "running") {
this.abortSideQuestion(event.id);
}
+ if (this.sideQuestionBash) {
+ // A side-conversation bash run dies with its pane. Its bash_* events may
+ // still be in flight (even bash_start), so swallow them until bash_end.
+ const ownsRunningBash = this.sideQuestionBashComponent !== undefined;
+ this.sideQuestionBashDiscarded = this.sideQuestionBash.runId;
+ this.sideQuestionBash = undefined;
+ this.sideQuestionBashComponent = undefined;
+ // abort_bash is session-scoped. Before our matching bash_start arrives,
+ // another client may own the slot, so only abort a run we have observed.
+ if (ownsRunningBash) {
+ void this.agentConnection.abortBash().catch(() => undefined);
+ }
+ }
this.sideQuestionEvent = undefined;
+ this.sideQuestionTurns = [];
this.sideQuestionComponent = undefined;
this.sideQuestionContainer.clear();
if (this.isInitialized) {
@@ -4237,6 +4328,29 @@ export class InteractiveMode {
const commandArgs = slashCommand?.args ?? "";
const canonicalCommandText = commandName ? `/${commandName}${commandArgs ? ` ${commandArgs}` : ""}` : text;
+ // Slash commands are disabled while a side conversation is open: they
+ // act on the main session, which is confusing mid-side-chat. The notice
+ // renders as a pane response and never reaches the model. A reply that
+ // merely starts with "/" (e.g. an absolute path) is not a command and
+ // falls through to the side-conversation capture below.
+ if (
+ this.sideQuestionComponent &&
+ slashCommand !== undefined &&
+ (isBuiltinSlashCommandName(slashCommand.name) ||
+ this.connectionCommands.some((command) => command.name === slashCommand.name))
+ ) {
+ this.editor.addToHistory?.(text);
+ this.sideQuestionComponent.addTurn({
+ id: `side-notice-${randomUUID()}`,
+ question: text,
+ answer:
+ "Slash commands are not available in side conversations. Press esc to return to the main thread.",
+ status: "complete",
+ });
+ this.ui.requestRender();
+ return;
+ }
+
// Handle commands
if (commandName === "btw") {
this.editor.setText("");
@@ -4472,14 +4586,35 @@ export class InteractiveMode {
);
return;
}
- this.clearSideQuestion({ abort: true });
+ // A streaming side turn blocks bash just like it blocks follow-up
+ // replies: overlapping pane turns would seed out of order.
+ if (this.sideQuestionComponent && this.activeSideQuestionId) {
+ this.editor.setText(text);
+ this.showWarning("Wait for the current side question to finish or cancel it first.");
+ return;
+ }
+ // Inside a side conversation the command runs inside the pane (its
+ // bash_start event mounts the usual BashExecutionComponent there),
+ // stays out of the main-session context, and (for !, not !!) seeds
+ // follow-up side questions.
+ const sideBash = this.sideQuestionComponent
+ ? { runId: randomUUID(), input: text, seedTranscript: !isExcluded }
+ : undefined;
+ if (sideBash) {
+ this.sideQuestionBash = sideBash;
+ } else {
+ this.clearSideQuestion({ abort: true });
+ }
this.editor.addToHistory?.(text);
this.editor.setText("");
// Optimistic: bash_start only fires after extension dispatch, and the
// clear key must already route to abortBash in that window.
this.patchConnectionState({ isBashRunning: true });
try {
- await this.agentConnection.executeBash(command, { excludeFromContext: isExcluded });
+ await this.agentConnection.executeBash(command, {
+ excludeFromContext: isExcluded || sideBash !== undefined,
+ ...(sideBash ? { transient: true, runId: sideBash.runId } : {}),
+ });
} catch (error) {
// Re-sync rather than assume idle: the rejection may mean another
// client's bash run already holds the slot.
@@ -4489,11 +4624,55 @@ export class InteractiveMode {
} catch {
this.patchConnectionState({ isBashRunning: false });
}
+ if (this.sideQuestionBash === sideBash) {
+ this.sideQuestionBash = undefined;
+ }
+ if (sideBash && this.sideQuestionBashDiscarded === sideBash.runId) {
+ // The pane discarded this run, but it never started, so no
+ // bash_end will arrive to consume the marker.
+ this.sideQuestionBashDiscarded = undefined;
+ }
this.showError(error instanceof Error ? error.message : String(error));
}
return;
}
+ // An open side-question pane captures replies as follow-up side
+ // questions; ! bash routed above and slash commands were rejected
+ // earlier with a notice. Esc returns to the main thread.
+ if (this.sideQuestionComponent) {
+ // A follow-up submitted mid-bash would seed the transcript ahead of
+ // the output it reacts to; make it wait like a running side turn.
+ // The editor cleared its buffer before onSubmit fired, so blocked
+ // paths put the draft back rather than merely skip clearing it.
+ if (this.sideQuestionBash) {
+ this.editor.setText(text);
+ this.showWarning("Wait for the running command to finish or cancel it first.");
+ return;
+ }
+ if (this.activeSideQuestionId) {
+ this.editor.setText(text);
+ await this.handleSideQuestion(text);
+ return;
+ }
+ // Side questions are text-only end to end; a reply with pasted
+ // images gets an in-pane notice instead of silently dropping them.
+ if (this.hasPastedImagesFor(text)) {
+ this.editor.setText(text);
+ this.sideQuestionComponent.addTurn({
+ id: `side-notice-${randomUUID()}`,
+ question: text,
+ answer: "Images are not supported in side conversations. Press esc to return to the main thread.",
+ status: "complete",
+ });
+ this.ui.requestRender();
+ return;
+ }
+ this.editor.addToHistory?.(text);
+ await this.handleSideQuestion(text);
+ return;
+ }
+
this.clearSideQuestion({ abort: true });
// Queue input during compaction (extension commands execute immediately)
@@ -4833,8 +5012,30 @@ export class InteractiveMode {
break;
case "bash_start": {
+ if (this.sideQuestionBashDiscarded !== undefined) {
+ if (event.runId === this.sideQuestionBashDiscarded) {
+ // The discarded side run now owns the bash slot. Abort only
+ // after matching its identity so a foreign run is never killed.
+ void this.agentConnection.abortBash().catch(() => undefined);
+ break;
+ }
+ // A different run claimed the slot, so the discarded run lost the
+ // race and can never start (its execute_bash will reject); render
+ // this run normally instead of swallowing it.
+ this.sideQuestionBashDiscarded = undefined;
+ }
+ const ownSideBash = this.sideQuestionBash !== undefined && event.runId === this.sideQuestionBash.runId;
+ if (event.transient && !ownSideBash) {
+ // Another client's side-conversation run: it renders only in that
+ // client's pane, never in this window's chat.
+ break;
+ }
const component = new BashExecutionComponent(event.command, this.ui, event.excludeFromContext);
- if (this.isAgentStreaming()) {
+ if (ownSideBash && this.sideQuestionComponent) {
+ // Same component as the main thread, mounted inside the pane.
+ this.sideQuestionComponent.addBash(component);
+ this.sideQuestionBashComponent = component;
+ } else if (this.isAgentStreaming()) {
this.pendingMessagesContainer.addChild(component);
this.pendingBashComponents.push(component);
} else {
@@ -4846,18 +5047,30 @@ export class InteractiveMode {
}
case "bash_output":
+ if (this.sideQuestionBashDiscarded !== undefined) {
+ break;
+ }
if (this.activeBashComponent) {
this.activeBashComponent.appendOutput(event.chunk);
this.ui.requestRender();
}
break;
- case "bash_end":
- if (this.activeBashComponent) {
+ case "bash_end": {
+ if (this.sideQuestionBashDiscarded !== undefined) {
+ // Only the discarded run's own end consumes the marker; bash_start
+ // already cleared it for any other run that claimed the slot.
+ this.sideQuestionBashDiscarded = undefined;
+ this.activeBashComponent = undefined;
+ this.ui.requestRender();
+ break;
+ }
+ const component = this.activeBashComponent;
+ if (component) {
if (event.errorMessage) {
- this.activeBashComponent.setFailed(event.errorMessage);
+ component.setFailed(event.errorMessage);
} else {
- this.activeBashComponent.setComplete(
+ component.setComplete(
event.exitCode,
event.cancelled,
event.truncated ? ({ truncated: true } as TruncationResult) : undefined,
@@ -4865,11 +5078,18 @@ export class InteractiveMode {
);
}
this.activeBashComponent = undefined;
- } else if (event.errorMessage) {
+ } else if (event.errorMessage && !event.transient) {
+ // Transient failures surface in the owning client's pane, not here.
this.showError(`Bash command failed: ${event.errorMessage}`);
}
+ // Seed the side transcript only when our own pane-mounted run ended.
+ if (component !== undefined && component === this.sideQuestionBashComponent) {
+ this.sideQuestionBashComponent = undefined;
+ this.finishSideQuestionBash(event, component.getOutput());
+ }
this.ui.requestRender();
break;
+ }
case "message_start":
if (event.message.role === "custom") {
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 7583c5e827..13c6edd4a1 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -360,6 +360,8 @@ class FakeDaemonClient {
};
}
return { type: "response", command: command.type, success: true };
+ case "start_side_question":
+ return { type: "response", command: command.type, success: true };
case "delete_saved_session":
return {
type: "response",
@@ -713,6 +715,59 @@ describe("DaemonAgentConnection", () => {
expect(commands.map((command) => command.promoteOwnedSession)).toEqual([true, false]);
});
+ it("gates side-question follow-up transcripts on the daemon capability", async () => {
+ const oldDaemonClient = new FakeDaemonClient();
+ const oldConnection = new DaemonAgentConnection(asDaemonClient(oldDaemonClient), "active-original");
+
+ // First questions carry no transcript and must keep working on old daemons.
+ await oldConnection.startSideQuestion("turn-1", "What changed?");
+ expect(oldDaemonClient.requests.map((request) => request.type)).toEqual(["start_side_question"]);
+
+ // Follow-ups would silently lose their side context on an old daemon.
+ await expect(
+ oldConnection.startSideQuestion("turn-2", "And then?", [{ question: "What changed?", answer: "The parser." }]),
+ ).rejects.toThrow("older build without side-conversation follow-ups");
+ expect(oldDaemonClient.requests).toHaveLength(1);
+
+ const newDaemonClient = new FakeDaemonClient();
+ newDaemonClient.serverCapabilities.add("side_question_transcript");
+ const newConnection = new DaemonAgentConnection(asDaemonClient(newDaemonClient), "active-original");
+
+ await newConnection.startSideQuestion("turn-2", "And then?", [
+ { question: "What changed?", answer: "The parser." },
+ ]);
+ const sent = newDaemonClient.requests.find(
+ (command): command is Extract<DaemonCommand, { type: "start_side_question" }> =>
+ command.type === "start_side_question",
+ );
+ expect(sent?.previousTurns).toEqual([{ question: "What changed?", answer: "The parser." }]);
+ });
+
+ it("gates transient bash on the daemon capability", async () => {
+ const oldDaemonClient = new FakeDaemonClient();
+ const oldConnection = new DaemonAgentConnection(asDaemonClient(oldDaemonClient), "active-original");
+
+ // Regular bash keeps working on old daemons.
+ await oldConnection.executeBash("ls");
+ expect(oldDaemonClient.requests.map((request) => request.type)).toEqual(["execute_bash"]);
+
+ // A transient run on an old daemon would be recorded into the session.
+ await expect(oldConnection.executeBash("ls", { transient: true })).rejects.toThrow(
+ "older build without side-conversation bash",
+ );
+ expect(oldDaemonClient.requests).toHaveLength(1);
+
+ const newDaemonClient = new FakeDaemonClient();
+ newDaemonClient.serverCapabilities.add("transient_bash");
+ const newConnection = new DaemonAgentConnection(asDaemonClient(newDaemonClient), "active-original");
+
+ await newConnection.executeBash("ls", { excludeFromContext: true, transient: true, runId: "side-run-1" });
+ const sent = newDaemonClient.requests.find(
+ (command): command is Extract<DaemonCommand, { type: "execute_bash" }> => command.type === "execute_bash",
+ );
+ expect(sent).toMatchObject({ command: "ls", excludeFromContext: true, transient: true, runId: "side-run-1" });
+ });
+
it("degrades an unavailable heartbeat catalog without sending an unsupported command", async () => {
const fakeClient = new FakeDaemonClient();
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index cf4b5f0b5d..15d23f6385 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -14,6 +14,7 @@ import {
DAEMON_PROTOCOL_VERSION,
DAEMON_SCHEMA_ID,
DAEMON_SCHEMA_REVISION,
+ type DaemonCommand,
type DaemonOutbound,
isDaemonCommandEnvelope,
isDaemonMutatingCommand,
@@ -73,11 +74,50 @@ describe("daemon protocol helpers", () => {
event: { type: "refine_failed", error: "disk full" },
};
- expect(DAEMON_SCHEMA_REVISION).toBe(3);
+ // Revision 3 introduced the refine events; later features moved it further.
+ expect(DAEMON_SCHEMA_REVISION).toBeGreaterThanOrEqual(3);
expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 1 });
expect(event).toMatchObject({ event: { type: "refine_failed", error: "disk full" } });
});
+ it("accepts legacy side-question and bash shapes in new daemons and clients", () => {
+ const oldClientSideQuestion: DaemonCommand = {
+ type: "start_side_question",
+ activeSessionId: "active-1",
+ sideQuestionId: "side-1",
+ question: "What changed?",
+ };
+ const oldClientBash: DaemonCommand = {
+ type: "execute_bash",
+ activeSessionId: "active-1",
+ command: "ls",
+ };
+ const oldDaemonBashStart: DaemonOutbound = {
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: { type: "bash_start", command: "ls", excludeFromContext: false },
+ };
+ const oldDaemonBashEnd: DaemonOutbound = {
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: { type: "bash_end", exitCode: 0, cancelled: false, truncated: false },
+ };
+
+ expect(DAEMON_COMMAND_COMPATIBILITY.start_side_question).toEqual({ minProtocol: 1 });
+ expect(DAEMON_COMMAND_COMPATIBILITY.execute_bash).toEqual({ minProtocol: 1 });
+ expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 1 });
+ expect(oldClientSideQuestion).not.toHaveProperty("previousTurns");
+ expect(oldClientBash).not.toHaveProperty("transient");
+ expect(oldClientBash).not.toHaveProperty("runId");
+ expect(oldDaemonBashStart.event).not.toHaveProperty("transient");
+ expect(oldDaemonBashStart.event).not.toHaveProperty("runId");
+ expect(oldDaemonBashEnd.event).not.toHaveProperty("transient");
+ expect(oldDaemonBashEnd.event).not.toHaveProperty("runId");
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toEqual(
+ expect.arrayContaining(["side_question_transcript", "transient_bash"]),
+ );
+ });
+
it("creates versioned command and event envelopes", () => {
const command = { id: "cmd-1", type: "attach", activeSessionId: "active-1" } as const;
const commandEnvelope = createDaemonCommandEnvelope(command, "cmd-1", "client-1");
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
index e49c8ca6f1..a35e69e39d 100644
--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -4,6 +4,7 @@ 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 { BashExecutionComponent } from "../../../src/modes/interactive/components/bash-execution.js";
import { SideQuestionComponent } from "../../../src/modes/interactive/components/side-question.js";
import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
import { getEditorTheme, initTheme, theme } from "../../../src/modes/interactive/theme/theme.js";
@@ -70,6 +71,48 @@ describe("ENG-4509 side questions", () => {
}
});
+ it("seeds follow-up turns with the prior side conversation and fresh main context", async () => {
+ const harness = await createHarness();
+ try {
+ harness.setResponses([fauxAssistantMessage("main answer")]);
+ await harness.session.prompt("Main context message.");
+
+ harness.setResponses([
+ (context) => {
+ const texts = context.messages.map(getMessageText);
+ expect(texts).toEqual([
+ "Main context message.",
+ "main answer",
+ expect.stringContaining("First side question?"),
+ "first side answer",
+ expect.stringContaining("Second side question?"),
+ ]);
+ expect(context.tools).toEqual([]);
+ // The instruction is repeated only on the first side turn.
+ expect(texts[2]).toContain("Answer this side question");
+ expect(texts[4]).not.toContain("Answer this side question");
+ return fauxAssistantMessage("second side answer");
+ },
+ ]);
+
+ const events: SideQuestionEvent[] = [];
+ const run = startSideQuestion(
+ harness.session.agent,
+ "turn-2",
+ "Second side question?",
+ (event) => {
+ events.push(event);
+ },
+ [{ question: "First side question?", answer: "first side answer" }],
+ );
+ await run.done;
+
+ expect(events.at(-1)).toMatchObject({ status: "complete", answer: "second side answer" });
+ } finally {
+ harness.cleanup();
+ }
+ });
+
it("can finish while the main agent is still working", async () => {
const harness = await createHarness();
const mainStarted = deferred();
@@ -235,6 +278,818 @@ describe("ENG-4509 side questions", () => {
expect(rendered).not.toContain("…");
});
+ it("renders follow-up turns as standard user bubbles with a visible escape hint", () => {
+ const component = new SideQuestionComponent({
+ id: "turn-1",
+ question: "First?",
+ answer: "First answer",
+ status: "complete",
+ });
+ component.addTurn({ id: "turn-2", question: "Second?", answer: "", status: "running" });
+ component.update({ id: "turn-2", question: "Second?", answer: "Second answer", status: "complete" });
+ const lines = component.render(60);
+ const rendered = stripAnsi(lines.join("\n"));
+
+ expect(rendered).toContain("/btw First?");
+ expect(rendered).toContain("First answer");
+ expect(rendered).toContain("Second?");
+ expect(rendered).not.toContain("↳");
+ expect(rendered).toContain("Second answer");
+ expect(rendered).toContain("reply to follow up · esc to return to session");
+ // The follow-up question is a user-message bubble: its padding rows carry
+ // the user-message background rather than the popup surface.
+ expect(lines).toContain(theme.getUserMessageBackgroundColor()(" ".repeat(60)));
+ const questionLine = lines.find((line) => stripAnsi(line).includes("Second?"));
+ expect(questionLine).not.toContain("/btw");
+ });
+
+ it("shows a cancel hint while a turn is running", () => {
+ const component = new SideQuestionComponent({
+ id: "turn-1",
+ question: "Still going?",
+ answer: "",
+ status: "running",
+ });
+ const rendered = stripAnsi(component.render(60).join("\n"));
+
+ expect(rendered).toContain("esc to cancel and return to session");
+ });
+
+ it("mounts bash runs in the pane with the main-thread component and hint gating", () => {
+ const component = new SideQuestionComponent({
+ id: "turn-1",
+ question: "First?",
+ answer: "done",
+ status: "complete",
+ });
+ const bash = {
+ render: () => ["$ sleep 5", "Running..."],
+ invalidate: vi.fn(),
+ };
+ component.addBash(bash);
+ let rendered = stripAnsi(component.render(60).join("\n"));
+
+ // The pane renders whatever the shared bash component renders — no
+ // pane-specific bash presentation.
+ expect(rendered).toContain("$ sleep 5");
+ expect(rendered).toContain("Running...");
+ expect(rendered).toContain("esc to cancel and return to session");
+
+ component.finishBash();
+ rendered = stripAnsi(component.render(60).join("\n"));
+ expect(rendered).toContain("reply to follow up · esc to return to session");
+
+ component.invalidate();
+ expect(bash.invalidate).toHaveBeenCalled();
+ });
+
+ it("continues the side conversation when the pane is open", async () => {
+ const startSideQuestion = vi.fn(async () => {});
+ const addTurn = vi.fn();
+ const firstTurn = { id: "turn-1", question: "First?", answer: "First answer", status: "complete" as const };
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ activeSideQuestionId: undefined,
+ sideQuestionEvent: firstTurn,
+ sideQuestionTurns: [firstTurn],
+ sideQuestionComponent: { addTurn },
+ agentConnection: { startSideQuestion },
+ ui: { requestRender: vi.fn() },
+ showWarning: vi.fn(),
+ });
+ const handleSideQuestion = (
+ InteractiveMode.prototype as unknown as {
+ handleSideQuestion(this: typeof fakeThis, question: string): Promise<void>;
+ }
+ ).handleSideQuestion;
+
+ await handleSideQuestion.call(fakeThis, "And a follow-up?");
+
+ expect(addTurn).toHaveBeenCalledTimes(1);
+ expect(startSideQuestion).toHaveBeenCalledWith(expect.any(String), "And a follow-up?", [
+ { question: "First?", answer: "First answer" },
+ ]);
+ expect(fakeThis.sideQuestionTurns).toHaveLength(2);
+ expect(fakeThis.activeSideQuestionId).toBe(fakeThis.sideQuestionTurns[1].id);
+ });
+
+ it("restores the draft when a follow-up is submitted while a turn is still running", async () => {
+ const setText = vi.fn();
+ const addToHistory = vi.fn();
+ const showWarning = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText, addToHistory },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: {},
+ activeSideQuestionId: "turn-1",
+ showWarning,
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("Queued follow-up?");
+
+ // The editor clears its buffer before onSubmit fires, so the handler must
+ // put the rejected draft back rather than merely skip clearing it.
+ expect(setText).toHaveBeenCalledWith("Queued follow-up?");
+ expect(addToHistory).not.toHaveBeenCalled();
+ expect(showWarning).toHaveBeenCalledWith("Wait for the current side question to finish or cancel it first.");
+ });
+
+ it("keeps path-like replies in the side conversation", async () => {
+ const handleSideQuestion = vi.fn(async () => {});
+ const prompt = vi.fn(async () => {});
+ const addToHistory = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText: vi.fn(), addToHistory },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: {},
+ activeSideQuestionId: undefined,
+ connectionCommands: [],
+ collectImagesFor: () => undefined,
+ handleSideQuestion,
+ agentConnection: { prompt },
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("/tmp/report.md can you summarize this?");
+
+ expect(handleSideQuestion).toHaveBeenCalledWith("/tmp/report.md can you summarize this?");
+ expect(addToHistory).toHaveBeenCalledWith("/tmp/report.md can you summarize this?");
+ expect(prompt).not.toHaveBeenCalled();
+ });
+
+ it("rejects slash commands in side conversations with an in-pane notice", async () => {
+ const cases = [
+ { text: "/context", connectionCommands: [] },
+ { text: "/btw another question?", connectionCommands: [] },
+ { text: "/mycmd do it", connectionCommands: [{ name: "mycmd", source: "extension", sourceInfo: {} }] },
+ ];
+ for (const { text, connectionCommands } of cases) {
+ const handleSideQuestion = vi.fn(async () => {});
+ const clearSideQuestion = vi.fn();
+ const prompt = vi.fn(async () => {});
+ const addTurn = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: { addTurn },
+ sideQuestionTurns: [],
+ activeSideQuestionId: undefined,
+ connectionCommands,
+ handleSideQuestion,
+ clearSideQuestion,
+ ui: { requestRender: vi.fn() },
+ agentConnection: { prompt },
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.(text);
+
+ expect(addTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ question: text,
+ answer:
+ "Slash commands are not available in side conversations. Press esc to return to the main thread.",
+ status: "complete",
+ }),
+ );
+ // The notice is pane-only: it never seeds follow-up context.
+ expect(fakeThis.sideQuestionTurns).toEqual([]);
+ expect(handleSideQuestion).not.toHaveBeenCalled();
+ expect(clearSideQuestion).not.toHaveBeenCalled();
+ expect(prompt).not.toHaveBeenCalled();
+ }
+ });
+
+ it("runs bash inside the side conversation without closing it", async () => {
+ const finishBash = vi.fn();
+ const clearSideQuestion = vi.fn();
+ const executeBash = vi.fn(async () => {});
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: { finishBash },
+ sideQuestionTurns: [],
+ activeSideQuestionId: undefined,
+ connectionCommands: [],
+ isBashRunning: () => false,
+ clearSideQuestion,
+ patchConnectionState: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ agentConnection: { executeBash },
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("!ls");
+
+ expect(executeBash).toHaveBeenCalledWith("ls", {
+ excludeFromContext: true,
+ transient: true,
+ runId: expect.any(String),
+ });
+ expect(clearSideQuestion).not.toHaveBeenCalled();
+ expect(fakeThis.sideQuestionBash).toMatchObject({
+ runId: expect.any(String),
+ input: "!ls",
+ seedTranscript: true,
+ });
+
+ const finishSideQuestionBash = (
+ InteractiveMode.prototype as unknown as {
+ finishSideQuestionBash(
+ this: typeof fakeThis,
+ event: { exitCode?: number; cancelled: boolean; truncated: boolean; errorMessage?: string },
+ rawOutput: string,
+ ): void;
+ }
+ ).finishSideQuestionBash;
+ finishSideQuestionBash.call(fakeThis, { exitCode: 0, cancelled: false, truncated: false }, "README.md\nsrc\n");
+
+ expect(finishBash).toHaveBeenCalled();
+ // A plain ! run seeds follow-up side questions with the output.
+ expect(fakeThis.sideQuestionTurns).toHaveLength(1);
+ expect(fakeThis.sideQuestionTurns[0]).toMatchObject({
+ question: "!ls",
+ answer: "```\nREADME.md\nsrc\n```",
+ status: "complete",
+ });
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ });
+
+ it("bounds side-bash output before seeding follow-up context", () => {
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionComponent: { finishBash: vi.fn() },
+ sideQuestionTurns: [],
+ sideQuestionBash: { runId: "side-run-1", input: "!generate-output", seedTranscript: true },
+ });
+ const finishSideQuestionBash = (
+ InteractiveMode.prototype as unknown as {
+ finishSideQuestionBash(
+ this: typeof fakeThis,
+ event: {
+ exitCode?: number;
+ cancelled: boolean;
+ truncated: boolean;
+ fullOutputPath?: string;
+ errorMessage?: string;
+ },
+ rawOutput: string,
+ ): void;
+ }
+ ).finishSideQuestionBash;
+ const rawOutput = Array.from({ length: 2101 }, (_, index) => `line-${index}`).join("\n");
+
+ finishSideQuestionBash.call(
+ fakeThis,
+ {
+ exitCode: 0,
+ cancelled: false,
+ truncated: true,
+ fullOutputPath: "/tmp/full-output.log",
+ },
+ rawOutput,
+ );
+
+ const answer = fakeThis.sideQuestionTurns[0].answer;
+ expect(answer).not.toContain("line-0\n");
+ expect(answer).toContain("line-2100");
+ expect(answer).toContain("[Output truncated. Full output: /tmp/full-output.log]");
+ expect(Buffer.byteLength(answer)).toBeLessThan(50 * 1024);
+ });
+
+ it("uses a safe markdown fence for side-bash output containing backticks", () => {
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionComponent: { finishBash: vi.fn() },
+ sideQuestionTurns: [],
+ sideQuestionBash: { runId: "side-run-1", input: "!show-fence", seedTranscript: true },
+ });
+ const finishSideQuestionBash = (
+ InteractiveMode.prototype as unknown as {
+ finishSideQuestionBash(
+ this: typeof fakeThis,
+ event: { exitCode?: number; cancelled: boolean; truncated: boolean; errorMessage?: string },
+ rawOutput: string,
+ ): void;
+ }
+ ).finishSideQuestionBash;
+
+ finishSideQuestionBash.call(
+ fakeThis,
+ { exitCode: 0, cancelled: false, truncated: false },
+ "before\n```\nafter\n",
+ );
+
+ expect(fakeThis.sideQuestionTurns[0].answer).toBe("````\nbefore\n```\nafter\n````");
+ });
+
+ it("keeps the cancel hint while an earlier turn streams behind a notice", () => {
+ const component = new SideQuestionComponent({
+ id: "turn-1",
+ question: "Still thinking?",
+ answer: "",
+ status: "running",
+ });
+ component.addTurn({
+ id: "side-notice-1",
+ question: "/context",
+ answer: "Slash commands are not available in side conversations. Press esc to return to the main thread.",
+ status: "complete",
+ });
+ const rendered = stripAnsi(component.render(60).join("\n"));
+
+ expect(rendered).toContain("esc to cancel and return to session");
+ expect(rendered).not.toContain("reply to follow up");
+ });
+
+ it("blocks bash while a side question is still streaming", async () => {
+ const executeBash = vi.fn(async () => {});
+ const addTurn = vi.fn();
+ const setText = vi.fn();
+ const showWarning = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText, addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: { addTurn },
+ sideQuestionTurns: [],
+ activeSideQuestionId: "turn-1",
+ connectionCommands: [],
+ isBashRunning: () => false,
+ showWarning,
+ agentConnection: { executeBash },
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("!ls");
+
+ expect(setText).toHaveBeenCalledWith("!ls");
+ expect(showWarning).toHaveBeenCalledWith("Wait for the current side question to finish or cancel it first.");
+ expect(executeBash).not.toHaveBeenCalled();
+ expect(addTurn).not.toHaveBeenCalled();
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ });
+
+ it("blocks follow-ups while a side-conversation bash is running", async () => {
+ const handleSideQuestion = vi.fn(async () => {});
+ const setText = vi.fn();
+ const showWarning = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText, addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: {},
+ sideQuestionTurns: [],
+ sideQuestionBash: { runId: "side-run-1", input: "!ls", seedTranscript: true },
+ activeSideQuestionId: undefined,
+ connectionCommands: [],
+ handleSideQuestion,
+ showWarning,
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("what are those files?");
+
+ expect(setText).toHaveBeenCalledWith("what are those files?");
+ expect(showWarning).toHaveBeenCalledWith("Wait for the running command to finish or cancel it first.");
+ expect(handleSideQuestion).not.toHaveBeenCalled();
+ });
+
+ it("rejects image follow-ups on text-only models with an in-pane notice and keeps the draft", async () => {
+ const handleSideQuestion = vi.fn(async () => {});
+ const addTurn = vi.fn();
+ const setText = vi.fn();
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText, addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: { addTurn },
+ sideQuestionTurns: [],
+ activeSideQuestionId: undefined,
+ connectionCommands: [],
+ pastedImages: new Map([[1, { type: "image", data: "abc", mimeType: "image/png" }]]),
+ getCurrentModel: () => ({ input: ["text"] }),
+ handleSideQuestion,
+ ui: { requestRender: vi.fn() },
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+
+ await defaultEditor.onSubmit?.("what is in [image #1]?");
+
+ expect(addTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ question: "what is in [image #1]?",
+ answer: "Images are not supported in side conversations. Press esc to return to the main thread.",
+ status: "complete",
+ }),
+ );
+ expect(setText).toHaveBeenCalledWith("what is in [image #1]?");
+ expect(fakeThis.sideQuestionTurns).toEqual([]);
+ expect(handleSideQuestion).not.toHaveBeenCalled();
+ });
+
+ it("waits for a pending side bash to claim the slot before aborting it", () => {
+ const abortBash = vi.fn(async () => {});
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionEvent: { id: "turn-1", question: "First?", answer: "done", status: "complete" },
+ sideQuestionTurns: [],
+ sideQuestionComponent: {},
+ sideQuestionContainer: new Container(),
+ sideQuestionBash: { runId: "side-run-1", input: "!sleep 5", seedTranscript: true },
+ sideQuestionBashDiscarded: undefined,
+ activeSideQuestionId: undefined,
+ agentConnection: { abortBash },
+ isInitialized: false,
+ });
+ const clearSideQuestion = (
+ InteractiveMode.prototype as unknown as {
+ clearSideQuestion(this: typeof fakeThis, options?: { abort?: boolean }): void;
+ }
+ ).clearSideQuestion;
+
+ clearSideQuestion.call(fakeThis, { abort: true });
+
+ // bash_start may not have been observed yet: the marker must swallow the
+ // run's remaining events so cancelled side output never reaches the chat.
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ expect(fakeThis.sideQuestionBashDiscarded).toBe("side-run-1");
+ expect(abortBash).not.toHaveBeenCalled();
+ });
+
+ it("aborts a side bash immediately after observing its matching start", () => {
+ const abortBash = vi.fn(async () => {});
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionEvent: { id: "turn-1", question: "First?", answer: "done", status: "complete" },
+ sideQuestionTurns: [],
+ sideQuestionComponent: {},
+ sideQuestionContainer: new Container(),
+ sideQuestionBash: { runId: "side-run-1", input: "!sleep 5", seedTranscript: true },
+ sideQuestionBashComponent: {},
+ sideQuestionBashDiscarded: undefined,
+ activeSideQuestionId: undefined,
+ agentConnection: { abortBash },
+ isInitialized: false,
+ });
+ const clearSideQuestion = (
+ InteractiveMode.prototype as unknown as {
+ clearSideQuestion(this: typeof fakeThis, options?: { abort?: boolean }): void;
+ }
+ ).clearSideQuestion;
+
+ clearSideQuestion.call(fakeThis, { abort: true });
+
+ expect(fakeThis.sideQuestionBashDiscarded).toBe("side-run-1");
+ expect(fakeThis.sideQuestionBashComponent).toBeUndefined();
+ expect(abortBash).toHaveBeenCalledOnce();
+ });
+
+ it("runs side bash through the real pipeline without recording into the session", async () => {
+ const harness = await createHarness();
+ try {
+ const addBash = vi.fn();
+ const finishBash = vi.fn();
+ const executeBash = (
+ command: string,
+ options?: { excludeFromContext?: boolean; transient?: boolean; runId?: string },
+ ) => harness.session.runUserBash(command, options);
+ const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
+ const chatContainer = new Container();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ defaultEditor,
+ editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ promptStashState: { stash: undefined },
+ clearShortcutGuide: vi.fn(),
+ sideQuestionComponent: { addBash, finishBash },
+ sideQuestionTurns: [],
+ sideQuestionEvent: { id: "turn-1", question: "First?", answer: "done", status: "complete" },
+ activeSideQuestionId: undefined,
+ connectionCommands: [],
+ isBashRunning: () => false,
+ patchConnectionState: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ agentConnection: { executeBash },
+ // handleEvent preamble stubs
+ isInitialized: true,
+ footer: { invalidate: vi.fn() },
+ updateConnectionStateFromEvent: vi.fn(),
+ activityTracker: { handleEvent: vi.fn(), getStatus: () => ({ tokens: 0 }) },
+ updateWorkingLoaderMessage: vi.fn(),
+ isAgentStreaming: () => false,
+ chatContainer,
+ pendingMessagesContainer: new Container(),
+ pendingBashComponents: [],
+ });
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: typeof fakeThis): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+ const handleEvent = (
+ InteractiveMode.prototype as unknown as {
+ handleEvent(this: typeof fakeThis, event: unknown): Promise<void>;
+ }
+ ).handleEvent;
+
+ // Route real session events through the real handler, like subscribeToAgent does.
+ const bashEvents: { type: string; transient?: boolean; runId?: string }[] = [];
+ harness.session.subscribe(async (event) => {
+ if (event.type === "bash_start" || event.type === "bash_end") {
+ bashEvents.push(event);
+ }
+ await handleEvent.call(fakeThis, event);
+ });
+
+ await defaultEditor.onSubmit?.("!echo hello from side");
+
+ // The wire events carry the transient marker and echoed runId, so other
+ // clients suppress the run and this client correlates it by identity.
+ const runId = bashEvents.at(0)?.runId;
+ expect(runId).toEqual(expect.any(String));
+ expect(bashEvents).toMatchObject([
+ { type: "bash_start", transient: true, runId },
+ { type: "bash_end", transient: true, runId },
+ ]);
+ // The run mounted the main-thread bash component in the pane, not the chat.
+ const component = addBash.mock.calls.at(0)?.[0] as BashExecutionComponent;
+ expect(component).toBeInstanceOf(BashExecutionComponent);
+ expect(component.getOutput()).toContain("hello from side");
+ expect(finishBash).toHaveBeenCalled();
+ expect(fakeThis.activeBashComponent).toBeUndefined();
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ expect(fakeThis.sideQuestionTurns).toHaveLength(1);
+ expect(fakeThis.sideQuestionTurns[0].answer).toContain("hello from side");
+ // Transient: nothing recorded, so reloads cannot resurface the side run.
+ expect(harness.session.messages.some((message) => message.role === "bashExecution")).toBe(false);
+
+ // A normal-mode run of the same command is recorded as usual and lands
+ // in the chat like any main-thread bash execution.
+ await harness.session.runUserBash("echo main thread");
+ expect(harness.session.messages.some((message) => message.role === "bashExecution")).toBe(true);
+ expect(chatContainer.children.some((child) => child instanceof BashExecutionComponent)).toBe(true);
+ } finally {
+ harness.cleanup();
+ }
+ });
+
+ it("releases side-bash state when a resync proves the run ended", async () => {
+ const bashComponent = { setComplete: vi.fn() };
+ const finishBash = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionBash: { runId: "side-run-1", input: "!sleep 5", seedTranscript: true },
+ sideQuestionBashComponent: bashComponent,
+ sideQuestionBashDiscarded: undefined,
+ sideQuestionComponent: { finishBash },
+ activeBashComponent: bashComponent,
+ isAgentCompacting: () => false,
+ isBashRunning: () => true,
+ applyConnectionStateSnapshot: vi.fn(),
+ replaceChildAgentInspector: vi.fn(),
+ getSessionContextFromConnectionSnapshot: vi.fn(() => ({
+ messages: [],
+ thinkingLevel: "medium",
+ model: null,
+ })),
+ renderSessionContext: vi.fn(async () => {}),
+ restoreStreamingMessageFromSnapshot: vi.fn(async () => {}),
+ refreshConnectionQueue: vi.fn(async () => {}),
+ flushCompactionQueue: vi.fn(async () => {}),
+ flushPendingBashComponents: vi.fn(),
+ updateTerminalTitle: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ syncGoalTray: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ getGoalState: () => ({ status: "none" }),
+ });
+ const renderResyncedSession = (
+ InteractiveMode.prototype as unknown as {
+ renderResyncedSession(
+ this: typeof fakeThis,
+ snapshot: {
+ state: { isCompacting: boolean; isBashRunning: boolean; isStreaming: boolean };
+ messages: [];
+ },
+ ): Promise<void>;
+ }
+ ).renderResyncedSession;
+
+ await renderResyncedSession.call(fakeThis, {
+ state: { isCompacting: false, isBashRunning: false, isStreaming: false },
+ messages: [],
+ });
+
+ expect(bashComponent.setComplete).toHaveBeenCalledWith(undefined, false);
+ expect(finishBash).toHaveBeenCalledOnce();
+ expect(fakeThis.activeBashComponent).toBeUndefined();
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ expect(fakeThis.sideQuestionBashComponent).toBeUndefined();
+ });
+
+ it("re-aborts a discarded side bash when its bash_start arrives late", async () => {
+ const abortBash = vi.fn(async () => {});
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionBash: undefined,
+ sideQuestionBashDiscarded: "side-run-1",
+ activeBashComponent: undefined,
+ agentConnection: { abortBash },
+ // handleEvent preamble stubs
+ isInitialized: true,
+ footer: { invalidate: vi.fn() },
+ updateConnectionStateFromEvent: vi.fn(),
+ activityTracker: { handleEvent: vi.fn(), getStatus: () => ({ tokens: 0 }) },
+ updateWorkingLoaderMessage: vi.fn(),
+ isAgentStreaming: () => false,
+ ui: { requestRender: vi.fn() },
+ chatContainer: new Container(),
+ pendingMessagesContainer: new Container(),
+ pendingBashComponents: [],
+ });
+ const handleEvent = (
+ InteractiveMode.prototype as unknown as {
+ handleEvent(this: typeof fakeThis, event: unknown): Promise<void>;
+ }
+ ).handleEvent;
+
+ await handleEvent.call(fakeThis, {
+ type: "bash_start",
+ command: "sleep 5",
+ excludeFromContext: true,
+ transient: true,
+ runId: "side-run-1",
+ });
+
+ // No session-scoped abort is sent until this matching run claims the slot.
+ expect(abortBash).toHaveBeenCalled();
+ expect(fakeThis.activeBashComponent).toBeUndefined();
+
+ await handleEvent.call(fakeThis, {
+ type: "bash_end",
+ exitCode: undefined,
+ cancelled: true,
+ truncated: false,
+ transient: true,
+ runId: "side-run-1",
+ });
+ expect(fakeThis.sideQuestionBashDiscarded).toBeUndefined();
+ });
+
+ it("does not abort or swallow another client's run after a discard", async () => {
+ const abortBash = vi.fn(async () => {});
+ const chatContainer = new Container();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ // Our side bash was discarded at pane close but never claimed the slot.
+ sideQuestionBash: undefined,
+ sideQuestionBashDiscarded: "side-run-1",
+ activeBashComponent: undefined,
+ agentConnection: { abortBash },
+ // handleEvent preamble stubs
+ isInitialized: true,
+ footer: { invalidate: vi.fn() },
+ updateConnectionStateFromEvent: vi.fn(),
+ activityTracker: { handleEvent: vi.fn(), getStatus: () => ({ tokens: 0 }) },
+ updateWorkingLoaderMessage: vi.fn(),
+ isAgentStreaming: () => false,
+ ui: { requestRender: vi.fn() },
+ chatContainer,
+ pendingMessagesContainer: new Container(),
+ pendingBashComponents: [],
+ });
+ const handleEvent = (
+ InteractiveMode.prototype as unknown as {
+ handleEvent(this: typeof fakeThis, event: unknown): Promise<void>;
+ }
+ ).handleEvent;
+
+ // Another client won the bash slot; its run must render, not be aborted.
+ await handleEvent.call(fakeThis, { type: "bash_start", command: "make build", excludeFromContext: false });
+
+ expect(abortBash).not.toHaveBeenCalled();
+ expect(fakeThis.sideQuestionBashDiscarded).toBeUndefined();
+ expect(chatContainer.children.some((child) => child instanceof BashExecutionComponent)).toBe(true);
+
+ await handleEvent.call(fakeThis, { type: "bash_output", chunk: "compiling\n" });
+ expect((fakeThis.activeBashComponent as BashExecutionComponent).getOutput()).toContain("compiling");
+ });
+
+ it("keeps foreign runs out of the pane and suppresses foreign transient runs", async () => {
+ const addBash = vi.fn();
+ const finishBash = vi.fn();
+ const showError = vi.fn();
+ const chatContainer = new Container();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ // Our side bash is pending; its runId has not appeared yet.
+ sideQuestionBash: { runId: "side-run-1", input: "!ls", seedTranscript: true },
+ sideQuestionBashComponent: undefined,
+ sideQuestionBashDiscarded: undefined,
+ sideQuestionComponent: { addBash, finishBash },
+ sideQuestionTurns: [],
+ activeBashComponent: undefined,
+ showError,
+ // handleEvent preamble stubs
+ isInitialized: true,
+ footer: { invalidate: vi.fn() },
+ updateConnectionStateFromEvent: vi.fn(),
+ activityTracker: { handleEvent: vi.fn(), getStatus: () => ({ tokens: 0 }) },
+ updateWorkingLoaderMessage: vi.fn(),
+ isAgentStreaming: () => false,
+ ui: { requestRender: vi.fn() },
+ chatContainer,
+ pendingMessagesContainer: new Container(),
+ pendingBashComponents: [],
+ });
+ const handleEvent = (
+ InteractiveMode.prototype as unknown as {
+ handleEvent(this: typeof fakeThis, event: unknown): Promise<void>;
+ }
+ ).handleEvent;
+
+ // A foreign main-chat run — even with the identical command string —
+ // renders in the chat, never in the pane.
+ await handleEvent.call(fakeThis, { type: "bash_start", command: "ls", excludeFromContext: false });
+ expect(addBash).not.toHaveBeenCalled();
+ expect(chatContainer.children.some((child) => child instanceof BashExecutionComponent)).toBe(true);
+ await handleEvent.call(fakeThis, { type: "bash_end", exitCode: 0, cancelled: false, truncated: false });
+ // The foreign run neither seeds the side transcript nor consumes the
+ // still-pending side bash (the rejected executeBash call clears it).
+ expect(fakeThis.sideQuestionTurns).toEqual([]);
+ expect(fakeThis.sideQuestionBash).toMatchObject({ runId: "side-run-1" });
+
+ // A foreign transient run (another client's side conversation) is
+ // suppressed entirely: no chat mount, no output, no failure toast.
+ chatContainer.clear();
+ await handleEvent.call(fakeThis, {
+ type: "bash_start",
+ command: "ls secret-dir",
+ excludeFromContext: true,
+ transient: true,
+ runId: "other-client-run",
+ });
+ expect(chatContainer.children).toEqual([]);
+ expect(fakeThis.activeBashComponent).toBeUndefined();
+ await handleEvent.call(fakeThis, {
+ type: "bash_end",
+ exitCode: undefined,
+ cancelled: false,
+ truncated: false,
+ errorMessage: "spawn failed",
+ transient: true,
+ runId: "other-client-run",
+ });
+ expect(showError).not.toHaveBeenCalled();
+ expect(fakeThis.sideQuestionTurns).toEqual([]);
+ });
+
+ it("keeps !! side-conversation bash display-only", async () => {
+ const finishBash = vi.fn();
+ const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
+ sideQuestionComponent: { finishBash },
+ sideQuestionTurns: [],
+ sideQuestionBash: { runId: "side-run-1", input: "!!pwd", seedTranscript: false },
+ });
+ const finishSideQuestionBash = (
+ InteractiveMode.prototype as unknown as {
+ finishSideQuestionBash(
+ this: typeof fakeThis,
+ event: { exitCode?: number; cancelled: boolean; truncated: boolean; errorMessage?: string },
+ rawOutput: string,
+ ): void;
+ }
+ ).finishSideQuestionBash;
+
+ finishSideQuestionBash.call(fakeThis, { exitCode: 0, cancelled: false, truncated: false }, "/repo\n");
+
+ expect(finishBash).toHaveBeenCalled();
+ expect(fakeThis.sideQuestionBash).toBeUndefined();
+ expect(fakeThis.sideQuestionTurns).toEqual([]);
+ });
+
it("aligns the thinking placeholder with the streamed response", () => {
const running = new SideQuestionComponent(
{ id: "question-5", question: "Still running?", answer: "", status: "running" },
@@ -267,6 +1122,20 @@ describe("ENG-4509 side questions", () => {
expect(rendered).toContain("\x1b[39mReadable response");
});
+ it("shows the failure reason beneath partial output", () => {
+ const component = new SideQuestionComponent({
+ id: "side-bash-1",
+ question: "!flaky-build",
+ answer: "```\ncompiling...\n```",
+ status: "error",
+ errorMessage: "spawn failed: exit 127",
+ });
+ const rendered = stripAnsi(component.render(60).join("\n"));
+
+ expect(rendered).toContain("compiling...");
+ expect(rendered).toContain("spawn failed: exit 127");
+ });
+
it("keeps streamed text when a side question is cancelled", () => {
const component = new SideQuestionComponent({
id: "question-5",