Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/coding-agent/src/core/export-html/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,9 @@
case 'thinking_level_change':
parts.push('thinking', entry.thinkingLevel);
break;
case 'plan':
parts.push('plan', entry.plan.title, entry.plan.markdown);
break;
}

return parts.join(' ').toLowerCase();
Expand Down Expand Up @@ -385,7 +388,14 @@
}

// Apply filter mode
const isSettingsEntry = ['label', 'custom', 'model_change', 'thinking_level_change'].includes(entry.type);
const isSettingsEntry = [
'label',
'custom',
'model_change',
'thinking_level_change',
'collaboration_mode_change',
'plan_resolution'
].includes(entry.type);
let passesFilter = true;

switch (filterMode) {
Expand Down Expand Up @@ -696,6 +706,12 @@
return labelHtml + `<span class="tree-muted">[model: ${escapeHtml(entry.modelId)}]</span>`;
case 'thinking_level_change':
return labelHtml + `<span class="tree-muted">[thinking: ${escapeHtml(entry.thinkingLevel)}]</span>`;
case 'collaboration_mode_change':
return labelHtml + `<span class="tree-muted">[mode: ${escapeHtml(entry.mode)}]</span>`;
case 'plan_resolution':
return labelHtml + `<span class="tree-muted">[plan resolution: ${escapeHtml(entry.resolution)}]</span>`;
case 'plan':
return labelHtml + `<span class="tree-custom">[plan]:</span> ${escapeHtml(truncate(normalize(entry.plan.title)))}`;
default:
return labelHtml + `<span class="tree-muted">[${escapeHtml(entry.type)}]</span>`;
}
Expand Down Expand Up @@ -1306,6 +1322,13 @@
</div>`;
}

if (entry.type === 'plan') {
return `<div class="branch-summary" id="${entryDomId}">${copyBtnHtml}${tsHtml}
<div class="branch-summary-header">Plan: ${escapeHtml(entry.plan.title)}</div>
<div class="markdown-content">${safeMarkedParse(entry.plan.markdown)}</div>
</div>`;
}

if (entry.type === 'custom_message' && entry.display) {
return `<div class="hook-message" id="${entryDomId}">${tsHtml}
<div class="hook-type">[${escapeHtml(entry.customType)}]</div>
Expand Down
20 changes: 17 additions & 3 deletions packages/coding-agent/src/modes/json-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ type ToJsonEvent<T> = T extends {
: T;

/** Session event shape emitted by the JSON and RPC stdout protocols. */
export type JsonAgentSessionEvent = ToJsonEvent<AgentSessionEvent>;
type PlanOnlyAgentSessionEvent = Extract<
AgentSessionEvent,
{ type: "collaboration_mode_changed" | "plan_submitted" | "plan_resolved" }
>;
type WireAgentSessionEvent = Exclude<AgentSessionEvent, PlanOnlyAgentSessionEvent>;

export type JsonAgentSessionEvent = ToJsonEvent<WireAgentSessionEvent>;

type MessageUpdateEvent = Extract<AgentSessionEvent, { type: "message_update" }>;
type JsonMessageUpdateEvent = Extract<JsonAgentSessionEvent, { type: "message_update" }>;
Expand All @@ -24,8 +30,16 @@ type JsonMessageUpdateEvent = Extract<JsonAgentSessionEvent, { type: "message_up
* `message_end` provides the final authoritative message.
*/
export function toJsonEvent(event: MessageUpdateEvent): JsonMessageUpdateEvent;
export function toJsonEvent(event: AgentSessionEvent): JsonAgentSessionEvent;
export function toJsonEvent(event: AgentSessionEvent): JsonAgentSessionEvent {
export function toJsonEvent(event: AgentSessionEvent): JsonAgentSessionEvent | undefined;
export function toJsonEvent(event: AgentSessionEvent): JsonAgentSessionEvent | undefined {
if (
event.type === "collaboration_mode_changed" ||
event.type === "plan_submitted" ||
event.type === "plan_resolved"
) {
return undefined;
}

if (event.type !== "message_update") {
return event;
}
Expand Down
41 changes: 34 additions & 7 deletions packages/coding-agent/src/modes/print-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import type { AgentSessionRuntime } from "../core/agent-session-runtime.ts";
import { flushRawStdout, waitForRawStdoutBackpressure, writeRawStdout } from "../core/output-guard.ts";
import { killTrackedDetachedChildren } from "../utils/shell.ts";
import { toJsonEvent } from "./json-event.ts";
import {
assertNonInteractivePlanModeDisabled,
validateNonInteractiveSessionTarget,
} from "./non-interactive-plan-mode.ts";

/**
* Options for print mode.
Expand All @@ -31,6 +35,7 @@ export interface PrintModeOptions {
* Sends prompts to the agent and outputs the result.
*/
export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: PrintModeOptions): Promise<number> {
assertNonInteractivePlanModeDisabled(runtimeHost.session);
const { mode, messages = [], initialMessage, initialImages } = options;
let exitCode = 0;
let session = runtimeHost.session;
Expand Down Expand Up @@ -72,17 +77,29 @@ export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: Pr
});

const rebindSession = async (): Promise<void> => {
session = runtimeHost.session;
const nextSession = runtimeHost.session;
assertNonInteractivePlanModeDisabled(nextSession);
session = nextSession;
await session.bindExtensions({
mode: mode === "json" ? "json" : "print",
commandContextActions: {
waitForIdle: () => session.waitForIdle(),
newSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions),
newSession: async (newSessionOptions) =>
runtimeHost.newSession({
...newSessionOptions,
validateTarget: validateNonInteractiveSessionTarget,
}),
fork: async (entryId, forkOptions) => {
const result = await runtimeHost.fork(entryId, forkOptions);
const result = await runtimeHost.fork(entryId, {
...forkOptions,
validateTarget: validateNonInteractiveSessionTarget,
});
return { cancelled: result.cancelled };
},
navigateTree: async (targetId, navigateOptions) => {
if (session.sessionManager.getEntry(targetId)) {
validateNonInteractiveSessionTarget(session.sessionManager, targetId);
}
const result = await session.navigateTree(targetId, {
summarize: navigateOptions?.summarize,
customInstructions: navigateOptions?.customInstructions,
Expand All @@ -92,7 +109,10 @@ export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: Pr
return { cancelled: result.cancelled };
},
switchSession: async (sessionPath, switchOptions) => {
return runtimeHost.switchSession(sessionPath, switchOptions);
return runtimeHost.switchSession(sessionPath, {
...switchOptions,
validateTarget: validateNonInteractiveSessionTarget,
});
},
reload: async () => {
await session.reload();
Expand All @@ -107,7 +127,10 @@ export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: Pr
unsubscribeBackpressure?.();
unsubscribe = session.subscribe((event) => {
if (mode === "json") {
writeRawStdout(`${JSON.stringify(toJsonEvent(event))}\n`);
const jsonEvent = toJsonEvent(event);
if (jsonEvent) {
writeRawStdout(`${JSON.stringify(jsonEvent)}\n`);
}
}
});
unsubscribeBackpressure =
Expand All @@ -129,11 +152,15 @@ export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: Pr
await rebindSession();

if (initialMessage) {
await session.prompt(initialMessage, { images: initialImages });
assertNonInteractivePlanModeDisabled(session);
await runtimeHost.prompt(initialMessage, { images: initialImages });
assertNonInteractivePlanModeDisabled(session);
}

for (const message of messages) {
await session.prompt(message);
assertNonInteractivePlanModeDisabled(session);
await runtimeHost.prompt(message);
assertNonInteractivePlanModeDisabled(session);
}

if (mode === "text") {
Expand Down
106 changes: 75 additions & 31 deletions packages/coding-agent/src/modes/rpc/rpc-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import {
import { killTrackedDetachedChildren } from "../../utils/shell.ts";
import { type Theme, theme } from "../interactive/theme/theme.ts";
import { toJsonEvent } from "../json-event.ts";
import {
assertNonInteractivePlanModeDisabled,
validateNonInteractiveSessionTarget,
} from "../non-interactive-plan-mode.ts";
import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.ts";
import type {
RpcCommand,
Expand All @@ -52,6 +56,7 @@ export type {
* Listens for JSON commands on stdin, outputs events and responses on stdout.
*/
export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<never> {
assertNonInteractivePlanModeDisabled(runtimeHost.session);
takeOverStdout();
let session = runtimeHost.session;
let unsubscribe: (() => void) | undefined;
Expand Down Expand Up @@ -315,18 +320,30 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
});

const rebindSession = async (): Promise<void> => {
session = runtimeHost.session;
const nextSession = runtimeHost.session;
assertNonInteractivePlanModeDisabled(nextSession);
session = nextSession;
await session.bindExtensions({
uiContext: createExtensionUIContext(),
mode: "rpc",
commandContextActions: {
waitForIdle: () => session.waitForIdle(),
newSession: async (options) => runtimeHost.newSession(options),
newSession: async (options) =>
runtimeHost.newSession({
...options,
validateTarget: validateNonInteractiveSessionTarget,
}),
fork: async (entryId, forkOptions) => {
const result = await runtimeHost.fork(entryId, forkOptions);
const result = await runtimeHost.fork(entryId, {
...forkOptions,
validateTarget: validateNonInteractiveSessionTarget,
});
return { cancelled: result.cancelled };
},
navigateTree: async (targetId, options) => {
if (session.sessionManager.getEntry(targetId)) {
validateNonInteractiveSessionTarget(session.sessionManager, targetId);
}
const result = await session.navigateTree(targetId, {
summarize: options?.summarize,
customInstructions: options?.customInstructions,
Expand All @@ -336,7 +353,10 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
return { cancelled: result.cancelled };
},
switchSession: async (sessionPath, options) => {
return runtimeHost.switchSession(sessionPath, options);
return runtimeHost.switchSession(sessionPath, {
...options,
validateTarget: validateNonInteractiveSessionTarget,
});
},
reload: async () => {
await session.reload();
Expand All @@ -353,7 +373,10 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
unsubscribe?.();
unsubscribeBackpressure?.();
unsubscribe = session.subscribe((event) => {
output(toJsonEvent(event));
const jsonEvent = toJsonEvent(event);
if (jsonEvent) {
output(jsonEvent);
}
if (event.type === "agent_settled") {
void checkShutdownRequested();
}
Expand Down Expand Up @@ -382,6 +405,34 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
await rebindSession();
registerSignalHandlers();

const dispatchPromptCommand = (
id: string | undefined,
command: "prompt" | "steer" | "follow_up",
message: string,
images: Extract<RpcCommand, { type: "prompt" }>["images"],
streamingBehavior?: "steer" | "followUp",
): void => {
assertNonInteractivePlanModeDisabled(session);
let preflightSucceeded = false;
void runtimeHost
.prompt(message, {
images,
streamingBehavior,
source: "rpc",
preflightResult: (didSucceed) => {
if (didSucceed && !preflightSucceeded) {
preflightSucceeded = true;
output(success(id, command));
}
},
})
.catch((promptError) => {
if (!preflightSucceeded) {
output(error(id, command, promptError instanceof Error ? promptError.message : String(promptError)));
}
});
};

// Handle a single command
const handleCommand = async (command: RpcCommand): Promise<RpcResponse | undefined> => {
const id = command.id;
Expand All @@ -394,35 +445,18 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
case "prompt": {
// Start prompt handling immediately, but emit the authoritative response only after
// prompt preflight succeeds. Queued and immediately handled prompts also count as success.
let preflightSucceeded = false;
void session
.prompt(command.message, {
images: command.images,
streamingBehavior: command.streamingBehavior,
source: "rpc",
preflightResult: (didSucceed) => {
if (didSucceed) {
preflightSucceeded = true;
output(success(id, "prompt"));
}
},
})
.catch((e) => {
if (!preflightSucceeded) {
output(error(id, "prompt", e.message));
}
});
dispatchPromptCommand(id, "prompt", command.message, command.images, command.streamingBehavior);
return undefined;
}

case "steer": {
await session.steer(command.message, command.images);
return success(id, "steer");
dispatchPromptCommand(id, "steer", command.message, command.images, "steer");
return undefined;
}

case "follow_up": {
await session.followUp(command.message, command.images);
return success(id, "follow_up");
dispatchPromptCommand(id, "follow_up", command.message, command.images, "followUp");
return undefined;
}

case "abort": {
Expand All @@ -431,7 +465,10 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
}

case "new_session": {
const options = command.parentSession ? { parentSession: command.parentSession } : undefined;
const options = {
...(command.parentSession ? { parentSession: command.parentSession } : {}),
validateTarget: validateNonInteractiveSessionTarget,
};
const result = await runtimeHost.newSession(options);
if (!result.cancelled) {
await rebindSession();
Expand Down Expand Up @@ -599,15 +636,19 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
}

case "switch_session": {
const result = await runtimeHost.switchSession(command.sessionPath);
const result = await runtimeHost.switchSession(command.sessionPath, {
validateTarget: validateNonInteractiveSessionTarget,
});
if (!result.cancelled) {
await rebindSession();
}
return success(id, "switch_session", result);
}

case "fork": {
const result = await runtimeHost.fork(command.entryId);
const result = await runtimeHost.fork(command.entryId, {
validateTarget: validateNonInteractiveSessionTarget,
});
if (!result.cancelled) {
await rebindSession();
}
Expand All @@ -619,7 +660,10 @@ export async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<neve
if (!leafId) {
return error(id, "clone", "Cannot clone session: no current entry selected");
}
const result = await runtimeHost.fork(leafId, { position: "at" });
const result = await runtimeHost.fork(leafId, {
position: "at",
validateTarget: validateNonInteractiveSessionTarget,
});
if (!result.cancelled) {
await rebindSession();
}
Expand Down
18 changes: 18 additions & 0 deletions packages/coding-agent/test/export-html-plan-mode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";

describe("export HTML native plan rendering", () => {
const templateJs = readFileSync(new URL("../src/core/export-html/template.js", import.meta.url), "utf-8");

it("renders and indexes plan artifacts while hiding plan bookkeeping by default", () => {
expect(templateJs).toContain("parts.push('plan', entry.plan.title, entry.plan.markdown)");
expect(templateJs).toMatch(
/const isSettingsEntry = \[[\s\S]*?'collaboration_mode_change',[\s\S]*?'plan_resolution'[\s\S]*?\]\.includes\(entry\.type\);/,
);
expect(templateJs).toMatch(/\[mode: \$\{escapeHtml\(entry\.mode\)\}\]/);
expect(templateJs).toMatch(/\[plan resolution: \$\{escapeHtml\(entry\.resolution\)\}\]/);
expect(templateJs).toContain("escapeHtml(truncate(normalize(entry.plan.title)))");
expect(templateJs).toMatch(/Plan: \$\{escapeHtml\(entry\.plan\.title\)\}/);
expect(templateJs).toContain("safeMarkedParse(entry.plan.markdown)");
});
});
Loading