Skip to content

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

Rust

chore: remove redundant comments and unused internals (#1505)

Seth Karten032e3ee74574
diff --git a/packages/agent/src/agent-loop.ts b/packages/agent/src/agent-loop.ts
index 0d3d7376dd..31b3a15ccc 100644
--- a/packages/agent/src/agent-loop.ts
+++ b/packages/agent/src/agent-loop.ts
@@ -301,9 +301,6 @@ function createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {
);
}
-/**
- * Main loop logic shared by agentLoop and agentLoopContinue.
- */
async function runLoop(
currentContext: AgentContext,
newMessages: AgentMessage[],
@@ -314,17 +311,14 @@ async function runLoop(
): Promise<void> {
let firstTurn = true;
let lastTurn: Parameters<NonNullable<AgentLoopConfig["getContinuationMessages"]>>[0] | undefined;
- // Check for steering messages at start (user may have typed while waiting)
let pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);
const shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);
- // Outer loop: continues when queued follow-up messages arrive after agent would stop
while (true) {
throwIfAborted(signal);
let hasMoreToolCalls = true;
- // Inner loop: process tool calls and steering messages
while (hasMoreToolCalls || pendingMessages.length > 0) {
throwIfAborted(signal);
if (!firstTurn) {
@@ -333,7 +327,6 @@ async function runLoop(
firstTurn = false;
}
- // Process pending messages (inject before next assistant response)
if (pendingMessages.length > 0) {
for (const message of pendingMessages) {
await emit({ type: "message_start", message });
@@ -344,7 +337,6 @@ async function runLoop(
pendingMessages = [];
}
- // Stream assistant response
const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);
newMessages.push(message);
@@ -354,7 +346,6 @@ async function runLoop(
return;
}
- // Check for tool calls
const toolCalls = message.content.filter((c) => c.type === "toolCall");
const toolResults: ToolResultMessage[] = [];
@@ -419,7 +410,6 @@ async function runLoop(
}
}
- // Agent would stop here. Check for follow-up messages.
if (shouldStopBeforeTurn()) break;
const followUpMessagesResult = await settlePostTurn(
pollMessagesUnlessAborted(config.getFollowUpMessages, signal),
@@ -431,7 +421,6 @@ async function runLoop(
}
const followUpMessages = followUpMessagesResult.value;
if (followUpMessages.length > 0) {
- // Set as pending so inner loop processes them
pendingMessages = followUpMessages;
continue;
}
@@ -453,17 +442,12 @@ async function runLoop(
continue;
}
- // No more messages, exit
break;
}
await emit({ type: "agent_end", messages: newMessages });
}
-/**
- * Stream an assistant response from the LLM.
- * This is where AgentMessage[] gets transformed to Message[] for the LLM.
- */
async function streamAssistantResponse(
context: AgentContext,
config: AgentLoopConfig,
@@ -487,24 +471,20 @@ async function streamAssistantResponse(
try {
throwIfAborted(signal);
- // Apply context transform if configured (AgentMessage[] → AgentMessage[])
let messages = context.messages;
if (config.transformContext) {
messages = await maybePromiseWithAbort(config.transformContext(messages, signal), signal);
}
- // Convert to LLM-compatible messages (AgentMessage[] → Message[])
const llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);
const streamFunction = streamFn || streamSimple;
- // Resolve API key (important for expiring tokens)
const resolvedApiKey =
(config.getApiKey
? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal)
: undefined) || config.apiKey;
- // Build LLM context immediately before starting the provider call.
const llmContext: Context = {
systemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,
messages: llmMessages,
@@ -602,9 +582,6 @@ async function streamAssistantResponse(
}
}
-/**
- * Execute tool calls from an assistant message.
- */
async function executeToolCalls(
currentContext: AgentContext,
assistantMessage: AssistantMessage,
diff --git a/packages/agent/src/agent.ts b/packages/agent/src/agent.ts
index cdef2db467..6f8849ac26 100644
--- a/packages/agent/src/agent.ts
+++ b/packages/agent/src/agent.ts
@@ -94,7 +94,6 @@ function createMutableAgentState(
};
}
-/** Options for constructing an {@link Agent}. */
export interface AgentOptions {
initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
@@ -173,12 +172,6 @@ type ActiveRun = {
abortController: AbortController;
};
-/**
- * Stateful wrapper around the low-level agent loop.
- *
- * `Agent` owns the current transcript, emits lifecycle events, executes tools,
- * and exposes queueing APIs for steering and follow-up messages.
- */
export class Agent {
private _state: MutableAgentState;
private readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();
@@ -206,15 +199,10 @@ export class Agent {
signal?: AbortSignal,
) => Promise<AgentMessage[]>;
private activeRun?: ActiveRun;
- /** Session identifier forwarded to providers for cache-aware backends. */
public sessionId?: string;
- /** Optional per-level thinking token budgets forwarded to the stream function. */
public thinkingBudgets?: ThinkingBudgets;
- /** Preferred transport forwarded to the stream function. */
public transport: Transport;
- /** Optional cap for provider-requested retry delays. */
public maxRetryDelayMs?: number;
- /** Tool execution strategy for assistant messages that contain multiple tool calls. */
public toolExecution: ToolExecutionMode;
constructor(options: AgentOptions = {}) {
@@ -263,7 +251,6 @@ export class Agent {
return this._state;
}
- /** Controls how queued steering messages are drained. */
set steeringMode(mode: QueueMode) {
this.steeringQueue.mode = mode;
}
@@ -272,7 +259,6 @@ export class Agent {
return this.steeringQueue.mode;
}
- /** Controls how queued follow-up messages are drained. */
set followUpMode(mode: QueueMode) {
this.followUpQueue.mode = mode;
}
@@ -291,38 +277,31 @@ export class Agent {
this.followUpQueue.enqueue(message);
}
- /** Remove all queued steering messages. */
clearSteeringQueue(): void {
this.steeringQueue.clear();
}
- /** Remove all queued follow-up messages. */
clearFollowUpQueue(): void {
this.followUpQueue.clear();
}
- /** Remove all queued steering and follow-up messages. */
clearAllQueues(): void {
this.clearSteeringQueue();
this.clearFollowUpQueue();
}
- /** Remove queued batches containing a message matching the predicate from both queues. */
removeQueuedMessages(predicate: (message: AgentMessage) => boolean): AgentMessage[] {
return [...this.steeringQueue.removeWhere(predicate), ...this.followUpQueue.removeWhere(predicate)];
}
- /** Returns true when either queue still contains pending messages. */
hasQueuedMessages(): boolean {
return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
}
- /** Active abort signal for the current run, if any. */
get signal(): AbortSignal | undefined {
return this.activeRun?.abortController.signal;
}
- /** Abort the current run, if one is active. */
abort(): void {
this.activeRun?.abortController.abort();
}
@@ -336,7 +315,6 @@ export class Agent {
return this.activeRun?.promise ?? Promise.resolve();
}
- /** Clear transcript state, runtime state, and queued messages. */
reset(): void {
this._state.messages = [];
this._state.isStreaming = false;
@@ -347,7 +325,6 @@ export class Agent {
this.clearSteeringQueue();
}
- /** Start a new prompt from text, a single message, or a batch of messages. */
async prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
async prompt(input: string, images?: ImageContent[]): Promise<void>;
async prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {
@@ -360,7 +337,7 @@ export class Agent {
await this.runPromptMessages(messages);
}
- /** Continue from the current transcript. The last message must be a user or tool-result message. */
+ /** The last message must convert to a user or tool-result message. */
async continue(): Promise<void> {
if (this.activeRun) {
throw new Error("Agent is already processing. Wait for completion before continuing.");
diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts
index d8ed5b8eb5..fdbe00b3ab 100644
--- a/packages/agent/src/index.ts
+++ b/packages/agent/src/index.ts
@@ -1,8 +1,4 @@
-// Core Agent
export * from "./agent.js";
-// Loop functions
export * from "./agent-loop.js";
-// Proxy utilities
export * from "./proxy.js";
-// Types
export * from "./types.js";
diff --git a/packages/agent/src/proxy.ts b/packages/agent/src/proxy.ts
index 5f0925c914..69920ce033 100644
--- a/packages/agent/src/proxy.ts
+++ b/packages/agent/src/proxy.ts
@@ -1,9 +1,3 @@
-/**
- * Proxy stream function for apps that route LLM calls through a server.
- * The server manages auth and proxies requests to LLM providers.
- */
-
-// Internal import for JSON parsing utility
import {
type AssistantMessage,
type AssistantMessageEvent,
@@ -16,7 +10,6 @@ import {
type ToolCall,
} from "@earendil-works/pi-ai";
-// Create stream class matching ProxyMessageEventStream
class ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
constructor() {
super(
@@ -30,9 +23,6 @@ class ProxyMessageEventStream extends EventStream<AssistantMessageEvent, Assista
}
}
-/**
- * Proxy event types - server sends these with partial field stripped to reduce bandwidth.
- */
export type ProxyAssistantMessageEvent =
| { type: "start" }
| { type: "text_start"; contentIndex: number }
@@ -71,11 +61,8 @@ type ProxySerializableStreamOptions = Pick<
>;
export interface ProxyStreamOptions extends ProxySerializableStreamOptions {
- /** Local abort signal for the proxy request */
signal?: AbortSignal;
- /** Auth token for the proxy server */
authToken: string;
- /** Proxy server URL (e.g., "https://genai.example.com") */
proxyUrl: string;
}
@@ -117,7 +104,6 @@ export function streamProxy(model: Model<any>, context: Context, options: ProxyS
const stream = new ProxyMessageEventStream();
(async () => {
- // Initialize the partial message that we'll build up from events
const partial: AssistantMessage = {
role: "assistant",
stopReason: "stop",
@@ -171,7 +157,7 @@ export function streamProxy(model: Model<any>, context: Context, options: ProxyS
errorMessage = `Proxy error: ${errorData.error}`;
}
} catch {
- // Couldn't parse error response
+ // Keep the status-text fallback when the error body is not JSON.
}
throw new Error(errorMessage);
}
@@ -232,9 +218,6 @@ export function streamProxy(model: Model<any>, context: Context, options: ProxyS
return stream;
}
-/**
- * Process a proxy event and update the partial message.
- */
function processProxyEvent(
proxyEvent: ProxyAssistantMessageEvent,
partial: AssistantMessage,
diff --git a/packages/agent/src/types.ts b/packages/agent/src/types.ts
index 92f68a6570..f29074abe0 100644
--- a/packages/agent/src/types.ts
+++ b/packages/agent/src/types.ts
@@ -36,7 +36,7 @@ export type StreamFn = (
*/
export type ToolExecutionMode = "sequential" | "parallel";
-/** A single tool call content block emitted by an assistant message. */
+/** A tool-call content block emitted by an assistant message. */
export type AgentToolCall = Extract<AssistantMessage["content"][number], { type: "toolCall" }>;
/**
@@ -73,47 +73,46 @@ export interface AfterToolCallResult {
terminate?: boolean;
}
-/** Context passed to `beforeToolCall`. */
+/** Context passed to `beforeToolCall` after arguments are validated. */
export interface BeforeToolCallContext {
- /** The assistant message that requested the tool call. */
+ /** Assistant message that requested the call. */
assistantMessage: AssistantMessage;
- /** The raw tool call block from `assistantMessage.content`. */
+ /** Raw tool-call block from `assistantMessage.content`. */
toolCall: AgentToolCall;
- /** Validated tool arguments for the target tool schema. */
+ /** Validated arguments for the target tool schema. */
args: unknown;
- /** Current agent context at the time the tool call is prepared. */
+ /** Agent context when this call is prepared. */
context: AgentContext;
}
/** Context passed to `afterToolCall`. */
export interface AfterToolCallContext {
- /** The assistant message that requested the tool call. */
+ /** Assistant message that requested the call. */
assistantMessage: AssistantMessage;
- /** The raw tool call block from `assistantMessage.content`. */
+ /** Raw tool-call block from `assistantMessage.content`. */
toolCall: AgentToolCall;
- /** Validated tool arguments for the target tool schema. */
+ /** Validated arguments for the target tool schema. */
args: unknown;
- /** The executed tool result before any `afterToolCall` overrides are applied. */
+ /** Executed result before any `afterToolCall` overrides. */
result: AgentToolResult<any>;
- /** Whether the executed tool result is currently treated as an error. */
+ /** Whether the executed result is currently treated as an error. */
isError: boolean;
- /** Current agent context at the time the tool call is finalized. */
+ /** Agent context when this call is finalized. */
context: AgentContext;
}
-/** Context passed to `shouldStopAfterTurn`. */
+/** Context passed to `shouldStopAfterTurn` and `getContinuationMessages`. */
export interface ShouldStopAfterTurnContext {
- /** The assistant message that completed the turn. */
+ /** Assistant message that completed the turn. */
message: AssistantMessage;
- /** Tool result messages passed to the preceding `turn_end` event. */
+ /** Tool-result messages included in the preceding `turn_end` event. */
toolResults: ToolResultMessage[];
- /** Current agent context after the turn's assistant message and tool results have been appended. */
+ /** Context after appending the turn's assistant message and tool results. */
context: AgentContext;
- /** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */
+ /** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */
newMessages: AgentMessage[];
}
-/** Context passed to `getContinuationMessages`. */
export type GetContinuationMessagesContext = ShouldStopAfterTurnContext;
export interface AgentLoopConfig extends SimpleStreamOptions {
@@ -244,13 +243,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
getContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;
/**
- * Tool execution mode.
- * - "sequential": execute tool calls one by one
- * - "parallel": preflight tool calls sequentially, then execute allowed tools concurrently;
- * emit `tool_execution_end` in tool completion order after each tool is finalized,
- * then emit tool-result message artifacts later in assistant source order
- *
- * Default: "parallel"
+ * Tool execution mode. Defaults to `"parallel"`.
+ * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits
+ * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.
*/
toolExecution?: ToolExecutionMode;
@@ -298,15 +293,8 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
* }
* ```
*/
-export interface CustomAgentMessages {
- // Empty by default - apps extend via declaration merging
-}
+export interface CustomAgentMessages {}
-/**
- * AgentMessage: Union of LLM messages + custom messages.
- * This abstraction allows apps to add custom message types while maintaining
- * type safety and compatibility with the base LLM messages.
- */
export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
/**
@@ -318,29 +306,25 @@ export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessag
export interface AgentState {
/** System prompt sent with each model request. */
systemPrompt: string;
- /** Active model used for future turns. */
+ /** Model used for future turns. */
model: Model<any>;
/** Requested reasoning level for future turns. */
thinkingLevel: ThinkingLevel;
/** Requested provider service tier for future turns. */
serviceTier: ServiceTier;
- /** Available tools. Assigning a new array copies the top-level array. */
+ /** Available tools. Assigning a new array copies its top-level array. */
set tools(tools: AgentTool<any>[]);
get tools(): AgentTool<any>[];
- /** Conversation transcript. Assigning a new array copies the top-level array. */
+ /** Conversation transcript. Assigning a new array copies its top-level array. */
set messages(messages: AgentMessage[]);
get messages(): AgentMessage[];
- /**
- * True while the agent is processing a prompt or continuation.
- *
- * This remains true until awaited `agent_end` listeners settle.
- */
+ /** True while processing a prompt or continuation, including awaited `agent_end` listeners. */
readonly isStreaming: boolean;
- /** Partial assistant message for the current streamed response, if any. */
+ /** Partial assistant message for the active streamed response, if any. */
readonly streamingMessage?: AgentMessage;
- /** Tool call ids currently executing. */
+ /** Tool-call IDs currently executing. */
readonly pendingToolCalls: ReadonlySet<string>;
- /** Error message from the most recent failed or aborted assistant turn, if any. */
+ /** Error from the most recent failed or aborted assistant turn, if any. */
readonly errorMessage?: string;
}
@@ -348,7 +332,7 @@ export interface AgentState {
export interface AgentToolResult<T> {
/** Text or image content returned to the model. */
content: (TextContent | ImageContent)[];
- /** Arbitrary structured details for logs or UI rendering. */
+ /** Structured details for logs or UI rendering. */
details: T;
/**
* Hint that the agent should stop after the current tool batch.
@@ -357,7 +341,7 @@ export interface AgentToolResult<T> {
terminate?: boolean;
}
-/** Callback used by tools to stream partial execution updates. */
+/** Callback used by tools to publish partial execution updates. */
export type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;
/** Tool definition used by the agent runtime. */
@@ -386,7 +370,7 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
executionMode?: ToolExecutionMode;
}
-/** Context snapshot passed into the low-level agent loop. */
+/** Context snapshot passed to the low-level agent loop and tool hooks. */
export interface AgentContext {
/** System prompt included with the request. */
systemPrompt: string;
@@ -404,18 +388,18 @@ export interface AgentContext {
* idle only after those listeners finish.
*/
export type AgentEvent =
- // Agent lifecycle
+ /** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */
| { type: "agent_start" }
| { type: "agent_end"; messages: AgentMessage[] }
- // Turn lifecycle - a turn is one assistant response + any tool calls/results
+ /** One assistant response and its resulting tool calls. */
| { type: "turn_start" }
| { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] }
- // Message lifecycle - emitted for user, assistant, and toolResult messages
+ /** Lifecycle events for user, assistant, and tool-result messages. */
| { type: "message_start"; message: AgentMessage }
- // Only emitted for assistant messages during streaming
+ /** Only emitted for assistant messages during streaming. */
| { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }
| { type: "message_end"; message: AgentMessage }
- // Tool execution lifecycle
+ /** Tool execution events; parallel calls may end in completion rather than source order. */
| { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any }
| { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any }
| { type: "tool_execution_end"; toolCallId: string; toolName: string; result: any; isError: boolean };
diff --git a/packages/agent/test/agent-loop.test.ts b/packages/agent/test/agent-loop.test.ts
index f8745d0a08..d8167c0c13 100644
--- a/packages/agent/test/agent-loop.test.ts
+++ b/packages/agent/test/agent-loop.test.ts
@@ -11,7 +11,6 @@ import { describe, expect, it, vi } from "vitest";
import { agentLoop, agentLoopContinue, runAgentLoop } from "../src/agent-loop.js";
import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool } from "../src/types.js";
-// Mock stream for testing - mimics MockAssistantStream
class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
constructor() {
super(
@@ -105,7 +104,6 @@ function createUserMessage(text: string): UserMessage {
};
}
-// Simple identity converter for tests - just passes through standard messages
function identityConverter(messages: AgentMessage[]): Message[] {
return messages.filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
}
@@ -136,7 +134,6 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([createUserMessage("Hello")], context, config, controller.signal, streamFn);
for await (const _event of stream) {
- // consume
}
const messages = await stream.result();
@@ -261,7 +258,6 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([createUserMessage("Hello")], context, config, controller.signal, streamFn);
for await (const _event of stream) {
- // consume
}
const messages = await stream.result();
@@ -358,7 +354,6 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([createUserMessage("Hello")], context, config, controller.signal, streamFn);
for await (const _event of stream) {
- // consume
}
await stream.result();
@@ -542,7 +537,6 @@ describe("agentLoop with AgentMessage", () => {
});
it("should handle custom message types via convertToLlm", async () => {
- // Create a custom message type
interface CustomNotification {
role: "notification";
text: string;
@@ -567,7 +561,6 @@ describe("agentLoop with AgentMessage", () => {
const config: AgentLoopConfig = {
model: createModel(),
convertToLlm: (messages) => {
- // Filter out notifications, convert rest
convertedMessages = messages
.filter((m) => (m as { role: string }).role !== "notification")
.filter((m) => m.role === "user" || m.role === "assistant" || m.role === "toolResult") as Message[];
@@ -591,7 +584,6 @@ describe("agentLoop with AgentMessage", () => {
events.push(event);
}
- // The notification should have been filtered out in convertToLlm
expect(convertedMessages.length).toBe(1); // Only user message
expect(convertedMessages[0].role).toBe("user");
});
@@ -637,7 +629,6 @@ describe("agentLoop with AgentMessage", () => {
);
const consume = (async () => {
for await (const _event of stream) {
- // consume
}
})();
@@ -669,7 +660,6 @@ describe("agentLoop with AgentMessage", () => {
const config: AgentLoopConfig = {
model: createModel(),
transformContext: async (messages) => {
- // Keep only last 2 messages (prune old ones)
transformedMessages = messages.slice(-2);
return transformedMessages;
},
@@ -693,12 +683,9 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
for await (const _ of stream) {
- // consume
}
- // transformContext should have been called first, keeping only last 2
expect(transformedMessages.length).toBe(2);
- // Then convertToLlm receives the pruned messages
expect(convertedMessages.length).toBe(2);
});
@@ -758,7 +745,6 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
for await (const _event of stream) {
- // consume
}
expect(executed).toEqual([123]);
@@ -838,7 +824,6 @@ describe("agentLoop with AgentMessage", () => {
const stream = agentLoop([userPrompt], context, config, undefined, streamFn);
for await (const _event of stream) {
- // consume
}
expect(executed).toEqual([[{ oldText: "before", newText: "after" }]]);
@@ -974,7 +959,6 @@ describe("agentLoop with AgentMessage", () => {
convertToLlm: identityConverter,
toolExecution: "sequential",
getSteeringMessages: async () => {
- // Return steering message after tool execution has started.
if (executed.length >= 1 && !queuedDelivered) {
queuedDelivered = true;
return [queuedUserMessage];
@@ -985,7 +969,6 @@ describe("agentLoop with AgentMessage", () => {
const events: AgentEvent[] = [];
const stream = agentLoop([userPrompt], context, config, undefined, (_model, ctx, _options) => {
- // Check if interrupt message is in context on second call
if (callIndex === 1) {
sawInterruptInContext = ctx.messages.some(
(m) => m.role === "user" && typeof m.content === "string" && m.content === "interrupt",
@@ -995,7 +978,6 @@ describe("agentLoop with AgentMessage", () => {
const mockStream = new MockAssistantStream();
queueMicrotask(() => {
if (callIndex === 0) {
- // First call: return two tool calls
const message = createAssistantMessage(
[
{ type: "toolCall", id: "tool-1", name: "echo", arguments: { value: "first" } },
@@ -1005,7 +987,6 @@ describe("agentLoop with AgentMessage", () => {
);
mockStream.push({ type: "done", reason: "toolUse", message });
} else {
- // Second call: return final response
const message = createAssistantMessage([{ type: "text", text: "done" }]);
mockStream.push({ type: "done", reason: "stop", message });
}
@@ -1018,7 +999,6 @@ describe("agentLoop with AgentMessage", () => {
events.push(event);
}
- // Both tools should execute before steering is injected
expect(executed).toEqual(["first", "second"]);
const toolEnds = events.filter(
@@ -1028,7 +1008,6 @@ describe("agentLoop with AgentMessage", () => {
expect(toolEnds[0].isError).toBe(false);
expect(toolEnds[1].isError).toBe(false);
- // Queued message should appear in events after both tool result messages
const eventSequence = events.flatMap((event) => {
if (event.type !== "message_start") return [];
if (event.message.role === "toolResult") return [`tool:${event.message.toolCallId}`];
@@ -1041,7 +1020,6 @@ describe("agentLoop with AgentMessage", () => {
expect(eventSequence.indexOf("tool:tool-1")).toBeLessThan(eventSequence.indexOf("interrupt"));
expect(eventSequence.indexOf("tool:tool-2")).toBeLessThan(eventSequence.indexOf("interrupt"));
- // Interrupt message should be in context when second LLM call is made
expect(sawInterruptInContext).toBe(true);
});
@@ -1084,7 +1062,6 @@ describe("agentLoop with AgentMessage", () => {
});
for await (const _event of stream) {
- // consume
}
const messages = await stream.result();
@@ -1137,7 +1114,6 @@ describe("agentLoop with AgentMessage", () => {
});
for await (const _event of stream) {
- // consume
}
expect(callIndex).toBe(2);
@@ -1182,7 +1158,6 @@ describe("agentLoop with AgentMessage", () => {
};
const userPrompt: AgentMessage = createUserMessage("run both");
- // config is parallel (default), but tool forces sequential
const config: AgentLoopConfig = {
model: createModel(),
convertToLlm: identityConverter,
@@ -1216,7 +1191,6 @@ describe("agentLoop with AgentMessage", () => {
events.push(event);
}
- // With sequential execution, second tool should NOT start before first finishes
expect(parallelObserved).toBe(false);
const toolResultIds = events.flatMap((event) => {
@@ -1259,7 +1233,6 @@ describe("agentLoop with AgentMessage", () => {
label: "Fast",
description: "Fast tool",
parameters: toolSchema,
- // no executionMode = defaults to parallel
async execute(_toolCallId, params) {
executionOrder.push(`fast:${params.value}`);
return {
@@ -1279,7 +1252,6 @@ describe("agentLoop with AgentMessage", () => {
const config: AgentLoopConfig = {
model: createModel(),
convertToLlm: identityConverter,
- // parallel by default, but slowTool forces sequential
};
let callIndex = 0;
@@ -1310,7 +1282,6 @@ describe("agentLoop with AgentMessage", () => {
events.push(event);
}
- // Fast tool should NOT run before slow tool finishes
expect(executionOrder[0]).toBe("slow:a");
expect(executionOrder).toContain("fast:b");
});
@@ -1385,7 +1356,6 @@ describe("agentLoop with AgentMessage", () => {
events.push(event);
}
- // With executionMode=parallel, second tool should start before first finishes
expect(parallelObserved).toBe(true);
});
@@ -1467,7 +1437,6 @@ describe("agentLoop with AgentMessage", () => {
},
);
for await (const _event of stream) {
- // Drain the stream.
}
expect(llmCalls).toBe(expected.llmCalls);
@@ -1496,7 +1465,6 @@ describe("agentLoop with AgentMessage", () => {
convertToLlm: identityConverter,
shouldStopBeforeTurn: () => stopRequested,
getSteeringMessages: async () => {
- // Flip only on the post-tool-batch poll; the pre-loop poll would stop before the recheck runs.
if (llmCalls > 0) stopRequested = true;
return [];
},
@@ -1519,7 +1487,6 @@ describe("agentLoop with AgentMessage", () => {
},
);
for await (const _event of stream) {
- // Drain the stream.
}
expect(llmCalls).toBe(1);
});
@@ -1541,7 +1508,6 @@ describe("agentLoop with AgentMessage", () => {
convertToLlm: identityConverter,
shouldStopBeforeTurn: () => stopRequested,
getSteeringMessages: async () => {
- // Only the post-tool-batch poll returns steering; the stop flips during it.
if (llmCalls !== 1 || stopRequested) return [];
stopRequested = true;
return [createUserMessage("late steer")];
@@ -1617,7 +1583,6 @@ describe("agentLoop with AgentMessage", () => {
},
);
for await (const _event of stream) {
- // Drain the stream.
}
expect(execute).toHaveBeenCalledOnce();
@@ -1824,7 +1789,6 @@ describe("agentLoop with AgentMessage", () => {
});
for await (const _event of stream) {
- // consume
}
const messages = await stream.result();
@@ -1880,7 +1844,6 @@ describe("agentLoop with AgentMessage", () => {
});
for await (const _event of stream) {
- // consume
}
expect(llmCalls).toBe(1);
@@ -1935,18 +1898,15 @@ describe("agentLoopContinue with AgentMessage", () => {
const messages = await stream.result();
- // Should only return the new assistant message (not the existing user message)
expect(messages.length).toBe(1);
expect(messages[0].role).toBe("assistant");
- // Should NOT have user message events (that's the key difference from agentLoop)
const messageEndEvents = events.filter((e) => e.type === "message_end");
expect(messageEndEvents.length).toBe(1);
expect((messageEndEvents[0] as any).message.role).toBe("assistant");
});
it("should allow custom message types as last message (caller responsibility)", async () => {
- // Custom message that will be converted to user message by convertToLlm
interface CustomMessage {
role: "custom";
text: string;
@@ -1968,7 +1928,6 @@ describe("agentLoopContinue with AgentMessage", () => {
const config: AgentLoopConfig = {
model: createModel(),
convertToLlm: (messages) => {
- // Convert custom to user message
return messages
.map((m) => {
if ((m as any).role === "custom") {
@@ -1993,7 +1952,6 @@ describe("agentLoopContinue with AgentMessage", () => {
return stream;
};
- // Should not throw - the custom message will be converted to user message
const stream = agentLoopContinue(context, config, undefined, streamFn);
const events: AgentEvent[] = [];
diff --git a/packages/agent/test/agent.test.ts b/packages/agent/test/agent.test.ts
index 2474a203bd..6ac4820ea7 100644
--- a/packages/agent/test/agent.test.ts
+++ b/packages/agent/test/agent.test.ts
@@ -10,7 +10,6 @@ import {
agentLoop,
} from "../src/index.js";
-// Mock stream that mimics AssistantMessageEventStream
class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
constructor() {
super(
@@ -122,15 +121,12 @@ describe("Agent", () => {
eventCount++;
});
- // No initial event on subscribe
expect(eventCount).toBe(0);
- // State mutators don't emit events
agent.state.systemPrompt = "Test prompt";
expect(eventCount).toBe(0);
expect(agent.state.systemPrompt).toBe("Test prompt");
- // Unsubscribe should work
unsubscribe();
agent.state.systemPrompt = "Another prompt";
expect(eventCount).toBe(0); // Should not increase
@@ -275,38 +271,31 @@ describe("Agent", () => {
it("should update state with mutators", () => {
const agent = new Agent();
- // Test setSystemPrompt
agent.state.systemPrompt = "Custom prompt";
expect(agent.state.systemPrompt).toBe("Custom prompt");
- // Test setModel
const newModel = getModel("google", "gemini-2.5-flash");
agent.state.model = newModel;
expect(agent.state.model).toBe(newModel);
- // Test setThinkingLevel
agent.state.thinkingLevel = "high";
expect(agent.state.thinkingLevel).toBe("high");
- // Test setTools
const tools = [{ name: "test", description: "test tool" } as any];
agent.state.tools = tools;
expect(agent.state.tools).toEqual(tools);
expect(agent.state.tools).not.toBe(tools); // Should be a copy
- // Test replaceMessages
const messages = [{ role: "user" as const, content: "Hello", timestamp: Date.now() }];
agent.state.messages = messages;
expect(agent.state.messages).toEqual(messages);
expect(agent.state.messages).not.toBe(messages); // Should be a copy
- // Test appendMessage
const newMessage = { role: "assistant" as const, content: [{ type: "text" as const, text: "Hi" }] };
agent.state.messages.push(newMessage as any);
expect(agent.state.messages).toHaveLength(2);
expect(agent.state.messages[1]).toBe(newMessage);
- // Test clearMessages
agent.state.messages = [];
expect(agent.state.messages).toEqual([]);
});
@@ -317,7 +306,6 @@ describe("Agent", () => {
const message = { role: "user" as const, content: "Steering message", timestamp: Date.now() };
agent.steer(message);
- // The message is queued but not yet in state.messages
expect(agent.state.messages).not.toContainEqual(message);
});
@@ -327,14 +315,12 @@ describe("Agent", () => {
const message = { role: "user" as const, content: "Follow-up message", timestamp: Date.now() };
agent.followUp(message);
- // The message is queued but not yet in state.messages
expect(agent.state.messages).not.toContainEqual(message);
});
it("should handle abort controller", () => {
const agent = new Agent();
- // Should not throw even if nothing is running
expect(() => agent.abort()).not.toThrow();
});
@@ -475,7 +461,6 @@ describe("Agent", () => {
controller.signal,
);
for await (const _event of stream) {
- // Drain the stream.
}
expect(await stream.result()).toEqual([]);
@@ -509,13 +494,11 @@ describe("Agent", () => {
it("should throw when prompt() called while streaming", async () => {
let abortSignal: AbortSignal | undefined;
const agent = new Agent({
- // Use a stream function that responds to abort
streamFn: (_model, _context, options) => {
abortSignal = options?.signal;
const stream = new MockAssistantStream();
queueMicrotask(() => {
stream.push({ type: "start", partial: createAssistantMessage("") });
- // Check abort signal periodically
const checkAbort = () => {
if (abortSignal?.aborted) {
stream.push({ type: "error", reason: "aborted", error: createAssistantMessage("Aborted") });
@@ -529,19 +512,15 @@ describe("Agent", () => {
},
});
- // Start first prompt (don't await, it will block until abort)
const firstPrompt = agent.prompt("First message");
- // Wait a tick for isStreaming to be set
await new Promise((resolve) => setTimeout(resolve, 10));
expect(agent.state.isStreaming).toBe(true);
- // Second prompt should reject
await expect(agent.prompt("Second message")).rejects.toThrow(
"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.",
);
- // Cleanup - abort to stop the stream
agent.abort();
await firstPrompt.catch(() => {}); // Ignore abort error
});
@@ -567,17 +546,14 @@ describe("Agent", () => {
},
});
- // Start first prompt
const firstPrompt = agent.prompt("First message");
await new Promise((resolve) => setTimeout(resolve, 10));
expect(agent.state.isStreaming).toBe(true);
- // continue() should reject
await expect(agent.continue()).rejects.toThrow(
"Agent is already processing. Wait for completion before continuing.",
);
- // Cleanup
agent.abort();
await firstPrompt.catch(() => {});
});
@@ -722,7 +698,6 @@ describe("Agent", () => {
await agent.prompt("hello");
expect(receivedSessionId).toBe("session-abc");
- // Test setter
agent.sessionId = "session-def";
expect(agent.sessionId).toBe("session-def");
diff --git a/packages/ai/scripts/generate-test-image.ts b/packages/ai/scripts/generate-test-image.ts
index 29a473d463..7b50eeaae6 100644
--- a/packages/ai/scripts/generate-test-image.ts
+++ b/packages/ai/scripts/generate-test-image.ts
@@ -8,25 +8,20 @@ import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-// Create a 200x200 canvas
const canvas = createCanvas(200, 200);
const ctx = canvas.getContext("2d");
-// Fill background with white
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 200, 200);
-// Draw a red circle in the center
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fill();
-// Save the image
const buffer = canvas.toBuffer("image/png");
const outputPath = join(__dirname, "..", "test", "data", "red-circle.png");
-// Ensure the directory exists
import { mkdirSync } from "fs";
mkdirSync(join(__dirname, "..", "test", "data"), { recursive: true });
diff --git a/packages/ai/src/env-api-keys.ts b/packages/ai/src/env-api-keys.ts
index c52f92f5de..eaeae11a84 100644
--- a/packages/ai/src/env-api-keys.ts
+++ b/packages/ai/src/env-api-keys.ts
@@ -16,7 +16,6 @@ const NODE_FS_SPECIFIER = "node:" + "fs";
const NODE_OS_SPECIFIER = "node:" + "os";
const NODE_PATH_SPECIFIER = "node:" + "path";
-// Eagerly load in Node.js/Bun environment only
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
dynamicImport(NODE_FS_SPECIFIER).then((m) => {
_existsSync = (m as { existsSync: typeof existsSync }).existsSync;
@@ -78,12 +77,10 @@ function hasVertexAdcCredentials(): boolean {
return false;
}
- // Check GOOGLE_APPLICATION_CREDENTIALS env var first (standard way)
const gacPath = process.env.GOOGLE_APPLICATION_CREDENTIALS || getProcEnv("GOOGLE_APPLICATION_CREDENTIALS");
if (gacPath) {
cachedVertexAdcCredentialsExists = _existsSync(gacPath);
} else {
- // Fall back to default ADC path (lazy evaluation)
cachedVertexAdcCredentialsExists = _existsSync(
_join(_homedir(), ".config", "gcloud", "application_default_credentials.json"),
);
@@ -167,8 +164,6 @@ export function getEnvApiKey(provider: string): string | undefined {
return process.env[envKeys[0]] || getProcEnv(envKeys[0]);
}
- // Vertex AI supports either an explicit API key or Application Default Credentials.
- // Auth is configured via `gcloud auth application-default login`.
if (provider === "google-vertex") {
const hasCredentials = hasVertexAdcCredentials();
const hasProject = !!(
@@ -185,13 +180,6 @@ export function getEnvApiKey(provider: string): string | undefined {
}
if (provider === "amazon-bedrock") {
- // Amazon Bedrock supports multiple credential sources:
- // 1. AWS_PROFILE - named profile from ~/.aws/credentials
- // 2. AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY - standard IAM keys
- // 3. AWS_BEARER_TOKEN_BEDROCK - Bedrock bearer token
- // 4. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI - ECS task roles
- // 5. AWS_CONTAINER_CREDENTIALS_FULL_URI - ECS task roles (full URI)
- // 6. AWS_WEB_IDENTITY_TOKEN_FILE - IRSA (IAM Roles for Service Accounts)
if (
process.env.AWS_PROFILE ||
(process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) ||
@@ -213,7 +201,6 @@ export function getEnvApiKey(provider: string): string | undefined {
return undefined;
}
-// PRIME_TEAM_ID env var, falling back to team_id in ~/.prime/config.json.
export function getPrimeTeamId(): string | undefined {
const fromEnv = process.env.PRIME_TEAM_ID || getProcEnv("PRIME_TEAM_ID");
if (fromEnv?.trim()) return fromEnv.trim();
@@ -228,7 +215,7 @@ export function getPrimeTeamId(): string | undefined {
if (typeof teamId === "string" && teamId.trim()) return teamId.trim();
}
} catch {
- // Unreadable/malformed config.json: behave as if no team is configured.
+ // Treat unreadable or malformed config as no configured team.
}
return undefined;
}
diff --git a/packages/ai/src/mcp/oauth.ts b/packages/ai/src/mcp/oauth.ts
index 092add6d2e..9b9109401c 100644
--- a/packages/ai/src/mcp/oauth.ts
+++ b/packages/ai/src/mcp/oauth.ts
@@ -1,6 +1,3 @@
-// Generic OAuth 2.1 (PKCE + dynamic client registration) for remote MCP servers.
-// One provider per server, registered as `mcp:<server>` so it reuses auth.json. Node-only (callback server).
-
import type { Server } from "node:http";
import { oauthErrorHtml, oauthSuccessHtml } from "../utils/oauth/oauth-page.js";
import { generatePKCE } from "../utils/oauth/pkce.js";
@@ -17,7 +14,6 @@ const redirectUriFor = (port: number) => `http://localhost:${port}${CALLBACK_PAT
const ALL_REDIRECT_URIS = CALLBACK_PORTS.map(redirectUriFor);
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
-/** Authorization-server metadata we rely on (RFC 8414 / OAuth 2.1 + DCR). */
interface AuthServerMetadata {
issuer?: string;
authorization_endpoint: string;
@@ -29,17 +25,16 @@ interface AuthServerMetadata {
export interface McpOAuthConfig {
/** MCP server name; provider id becomes `mcp:<server>`. */
server: string;
- /** Human label for UI. */
+ /** Human-readable label shown in OAuth UI; defaults to `server`. */
label?: string;
/** The MCP endpoint URL — discovery is rooted at its origin. */
url: string;
/** Pre-registered client id (servers without DCR, e.g. Slack). */
clientId?: string;
- /** Explicit scopes; falls back to the server's advertised scopes. */
+ /** Requested OAuth scopes; defaults to the server's advertised scopes. */
scopes?: string;
}
-/** Extra fields we persist alongside the standard credential triple. */
interface McpCredentials extends OAuthCredentials {
tokenEndpoint?: string;
clientId?: string;
@@ -87,7 +82,6 @@ async function discover(url: string): Promise<AuthServerMetadata> {
);
}
-/** Dynamic client registration (RFC 7591). Returns the issued client_id. */
async function registerClient(registrationEndpoint: string, label: string): Promise<string> {
const body = {
client_name: label,
@@ -246,7 +240,6 @@ function toCredentials(
};
}
-/** Build a provider for one MCP server. Register it with registerOAuthProvider(). */
export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInterface {
const label = config.label ?? config.server;
diff --git a/packages/ai/src/models.ts b/packages/ai/src/models.ts
index fc7ba59b49..fc1910ce7a 100644
--- a/packages/ai/src/models.ts
+++ b/packages/ai/src/models.ts
@@ -3,7 +3,6 @@ import type { Api, KnownProvider, Model, ModelThinkingLevel, Usage } from "./typ
const modelRegistry: Map<string, Map<string, Model<Api>>> = new Map();
-// Initialize registry from MODELS on module load
for (const [provider, models] of Object.entries(MODELS)) {
const providerModels = new Map<string, Model<Api>>();
for (const [id, model] of Object.entries(models)) {
@@ -95,10 +94,6 @@ export function clampThinkingLevel<TApi extends Api>(
return availableLevels[0] ?? "off";
}
-/**
- * Check if two models are equal by comparing both their id and provider.
- * Returns false if either model is null or undefined.
- */
export function modelsAreEqual<TApi extends Api>(
a: Model<TApi> | null | undefined,
b: Model<TApi> | null | undefined,
diff --git a/packages/ai/src/openrouter-reasoning.ts b/packages/ai/src/openrouter-reasoning.ts
index b0e93fc507..a09c4595ea 100644
--- a/packages/ai/src/openrouter-reasoning.ts
+++ b/packages/ai/src/openrouter-reasoning.ts
@@ -33,14 +33,6 @@ function enabledOnlyCapabilities(mandatory: boolean): OpenRouterReasoningCapabil
};
}
-/**
- * Normalize the reasoning capability metadata published by OpenRouter.
- *
- * The top-level reasoning object is only trusted after supported_parameters
- * confirms that the route accepts reasoning controls. An omitted
- * supported_efforts field means the route exposes an enabled toggle but no
- * effort selector; null means every gateway effort is accepted.
- */
export function getOpenRouterReasoningCapabilities(model: unknown): OpenRouterReasoningCapabilities | undefined {
if (!isRecord(model)) return undefined;
const supportedParameters = Array.isArray(model.supported_parameters) ? model.supported_parameters : [];
diff --git a/packages/ai/src/providers/amazon-bedrock.ts b/packages/ai/src/providers/amazon-bedrock.ts
index 3de36f60eb..0a540c337e 100644
--- a/packages/ai/src/providers/amazon-bedrock.ts
+++ b/packages/ai/src/providers/amazon-bedrock.ts
@@ -125,18 +125,14 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
hasConfiguredProfile,
);
- // Only pin standard AWS Bedrock runtime endpoints when no region/profile is configured.
- // This preserves custom endpoints (VPC/proxy) from #3402 without forcing built-in
- // catalog defaults such as us-east-1 to override AWS_REGION/AWS_PROFILE.
+ // Preserve custom endpoints and AWS region/profile configuration.
if (useExplicitEndpoint) {
config.endpoint = model.baseUrl;
}
- // Resolve bearer token for Bedrock API key auth.
const bearerToken = options.bearerToken || process.env.AWS_BEARER_TOKEN_BEDROCK || undefined;
const useBearerToken = bearerToken !== undefined && process.env.AWS_BEDROCK_SKIP_AUTH !== "1";
- // in Node.js/Bun environment only
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
// Region resolution: explicit option > env vars > SDK default chain.
// When AWS_PROFILE is set, we leave region undefined so the SDK can
@@ -149,7 +145,6 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
config.region = "us-east-1";
}
- // Support proxies that don't need authentication
if (process.env.AWS_BEDROCK_SKIP_AUTH === "1") {
config.credentials = {
accessKeyId: "dummy-access-key",
@@ -178,7 +173,6 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
httpsAgent: agent,
});
} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === "1") {
- // Some custom endpoints require HTTP/1.1 instead of HTTP/2
const nodeHttpHandler = await import("@smithy/node-http-handler");
config.requestHandler = new nodeHttpHandler.NodeHttpHandler();
}
@@ -601,11 +595,8 @@ function supportsPromptCaching(model: Model<"bedrock-converse-stream">): boolean
if (typeof process !== "undefined" && process.env.AWS_BEDROCK_FORCE_CACHE === "1") return true;
return false;
}
- // Claude 4.x models (opus-4, sonnet-4, haiku-4)
if (candidates.some((s) => s.includes("-4-"))) return true;
- // Claude 3.7 Sonnet
if (candidates.some((s) => s.includes("claude-3-7-sonnet"))) return true;
- // Claude 3.5 Haiku
if (candidates.some((s) => s.includes("claude-3-5-haiku"))) return true;
return false;
}
@@ -631,7 +622,6 @@ function buildSystemPrompt(
const blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];
- // Add cache point for supported Claude models when caching is enabled
if (cacheRetention !== "none" && supportsPromptCaching(model)) {
blocks.push({
cachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === "long" ? { ttl: CacheTTL.ONE_HOUR } : {}) },
@@ -686,7 +676,6 @@ function convertMessages(
for (const c of m.content) {
switch (c.type) {
case "text":
- // Skip empty text blocks
if (c.text.trim().length === 0) continue;
contentBlocks.push({ text: sanitizeSurrogates(c.text) });
break;
@@ -696,7 +685,6 @@ function convertMessages(
});
break;
case "thinking":
- // Skip empty thinking blocks
if (c.thinking.trim().length === 0) continue;
// Only Anthropic models support the signature field in reasoningText.
// For other models, we omit the signature to avoid errors like:
@@ -729,7 +717,6 @@ function convertMessages(
throw new Error("Unknown assistant content type");
}
}
- // Skip if all content blocks were filtered out
if (contentBlocks.length === 0) {
continue;
}
@@ -744,7 +731,6 @@ function convertMessages(
// Bedrock requires all tool results to be in one message
const toolResults: ContentBlock.ToolResultMember[] = [];
- // Add current tool result with all content blocks combined
toolResults.push({
toolResult: {
toolUseId: m.toolCallId,
@@ -757,7 +743,6 @@ function convertMessages(
},
});
- // Look ahead for consecutive toolResult messages
let j = i + 1;
while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
const nextMsg = transformedMessages[j] as ToolResultMessage;
@@ -775,7 +760,6 @@ function convertMessages(
j++;
}
- // Skip the messages we've already processed
i = j - 1;
result.push({
@@ -931,7 +915,6 @@ function buildAdditionalModelRequestFields(
max: 16384, // Budget-based Claude has no max tier, clamp to high
};
- // Custom budgets override defaults (xhigh/max not in ThinkingBudgets, use high)
const level = options.reasoning === "xhigh" || options.reasoning === "max" ? "high" : options.reasoning;
const budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];
diff --git a/packages/ai/src/providers/anthropic.ts b/packages/ai/src/providers/anthropic.ts
index 0f3232dc0f..55596aa0c3 100644
--- a/packages/ai/src/providers/anthropic.ts
+++ b/packages/ai/src/providers/anthropic.ts
@@ -104,7 +104,6 @@ const claudeCodeTools = [
const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
-// Convert tool name to CC canonical casing if it matches (case-insensitive)
const toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;
const fromClaudeCodeName = (name: string, tools?: Tool[]) => {
if (tools && tools.length > 0) {
@@ -131,13 +130,11 @@ function convertContentBlocks(content: (TextContent | ImageContent)[]):
};
}
> {
- // If only text blocks, return as concatenated string for simplicity
const hasImages = content.some((c) => c.type === "image");
if (!hasImages) {
return sanitizeSurrogates(content.map((c) => (c as TextContent).text).join("\n"));
}
- // If we have images, convert to content block array
const blocks = content.map((block) => {
if (block.type === "text") {
return {
@@ -155,7 +152,6 @@ function convertContentBlocks(content: (TextContent | ImageContent)[]):
};
});
- // If only images (no text), add placeholder text block
const hasText = blocks.some((b) => b.type === "text");
if (!hasText) {
blocks.unshift({
@@ -544,7 +540,6 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
output.usage.output = event.message.usage.output_tokens || 0;
output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
- // Anthropic doesn't provide total_tokens, compute from components
output.usage.totalTokens =
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
if (cacheControl && usesAnthropicCachePricing) {
@@ -700,7 +695,6 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
if (event.usage.cache_creation_input_tokens != null) {
output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
}
- // Anthropic doesn't provide total_tokens, compute from components
output.usage.totalTokens =
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
calculateCost(
@@ -888,7 +882,6 @@ function createClient(
return { client, isOAuthToken: false };
}
- // Copilot: Bearer auth, selective betas.
if (model.provider === "github-copilot") {
const client = new Anthropic({
apiKey: null,
@@ -910,7 +903,6 @@ function createClient(
return { client, isOAuthToken: false };
}
- // OAuth: Bearer auth, Claude Code identity headers
if (isOAuthToken(apiKey)) {
const client = new Anthropic({
apiKey: null,
@@ -933,7 +925,6 @@ function createClient(
return { client, isOAuthToken: true };
}
- // API key auth
const client = new Anthropic({
apiKey,
baseURL: model.baseUrl,
@@ -1028,7 +1019,6 @@ function buildParams(
: { effort: options.effort };
}
} else {
- // Budget-based thinking for older models
params.thinking = {
type: "enabled",
budget_tokens: options.thinkingBudgetTokens || 1024,
@@ -1071,7 +1061,6 @@ function convertMessages(
): MessageParam[] {
const params: MessageParam[] = [];
- // Transform messages for cross-provider compatibility
const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
for (let i = 0; i < transformedMessages.length; i++) {
@@ -1168,7 +1157,6 @@ function convertMessages(
// Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint
const toolResults: ContentBlockParam[] = [];
- // Add the current tool result
toolResults.push({
type: "tool_result",
tool_use_id: msg.toolCallId,
@@ -1176,7 +1164,6 @@ function convertMessages(
is_error: msg.isError,
});
- // Look ahead for consecutive toolResult messages
let j = i + 1;
while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
const nextMsg = transformedMessages[j] as ToolResultMessage; // We know it's a toolResult
@@ -1189,10 +1176,8 @@ function convertMessages(
j++;
}
- // Skip the messages we've already processed
i = j - 1;
- // Add a single user message with all tool results
params.push({
role: "user",
content: toolResults,
diff --git a/packages/ai/src/providers/azure-openai-responses.ts b/packages/ai/src/providers/azure-openai-responses.ts
index 6265a72301..6e869afc44 100644
--- a/packages/ai/src/providers/azure-openai-responses.ts
+++ b/packages/ai/src/providers/azure-openai-responses.ts
@@ -45,7 +45,6 @@ function resolveDeploymentName(model: Model<"azure-openai-responses">, options?:
return mappedDeployment || model.id;
}
-// Azure OpenAI Responses-specific options
export interface AzureOpenAIResponsesOptions extends StreamOptions {
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
reasoningSummary?: "auto" | "detailed" | "concise" | null;
@@ -55,9 +54,6 @@ export interface AzureOpenAIResponsesOptions extends StreamOptions {
azureDeploymentName?: string;
}
-/**
- * Generate function for Azure OpenAI Responses API
- */
export const streamAzureOpenAIResponses: StreamFunction<"azure-openai-responses", AzureOpenAIResponsesOptions> = (
model: Model<"azure-openai-responses">,
context: Context,
@@ -65,7 +61,6 @@ export const streamAzureOpenAIResponses: StreamFunction<"azure-openai-responses"
): AssistantMessageEventStream => {
const stream = new AssistantMessageEventStream();
- // Start async processing
(async () => {
const deploymentName = resolveDeploymentName(model, options);
@@ -88,7 +83,6 @@ export const streamAzureOpenAIResponses: StreamFunction<"azure-openai-responses"
};
try {
- // Create Azure OpenAI client
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
const client = createClient(model, apiKey, options);
let params = buildParams(model, context, options, deploymentName);
diff --git a/packages/ai/src/providers/cloudflare.ts b/packages/ai/src/providers/cloudflare.ts
index 8e9d44cbae..01afdba2cb 100644
--- a/packages/ai/src/providers/cloudflare.ts
+++ b/packages/ai/src/providers/cloudflare.ts
@@ -1,6 +1,5 @@
import type { Api, Model } from "../types.js";
-/** Workers AI direct endpoint. */
export const CLOUDFLARE_WORKERS_AI_BASE_URL =
"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT_ID}/ai/v1";
@@ -8,11 +7,9 @@ export const CLOUDFLARE_WORKERS_AI_BASE_URL =
export const CLOUDFLARE_AI_GATEWAY_COMPAT_BASE_URL =
"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/compat";
-/** AI Gateway → OpenAI passthrough. Used until /compat supports /v1/responses. */
export const CLOUDFLARE_AI_GATEWAY_OPENAI_BASE_URL =
"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/openai";
-/** AI Gateway → Anthropic passthrough. */
export const CLOUDFLARE_AI_GATEWAY_ANTHROPIC_BASE_URL =
"https://gateway.ai.cloudflare.com/v1/{CLOUDFLARE_ACCOUNT_ID}/{CLOUDFLARE_GATEWAY_ID}/anthropic";
diff --git a/packages/ai/src/providers/github-copilot-headers.ts b/packages/ai/src/providers/github-copilot-headers.ts
index 4f01a9d2ac..812b8fcd03 100644
--- a/packages/ai/src/providers/github-copilot-headers.ts
+++ b/packages/ai/src/providers/github-copilot-headers.ts
@@ -1,13 +1,10 @@
import type { Message } from "../types.js";
-// Copilot expects X-Initiator to indicate whether the request is user-initiated
-// or agent-initiated (e.g. follow-up after assistant/tool messages).
export function inferCopilotInitiator(messages: Message[]): "user" | "agent" {
const last = messages[messages.length - 1];
return last && last.role !== "user" ? "agent" : "user";
}
-// Copilot requires Copilot-Vision-Request header when sending images
export function hasCopilotVisionInput(messages: Message[]): boolean {
return messages.some((msg) => {
if (msg.role === "user" && Array.isArray(msg.content)) {
diff --git a/packages/ai/src/providers/google-shared.ts b/packages/ai/src/providers/google-shared.ts
index e9d05e37a7..aa1e4e41e1 100644
--- a/packages/ai/src/providers/google-shared.ts
+++ b/packages/ai/src/providers/google-shared.ts
@@ -1,6 +1,4 @@
-/**
- * Shared utilities for Google Generative AI and Google Vertex providers.
- */
+/** Shared utilities for Google Generative AI and Vertex providers. */
import { type Content, FinishReason, FunctionCallingConfigMode, type Part } from "@google/genai";
import type { Context, ImageContent, Model, StopReason, TextContent, ThinkingBudgets, Tool } from "../types.js";
@@ -9,10 +7,7 @@ import { transformMessages } from "./transform-messages.js";
type GoogleApiType = "google-generative-ai" | "google-vertex";
-/**
- * Thinking level for Gemini 3 models.
- * Mirrors Google's ThinkingLevel enum values.
- */
+/** Thinking level values accepted by Gemini 3 models. */
export type GoogleThinkingLevel = "THINKING_LEVEL_UNSPECIFIED" | "MINIMAL" | "LOW" | "MEDIUM" | "HIGH";
type GoogleBudgetThinkingLevel = "minimal" | "low" | "medium" | "high";
@@ -83,16 +78,12 @@ function isValidThoughtSignature(signature: string | undefined): boolean {
return base64SignaturePattern.test(signature);
}
-/**
- * Only keep signatures from the same provider/model and with valid base64.
- */
+/** Retains a thought signature only for the originating provider/model and when it is valid base64. */
function resolveThoughtSignature(isSameProviderAndModel: boolean, signature: string | undefined): string | undefined {
return isSameProviderAndModel && isValidThoughtSignature(signature) ? signature : undefined;
}
-/**
- * Models via Google APIs that require explicit tool call IDs in function calls/responses.
- */
+/** Whether this Google API model requires tool-call IDs on function calls and responses. */
export function requiresToolCallId(modelId: string): boolean {
return modelId.startsWith("claude-") || modelId.startsWith("gpt-oss-");
}
@@ -111,9 +102,7 @@ function supportsMultimodalFunctionResponse(modelId: string): boolean {
return true;
}
-/**
- * Convert internal messages to Gemini Content[] format.
- */
+/** Converts internal context to Google `Content[]`, preserving replayable signatures only when protocol-valid. */
export function convertMessages<T extends GoogleApiType>(model: Model<T>, context: Context): Content[] {
const contents: Content[] = [];
const normalizeToolCallId = (id: string): string => {
@@ -151,12 +140,10 @@ export function convertMessages<T extends GoogleApiType>(model: Model<T>, contex
}
} else if (msg.role === "assistant") {
const parts: Part[] = [];
- // Check if message is from same provider and model - only then keep thinking blocks
const isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id;
for (const block of msg.content) {
if (block.type === "text") {
- // Skip empty text blocks
if (!block.text || block.text.trim() === "") continue;
const thoughtSignature = resolveThoughtSignature(isSameProviderAndModel, block.textSignature);
parts.push({
@@ -164,7 +151,6 @@ export function convertMessages<T extends GoogleApiType>(model: Model<T>, contex
...(thoughtSignature && { thoughtSignature }),
});
} else if (block.type === "thinking") {
- // Skip empty thinking blocks
if (!block.thinking || block.thinking.trim() === "") continue;
// Only keep as thinking block if same provider AND same model
// Otherwise convert to plain text (no tags to avoid model mimicking them)
@@ -200,7 +186,6 @@ export function convertMessages<T extends GoogleApiType>(model: Model<T>, contex
parts,
});
} else if (msg.role === "toolResult") {
- // Extract text and image content
const textContent = msg.content.filter((c): c is TextContent => c.type === "text");
const textResult = textContent.map((c) => c.text).join("\n");
const imageContent = model.input.includes("image")
@@ -271,9 +256,6 @@ const JSON_SCHEMA_META_DECLARATIONS = new Set([
"definitions", // pre-draft-2019-09 equivalent of $defs
]);
-/**
- * Strip meta-declarations from a schema obj
- */
function sanitizeForOpenApi(schema: unknown): unknown {
if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
return schema;
@@ -313,9 +295,7 @@ export function convertTools(
];
}
-/**
- * Map tool choice string to Gemini FunctionCallingConfigMode.
- */
+/** Converts the generic tool-choice mode to Google's function-calling mode. */
export function mapToolChoice(choice: string): FunctionCallingConfigMode {
switch (choice) {
case "auto":
@@ -329,9 +309,7 @@ export function mapToolChoice(choice: string): FunctionCallingConfigMode {
}
}
-/**
- * Map Gemini FinishReason to our StopReason.
- */
+/** Converts Google finish reasons to the shared stop-reason protocol. */
export function mapStopReason(reason: FinishReason): StopReason {
switch (reason) {
case FinishReason.STOP:
@@ -360,17 +338,3 @@ export function mapStopReason(reason: FinishReason): StopReason {
}
}
}
-
-/**
- * Map string finish reason to our StopReason (for raw API responses).
- */
-export function mapStopReasonString(reason: string): StopReason {
- switch (reason) {
- case "STOP":
- return "stop";
- case "MAX_TOKENS":
- return "length";
- default:
- return "error";
- }
-}
diff --git a/packages/ai/src/providers/google-vertex.ts b/packages/ai/src/providers/google-vertex.ts
index d48a8f4580..b6291d68b3 100644
--- a/packages/ai/src/providers/google-vertex.ts
+++ b/packages/ai/src/providers/google-vertex.ts
@@ -62,7 +62,6 @@ const THINKING_LEVEL_MAP: Record<GoogleThinkingLevel, ThinkingLevel> = {
HIGH: ThinkingLevel.HIGH,
};
-// Counter for generating unique tool call IDs
let toolCallCounter = 0;
export const streamGoogleVertex: StreamFunction<"google-vertex", GoogleVertexOptions> = (
@@ -93,7 +92,6 @@ export const streamGoogleVertex: StreamFunction<"google-vertex", GoogleVertexOpt
try {
const apiKey = resolveApiKey(options);
- // Create the client using either a Vertex API key, if provided, or ADC with project and location
const client = apiKey
? createClientWithApiKey(model, apiKey, options?.headers)
: createClient(model, resolveProject(options), resolveLocation(options), options?.headers);
diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts
index f43c54f23b..4a9c0a73c9 100644
--- a/packages/ai/src/providers/google.ts
+++ b/packages/ai/src/providers/google.ts
@@ -47,7 +47,6 @@ export interface GoogleOptions extends StreamOptions {
};
}
-// Counter for generating unique tool call IDs
let toolCallCounter = 0;
export const streamGoogle: StreamFunction<"google-generative-ai", GoogleOptions> = (
@@ -178,7 +177,6 @@ export const streamGoogle: StreamFunction<"google-generative-ai", GoogleOptions>
currentBlock = null;
}
- // Generate unique ID if not provided or if it's a duplicate
const providedId = part.functionCall.id;
const needsNewId =
!providedId || output.content.some((b) => b.type === "toolCall" && b.id === providedId);
diff --git a/packages/ai/src/providers/mistral.ts b/packages/ai/src/providers/mistral.ts
index f153e36403..fad46e2544 100644
--- a/packages/ai/src/providers/mistral.ts
+++ b/packages/ai/src/providers/mistral.ts
@@ -33,20 +33,17 @@ import { transformMessages } from "./transform-messages.js";
const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
const MAX_MISTRAL_ERROR_BODY_CHARS = 4000;
-/**
- * Provider-specific options for the Mistral API.
- */
+/** Mistral reasoning-effort values. */
type MistralReasoningEffort = "none" | "high";
+/** Provider-specific request options for the Mistral API. */
export interface MistralOptions extends StreamOptions {
toolChoice?: "auto" | "none" | "any" | "required" | { type: "function"; function: { name: string } };
promptMode?: "reasoning";
reasoningEffort?: MistralReasoningEffort;
}
-/**
- * Stream responses from Mistral using `chat.stream`.
- */
+/** Streams Mistral chat completions through `chat.stream`. */
export const streamMistral: StreamFunction<"mistral-conversations", MistralOptions> = (
model: Model<"mistral-conversations">,
context: Context,
@@ -107,9 +104,7 @@ export const streamMistral: StreamFunction<"mistral-conversations", MistralOptio
return stream;
};
-/**
- * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.
- */
+/** Maps provider-agnostic `SimpleStreamOptions` to Mistral request options. */
export const streamSimpleMistral: StreamFunction<"mistral-conversations", SimpleStreamOptions> = (
model: Model<"mistral-conversations">,
context: Context,
diff --git a/packages/ai/src/providers/openai-codex-responses.ts b/packages/ai/src/providers/openai-codex-responses.ts
index 43c95d2690..01f0d77825 100644
--- a/packages/ai/src/providers/openai-codex-responses.ts
+++ b/packages/ai/src/providers/openai-codex-responses.ts
@@ -43,10 +43,6 @@ import { headersToRecord } from "../utils/headers.js";
import { convertResponsesMessages, convertResponsesTools, processResponsesStream } from "./openai-responses-shared.js";
import { buildBaseOptions } from "./simple-options.js";
-// ============================================================================
-// Configuration
-// ============================================================================
-
const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
const JWT_CLAIM_PATH = "https://api.openai.com/auth" as const;
const MAX_RETRIES = 3;
@@ -63,10 +59,6 @@ const CODEX_RESPONSE_STATUSES = new Set<CodexResponseStatus>([
"in_progress",
]);
-// ============================================================================
-// Types
-// ============================================================================
-
export interface OpenAICodexResponsesOptions extends StreamOptions {
reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
reasoningSummary?: "auto" | "concise" | "detailed" | "off" | "on" | null;
@@ -95,10 +87,6 @@ interface RequestBody {
[key: string]: unknown;
}
-// ============================================================================
-// Retry Helpers
-// ============================================================================
-
function isRetryableError(status: number, errorText: string): boolean {
if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
return true;
@@ -120,10 +108,6 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
});
}
-// ============================================================================
-// Main Stream Function
-// ============================================================================
-
export const streamOpenAICodexResponses: StreamFunction<"openai-codex-responses", OpenAICodexResponsesOptions> = (
model: Model<"openai-codex-responses">,
context: Context,
@@ -227,7 +211,6 @@ export const streamOpenAICodexResponses: StreamFunction<"openai-codex-responses"
}
}
- // Fetch with retry logic for rate limits and transient errors
let response: Response | undefined;
let lastError: Error | undefined;
@@ -259,7 +242,6 @@ export const streamOpenAICodexResponses: StreamFunction<"openai-codex-responses"
continue;
}
- // Parse error for friendly message on final attempt or non-retryable error
const fakeResponse = new Response(errorText, {
status: response.status,
statusText: response.statusText,
@@ -273,7 +255,6 @@ export const streamOpenAICodexResponses: StreamFunction<"openai-codex-responses"
}
}
lastError = error instanceof Error ? error : new Error(String(error));
- // Network errors are retryable
if (attempt < MAX_RETRIES && !lastError.message.includes("usage limit")) {
const delayMs = BASE_DELAY_MS * 2 ** attempt;
await sleep(delayMs, options?.signal);
@@ -335,10 +316,6 @@ export const streamSimpleOpenAICodexResponses: StreamFunction<"openai-codex-resp
} satisfies OpenAICodexResponsesOptions);
};
-// ============================================================================
-// Request Building
-// ============================================================================
-
function buildRequestBody(
model: Model<"openai-codex-responses">,
context: Context,
@@ -443,10 +420,6 @@ function resolveCodexWebSocketUrl(baseUrl?: string): string {
return url.toString();
}
-// ============================================================================
-// Response Processing
-// ============================================================================
-
async function processStream(
response: Response,
output: AssistantMessage,
@@ -528,10 +501,6 @@ function normalizeCodexStatus(status: unknown): CodexResponseStatus | undefined
return CODEX_RESPONSE_STATUSES.has(status as CodexResponseStatus) ? (status as CodexResponseStatus) : undefined;
}
-// ============================================================================
-// SSE Parsing
-// ============================================================================
-
async function* parseSSE(response: Response): AsyncGenerator<Record<string, unknown>> {
if (!response.body) return;
@@ -571,24 +540,19 @@ async function* parseSSE(response: Response): AsyncGenerator<Record<string, unkn
}
}
} finally {
- // Best-effort stream teardown: the reader may already be closed or errored.
try {
await reader.cancel();
} catch {
- // Already closed.
+ // The reader may already be closed.
}
try {
reader.releaseLock();
} catch {
- // Lock already released.
+ // The reader lock may already be released.
}
}
}
-// ============================================================================
-// WebSocket Parsing
-// ============================================================================
-
const OPENAI_BETA_RESPONSES_WEBSOCKETS = "responses_websockets=2026-02-06";
const SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;
@@ -1218,10 +1182,6 @@ async function processWebSocketStream(
}
}
-// ============================================================================
-// Error Handling
-// ============================================================================
-
async function parseErrorResponse(response: Response): Promise<{ message: string; friendlyMessage?: string }> {
const raw = await response.text();
let message = raw || response.statusText || "Request failed";
@@ -1251,10 +1211,6 @@ async function parseErrorResponse(response: Response): Promise<{ message: string
return { message, friendlyMessage };
}
-// ============================================================================
-// Auth & Headers
-// ============================================================================
-
function extractAccountId(token: string): string {
try {
const parts = token.split(".");
diff --git a/packages/ai/src/providers/openai-completions.ts b/packages/ai/src/providers/openai-completions.ts
index ecd16b4f7a..647009d59e 100644
--- a/packages/ai/src/providers/openai-completions.ts
+++ b/packages/ai/src/providers/openai-completions.ts
@@ -484,7 +484,6 @@ function createClient(
headers["x-session-affinity"] = sessionId;
}
- // Merge options headers last so they can override defaults
if (optionsHeaders) {
Object.assign(headers, optionsHeaders);
}
@@ -597,7 +596,6 @@ function buildParams(
: { enabled: false };
}
} else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
- // OpenAI-style reasoning_effort
(params as any).reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
} else if (options?.reasoningEnabled === false && model.reasoning && compat.supportsReasoningEffort) {
const offValue = model.thinkingLevelMap?.off;
@@ -606,12 +604,10 @@ function buildParams(
}
}
- // OpenRouter provider routing preferences
if (model.baseUrl.includes("openrouter.ai") && model.compat?.openRouterRouting) {
(params as any).provider = model.compat.openRouterRouting;
}
- // Vercel AI Gateway provider routing preferences
if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
const routing = model.compat.vercelGatewayRouting;
if (routing.only || routing.order) {
@@ -929,7 +925,6 @@ export function convertMessages(
for (; j < transformedMessages.length && transformedMessages[j].role === "toolResult"; j++) {
const toolMsg = transformedMessages[j] as ToolResultMessage;
- // Extract text and image content
const textResult = toolMsg.content
.filter(isTextContentBlock)
.map((block) => block.text)
@@ -938,7 +933,6 @@ export function convertMessages(
// Always send tool result with text (or placeholder if only images)
const hasText = textResult.length > 0;
- // Some providers require the 'name' field in tool results
const toolResultMsg: ChatCompletionToolMessageParam = {
role: "tool",
content: sanitizeSurrogates(hasText ? textResult : hasImages ? "(see attached image)" : ""),
diff --git a/packages/ai/src/providers/openai-responses-shared.ts b/packages/ai/src/providers/openai-responses-shared.ts
index 8a22f03ff4..ae312d9457 100644
--- a/packages/ai/src/providers/openai-responses-shared.ts
+++ b/packages/ai/src/providers/openai-responses-shared.ts
@@ -34,10 +34,6 @@ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
import { classifyStreamFailure, StreamFailureError } from "../utils/stream-failure.js";
import { transformMessages } from "./transform-messages.js";
-// =============================================================================
-// Utilities
-// =============================================================================
-
function encodeTextSignatureV1(id: string, phase?: TextSignatureV1["phase"]): string {
const payload: TextSignatureV1 = { v: 1, id };
if (phase) payload.phase = phase;
@@ -84,10 +80,6 @@ export interface ConvertResponsesToolsOptions {
strict?: boolean | null;
}
-// =============================================================================
-// Message conversion
-// =============================================================================
-
export function convertResponsesMessages<TApi extends Api>(
model: Model<TApi>,
context: Context,
@@ -262,10 +254,6 @@ export function convertResponsesMessages<TApi extends Api>(
return messages;
}
-// =============================================================================
-// Tool conversion
-// =============================================================================
-
export function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {
const strict = options?.strict === undefined ? false : options.strict;
return tools.map((tool) => ({
@@ -277,10 +265,6 @@ export function convertResponsesTools(tools: Tool[], options?: ConvertResponsesT
}));
}
-// =============================================================================
-// Stream processing
-// =============================================================================
-
export async function processResponsesStream<TApi extends Api>(
openaiStream: AsyncIterable<ResponseStreamEvent>,
output: AssistantMessage,
@@ -368,7 +352,6 @@ export async function processResponsesStream<TApi extends Api>(
} else if (event.type === "response.content_part.added") {
if (currentItem?.type === "message") {
currentItem.content = currentItem.content || [];
- // Filter out ReasoningText, only accept output_text and refusal
if (event.part.type === "output_text" || event.part.type === "refusal") {
currentItem.content.push(event.part);
}
@@ -510,7 +493,6 @@ export async function processResponsesStream<TApi extends Api>(
: (response?.service_tier ?? options.serviceTier);
options.applyServiceTierPricing(output.usage, serviceTier);
}
- // Map status to stop reason
output.stopReason = mapStopReason(response?.status);
if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
output.stopReason = "toolUse";
@@ -550,7 +532,6 @@ function mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): Sto
case "failed":
case "cancelled":
return "error";
- // These two are wonky ...
case "in_progress":
case "queued":
return "stop";
diff --git a/packages/ai/src/providers/openai-responses.ts b/packages/ai/src/providers/openai-responses.ts
index d152f7d3c2..e0a4f72284 100644
--- a/packages/ai/src/providers/openai-responses.ts
+++ b/packages/ai/src/providers/openai-responses.ts
@@ -56,16 +56,12 @@ function getPromptCacheRetention(
return cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : undefined;
}
-// OpenAI Responses-specific options
export interface OpenAIResponsesOptions extends StreamOptions {
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
reasoningSummary?: "auto" | "detailed" | "concise" | null;
serviceTier?: ResponseCreateParamsStreaming["service_tier"];
}
-/**
- * Generate function for OpenAI Responses API
- */
export const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIResponsesOptions> = (
model: Model<"openai-responses">,
context: Context,
@@ -73,7 +69,6 @@ export const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIRes
): AssistantMessageEventStream => {
const stream = new AssistantMessageEventStream();
- // Start async processing
(async () => {
const output: AssistantMessage = {
role: "assistant",
@@ -94,7 +89,6 @@ export const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIRes
};
try {
- // Create OpenAI client
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
@@ -200,7 +194,6 @@ function createClient(
headers["x-client-request-id"] = sessionId;
}
- // Merge options headers last so they can override defaults
if (optionsHeaders) {
Object.assign(headers, optionsHeaders);
}
diff --git a/packages/ai/src/providers/simple-options.ts b/packages/ai/src/providers/simple-options.ts
index 6dced0f032..76f6ea8b44 100644
--- a/packages/ai/src/providers/simple-options.ts
+++ b/packages/ai/src/providers/simple-options.ts
@@ -21,7 +21,6 @@ export function buildBaseOptions(model: Model<Api>, options?: SimpleStreamOption
}
export function clampReasoning(effort: ThinkingLevel | undefined): Exclude<ThinkingLevel, "xhigh" | "max"> | undefined {
- // Token-budget providers have no distinct xhigh/max budget tier; clamp both to high.
return effort === "xhigh" || effort === "max" ? "high" : effort;
}
diff --git a/packages/ai/src/providers/transform-messages.ts b/packages/ai/src/providers/transform-messages.ts
index 8fde3716d1..cc3c74e5b0 100644
--- a/packages/ai/src/providers/transform-messages.ts
+++ b/packages/ai/src/providers/transform-messages.ts
@@ -66,18 +66,14 @@ export function transformMessages<TApi extends Api>(
model: Model<TApi>,
normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,
): Message[] {
- // Build a map of original tool call IDs to normalized IDs
const toolCallIdMap = new Map<string, string>();
const imageAwareMessages = downgradeUnsupportedImages(messages, model);
- // First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)
const transformed = imageAwareMessages.map((msg) => {
- // User messages pass through unchanged
if (msg.role === "user") {
return msg;
}
- // Handle toolResult messages - normalize toolCallId if we have a mapping
if (msg.role === "toolResult") {
const normalizedId = toolCallIdMap.get(msg.toolCallId);
if (normalizedId && normalizedId !== msg.toolCallId) {
@@ -86,7 +82,6 @@ export function transformMessages<TApi extends Api>(
return msg;
}
- // Assistant messages need transformation check
if (msg.role === "assistant") {
const assistantMsg = msg as AssistantMessage;
const isSameModel =
@@ -152,7 +147,6 @@ export function transformMessages<TApi extends Api>(
return msg;
});
- // Second pass: insert synthetic empty tool results for orphaned tool calls
// This preserves thinking signatures and satisfies API requirements
const result: Message[] = [];
let pendingToolCalls: ToolCall[] = [];
@@ -180,7 +174,6 @@ export function transformMessages<TApi extends Api>(
const msg = transformed[i];
if (msg.role === "assistant") {
- // If we have pending orphaned tool calls from a previous assistant, insert synthetic results now
insertSyntheticToolResults();
// Skip errored/aborted assistant messages entirely.
@@ -193,7 +186,6 @@ export function transformMessages<TApi extends Api>(
continue;
}
- // Track tool calls from this assistant message
const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall") as ToolCall[];
if (toolCalls.length > 0) {
pendingToolCalls = toolCalls;
@@ -205,7 +197,6 @@ export function transformMessages<TApi extends Api>(
existingToolResultIds.add(msg.toolCallId);
result.push(msg);
} else if (msg.role === "user") {
- // User message interrupts tool flow - insert synthetic results for orphaned calls
insertSyntheticToolResults();
result.push(msg);
} else {
@@ -213,7 +204,6 @@ export function transformMessages<TApi extends Api>(
}
}
- // If the conversation ends with unresolved tool calls, synthesize results now.
insertSyntheticToolResults();
return result;
diff --git a/packages/ai/src/utils/event-stream.ts b/packages/ai/src/utils/event-stream.ts
index f4a7ceba8d..79dbbf2009 100644
--- a/packages/ai/src/utils/event-stream.ts
+++ b/packages/ai/src/utils/event-stream.ts
@@ -1,6 +1,5 @@
import type { AssistantMessage, AssistantMessageEvent } from "../types.js";
-// Generic event stream class for async iteration
export class EventStream<T, R = T> implements AsyncIterable<T> {
private queue: T[] = [];
private waiting: ((value: IteratorResult<T>) => void)[] = [];
@@ -25,7 +24,6 @@ export class EventStream<T, R = T> implements AsyncIterable<T> {
this.resolveFinalResult(this.extractResult(event));
}
- // Deliver to waiting consumer or queue it
const waiter = this.waiting.shift();
if (waiter) {
waiter({ value: event, done: false });
@@ -39,7 +37,6 @@ export class EventStream<T, R = T> implements AsyncIterable<T> {
if (result !== undefined) {
this.resolveFinalResult(result);
}
- // Notify all waiting consumers that we're done
while (this.waiting.length > 0) {
const waiter = this.waiting.shift()!;
waiter({ value: undefined as any, done: true });
diff --git a/packages/ai/src/utils/hash.ts b/packages/ai/src/utils/hash.ts
index 1ff55e8b41..8c6570c4e6 100644
--- a/packages/ai/src/utils/hash.ts
+++ b/packages/ai/src/utils/hash.ts
@@ -1,4 +1,3 @@
-/** Fast deterministic hash to shorten long strings */
export function shortHash(str: string): string {
let h1 = 0xdeadbeef;
let h2 = 0x41c6ce57;
diff --git a/packages/ai/src/utils/oauth/github-copilot.ts b/packages/ai/src/utils/oauth/github-copilot.ts
index dcacb43d2a..67263b8420 100644
--- a/packages/ai/src/utils/oauth/github-copilot.ts
+++ b/packages/ai/src/utils/oauth/github-copilot.ts
@@ -1,7 +1,3 @@
-/**
- * GitHub Copilot OAuth flow
- */
-
import { getModels } from "../../models.js";
import type { Api, Model } from "../../types.js";
import type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from "./types.js";
@@ -75,18 +71,15 @@ function getBaseUrlFromToken(token: string): string | null {
const match = token.match(/proxy-ep=([^;]+)/);
if (!match) return null;
const proxyHost = match[1];
- // Convert proxy.xxx to api.xxx
const apiHost = proxyHost.replace(/^proxy\./, "api.");
return `https://${apiHost}`;
}
export function getGitHubCopilotBaseUrl(token?: string, enterpriseDomain?: string): string {
- // If we have a token, extract the base URL from proxy-ep
if (token) {
const urlFromToken = getBaseUrlFromToken(token);
if (urlFromToken) return urlFromToken;
}
- // Fallback for enterprise or if token parsing fails
if (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;
return "https://api.individual.githubcopilot.com";
}
@@ -144,9 +137,6 @@ async function startDeviceFlow(domain: string): Promise<DeviceCodeResponse> {
};
}
-/**
- * Sleep that can be interrupted by an AbortSignal
- */
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
@@ -235,9 +225,6 @@ async function pollForGitHubAccessToken(
throw new Error("Device flow timed out");
}
-/**
- * Refresh GitHub Copilot token
- */
export async function refreshGitHubCopilotToken(
refreshToken: string,
enterpriseDomain?: string,
@@ -359,7 +346,6 @@ export async function loginGitHubCopilot(options: {
);
const credentials = await refreshGitHubCopilotToken(githubAccessToken, enterpriseDomain ?? undefined);
- // Enable all models after successful login
options.onProgress?.("Enabling models...");
await enableAllGitHubCopilotModels(credentials.access, enterpriseDomain ?? undefined);
return credentials;
diff --git a/packages/ai/src/utils/oauth/index.ts b/packages/ai/src/utils/oauth/index.ts
index f5f180bf04..6c0b356ed3 100644
--- a/packages/ai/src/utils/oauth/index.ts
+++ b/packages/ai/src/utils/oauth/index.ts
@@ -7,9 +7,7 @@
* - GitHub Copilot
*/
-// Anthropic
export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
-// GitHub Copilot
export {
getGitHubCopilotBaseUrl,
githubCopilotOAuthProvider,
@@ -17,15 +15,10 @@ export {
normalizeDomain,
refreshGitHubCopilotToken,
} from "./github-copilot.js";
-// OpenAI Codex (ChatGPT OAuth)
export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
export * from "./types.js";
-// ============================================================================
-// Provider Registry
-// ============================================================================
-
import { anthropicOAuthProvider } from "./anthropic.js";
import { githubCopilotOAuthProvider } from "./github-copilot.js";
import { openaiCodexOAuthProvider } from "./openai-codex.js";
@@ -41,16 +34,10 @@ const oauthProviderRegistry = new Map<string, OAuthProviderInterface>(
BUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]),
);
-/**
- * Get an OAuth provider by ID
- */
export function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {
return oauthProviderRegistry.get(id);
}
-/**
- * Register a custom OAuth provider
- */
export function registerOAuthProvider(provider: OAuthProviderInterface): void {
oauthProviderRegistry.set(provider.id, provider);
}
@@ -70,9 +57,6 @@ export function unregisterOAuthProvider(id: string): void {
oauthProviderRegistry.delete(id);
}
-/**
- * Reset OAuth providers to built-ins.
- */
export function resetOAuthProviders(): void {
oauthProviderRegistry.clear();
for (const provider of BUILT_IN_OAUTH_PROVIDERS) {
@@ -80,9 +64,6 @@ export function resetOAuthProviders(): void {
}
}
-/**
- * Get all registered OAuth providers
- */
export function getOAuthProviders(): OAuthProviderInterface[] {
return Array.from(oauthProviderRegistry.values());
}
@@ -98,10 +79,6 @@ export function getOAuthProviderInfoList(): OAuthProviderInfo[] {
}));
}
-// ============================================================================
-// High-level API (uses provider registry)
-// ============================================================================
-
/**
* Refresh token for any OAuth provider.
* @deprecated Use getOAuthProvider(id).refreshToken() instead
@@ -138,7 +115,6 @@ export async function getOAuthApiKey(
return null;
}
- // Refresh if expired
if (Date.now() >= creds.expires) {
try {
creds = await provider.refreshToken(creds);
diff --git a/packages/ai/src/utils/oauth/pkce.ts b/packages/ai/src/utils/oauth/pkce.ts
index bf7ac7d587..f59c6fcb0a 100644
--- a/packages/ai/src/utils/oauth/pkce.ts
+++ b/packages/ai/src/utils/oauth/pkce.ts
@@ -3,9 +3,6 @@
* Works in both Node.js 20+ and browsers.
*/
-/**
- * Encode bytes as base64url string.
- */
function base64urlEncode(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) {
@@ -19,12 +16,10 @@ function base64urlEncode(bytes: Uint8Array): string {
* Uses Web Crypto API for cross-platform compatibility.
*/
export async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
- // Generate random verifier
const verifierBytes = new Uint8Array(32);
crypto.getRandomValues(verifierBytes);
const verifier = base64urlEncode(verifierBytes);
- // Compute SHA-256 challenge
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
diff --git a/packages/ai/src/utils/overflow.ts b/packages/ai/src/utils/overflow.ts
index b06a3fd17b..648f2343ed 100644
--- a/packages/ai/src/utils/overflow.ts
+++ b/packages/ai/src/utils/overflow.ts
@@ -115,7 +115,6 @@ const NON_OVERFLOW_PATTERNS = [
* @returns true if the message indicates a context overflow
*/
export function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean {
- // Case 1: Check error message patterns
if (message.stopReason === "error" && message.errorMessage) {
// Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit)
const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!));
@@ -124,7 +123,6 @@ export function isContextOverflow(message: AssistantMessage, contextWindow?: num
}
}
- // Case 2: Silent overflow (z.ai style) - successful but usage exceeds context
if (contextWindow && message.stopReason === "stop") {
const inputTokens = message.usage.input + message.usage.cacheRead;
if (inputTokens > contextWindow) {
diff --git a/packages/ai/test/abort.test.ts b/packages/ai/test/abort.test.ts
index 0973e3a192..c6ac1fb96f 100644
--- a/packages/ai/test/abort.test.ts
+++ b/packages/ai/test/abort.test.ts
@@ -10,7 +10,6 @@ import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-u
import { hasBedrockCredentials } from "./bedrock-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const [openaiCodexToken] = await Promise.all([resolveApiKey("openai-codex")]);
async function testAbortSignal<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
@@ -41,7 +40,6 @@ async function testAbortSignal<TApi extends Api>(llm: Model<TApi>, options: Stre
}
const msg = await response.result();
- // If we get here without throwing, the abort didn't work
expect(msg.stopReason).toBe("aborted");
expect(msg.content.length).toBeGreaterThan(0);
@@ -71,7 +69,6 @@ async function testImmediateAbort<TApi extends Api>(llm: Model<TApi>, options: S
}
async function testAbortThenNewMessage<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // First request: abort immediately before any response content arrives
const controller = new AbortController();
controller.abort();
@@ -81,13 +78,10 @@ async function testAbortThenNewMessage<TApi extends Api>(llm: Model<TApi>, optio
const abortedResponse = await complete(llm, context, { ...options, signal: controller.signal });
expect(abortedResponse.stopReason).toBe("aborted");
- // The aborted message has empty content since we aborted before anything arrived
expect(abortedResponse.content.length).toBe(0);
- // Add the aborted assistant message to context (this is what happens in the real coding agent)
context.messages.push(abortedResponse);
- // Second request: send a new message - this should work even with the aborted message in context
context.messages.push({
role: "user",
content: "What is 2 + 2?",
diff --git a/packages/ai/test/anthropic-eager-tool-input-e2e.test.ts b/packages/ai/test/anthropic-eager-tool-input-e2e.test.ts
index 3fed7ce260..03da8be79a 100644
--- a/packages/ai/test/anthropic-eager-tool-input-e2e.test.ts
+++ b/packages/ai/test/anthropic-eager-tool-input-e2e.test.ts
@@ -51,8 +51,6 @@ function getProbePriority(model: Model<"anthropic-messages">): number {
const cost = model.cost.input + model.cost.output;
let priority = cost;
- // Prefer current Claude 4 Haiku routes when present: they are cheap and avoid
- // stale Claude 3.x aliases that can remain in catalogs after upstream removal.
if (modelId.includes("haiku") && (modelId.includes("4-5") || modelId.includes("4.5"))) {
priority -= 1000;
} else if (modelId.includes("sonnet") && (modelId.includes("4-") || modelId.includes("4."))) {
diff --git a/packages/ai/test/anthropic-tool-name-normalization.test.ts b/packages/ai/test/anthropic-tool-name-normalization.test.ts
index 1ea6bdb217..0a0b8ec943 100644
--- a/packages/ai/test/anthropic-tool-name-normalization.test.ts
+++ b/packages/ai/test/anthropic-tool-name-normalization.test.ts
@@ -7,28 +7,10 @@ import { resolveApiKey } from "./oauth.js";
const oauthToken = await resolveApiKey("anthropic");
-/**
- * Tests for Anthropic OAuth tool name normalization.
- *
- * When using Claude Code OAuth, tool names must match CC's canonical casing.
- * The normalization should:
- * 1. Convert tool names that match CC tools (case-insensitive) to CC casing on outbound
- * 2. Convert tool names back to the original casing on inbound
- *
- * This is a simple case-insensitive lookup, NOT a mapping of different names.
- * e.g., "todowrite" -> "TodoWrite" -> "todowrite" (round-trip works)
- *
- * The old `find -> Glob` mapping was WRONG because:
- * - Outbound: "find" -> "Glob"
- * - Inbound: "Glob" -> ??? (no tool named "glob" in context.tools, only "find")
- * - Result: tool call has name "Glob" but no tool exists with that name
- */
describe.skipIf(!oauthToken)("Anthropic OAuth tool name normalization", () => {
const model = getModel("anthropic", "claude-sonnet-4-6");
it("should normalize user-defined tool matching CC name (todowrite -> TodoWrite -> todowrite)", async () => {
- // User defines a tool named "todowrite" (lowercase)
- // CC has "TodoWrite" - this should round-trip correctly
const todoTool: Tool = {
name: "todowrite",
description: "Write a todo item",
@@ -64,12 +46,10 @@ describe.skipIf(!oauthToken)("Anthropic OAuth tool name normalization", () => {
const response = await s.result();
expect(response.stopReason, `Error: ${response.errorMessage}`).toBe("toolUse");
- // The tool call should come back with the ORIGINAL name "todowrite", not "TodoWrite"
expect(toolCallName).toBe("todowrite");
});
it("should handle pi's built-in tools (read, write, edit, bash)", async () => {
- // Pi's tools use lowercase names, CC uses PascalCase
const readTool: Tool = {
name: "read",
description: "Read a file",
@@ -105,14 +85,10 @@ describe.skipIf(!oauthToken)("Anthropic OAuth tool name normalization", () => {
const response = await s.result();
expect(response.stopReason, `Error: ${response.errorMessage}`).toBe("toolUse");
- // The tool call should come back with the ORIGINAL name "read", not "Read"
expect(toolCallName).toBe("read");
});
it("should NOT map find to Glob - find is not a CC tool name", async () => {
- // Pi has a "find" tool, CC has "Glob" - these are DIFFERENT tools
- // The old code incorrectly mapped find -> Glob, which broke the round-trip
- // because there's no tool named "glob" in context.tools
const findTool: Tool = {
name: "find",
description: "Find files by pattern",
@@ -148,22 +124,10 @@ describe.skipIf(!oauthToken)("Anthropic OAuth tool name normalization", () => {
const response = await s.result();
expect(response.stopReason, `Error: ${response.errorMessage}`).toBe("toolUse");
- // With the BROKEN find -> Glob mapping:
- // - Sent as "Glob" to Anthropic
- // - Received back as "Glob"
- // - fromClaudeCodeName("Glob", tools) looks for tool.name.toLowerCase() === "glob"
- // - No match (tool is named "find"), returns "Glob"
- // - Test fails: toolCallName is "Glob" instead of "find"
- //
- // With the CORRECT implementation (no find->Glob mapping):
- // - Sent as "find" to Anthropic (no CC tool named "Find")
- // - Received back as "find"
- // - Test passes: toolCallName is "find"
expect(toolCallName).toBe("find");
});
it("should handle custom tools that don't match any CC tool names", async () => {
- // A completely custom tool should pass through unchanged
const customTool: Tool = {
name: "my_custom_tool",
description: "A custom tool",
@@ -199,7 +163,6 @@ describe.skipIf(!oauthToken)("Anthropic OAuth tool name normalization", () => {
const response = await s.result();
expect(response.stopReason, `Error: ${response.errorMessage}`).toBe("toolUse");
- // Custom tool names should pass through unchanged
expect(toolCallName).toBe("my_custom_tool");
});
});
diff --git a/packages/ai/test/azure-utils.ts b/packages/ai/test/azure-utils.ts
index d83b198a63..2c668f06a6 100644
--- a/packages/ai/test/azure-utils.ts
+++ b/packages/ai/test/azure-utils.ts
@@ -1,7 +1,3 @@
-/**
- * Utility functions for Azure OpenAI tests
- */
-
function parseDeploymentNameMap(value: string | undefined): Map<string, string> {
const map = new Map<string, string>();
if (!value) return map;
diff --git a/packages/ai/test/bedrock-models.test.ts b/packages/ai/test/bedrock-models.test.ts
index 453a395375..da86e71d4c 100644
--- a/packages/ai/test/bedrock-models.test.ts
+++ b/packages/ai/test/bedrock-models.test.ts
@@ -1,21 +1,3 @@
-/**
- * A test suite to ensure all configured Amazon Bedrock models are usable.
- *
- * This is here to make sure we got correct model identifiers from models.dev and other sources.
- * Because Amazon Bedrock requires cross-region inference in some models,
- * plain model identifiers are not always usable and it requires tweaking of model identifiers to use cross-region inference.
- * See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html#inference-profiles-support-system for more details.
- *
- * This test suite is not enabled by default unless AWS credentials and `BEDROCK_EXTENSIVE_MODEL_TEST` environment variables are set.
- * This test suite takes ~2 minutes to run. Because not all models are available in all regions,
- * it's recommended to use `us-west-2` region for best coverage for running this test suite.
- *
- * You can run this test suite with:
- * ```bash
- * $ AWS_REGION=us-west-2 BEDROCK_EXTENSIVE_MODEL_TEST=1 AWS_PROFILE=... npm test -- ./test/bedrock-models.test.ts
- * ```
- */
-
import { describe, expect, it } from "vitest";
import { getModels } from "../src/models.js";
import { complete } from "../src/stream.js";
diff --git a/packages/ai/test/bedrock-thinking-payload.test.ts b/packages/ai/test/bedrock-thinking-payload.test.ts
index 0b2151f693..741b839c03 100644
--- a/packages/ai/test/bedrock-thinking-payload.test.ts
+++ b/packages/ai/test/bedrock-thinking-payload.test.ts
@@ -180,11 +180,9 @@ describe("Application inference profile support", () => {
if (event.type === "error") break;
}
- // System prompt should have a cache point
expect(capturedPayload.system).toHaveLength(2);
expect(capturedPayload.system[1]).toHaveProperty("cachePoint");
- // Last user message should have a cache point
const lastMsg = capturedPayload.messages[capturedPayload.messages.length - 1];
const lastContent = lastMsg.content[lastMsg.content.length - 1];
expect(lastContent).toHaveProperty("cachePoint");
diff --git a/packages/ai/test/bedrock-utils.ts b/packages/ai/test/bedrock-utils.ts
index 11ac93de72..4e0ecc6ef4 100644
--- a/packages/ai/test/bedrock-utils.ts
+++ b/packages/ai/test/bedrock-utils.ts
@@ -1,14 +1,3 @@
-/**
- * Utility functions for Amazon Bedrock tests
- */
-
-/**
- * Check if any valid AWS credentials are configured for Bedrock.
- * Returns true if any of the following are set:
- * - AWS_PROFILE (named profile from ~/.aws/credentials)
- * - AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY (IAM keys)
- * - AWS_BEARER_TOKEN_BEDROCK (Bedrock API key)
- */
export function hasBedrockCredentials(): boolean {
return !!(
process.env.AWS_PROFILE ||
diff --git a/packages/ai/test/cache-retention.test.ts b/packages/ai/test/cache-retention.test.ts
index 2f234ab081..554a14f39a 100644
--- a/packages/ai/test/cache-retention.test.ts
+++ b/packages/ai/test/cache-retention.test.ts
@@ -36,13 +36,10 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // Consume the stream to trigger the request
for await (const _ of s) {
- // Just consume
}
expect(capturedPayload).not.toBeNull();
- // System prompt should have cache_control without ttl
expect(capturedPayload.system).toBeDefined();
expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral" });
},
@@ -59,13 +56,10 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // Consume the stream to trigger the request
for await (const _ of s) {
- // Just consume
}
expect(capturedPayload).not.toBeNull();
- // System prompt should have cache_control with ttl: "1h"
expect(capturedPayload.system).toBeDefined();
expect(capturedPayload.system[0].cache_control).toEqual({ type: "ephemeral", ttl: "1h" });
});
@@ -73,7 +67,6 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
it("should add ttl for non-api.anthropic.com baseUrl by default", async () => {
process.env.PI_CACHE_RETENTION = "long";
- // Create a model with a different baseUrl (simulating a proxy)
const baseModel = getModel("anthropic", "claude-haiku-4-5");
const proxyModel = {
...baseModel,
@@ -82,12 +75,6 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
let capturedPayload: any = null;
- // We can't actually make the request (no proxy), but we can verify the payload
- // by using a mock or checking the logic directly
- // For this test, we'll import the helper directly
-
- // Since we can't easily test this without mocking, we'll skip the actual API call
- // and just verify the helper logic works correctly
const { streamAnthropic } = await import("../src/providers/anthropic.js");
try {
@@ -98,12 +85,11 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // This will fail since we're using a fake key and fake proxy, but the payload should be captured
for await (const event of s) {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -134,7 +120,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -160,7 +146,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -185,7 +171,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -214,7 +200,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -235,9 +221,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // Consume the stream to trigger the request
for await (const _ of s) {
- // Just consume
}
expect(capturedPayload).not.toBeNull();
@@ -258,9 +242,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // Consume the stream to trigger the request
for await (const _ of s) {
- // Just consume
}
expect(capturedPayload).not.toBeNull();
@@ -271,7 +253,6 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
it("should set prompt_cache_retention for non-api.openai.com baseUrl by default", async () => {
process.env.PI_CACHE_RETENTION = "long";
- // Create a model with a different baseUrl (simulating a proxy)
const baseModel = getModel("openai", "gpt-4o-mini");
const proxyModel = {
...baseModel,
@@ -290,12 +271,11 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
},
});
- // This will fail since we're using a fake key and fake proxy, but the payload should be captured
for await (const event of s) {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -325,7 +305,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -352,7 +332,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -380,7 +360,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -424,7 +404,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
@@ -450,7 +430,7 @@ describe("Cache Retention (PI_CACHE_RETENTION)", () => {
if (event.type === "error") break;
}
} catch {
- // Expected to fail
+ // The fake proxy request fails after the payload capture used by this assertion.
}
expect(capturedPayload).not.toBeNull();
diff --git a/packages/ai/test/codex-websocket-cached-probe.ts b/packages/ai/test/codex-websocket-cached-probe.ts
index ccc875f854..9bab146687 100644
--- a/packages/ai/test/codex-websocket-cached-probe.ts
+++ b/packages/ai/test/codex-websocket-cached-probe.ts
@@ -1,10 +1,4 @@
#!/usr/bin/env tsx
-/**
- * Live probe for OpenAI Codex Responses websocket-cached mode.
- *
- * Runs a simple tool loop directly against the pi-ai provider source so it does not
- * depend on built dist packages or coding-agent SDK wiring.
- */
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
diff --git a/packages/ai/test/context-overflow.test.ts b/packages/ai/test/context-overflow.test.ts
index 7adea16643..63d185ef71 100644
--- a/packages/ai/test/context-overflow.test.ts
+++ b/packages/ai/test/context-overflow.test.ts
@@ -1,16 +1,3 @@
-/**
- * Test context overflow error handling across providers.
- *
- * Context overflow occurs when the input (prompt + history) exceeds
- * the model's context window. This is different from output token limits.
- *
- * Expected behavior: All providers should return stopReason: "error"
- * with an errorMessage that indicates the context was too large,
- * OR (for z.ai) return successfully with usage.input > contextWindow.
- *
- * The isContextOverflow() function must return true for all providers.
- */
-
import type { ChildProcess } from "child_process";
import { execSync, spawn } from "child_process";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
@@ -24,15 +11,11 @@ import { getKimiCodingTestModel } from "./kimi-test-model.js";
import { resolveApiKey } from "./oauth.js";
import { getZaiTestModel } from "./zai-test-model.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([resolveApiKey("github-copilot"), resolveApiKey("openai-codex")]);
const [githubCopilotToken, openaiCodexToken] = oauthTokens;
-// Lorem ipsum paragraph for realistic token estimation
const LOREM_IPSUM = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. `;
-// Generate a string that will exceed the context window
-// Using chars/4 as token estimate (works better with varied text than repeated chars)
function generateOverflowContent(contextWindow: number): string {
const targetTokens = contextWindow + 10000; // Exceed by 10k tokens
const targetChars = targetTokens * 4 * 1.5;
@@ -90,11 +73,6 @@ function logResult(result: OverflowResult) {
console.log(` hasUsageData: ${result.hasUsageData}`);
}
-// =============================================================================
-// Anthropic
-// Expected pattern: "prompt is too long: X tokens > Y maximum"
-// =============================================================================
-
describe("Context overflow error handling", () => {
describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic (API Key)", () => {
it("claude-haiku-4-5 - should detect overflow via isContextOverflow", async () => {
@@ -120,13 +98,7 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // GitHub Copilot (OAuth)
- // Tests both OpenAI and Anthropic models via Copilot
- // =============================================================================
-
describe("GitHub Copilot (OAuth)", () => {
- // OpenAI model via Copilot
it.skipIf(!githubCopilotToken)(
"gpt-5-mini - should detect overflow via isContextOverflow",
async () => {
@@ -141,7 +113,6 @@ describe("Context overflow error handling", () => {
120000,
);
- // Anthropic model via Copilot
it.skipIf(!githubCopilotToken)(
"claude-sonnet-4 - should detect overflow via isContextOverflow",
async () => {
@@ -157,11 +128,6 @@ describe("Context overflow error handling", () => {
);
});
- // =============================================================================
- // OpenAI
- // Expected pattern: "exceeds the context window"
- // =============================================================================
-
describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions", () => {
it("gpt-4o-mini - should detect overflow via isContextOverflow", async () => {
const model = { ...getModel("openai", "gpt-4o-mini") };
@@ -199,11 +165,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Google
- // Expected pattern: "input token count (X) exceeds the maximum"
- // =============================================================================
-
describe.skipIf(!process.env.GEMINI_API_KEY)("Google", () => {
it("gemini-2.5-flash - should detect overflow via isContextOverflow", async () => {
const model = getModel("google", "gemini-2.5-flash");
@@ -216,18 +177,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Uses same API as Google, expects same error pattern
- // =============================================================================
-
- // =============================================================================
- // =============================================================================
-
- // =============================================================================
- // OpenAI Codex (OAuth)
- // Uses ChatGPT Plus/Pro subscription via OAuth
- // =============================================================================
-
describe("OpenAI Codex (OAuth)", () => {
it.skipIf(!openaiCodexToken)(
"gpt-5.2-codex - should detect overflow via isContextOverflow",
@@ -243,11 +192,6 @@ describe("Context overflow error handling", () => {
);
});
- // =============================================================================
- // Amazon Bedrock
- // Expected pattern: "Input is too long for requested model"
- // =============================================================================
-
describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock", () => {
it("claude-sonnet-4-5 - should detect overflow via isContextOverflow", async () => {
const model = getModel("amazon-bedrock", "global.anthropic.claude-sonnet-4-5-20250929-v1:0");
@@ -259,11 +203,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // xAI
- // Expected pattern: "maximum prompt length is X but the request contains Y"
- // =============================================================================
-
describe.skipIf(!process.env.XAI_API_KEY)("xAI", () => {
it("grok-4.3 - should detect overflow via isContextOverflow", async () => {
const model = getModel("xai", "grok-4.3");
@@ -276,11 +215,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Groq
- // Expected pattern: "reduce the length of the messages"
- // =============================================================================
-
describe.skipIf(!process.env.GROQ_API_KEY)("Groq", () => {
it("llama-3.3-70b-versatile - should detect overflow via isContextOverflow", async () => {
const model = getModel("groq", "llama-3.3-70b-versatile");
@@ -293,11 +227,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Cerebras
- // Expected: 400/413 status code with no body
- // =============================================================================
-
describe.skipIf(!process.env.CEREBRAS_API_KEY)("Cerebras", () => {
it("gpt-oss-120b - should detect overflow via isContextOverflow", async () => {
const model = getModel("cerebras", "gpt-oss-120b");
@@ -305,17 +234,11 @@ describe("Context overflow error handling", () => {
logResult(result);
expect(result.stopReason).toBe("error");
- // Cerebras returns status code with no body (400, 413, or 429 for token rate limit)
expect(result.errorMessage).toMatch(/4(00|13|29).*\(no body\)/i);
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}, 120000);
});
- // =============================================================================
- // Hugging Face
- // Uses OpenAI-compatible Inference Router
- // =============================================================================
-
describe.skipIf(!process.env.HF_TOKEN)("Hugging Face", () => {
it("Kimi-K2.5 - should detect overflow via isContextOverflow", async () => {
const model = getModel("huggingface", "moonshotai/Kimi-K2.5");
@@ -327,22 +250,12 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // z.ai
- // Special case: may return explicit overflow error text, may accept overflow silently,
- // or may rate limit instead
- // =============================================================================
-
describe.skipIf(!process.env.ZAI_API_KEY)("z.ai", () => {
it("should detect overflow via isContextOverflow when z.ai reports it", async () => {
const model = getZaiTestModel({ smallestContextWindow: true });
const result = await testContextOverflow(model, process.env.ZAI_API_KEY!);
logResult(result);
- // z.ai behavior is inconsistent:
- // - Sometimes returns explicit overflow error text via non-standard finish_reason handling
- // - Sometimes accepts overflow and returns successfully with usage.input > contextWindow
- // - Sometimes returns rate limit error
if (result.stopReason === "error") {
if (result.errorMessage?.match(/model_context_window_exceeded/i)) {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
@@ -359,10 +272,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Mistral
- // =============================================================================
-
describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral", () => {
it("devstral-medium-latest - should detect overflow via isContextOverflow", async () => {
const model = getModel("mistral", "devstral-medium-latest");
@@ -375,11 +284,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // MiniMax
- // Expected pattern: TBD - need to test actual error message
- // =============================================================================
-
describe.skipIf(!process.env.MINIMAX_API_KEY)("MiniMax", () => {
it("MiniMax-M2.7 - should detect overflow via isContextOverflow", async () => {
const model = getModel("minimax", "MiniMax-M2.7");
@@ -391,14 +295,7 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Xiaomi MiMo
- // =============================================================================
-
describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing)", () => {
- // Xiaomi silently truncates oversized input to fill the context window exactly,
- // then returns finish_reason "length" with output=0 (no room left to generate).
- // This is a detectable overflow signal but uses stopReason "length" rather than "error".
it("mimo-v2.5-pro - should detect overflow via isContextOverflow", async () => {
const model = getModel("xiaomi", "mimo-v2.5-pro");
const result = await testContextOverflow(model, process.env.XIAOMI_API_KEY!);
@@ -446,10 +343,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Kimi For Coding
- // =============================================================================
-
describe.skipIf(!process.env.KIMI_API_KEY)("Kimi For Coding", () => {
it("should detect overflow via isContextOverflow", async () => {
const model = getKimiCodingTestModel();
@@ -461,10 +354,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Vercel AI Gateway - Unified API for multiple providers
- // =============================================================================
-
describe.skipIf(!process.env.AI_GATEWAY_API_KEY)("Vercel AI Gateway", () => {
it("google/gemini-2.5-flash via AI Gateway - should detect overflow via isContextOverflow", async () => {
const model = getModel("vercel-ai-gateway", "google/gemini-2.5-flash");
@@ -476,13 +365,7 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // OpenRouter - Multiple backend providers
- // Expected pattern: "maximum context length is X tokens"
- // =============================================================================
-
describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter", () => {
- // Anthropic backend
it("anthropic/claude-sonnet-4 via OpenRouter - should detect overflow via isContextOverflow", async () => {
const model = getModel("openrouter", "anthropic/claude-sonnet-4");
const result = await testContextOverflow(model, process.env.OPENROUTER_API_KEY!);
@@ -493,7 +376,6 @@ describe("Context overflow error handling", () => {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}, 120000);
- // DeepSeek backend
it("deepseek/deepseek-v3.2 via OpenRouter - should detect overflow via isContextOverflow", async () => {
const model = getModel("openrouter", "deepseek/deepseek-v3.2");
const result = await testContextOverflow(model, process.env.OPENROUTER_API_KEY!);
@@ -504,7 +386,6 @@ describe("Context overflow error handling", () => {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}, 120000);
- // Mistral backend
it("mistralai/mistral-large-2512 via OpenRouter - should detect overflow via isContextOverflow", async () => {
const model = getModel("openrouter", "mistralai/mistral-large-2512");
const result = await testContextOverflow(model, process.env.OPENROUTER_API_KEY!);
@@ -515,7 +396,6 @@ describe("Context overflow error handling", () => {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}, 120000);
- // Google backend
it("google/gemini-2.5-flash via OpenRouter - should detect overflow via isContextOverflow", async () => {
const model = getModel("openrouter", "google/gemini-2.5-flash");
const result = await testContextOverflow(model, process.env.OPENROUTER_API_KEY!);
@@ -526,7 +406,6 @@ describe("Context overflow error handling", () => {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}, 120000);
- // Meta/Llama backend
it("meta-llama/llama-4-scout via OpenRouter - should detect overflow via isContextOverflow", async () => {
const model = getModel("openrouter", "meta-llama/llama-4-scout");
const result = await testContextOverflow(model, process.env.OPENROUTER_API_KEY!);
@@ -538,11 +417,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // Ollama (local)
- // =============================================================================
-
- // Check if ollama is installed and local LLM tests are enabled
let ollamaInstalled = false;
if (!process.env.PI_NO_LOCAL_LLM) {
try {
@@ -558,7 +432,6 @@ describe("Context overflow error handling", () => {
let model: Model<"openai-completions">;
beforeAll(async () => {
- // Check if model is available, if not pull it
try {
execSync("ollama list | grep -q 'gpt-oss:20b'", { stdio: "ignore" });
} catch {
@@ -571,13 +444,11 @@ describe("Context overflow error handling", () => {
}
}
- // Start ollama server
ollamaProcess = spawn("ollama", ["serve"], {
detached: false,
stdio: "ignore",
});
- // Wait for server to be ready
await new Promise<void>((resolve) => {
const checkServer = async () => {
try {
@@ -619,24 +490,14 @@ describe("Context overflow error handling", () => {
const result = await testContextOverflow(model, "ollama");
logResult(result);
- // Ollama silently truncates input instead of erroring
- // It returns stopReason "stop" with truncated usage
- // We cannot detect overflow via error message, only via usage comparison
if (result.stopReason === "stop" && result.hasUsageData) {
- // Ollama truncated - check if reported usage is less than what we sent
- // This is a "silent overflow" - we can detect it if we know expected input size
console.log(" Ollama silently truncated input to", result.usage.input, "tokens");
- // For now, we accept this behavior - Ollama doesn't give us a way to detect overflow
} else if (result.stopReason === "error") {
expect(isContextOverflow(result.response, model.contextWindow)).toBe(true);
}
}, 300000); // 5 min timeout for local model
});
- // =============================================================================
- // LM Studio (local) - Skip if not running or local LLM tests disabled
- // =============================================================================
-
let lmStudioRunning = false;
if (!process.env.PI_NO_LOCAL_LLM) {
try {
@@ -670,10 +531,6 @@ describe("Context overflow error handling", () => {
}, 120000);
});
- // =============================================================================
- // llama.cpp server (local) - Skip if not running or not exposing /v1/completions
- // =============================================================================
-
let llamaCppRunning = false;
if (!process.env.PI_NO_LOCAL_LLM) {
try {
@@ -690,7 +547,6 @@ describe("Context overflow error handling", () => {
describe.skipIf(!llamaCppRunning)("llama.cpp (local)", () => {
it("should detect overflow via isContextOverflow", async () => {
- // Using small context (4096) to match server --ctx-size setting
const model: Model<"openai-completions"> = {
id: "local-model",
api: "openai-completions",
diff --git a/packages/ai/test/cross-provider-handoff.test.ts b/packages/ai/test/cross-provider-handoff.test.ts
index 69bb2fdc59..cf29af3807 100644
--- a/packages/ai/test/cross-provider-handoff.test.ts
+++ b/packages/ai/test/cross-provider-handoff.test.ts
@@ -1,27 +1,3 @@
-/**
- * Cross-Provider Handoff Test
- *
- * Tests that contexts generated by one provider/model can be consumed by another.
- * This catches issues like:
- * - Tool call ID format incompatibilities (e.g., OpenAI Codex pipe characters)
- * - Thinking block transformation issues
- * - Message format incompatibilities
- *
- * Strategy:
- * 1. beforeAll: For each provider/model, generate a "small context" (if not cached):
- * - User message asking to use a tool
- * - Assistant response with thinking + tool call
- * - Tool result
- * - Final assistant response
- *
- * 2. Test: For each target provider/model:
- * - Concatenate ALL other contexts into one
- * - Ask the model to "say hi"
- * - If it fails, there's a compatibility issue
- *
- * Fixtures are generated fresh on each run.
- */
-
import { writeFileSync } from "fs";
import { Type } from "typebox";
import { beforeAll, describe, expect, it } from "vitest";
@@ -33,7 +9,6 @@ import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials }
import { getKimiCodingTestModel } from "./kimi-test-model.js";
import { resolveApiKey } from "./oauth.js";
-// Simple tool for testing
const testToolSchema = Type.Object({
value: Type.Number({ description: "A number to double" }),
});
@@ -44,7 +19,6 @@ const testTool: Tool<typeof testToolSchema> = {
parameters: testToolSchema,
};
-// Provider/model pairs to test
interface ProviderModelPair {
provider: string;
model: string;
@@ -54,11 +28,8 @@ interface ProviderModelPair {
}
const PROVIDER_MODEL_PAIRS: ProviderModelPair[] = [
- // Anthropic
{ provider: "anthropic", model: "claude-sonnet-4-5", label: "anthropic-claude-sonnet-4-5" },
- // Google
{ provider: "google", model: "gemini-3-flash-preview", label: "google-gemini-3-flash-preview" },
- // OpenAI
{
provider: "openai",
model: "gpt-4o-mini",
@@ -67,28 +38,20 @@ const PROVIDER_MODEL_PAIRS: ProviderModelPair[] = [
},
{ provider: "openai", model: "gpt-5-mini", label: "openai-responses-gpt-5-mini" },
{ provider: "azure-openai-responses", model: "gpt-4o-mini", label: "azure-openai-responses-gpt-4o-mini" },
- // OpenAI Codex
{ provider: "openai-codex", model: "gpt-5.2-codex", label: "openai-codex-gpt-5.2-codex" },
- // Prime Inference
{ provider: "prime-inference", model: "openai/gpt-5.5", label: "prime-inference-gpt-5.5" },
- // GitHub Copilot
{ provider: "github-copilot", model: "claude-sonnet-4.5", label: "copilot-claude-sonnet-4.5" },
{ provider: "github-copilot", model: "gpt-5.2-codex", label: "copilot-gpt-5.2-codex" },
{ provider: "github-copilot", model: "gemini-3.5-flash", label: "copilot-gemini-3.5-flash" },
{ provider: "github-copilot", model: "grok-4.5", label: "copilot-grok-4.5" },
- // Amazon Bedrock
{
provider: "amazon-bedrock",
model: "global.anthropic.claude-sonnet-4-5-20250929-v1:0",
label: "bedrock-claude-sonnet-4-5",
},
- // xAI
{ provider: "xai", model: "grok-code-fast-1", label: "xai-grok-code-fast-1" },
- // Cerebras
{ provider: "cerebras", model: "gpt-oss-120b", label: "cerebras-gpt-oss-120b" },
- // Cloudflare Workers AI
{ provider: "cloudflare-workers-ai", model: "@cf/moonshotai/kimi-k2.6", label: "cloudflare-kimi-k2.6" },
- // Cloudflare AI Gateway
{
provider: "cloudflare-ai-gateway",
model: "workers-ai/@cf/moonshotai/kimi-k2.6",
@@ -106,28 +69,20 @@ const PROVIDER_MODEL_PAIRS: ProviderModelPair[] = [
label: "cloudflare-gateway-gpt-5.1",
upstreamApiKeyEnv: "OPENAI_API_KEY",
},
- // Groq
{ provider: "groq", model: "openai/gpt-oss-120b", label: "groq-gpt-oss-120b" },
- // Hugging Face
{ provider: "huggingface", model: "moonshotai/Kimi-K2.5", label: "huggingface-kimi-k2.5" },
- // Kimi For Coding
{ provider: "kimi-coding", model: getKimiCodingTestModel().id, label: "kimi-coding" },
- // Mistral
{ provider: "mistral", model: "devstral-medium-latest", label: "mistral-devstral-medium" },
- // MiniMax
{ provider: "minimax", model: "MiniMax-M2.7", label: "minimax-m2.7" },
{ provider: "minimax-cn", model: "MiniMax-M2.7", label: "minimax-m2.7" },
- // OpenCode Zen
{ provider: "opencode", model: "big-pickle", label: "zen-big-pickle" },
{ provider: "opencode", model: "claude-sonnet-4-5", label: "zen-claude-sonnet-4-5" },
{ provider: "opencode", model: "gemini-3-flash", label: "zen-gemini-3-flash" },
{ provider: "opencode", model: "glm-5.2", label: "zen-glm-5.2" },
{ provider: "opencode", model: "gpt-5.2-codex", label: "zen-gpt-5.2-codex" },
{ provider: "opencode", model: "minimax-m2.7", label: "zen-minimax-m2.7" },
- // OpenCode Go
{ provider: "opencode-go", model: "kimi-k2.6", label: "go-kimi-k2.6" },
{ provider: "opencode-go", model: "minimax-m2.7", label: "go-minimax-m2.7" },
- // Xiaomi MiMo
{ provider: "xiaomi", model: "mimo-v2.5-pro", label: "xiaomi-mimo-v2.5-pro" },
{ provider: "xiaomi-token-plan-cn", model: "mimo-v2.5-pro", label: "xiaomi-token-plan-cn-mimo-v2.5-pro" },
{ provider: "xiaomi-token-plan-ams", model: "mimo-v2.5-pro", label: "xiaomi-token-plan-ams-mimo-v2.5-pro" },
@@ -147,7 +102,6 @@ describe("Cross-Provider Handoff configuration", () => {
});
});
-// Cached context structure
interface CachedContext {
label: string;
provider: string;
@@ -157,18 +111,12 @@ interface CachedContext {
generatedAt: string;
}
-/**
- * Get API key for provider - checks OAuth storage first, then env vars
- */
async function getApiKey(provider: string): Promise<string | undefined> {
const oauthKey = await resolveApiKey(provider);
if (oauthKey) return oauthKey;
return getEnvApiKey(provider);
}
-/**
- * Synchronous check for API key availability (env vars only, for skipIf)
- */
function hasApiKey(pair: ProviderModelPair): boolean {
if (pair.provider === "azure-openai-responses") {
return hasAzureOpenAICredentials();
@@ -189,9 +137,6 @@ function getHeaders(pair: ProviderModelPair): Record<string, string> | undefined
return upstreamApiKey ? { Authorization: `Bearer ${upstreamApiKey}` } : undefined;
}
-/**
- * Check if any provider has API keys available (for skipIf at describe level)
- */
function hasAnyApiKey(): boolean {
return PROVIDER_MODEL_PAIRS.some((pair) => hasApiKey(pair));
}
@@ -208,10 +153,6 @@ function dumpFailurePayload(params: { label: string; error: string; payload?: un
console.log(`Wrote failure payload to ${filename}`);
}
-/**
- * Generate a context from a provider/model pair.
- * Makes a real API call to get authentic tool call IDs and thinking blocks.
- */
async function generateContext(
pair: ProviderModelPair,
apiKey: string,
@@ -407,7 +348,6 @@ describe.skipIf(!hasAnyApiKey())("Cross-Provider Handoff", () => {
continue;
}
- // Collect messages from ALL OTHER contexts
const otherMessages: Message[] = [];
for (const [label, ctx] of Object.entries(contexts)) {
if (label === targetPair.label) continue;
diff --git a/packages/ai/test/empty.test.ts b/packages/ai/test/empty.test.ts
index 4539b3f39a..c2850f82eb 100644
--- a/packages/ai/test/empty.test.ts
+++ b/packages/ai/test/empty.test.ts
@@ -12,7 +12,6 @@ import { hasBedrockCredentials } from "./bedrock-utils.js";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -21,7 +20,6 @@ const oauthTokens = await Promise.all([
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
async function testEmptyMessage<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // Test with completely empty content array
const emptyMessage: UserMessage = {
role: "user",
content: [],
@@ -34,10 +32,8 @@ async function testEmptyMessage<TApi extends Api>(llm: Model<TApi>, options: Str
const response = await complete(llm, context, options);
- // Should either handle gracefully or return an error
expect(response).toBeDefined();
expect(response.role).toBe("assistant");
- // Should handle empty string gracefully
if (response.stopReason === "error") {
expect(response.errorMessage).toBeDefined();
} else {
@@ -46,7 +42,6 @@ async function testEmptyMessage<TApi extends Api>(llm: Model<TApi>, options: Str
}
async function testEmptyStringMessage<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // Test with empty string content
const context: Context = {
messages: [
{
@@ -62,7 +57,6 @@ async function testEmptyStringMessage<TApi extends Api>(llm: Model<TApi>, option
expect(response).toBeDefined();
expect(response.role).toBe("assistant");
- // Should handle empty string gracefully
if (response.stopReason === "error") {
expect(response.errorMessage).toBeDefined();
} else {
@@ -71,7 +65,6 @@ async function testEmptyStringMessage<TApi extends Api>(llm: Model<TApi>, option
}
async function testWhitespaceOnlyMessage<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // Test with whitespace-only content
const context: Context = {
messages: [
{
@@ -87,7 +80,6 @@ async function testWhitespaceOnlyMessage<TApi extends Api>(llm: Model<TApi>, opt
expect(response).toBeDefined();
expect(response.role).toBe("assistant");
- // Should handle whitespace-only gracefully
if (response.stopReason === "error") {
expect(response.errorMessage).toBeDefined();
} else {
@@ -96,8 +88,6 @@ async function testWhitespaceOnlyMessage<TApi extends Api>(llm: Model<TApi>, opt
}
async function testEmptyAssistantMessage<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // Test with empty assistant message in conversation flow
- // User -> Empty Assistant -> User
const emptyAssistant: AssistantMessage = {
role: "assistant",
content: [],
@@ -137,7 +127,6 @@ async function testEmptyAssistantMessage<TApi extends Api>(llm: Model<TApi>, opt
expect(response).toBeDefined();
expect(response.role).toBe("assistant");
- // Should handle empty assistant message in context gracefully
if (response.stopReason === "error") {
expect(response.errorMessage).toBeDefined();
} else {
@@ -578,10 +567,6 @@ describe("AI Providers Empty Message Tests", () => {
});
});
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // =========================================================================
-
describe("Anthropic OAuth Provider Empty Messages", () => {
const llm = getModel("anthropic", "claude-haiku-4-5");
diff --git a/packages/ai/test/github-copilot-anthropic.test.ts b/packages/ai/test/github-copilot-anthropic.test.ts
index dc9589ea9e..92bff083be 100644
--- a/packages/ai/test/github-copilot-anthropic.test.ts
+++ b/packages/ai/test/github-copilot-anthropic.test.ts
@@ -66,24 +66,19 @@ describe("Copilot Claude via Anthropic Messages", () => {
const opts = mockState.constructorOpts!;
expect(opts).toBeDefined();
- // Auth: apiKey null, authToken for Bearer
expect(opts.apiKey).toBeNull();
expect(opts.authToken).toBe("tid_copilot_session_test_token");
const headers = opts.defaultHeaders as Record<string, string>;
- // Copilot static headers from model.headers
expect(headers["User-Agent"]).toContain("GitHubCopilotChat");
expect(headers["Copilot-Integration-Id"]).toBe("vscode-chat");
- // Dynamic headers
expect(headers["X-Initiator"]).toBe("user");
expect(headers["Openai-Intent"]).toBe("conversation-edits");
- // No fine-grained-tool-streaming (Copilot doesn't support it)
const beta = headers["anthropic-beta"] ?? "";
expect(beta).not.toContain("fine-grained-tool-streaming");
- // Payload is valid Anthropic Messages format
const params = mockState.createParams!;
expect(params.model).toBe("claude-sonnet-4.5");
expect(params.stream).toBe(true);
diff --git a/packages/ai/test/google-thinking-signature.test.ts b/packages/ai/test/google-thinking-signature.test.ts
index c90f7caae6..daf6b28f7d 100644
--- a/packages/ai/test/google-thinking-signature.test.ts
+++ b/packages/ai/test/google-thinking-signature.test.ts
@@ -8,9 +8,6 @@ describe("Google thinking detection (thoughtSignature)", () => {
});
it("does not treat thoughtSignature alone as thinking", () => {
- // Per Google docs, thoughtSignature is for context replay and can appear on any part type.
- // Only thought === true indicates thinking content.
- // See: https://ai.google.dev/gemini-api/docs/thought-signatures
expect(isThinkingPart({ thought: undefined, thoughtSignature: "opaque-signature" })).toBe(false);
expect(isThinkingPart({ thought: false, thoughtSignature: "opaque-signature" })).toBe(false);
});
diff --git a/packages/ai/test/image-tool-result.test.ts b/packages/ai/test/image-tool-result.test.ts
index e467a478b6..3f06cecb82 100644
--- a/packages/ai/test/image-tool-result.test.ts
+++ b/packages/ai/test/image-tool-result.test.ts
@@ -13,7 +13,6 @@ import { hasAzureOpenAICredentials, resolveAzureDeploymentName } from "./azure-u
import { hasBedrockCredentials } from "./bedrock-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -21,26 +20,16 @@ const oauthTokens = await Promise.all([
]);
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
-/**
- * Test that tool results containing only images work correctly across all providers.
- * This verifies that:
- * 1. Tool results can contain image content blocks
- * 2. Providers correctly pass images from tool results to the LLM
- * 3. The LLM can see and describe images returned by tools
- */
async function handleToolWithImageResult<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
- // Check if the model supports images
if (!model.input.includes("image")) {
console.log(`Skipping tool image result test - model ${model.id} doesn't support images`);
return;
}
- // Read the test image
const imagePath = join(__dirname, "data", "red-circle.png");
const imageBuffer = readFileSync(imagePath);
const base64Image = imageBuffer.toString("base64");
- // Define a tool that returns only an image (no text)
const getImageSchema = Type.Object({});
const getImageTool: Tool<typeof getImageSchema> = {
name: "get_circle",
@@ -60,11 +49,9 @@ async function handleToolWithImageResult<TApi extends Api>(model: Model<TApi>, o
tools: [getImageTool],
};
- // First request - LLM should call the tool
const firstResponse = await complete(model, context, options);
expect(firstResponse.stopReason).toBe("toolUse");
- // Find the tool call
const toolCall = firstResponse.content.find((b) => b.type === "toolCall");
expect(toolCall).toBeTruthy();
if (!toolCall || toolCall.type !== "toolCall") {
@@ -72,10 +59,8 @@ async function handleToolWithImageResult<TApi extends Api>(model: Model<TApi>, o
}
expect(toolCall.name).toBe("get_circle");
- // Add the tool call to context
context.messages.push(firstResponse);
- // Create tool result with ONLY an image (no text)
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: toolCall.id,
@@ -93,45 +78,32 @@ async function handleToolWithImageResult<TApi extends Api>(model: Model<TApi>, o
context.messages.push(toolResult);
- // Second request - LLM should describe the image from the tool result
const secondResponse = await complete(model, context, options);
expect(secondResponse.stopReason).toBe("stop");
expect(secondResponse.errorMessage).toBeFalsy();
- // Verify the LLM can see and describe the image
const textContent = secondResponse.content.find((b) => b.type === "text");
expect(textContent).toBeTruthy();
if (textContent && textContent.type === "text") {
const lowerContent = textContent.text.toLowerCase();
- // Should mention red and circle since that's what the image shows
expect(lowerContent).toContain("red");
expect(lowerContent).toContain("circle");
}
}
-/**
- * Test that tool results containing both text and images work correctly across all providers.
- * This verifies that:
- * 1. Tool results can contain mixed content blocks (text + images)
- * 2. Providers correctly pass both text and images from tool results to the LLM
- * 3. The LLM can see both the text and images in tool results
- */
async function handleToolWithTextAndImageResult<TApi extends Api>(
model: Model<TApi>,
options?: StreamOptionsWithExtras,
) {
- // Check if the model supports images
if (!model.input.includes("image")) {
console.log(`Skipping tool text+image result test - model ${model.id} doesn't support images`);
return;
}
- // Read the test image
const imagePath = join(__dirname, "data", "red-circle.png");
const imageBuffer = readFileSync(imagePath);
const base64Image = imageBuffer.toString("base64");
- // Define a tool that returns both text and an image
const getImageSchema = Type.Object({});
const getImageTool: Tool<typeof getImageSchema> = {
name: "get_circle_with_description",
@@ -152,11 +124,9 @@ async function handleToolWithTextAndImageResult<TApi extends Api>(
tools: [getImageTool],
};
- // First request - LLM should call the tool
const firstResponse = await complete(model, context, options);
expect(firstResponse.stopReason).toBe("toolUse");
- // Find the tool call
const toolCall = firstResponse.content.find((b) => b.type === "toolCall");
expect(toolCall).toBeTruthy();
if (!toolCall || toolCall.type !== "toolCall") {
@@ -164,10 +134,8 @@ async function handleToolWithTextAndImageResult<TApi extends Api>(
}
expect(toolCall.name).toBe("get_circle_with_description");
- // Add the tool call to context
context.messages.push(firstResponse);
- // Create tool result with BOTH text and image
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: toolCall.id,
@@ -189,19 +157,15 @@ async function handleToolWithTextAndImageResult<TApi extends Api>(
context.messages.push(toolResult);
- // Second request - LLM should describe both the text and image from the tool result
const secondResponse = await complete(model, context, options);
expect(secondResponse.stopReason).toBe("stop");
expect(secondResponse.errorMessage).toBeFalsy();
- // Verify the LLM can see both text and image
const textContent = secondResponse.content.find((b) => b.type === "text");
expect(textContent).toBeTruthy();
if (textContent && textContent.type === "text") {
const lowerContent = textContent.text.toLowerCase();
- // Should mention details from the text (diameter/pixels)
expect(lowerContent.match(/diameter|100|pixel/)).toBeTruthy();
- // Should also mention the visual properties (red and circle)
expect(lowerContent).toContain("red");
expect(lowerContent).toContain("circle");
}
@@ -306,13 +270,8 @@ describe("Tool Results with Images", () => {
await handleToolWithImageResult(llm);
});
- // FIXME(xiaomi): when a tool_result contains both a descriptive text block
- // and an image block, MiMo locks onto the text and ignores the image (it
- // reports the text-derived diameter but never mentions the image's color).
- // The image-only case above proves the image reaches the model, and the
- // text-only path obviously works, so this is a multimodal-fusion quality
- // issue in the model, not a transport bug. Re-enable when upstream model
- // quality improves.
+ // MiMo ignores image content when paired with descriptive text, although its
+ // image-only path is covered above, so this model-quality limitation stays skipped.
it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
await handleToolWithTextAndImageResult(llm);
});
@@ -327,8 +286,7 @@ describe("Tool Results with Images", () => {
await handleToolWithImageResult(llm);
});
- // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
- // limitation applies to Token Plan endpoints (same model behind both).
+ // Same MiMo multimodal-fusion limitation as the API-billing route.
it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
await handleToolWithTextAndImageResult(llm);
});
@@ -344,8 +302,7 @@ describe("Tool Results with Images", () => {
await handleToolWithImageResult(llm);
});
- // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
- // limitation applies to Token Plan endpoints (same model behind both).
+ // Same MiMo multimodal-fusion limitation as the API-billing route.
it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
await handleToolWithTextAndImageResult(llm);
});
@@ -361,8 +318,7 @@ describe("Tool Results with Images", () => {
await handleToolWithImageResult(llm);
});
- // FIXME(xiaomi): see the API-billing block above — same multimodal-fusion
- // limitation applies to Token Plan endpoints (same model behind both).
+ // Same MiMo multimodal-fusion limitation as the API-billing route.
it.skip("should handle tool result with text and image", { retry: 3, timeout: 30000 }, async () => {
await handleToolWithTextAndImageResult(llm);
});
@@ -405,10 +361,6 @@ describe("Tool Results with Images", () => {
});
});
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // =========================================================================
-
describe("Anthropic OAuth Provider (claude-sonnet-4-5)", () => {
const model = getModel("anthropic", "claude-sonnet-4-5");
diff --git a/packages/ai/test/mcp-oauth.test.ts b/packages/ai/test/mcp-oauth.test.ts
index 298915a540..fa70af30f0 100644
--- a/packages/ai/test/mcp-oauth.test.ts
+++ b/packages/ai/test/mcp-oauth.test.ts
@@ -56,8 +56,6 @@ describe.sequential("MCP OAuth provider", () => {
authUrl = info.url;
},
onPrompt: async () => "",
- // Headless: supply the redirect URL via the manual-input path, which
- // races (and wins against) the local callback server.
onManualCodeInput: async () => {
const state = new URL(authUrl).searchParams.get("state") ?? "";
return `${REDIRECT}?code=the-code&state=${state}`;
@@ -67,7 +65,6 @@ describe.sequential("MCP OAuth provider", () => {
expect(creds.access).toBe("access-1");
expect(creds.refresh).toBe("refresh-1");
expect(creds.expires).toBeGreaterThan(Date.now());
- // auth URL carries PKCE challenge + registered client id
const authParams = new URL(authUrl).searchParams;
expect(authParams.get("client_id")).toBe("client-xyz");
expect(authParams.get("code_challenge")).toBeTruthy();
@@ -76,8 +73,6 @@ describe.sequential("MCP OAuth provider", () => {
it("falls back to the next port when the base callback port is in use", async () => {
const http = await import("node:http");
- // Occupy the base callback port. If something already holds it (e.g. a stray
- // local daemon), that satisfies the precondition too — bind best-effort.
const blocker = http.createServer();
const blockerBound = await new Promise<boolean>((resolve) => {
blocker.once("error", () => resolve(false));
@@ -107,7 +102,6 @@ describe.sequential("MCP OAuth provider", () => {
},
});
expect(creds.access).toBe("a");
- // Did NOT use the blocked base port.
const redirect = new URL(authUrl).searchParams.get("redirect_uri") ?? "";
expect(redirect).not.toContain(":53700/");
expect(redirect).toContain(":5370");
diff --git a/packages/ai/test/oauth.ts b/packages/ai/test/oauth.ts
index bd32f3d67e..ade53377cc 100644
--- a/packages/ai/test/oauth.ts
+++ b/packages/ai/test/oauth.ts
@@ -1,10 +1,3 @@
-/**
- * Test helper for resolving API keys from ~/.pi/agent/auth.json
- *
- * Supports both API key and OAuth credentials.
- * OAuth tokens are automatically refreshed if expired and saved back to auth.json.
- */
-
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
@@ -47,13 +40,6 @@ function saveAuthStorage(storage: AuthStorage): void {
chmodSync(AUTH_PATH, 0o600);
}
-/**
- * Resolve API key for a provider from ~/.pi/agent/auth.json
- *
- * For API key credentials, returns the key directly.
- * For OAuth credentials, returns the access token (refreshing if expired and saving back).
- *
- */
export async function resolveApiKey(provider: string): Promise<string | undefined> {
const storage = loadAuthStorage();
const entry = storage[provider];
@@ -65,7 +51,6 @@ export async function resolveApiKey(provider: string): Promise<string | undefine
}
if (entry.type === "oauth") {
- // Build OAuthCredentials record for getOAuthApiKey
const oauthCredentials: Record<string, OAuthCredentials> = {};
for (const [key, value] of Object.entries(storage)) {
if (value.type === "oauth") {
@@ -77,7 +62,6 @@ export async function resolveApiKey(provider: string): Promise<string | undefine
const result = await getOAuthApiKey(provider as OAuthProvider, oauthCredentials);
if (!result) return undefined;
- // Save refreshed credentials back to auth.json
storage[provider] = { type: "oauth", ...result.newCredentials };
saveAuthStorage(storage);
diff --git a/packages/ai/test/openai-codex-stream.test.ts b/packages/ai/test/openai-codex-stream.test.ts
index ca26eb0715..f2e6926a24 100644
--- a/packages/ai/test/openai-codex-stream.test.ts
+++ b/packages/ai/test/openai-codex-stream.test.ts
@@ -371,11 +371,9 @@ describe("openai-codex streaming", () => {
}
if (url === "https://chatgpt.com/backend-api/codex/responses") {
const headers = init?.headers instanceof Headers ? init.headers : undefined;
- // Verify sessionId is set in headers
expect(headers?.get("session_id")).toBe(sessionId);
expect(headers?.get("x-client-request-id")).toBe(sessionId);
- // Verify sessionId is set in request body as prompt_cache_key
const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
expect(body?.prompt_cache_key).toBe(sessionId);
@@ -720,7 +718,6 @@ describe("openai-codex streaming", () => {
}
if (url === "https://chatgpt.com/backend-api/codex/responses") {
const headers = init?.headers instanceof Headers ? init.headers : undefined;
- // Verify headers are not set when sessionId is not provided
expect(headers?.has("session_id")).toBe(false);
expect(headers?.has("x-client-request-id")).toBe(false);
@@ -752,7 +749,6 @@ describe("openai-codex streaming", () => {
messages: [{ role: "user", content: "Say hello", timestamp: Date.now() }],
};
- // No sessionId provided
const streamResult = streamOpenAICodexResponses(model, context, { apiKey: token });
await streamResult.result();
});
diff --git a/packages/ai/test/openai-completions-empty-tools.test.ts b/packages/ai/test/openai-completions-empty-tools.test.ts
index 0fbdc7ab34..f04e2cfe83 100644
--- a/packages/ai/test/openai-completions-empty-tools.test.ts
+++ b/packages/ai/test/openai-completions-empty-tools.test.ts
@@ -3,11 +3,6 @@ import { getModel } from "../src/models.js";
import { streamSimple } from "../src/stream.js";
import type { Model } from "../src/types.js";
-// Empty tools arrays must NOT be serialized as `tools: []` — some OpenAI-compatible
-// backends (e.g. DashScope / Aliyun Qwen via compatible-mode) reject the request with
-// `"[] is too short - 'tools'"` (HTTP 400) when `--no-tools` produces an empty array.
-// Regression for https://github.com/earendil-works/pi-mono/issues/<issue-number>
-
const mockState = vi.hoisted(() => ({
lastParams: undefined as unknown,
lastClientOptions: undefined as unknown,
diff --git a/packages/ai/test/openai-completions-reasoning-replay.test.ts b/packages/ai/test/openai-completions-reasoning-replay.test.ts
index 7f641d4e7b..10d48a064f 100644
--- a/packages/ai/test/openai-completions-reasoning-replay.test.ts
+++ b/packages/ai/test/openai-completions-reasoning-replay.test.ts
@@ -11,7 +11,6 @@ const emptyUsage: Usage = {
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
-// requiresThinkingAsText: false -> exercises the native reasoning-field replay path.
const compat = {
supportsStore: true,
supportsDeveloperRole: true,
@@ -96,8 +95,6 @@ describe("openai-completions reasoning replay", () => {
);
const assistant = messages[1] as unknown as Record<string, unknown>;
- // No recorded field and provider doesn't force reasoning_content: prepend as text so the
- // trace is still sent back without inventing a non-standard field.
expect(assistant.reasoning_content).toBeUndefined();
expect(assistant.content).toBe("unsigned reasoning\n\nanswer");
});
@@ -122,8 +119,6 @@ describe("openai-completions reasoning replay", () => {
const reasoningCompat = { ...compat, requiresReasoningContentOnAssistantMessages: true };
const messages = convertMessages(
buildModel(),
- // Recorded signature is "reasoning", but a reasoning_content provider must get the
- // trace in reasoning_content or the reasoning_content="" default would erase it.
buildContext([
{ type: "thinking", thinking: "step by step", thinkingSignature: "reasoning" },
{ type: "text", text: "answer" },
@@ -139,7 +134,6 @@ describe("openai-completions reasoning replay", () => {
const reasoningCompat = { ...compat, requiresReasoningContentOnAssistantMessages: true };
const messages = convertMessages(
buildModel(),
- // Lone high surrogate (U+D800) would break JSON serialization on the next turn.
buildContext([
{ type: "thinking", thinking: "before\ud800after" },
{ type: "text", text: "answer" },
diff --git a/packages/ai/test/openai-completions-response-model.test.ts b/packages/ai/test/openai-completions-response-model.test.ts
index 32d4edf72e..a7592b0eb0 100644
--- a/packages/ai/test/openai-completions-response-model.test.ts
+++ b/packages/ai/test/openai-completions-response-model.test.ts
@@ -2,9 +2,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { complete } from "../src/stream.js";
import type { Model } from "../src/types.js";
-// Router/virtual ids (e.g. OpenRouter `auto`) keep `model` pinned to the
-// requested id and surface the routed concrete id on `responseModel`.
-
const mockState = vi.hoisted(() => ({
chunks: [] as unknown[],
}));
diff --git a/packages/ai/test/openai-responses-reasoning-replay-e2e.test.ts b/packages/ai/test/openai-responses-reasoning-replay-e2e.test.ts
index 27a55c4662..7035712623 100644
--- a/packages/ai/test/openai-responses-reasoning-replay-e2e.test.ts
+++ b/packages/ai/test/openai-responses-reasoning-replay-e2e.test.ts
@@ -74,22 +74,12 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
reasoningEffort: "high",
});
- // The key assertion: no 400 error from orphaned reasoning item
expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
expect(response.errorMessage).toBeFalsy();
- // Model should respond (text or tool call)
expect(response.content.length).toBeGreaterThan(0);
});
it("handles same-provider different-model handoff with tool calls", { retry: 2 }, async () => {
- // This tests the scenario where:
- // 1. Model A (gpt-5-mini) generates reasoning + function_call
- // 2. User switches to Model B (gpt-5.4) - same provider, different model
- // 3. transform-messages: isSameModel=false, thinking converted to text
- // 4. But tool call ID still has OpenAI pairing history (fc_xxx paired with rs_xxx)
- // 5. Without fix: OpenAI returns 400 "function_call without required reasoning item"
- // 6. With fix: tool calls/results converted to text, conversation continues
-
const modelA = getModel("openai", "gpt-5-mini");
const modelB = getModel("openai", "gpt-5.4");
@@ -104,7 +94,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
timestamp: Date.now(),
};
- // Get a real response from Model A with reasoning + tool call
const assistantResponse = await complete(
modelA,
{
@@ -126,7 +115,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
throw new Error("Missing tool call from OpenAI Responses - model did not use the tool");
}
- // Provide a tool result
const toolResult: Message = {
role: "toolResult",
toolCallId: toolCallBlock.id,
@@ -142,7 +130,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
timestamp: Date.now(),
};
- // Now continue with Model B (different model, same provider)
const context: Context = {
systemPrompt: "You are a helpful assistant. Answer concisely.",
messages: [userMessage, assistantResponse, toolResult, followUp],
@@ -158,12 +145,10 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
},
});
- // The key assertion: no 400 error from orphaned function_call
expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
expect(response.errorMessage).toBeFalsy();
expect(response.content.length).toBeGreaterThan(0);
- // Log what was sent for debugging
const input = capturedPayload?.input as any[];
const functionCalls = input?.filter((item: any) => item.type === "function_call") || [];
const reasoningItems = input?.filter((item: any) => item.type === "reasoning") || [];
@@ -173,7 +158,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
console.log("- reasoning items:", reasoningItems.length);
console.log("- full input:", JSON.stringify(input, null, 2));
- // Verify the model understood the context
const responseText = response.content
.filter((b) => b.type === "text")
.map((b) => (b as any).text)
@@ -182,13 +166,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
});
it("handles cross-provider handoff from Anthropic to OpenAI", { retry: 2 }, async () => {
- // This tests cross-provider handoff:
- // 1. Anthropic model generates thinking + function_call (toolu_xxx ID)
- // 2. User switches to OpenAI
- // 3. transform-messages: isSameModel=false, thinking converted to text
- // 4. Tool call ID is Anthropic format (toolu_xxx), no OpenAI pairing history
- // 5. Should work because foreign IDs have no pairing expectation
-
const anthropicModel = getModel("anthropic", "claude-sonnet-4-5");
const openaiModel = getModel("openai", "gpt-5.4");
@@ -204,7 +181,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
timestamp: Date.now(),
};
- // Get a real response from Anthropic with thinking + tool call
const assistantResponse = await complete(
anthropicModel,
{
@@ -229,7 +205,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
console.log("Anthropic tool call ID:", toolCallBlock.id);
- // Provide a tool result
const toolResult: Message = {
role: "toolResult",
toolCallId: toolCallBlock.id,
@@ -245,7 +220,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
timestamp: Date.now(),
};
- // Now continue with Codex (different provider)
const context: Context = {
systemPrompt: "You are a helpful assistant. Answer concisely.",
messages: [userMessage, assistantResponse, toolResult, followUp],
@@ -261,7 +235,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
},
});
- // Log what was sent
const input = capturedPayload?.input as any[];
const functionCalls = input?.filter((item: any) => item.type === "function_call") || [];
const reasoningItems = input?.filter((item: any) => item.type === "reasoning") || [];
@@ -276,12 +249,10 @@ describe.skipIf(!process.env.OPENAI_API_KEY || !process.env.ANTHROPIC_API_KEY)(
);
}
- // The key assertion: no 400 error
expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
expect(response.errorMessage).toBeFalsy();
expect(response.content.length).toBeGreaterThan(0);
- // Verify the model understood the context
const responseText = response.content
.filter((b) => b.type === "text")
.map((b) => (b as any).text)
diff --git a/packages/ai/test/openrouter-cache-write-repro.test.ts b/packages/ai/test/openrouter-cache-write-repro.test.ts
index ce5abde9e8..fefe3ee13e 100644
--- a/packages/ai/test/openrouter-cache-write-repro.test.ts
+++ b/packages/ai/test/openrouter-cache-write-repro.test.ts
@@ -69,8 +69,6 @@ describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter cache_write repro E
const second = await completeSimple(model, context, options);
expect(second.stopReason, second.errorMessage).toBe("stop");
- // Regression expectation: cache_write_tokens from provider usage must be preserved.
- // With the cache_control marker above, at least one of the two calls should create cache.
const hasCacheWrite = first.usage.cacheWrite > 0 || second.usage.cacheWrite > 0;
expect(hasCacheWrite).toBe(true);
});
diff --git a/packages/ai/test/overflow.test.ts b/packages/ai/test/overflow.test.ts
index 633ba66386..3343e730b3 100644
--- a/packages/ai/test/overflow.test.ts
+++ b/packages/ai/test/overflow.test.ts
@@ -41,8 +41,6 @@ describe("isContextOverflow", () => {
});
it("does not treat Bedrock throttling 'Too many tokens' as overflow", () => {
- // Bedrock returns this for HTTP 429 rate limiting, NOT context overflow.
- // formatBedrockError uses a human-readable prefix for ThrottlingException.
const message = createErrorMessage("Throttling error: Too many tokens, please wait before trying again.");
expect(isContextOverflow(message, 200000)).toBe(false);
});
diff --git a/packages/ai/test/prime-inference-models.test.ts b/packages/ai/test/prime-inference-models.test.ts
index ccf748857d..7c774924d9 100644
--- a/packages/ai/test/prime-inference-models.test.ts
+++ b/packages/ai/test/prime-inference-models.test.ts
@@ -16,9 +16,6 @@ describe("Prime Inference models", () => {
it("registers the Prime Inference catalog", () => {
const modelIds = getModels("prime-inference").map((model) => model.id);
- // Lower bound, not an exact count — the catalog grows with each release and an
- // exact number breaks on every routine addition. The membership checks below
- // are the meaningful assertions.
expect(modelIds.length).toBeGreaterThanOrEqual(90);
expect(modelIds).toEqual(
expect.arrayContaining([
@@ -111,10 +108,6 @@ describe("Prime Inference models", () => {
expect(gemini.input).toEqual(["text", "image"]);
expect(gemini.reasoning).toBe(true);
- // Modality and reasoning are read from OpenRouter's published spec for the
- // same upstream model, but the Prime route enforces a smaller window and
- // output cap than that spec lists (1M/16k), so the curated override wins
- // for contextWindow and maxTokens.
const nemotronSuper = getModel("prime-inference", "nvidia/nemotron-3-super-120b-a12b");
expect(nemotronSuper.reasoning).toBe(true);
expect(nemotronSuper.input).toEqual(["text"]);
@@ -214,8 +207,6 @@ describe("Prime Inference models", () => {
expect(getModel("prime-inference", "anthropic/claude-sonnet-4.6").contextWindow).toBe(1000000);
expect(getModel("prime-inference", "anthropic/claude-sonnet-5").contextWindow).toBe(1000000);
expect(getModel("prime-inference", "anthropic/claude-haiku-4.5").contextWindow).toBe(200000);
- // Confirmed against the live API: this route serves a 200k window, not the
- // larger one the upstream model's published spec lists.
expect(getModel("prime-inference", "anthropic/claude-sonnet-4.5").contextWindow).toBe(200000);
});
diff --git a/packages/ai/test/stream.test.ts b/packages/ai/test/stream.test.ts
index 74bc938c7a..30bfe6a583 100644
--- a/packages/ai/test/stream.test.ts
+++ b/packages/ai/test/stream.test.ts
@@ -22,7 +22,6 @@ import { resolveApiKey } from "./oauth.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -31,9 +30,6 @@ const oauthTokens = await Promise.all([
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
const primeInferenceApiKey = getEnvApiKey("prime-inference");
-// Calculator tool definition (same as examples)
-// Note: Using StringEnum helper because Google's API doesn't support anyOf/const patterns
-// that Type.Enum generates. Google requires { type: "string", enum: [...] } format.
const calculatorSchema = Type.Object({
a: Type.Number({ description: "First number" }),
b: Type.Number({ description: "Second number" }),
@@ -115,11 +111,8 @@ async function handleToolCall<TApi extends Api>(model: Model<TApi>, options?: St
if (toolCall.type === "toolCall") {
expect(toolCall.name).toBe("math_operation");
accumulatedToolArgs += event.delta;
- // Check that we have a parsed arguments object during streaming
expect(toolCall.arguments).toBeDefined();
expect(typeof toolCall.arguments).toBe("object");
- // The arguments should be partially populated as we stream
- // At minimum it should be an empty object, never undefined
expect(toolCall.arguments).not.toBeNull();
}
}
@@ -223,13 +216,11 @@ async function handleThinking<TApi extends Api>(model: Model<TApi>, options?: St
}
async function handleImage<TApi extends Api>(model: Model<TApi>, options?: StreamOptionsWithExtras) {
- // Check if the model supports images
if (!model.input.includes("image")) {
console.log(`Skipping image test - model ${model.id} doesn't support images`);
return;
}
- // Read the test image
const imagePath = join(__dirname, "data", "red-circle.png");
const imageBuffer = readFileSync(imagePath);
const base64Image = imageBuffer.toString("base64");
@@ -259,7 +250,6 @@ async function handleImage<TApi extends Api>(model: Model<TApi>, options?: Strea
const response = await complete(model, context, options);
- // Check the response mentions red and circle
expect(response.content.length > 0).toBeTruthy();
const textContent = response.content.find((b) => b.type === "text");
if (textContent && textContent.type === "text") {
@@ -282,7 +272,6 @@ async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamO
tools: [calculatorTool],
};
- // Collect all text content from all assistant responses
let allTextContent = "";
let hasSeenThinking = false;
let hasSeenToolCalls = false;
@@ -291,10 +280,8 @@ async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamO
for (let turn = 0; turn < maxTurns; turn++) {
const response = await complete(model, context, options);
- // Add the assistant response to context
context.messages.push(response);
- // Process content blocks
const results: ToolResultMessage[] = [];
for (const block of response.content) {
if (block.type === "text") {
@@ -304,7 +291,6 @@ async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamO
} else if (block.type === "toolCall") {
hasSeenToolCalls = true;
- // Process the tool call
expect(block.name).toBe("math_operation");
expect(block.id).toBeTruthy();
expect(block.arguments).toBeTruthy();
@@ -322,7 +308,6 @@ async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamO
result = 0;
}
- // Add tool result to context
results.push({
role: "toolResult",
toolCallId: block.id,
@@ -335,17 +320,14 @@ async function multiTurn<TApi extends Api>(model: Model<TApi>, options?: StreamO
}
context.messages.push(...results);
- // If we got a stop response with text content, we're likely done
expect(response.stopReason, `Error: ${response.errorMessage}`).not.toBe("error");
if (response.stopReason === "stop") {
break;
}
}
- // Verify we got either thinking content or tool calls (or both)
expect(hasSeenThinking || hasSeenToolCalls).toBe(true);
- // The accumulated text should reference both calculations
expect(allTextContent).toBeTruthy();
expect(allTextContent.includes("714")).toBe(true);
expect(allTextContent.includes("887")).toBe(true);
@@ -1139,11 +1121,6 @@ describe("Generate E2E Tests", () => {
},
);
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // Tokens are resolved at module level (see oauthTokens above)
- // =========================================================================
-
describe("Anthropic OAuth Provider (claude-sonnet-4-6)", () => {
const model = getModel("anthropic", "claude-sonnet-4-6");
@@ -1480,7 +1457,6 @@ describe("Generate E2E Tests", () => {
});
});
- // Check if ollama is installed and local LLM tests are enabled
let ollamaInstalled = false;
if (!process.env.PI_NO_LOCAL_LLM) {
try {
@@ -1496,7 +1472,6 @@ describe("Generate E2E Tests", () => {
let ollamaProcess: ChildProcess | null = null;
beforeAll(async () => {
- // Check if model is available, if not pull it
try {
execSync("ollama list | grep -q 'gpt-oss:20b'", { stdio: "ignore" });
} catch {
@@ -1509,13 +1484,11 @@ describe("Generate E2E Tests", () => {
}
}
- // Start ollama server
ollamaProcess = spawn("ollama", ["serve"], {
detached: false,
stdio: "ignore",
});
- // Wait for server to be ready
await new Promise<void>((resolve) => {
const checkServer = async () => {
try {
@@ -1552,7 +1525,6 @@ describe("Generate E2E Tests", () => {
}, 30000); // 30 second timeout for setup
afterAll(() => {
- // Kill ollama server
if (ollamaProcess) {
ollamaProcess.kill("SIGTERM");
ollamaProcess = null;
diff --git a/packages/ai/test/tokens.test.ts b/packages/ai/test/tokens.test.ts
index 5fceca1e06..d4a73abca9 100644
--- a/packages/ai/test/tokens.test.ts
+++ b/packages/ai/test/tokens.test.ts
@@ -12,7 +12,6 @@ import { hasBedrockCredentials } from "./bedrock-utils.js";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -51,9 +50,6 @@ async function testTokensOnAbort<TApi extends Api>(llm: Model<TApi>, options: St
expect(msg.stopReason).toBe("aborted");
- // OpenAI providers, OpenAI Codex, zai, and Amazon Bedrock only send usage in the final chunk,
- // so when aborted they have no token stats. Anthropic and Google send usage information early in the stream.
- // MiniMax and Kimi report input tokens but not output tokens differently on aborted requests.
if (
llm.api === "openai-completions" ||
llm.api === "mistral-conversations" ||
@@ -67,18 +63,15 @@ async function testTokensOnAbort<TApi extends Api>(llm: Model<TApi>, options: St
expect(msg.usage.input).toBe(0);
expect(msg.usage.output).toBe(0);
} else if (llm.provider === "minimax") {
- // MiniMax M2.7 does not report token usage for aborted requests.
expect(msg.usage.input).toBe(0);
expect(msg.usage.output).toBe(0);
} else if (llm.provider === "kimi-coding") {
- // Kimi reports input tokens early but output tokens only in the final chunk.
expect(msg.usage.input).toBeGreaterThan(0);
expect(msg.usage.output).toBe(0);
} else {
expect(msg.usage.input).toBeGreaterThan(0);
expect(msg.usage.output).toBeGreaterThan(0);
- // Some providers (Copilot) have zero cost rates
if (llm.cost.input > 0) {
expect(msg.usage.cost.input).toBeGreaterThan(0);
expect(msg.usage.cost.total).toBeGreaterThan(0);
@@ -225,11 +218,7 @@ describe("Token Statistics on Abort", () => {
describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing) Provider", () => {
const llm = getModel("xiaomi", "mimo-v2.5-pro");
- // FIXME(xiaomi): Xiaomi's Anthropic-compatible stream does not populate
- // usage in the message_start event the way Anthropic does — usage only
- // arrives at message_stop. Aborting mid-stream therefore loses input/output
- // token counts. Non-streaming usage works (see total-tokens.test.ts).
- // Re-enable once upstream sends usage in message_start.
+ // Xiaomi only reports this streaming usage at message_stop, after an abort.
it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
await testTokensOnAbort(llm);
});
@@ -238,8 +227,6 @@ describe("Token Statistics on Abort", () => {
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)("Xiaomi MiMo Token Plan (CN) Provider", () => {
const llm = getModel("xiaomi-token-plan-cn", "mimo-v2.5-pro");
- // FIXME(xiaomi): see the API-billing block above — same upstream streaming
- // usage limitation applies to Token Plan endpoints.
it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
await testTokensOnAbort(llm);
});
@@ -248,8 +235,6 @@ describe("Token Statistics on Abort", () => {
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)("Xiaomi MiMo Token Plan (AMS) Provider", () => {
const llm = getModel("xiaomi-token-plan-ams", "mimo-v2.5-pro");
- // FIXME(xiaomi): see the API-billing block above — same upstream streaming
- // usage limitation applies to Token Plan endpoints.
it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
await testTokensOnAbort(llm);
});
@@ -258,17 +243,11 @@ describe("Token Statistics on Abort", () => {
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)("Xiaomi MiMo Token Plan (SGP) Provider", () => {
const llm = getModel("xiaomi-token-plan-sgp", "mimo-v2.5-pro");
- // FIXME(xiaomi): see the API-billing block above — same upstream streaming
- // usage limitation applies to Token Plan endpoints.
it.skip("should include token stats when aborted mid-stream", { retry: 3, timeout: 30000 }, async () => {
await testTokensOnAbort(llm);
});
});
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // =========================================================================
-
describe("Anthropic OAuth Provider", () => {
const llm = getModel("anthropic", "claude-sonnet-4-6");
diff --git a/packages/ai/test/tool-call-id-normalization.test.ts b/packages/ai/test/tool-call-id-normalization.test.ts
index 0655f75484..a41eaeba73 100644
--- a/packages/ai/test/tool-call-id-normalization.test.ts
+++ b/packages/ai/test/tool-call-id-normalization.test.ts
@@ -1,15 +1,3 @@
-/**
- * Tool Call ID Normalization Tests
- *
- * Tests that tool call IDs from OpenAI Responses API (github-copilot, openai-codex, opencode)
- * are properly normalized when sent to other providers.
- *
- * OpenAI Responses API generates IDs in format: {call_id}|{id}
- * where {id} can be 400+ chars with special characters (+, /, =).
- *
- * Regression test for: https://github.com/earendil-works/pi-mono/issues/1022
- */
-
import { Type } from "typebox";
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.js";
@@ -17,12 +5,10 @@ import { completeSimple, getEnvApiKey } from "../src/stream.js";
import type { AssistantMessage, Message, Tool, ToolResultMessage } from "../src/types.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve API keys
const copilotToken = await resolveApiKey("github-copilot");
const openrouterKey = getEnvApiKey("openrouter");
const codexToken = await resolveApiKey("openai-codex");
-// Simple echo tool for testing
const echoToolSchema = Type.Object({
message: Type.String({ description: "Message to echo back" }),
});
@@ -33,15 +19,6 @@ const echoTool: Tool<typeof echoToolSchema> = {
parameters: echoToolSchema,
};
-/**
- * Test 1: Live cross-provider handoff
- *
- * 1. Use github-copilot gpt-5.2-codex to generate a tool call
- * 2. Switch to openrouter openai/gpt-5.2-codex and complete
- * 3. Switch to openai-codex gpt-5.2-codex and complete
- *
- * Both should succeed without "call_id too long" errors.
- */
describe("Tool Call ID Normalization - Live Handoff", () => {
it.skipIf(!copilotToken || !openrouterKey)(
"github-copilot -> openrouter should normalize pipe-separated IDs",
@@ -49,7 +26,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
const copilotModel = getModel("github-copilot", "gpt-5.2-codex");
const openrouterModel = getModel("openrouter", "openai/gpt-5.2-codex");
- // Step 1: Generate tool call with github-copilot
const userMessage: Message = {
role: "user",
content: "Use the echo tool to echo 'hello world'",
@@ -72,13 +48,11 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
expect(toolCall).toBeDefined();
expect(toolCall!.type).toBe("toolCall");
- // Verify it's a pipe-separated ID (OpenAI Responses format)
if (toolCall?.type === "toolCall") {
expect(toolCall.id).toContain("|");
console.log(`Tool call ID from github-copilot: ${toolCall.id.slice(0, 80)}...`);
}
- // Create tool result
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: (toolCall as any).id,
@@ -88,7 +62,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
timestamp: Date.now(),
};
- // Step 2: Complete with openrouter (uses openai-completions API)
const openrouterResponse = await completeSimple(
openrouterModel,
{
@@ -104,7 +77,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
{ apiKey: openrouterKey },
);
- // Should NOT fail with "call_id too long" error
expect(openrouterResponse.stopReason, `OpenRouter error: ${openrouterResponse.errorMessage}`).not.toBe(
"error",
);
@@ -119,7 +91,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
const copilotModel = getModel("github-copilot", "gpt-5.2-codex");
const codexModel = getModel("openai-codex", "gpt-5.2-codex");
- // Step 1: Generate tool call with github-copilot
const userMessage: Message = {
role: "user",
content: "Use the echo tool to echo 'test message'",
@@ -141,7 +112,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
const toolCall = assistantResponse.content.find((c) => c.type === "toolCall");
expect(toolCall).toBeDefined();
- // Create tool result
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: (toolCall as any).id,
@@ -151,7 +121,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
timestamp: Date.now(),
};
- // Step 2: Complete with openai-codex (uses openai-codex-responses API)
const codexResponse = await completeSimple(
codexModel,
{
@@ -167,7 +136,6 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
{ apiKey: codexToken },
);
- // Should NOT fail with ID validation error
expect(codexResponse.stopReason, `Codex error: ${codexResponse.errorMessage}`).not.toBe("error");
expect(codexResponse.errorMessage).toBeUndefined();
},
@@ -175,18 +143,10 @@ describe("Tool Call ID Normalization - Live Handoff", () => {
);
});
-/**
- * Test 2: Prefilled context with exact failing IDs from issue #1022
- *
- * Uses the exact tool call ID format that caused the error:
- * "call_xxx|very_long_base64_with_special_chars+/="
- */
describe("Tool Call ID Normalization - Prefilled Context", () => {
- // Exact tool call ID from issue #1022 JSONL
const FAILING_TOOL_CALL_ID =
"call_pAYbIr76hXIjncD9UE4eGfnS|t5nnb2qYMFWGSsr13fhCd1CaCu3t3qONEPuOudu4HSVEtA8YJSL6FAZUxvoOoD792VIJWl91g87EdqsCWp9krVsdBysQoDaf9lMCLb8BS4EYi4gQd5kBQBYLlgD71PYwvf+TbMD9J9/5OMD42oxSRj8H+vRf78/l2Xla33LWz4nOgsddBlbvabICRs8GHt5C9PK5keFtzyi3lsyVKNlfduK3iphsZqs4MLv4zyGJnvZo/+QzShyk5xnMSQX/f98+aEoNflEApCdEOXipipgeiNWnpFSHbcwmMkZoJhURNu+JEz3xCh1mrXeYoN5o+trLL3IXJacSsLYXDrYTipZZbJFRPAucgbnjYBC+/ZzJOfkwCs+Gkw7EoZR7ZQgJ8ma+9586n4tT4cI8DEhBSZsWMjrCt8dxKg==";
- // Build prefilled context with the failing ID
function buildPrefilledMessages(): Message[] {
const userMessage: Message = {
role: "user",
@@ -253,7 +213,6 @@ describe("Tool Call ID Normalization - Prefilled Context", () => {
{ apiKey: openrouterKey },
);
- // Should NOT fail with "call_id too long" error
expect(response.stopReason, `OpenRouter error: ${response.errorMessage}`).not.toBe("error");
if (response.errorMessage) {
expect(response.errorMessage).not.toContain("call_id");
@@ -279,7 +238,6 @@ describe("Tool Call ID Normalization - Prefilled Context", () => {
{ apiKey: codexToken },
);
- // Should NOT fail with ID validation error
expect(response.stopReason, `Codex error: ${response.errorMessage}`).not.toBe("error");
if (response.errorMessage) {
expect(response.errorMessage).not.toContain("id");
diff --git a/packages/ai/test/tool-call-without-result.test.ts b/packages/ai/test/tool-call-without-result.test.ts
index 39c314a9a2..10e4be9648 100644
--- a/packages/ai/test/tool-call-without-result.test.ts
+++ b/packages/ai/test/tool-call-without-result.test.ts
@@ -13,7 +13,6 @@ import { hasBedrockCredentials } from "./bedrock-utils.js";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -21,7 +20,6 @@ const oauthTokens = await Promise.all([
]);
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
-// Simple calculate tool
const calculateSchema = Type.Object({
expression: Type.String({ description: "The mathematical expression to evaluate" }),
});
@@ -33,27 +31,23 @@ const calculateTool: Tool = {
};
async function testToolCallWithoutResult<TApi extends Api>(model: Model<TApi>, options: StreamOptionsWithExtras = {}) {
- // Step 1: Create context with the calculate tool
const context: Context = {
systemPrompt: "You are a helpful assistant. Use the calculate tool when asked to perform calculations.",
messages: [],
tools: [calculateTool],
};
- // Step 2: Ask the LLM to make a tool call
context.messages.push({
role: "user",
content: "Please calculate 25 * 18 using the calculate tool.",
timestamp: Date.now(),
});
- // Step 3: Get the assistant's response (should contain a tool call)
const firstResponse = await complete(model, context, options);
context.messages.push(firstResponse);
console.log("First response:", JSON.stringify(firstResponse, null, 2));
- // Verify the response contains a tool call
const hasToolCall = firstResponse.content.some((block) => block.type === "toolCall");
expect(hasToolCall).toBe(true);
@@ -61,26 +55,19 @@ async function testToolCallWithoutResult<TApi extends Api>(model: Model<TApi>, o
throw new Error("Expected assistant to make a tool call, but none was found");
}
- // Step 4: Send a user message WITHOUT providing tool result
- // This simulates the scenario where a tool call was aborted/cancelled
context.messages.push({
role: "user",
content: "Never mind, just tell me what is 2+2?",
timestamp: Date.now(),
});
- // Step 5: The fix should filter out the orphaned tool call, and the request should succeed
const secondResponse = await complete(model, context, options);
console.log("Second response:", JSON.stringify(secondResponse, null, 2));
- // The request should succeed (not error) - that's the main thing we're testing
expect(secondResponse.stopReason).not.toBe("error");
- // Should have some content in the response
expect(secondResponse.content.length).toBeGreaterThan(0);
- // The LLM may choose to answer directly or make a new tool call - either is fine
- // The important thing is it didn't fail with the orphaned tool call error
const textContent = secondResponse.content
.filter((block) => block.type === "text")
.map((block) => (block.type === "text" ? block.text : ""))
@@ -89,15 +76,10 @@ async function testToolCallWithoutResult<TApi extends Api>(model: Model<TApi>, o
expect(toolCalls || textContent.length).toBeGreaterThan(0);
console.log("Answer:", textContent);
- // Verify the stop reason is either "stop" or "toolUse" (new tool call)
expect(["stop", "toolUse"]).toContain(secondResponse.stopReason);
}
describe("Tool Call Without Result Tests", () => {
- // =========================================================================
- // API Key-based providers
- // =========================================================================
-
describe.skipIf(!process.env.GEMINI_API_KEY)("Google Provider", () => {
const model = getModel("google", "gemini-2.5-flash");
@@ -273,10 +255,6 @@ describe("Tool Call Without Result Tests", () => {
});
});
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // =========================================================================
-
describe("Anthropic OAuth Provider", () => {
const model = getModel("anthropic", "claude-haiku-4-5");
diff --git a/packages/ai/test/total-tokens.test.ts b/packages/ai/test/total-tokens.test.ts
index 06156baeff..1b61538b92 100644
--- a/packages/ai/test/total-tokens.test.ts
+++ b/packages/ai/test/total-tokens.test.ts
@@ -1,17 +1,3 @@
-/**
- * Test totalTokens field across all providers.
- *
- * totalTokens represents the total number of tokens processed by the LLM,
- * including input (with cache) and output (with thinking). This is the
- * base for calculating context size for the next request.
- *
- * - OpenAI Completions: Uses native total_tokens field
- * - OpenAI Responses: Uses native total_tokens field
- * - Google: Uses native totalTokenCount field
- * - Anthropic: Computed as input + output + cacheRead + cacheWrite
- * - Other OpenAI-compatible providers: Uses native total_tokens field
- */
-
import { describe, expect, it } from "vitest";
import { getModel } from "../src/models.js";
import { complete } from "../src/stream.js";
@@ -26,7 +12,6 @@ import { hasBedrockCredentials } from "./bedrock-utils.js";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -34,7 +19,6 @@ const oauthTokens = await Promise.all([
]);
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
-// Generate a long system prompt to trigger caching (>2k bytes for most providers)
const LONG_SYSTEM_PROMPT = `You are a helpful assistant. Be concise in your responses.
Here is some additional context that makes this system prompt long enough to trigger caching:
@@ -51,7 +35,6 @@ async function testTotalTokensWithCache<TApi extends Api>(
llm: Model<TApi>,
options: StreamOptionsWithExtras = {},
): Promise<{ first: Usage; second: Usage }> {
- // First request - no cache
const context1: Context = {
systemPrompt: LONG_SYSTEM_PROMPT,
messages: [
@@ -66,7 +49,6 @@ async function testTotalTokensWithCache<TApi extends Api>(
const response1 = await complete(llm, context1, options);
expect(response1.stopReason).toBe("stop");
- // Second request - should trigger cache read (same system prompt, add conversation)
const context2: Context = {
systemPrompt: LONG_SYSTEM_PROMPT,
messages: [
@@ -101,10 +83,6 @@ function assertTotalTokensEqualsComponents(usage: Usage) {
}
describe("totalTokens field", () => {
- // =========================================================================
- // Anthropic
- // =========================================================================
-
describe.skipIf(!process.env.ANTHROPIC_API_KEY)("Anthropic (API Key)", () => {
it("claude-sonnet-4-5 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -121,7 +99,6 @@ describe("totalTokens field", () => {
assertTotalTokensEqualsComponents(first);
assertTotalTokensEqualsComponents(second);
- // Anthropic should have cache activity
const hasCache = second.cacheRead > 0 || second.cacheWrite > 0 || first.cacheWrite > 0;
expect(hasCache).toBe(true);
});
@@ -143,17 +120,12 @@ describe("totalTokens field", () => {
assertTotalTokensEqualsComponents(first);
assertTotalTokensEqualsComponents(second);
- // Anthropic should have cache activity
const hasCache = second.cacheRead > 0 || second.cacheWrite > 0 || first.cacheWrite > 0;
expect(hasCache).toBe(true);
},
);
});
- // =========================================================================
- // OpenAI
- // =========================================================================
-
describe.skipIf(!process.env.OPENAI_API_KEY)("OpenAI Completions", () => {
it("gpt-4o-mini - should return totalTokens equal to sum of components", {
retry: 3,
@@ -212,10 +184,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Google
- // =========================================================================
-
describe.skipIf(!process.env.GEMINI_API_KEY)("Google", () => {
it("gemini-2.5-flash - should return totalTokens equal to sum of components", {
retry: 3,
@@ -234,10 +202,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // xAI
- // =========================================================================
-
describe.skipIf(!process.env.XAI_API_KEY)("xAI", () => {
it("grok-4.3 - should return totalTokens equal to sum of components", { retry: 3, timeout: 60000 }, async () => {
const llm = getModel("xai", "grok-4.3");
@@ -253,10 +217,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Groq
- // =========================================================================
-
describe.skipIf(!process.env.GROQ_API_KEY)("Groq", () => {
it("openai/gpt-oss-120b - should return totalTokens equal to sum of components", {
retry: 3,
@@ -275,10 +235,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Cerebras
- // =========================================================================
-
describe.skipIf(!process.env.CEREBRAS_API_KEY)("Cerebras", () => {
it("gpt-oss-120b - should return totalTokens equal to sum of components", {
retry: 3,
@@ -297,10 +253,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Cloudflare Workers AI
- // =========================================================================
-
describe.skipIf(!hasCloudflareWorkersAICredentials())("Cloudflare Workers AI", () => {
it("@cf/moonshotai/kimi-k2.6 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -321,10 +273,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Cloudflare AI Gateway
- // =========================================================================
-
describe.skipIf(!hasCloudflareAiGatewayCredentials())("Cloudflare AI Gateway", () => {
it("workers-ai/@cf/moonshotai/kimi-k2.6 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -345,10 +293,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Hugging Face
- // =========================================================================
-
describe.skipIf(!process.env.HF_TOKEN)("Hugging Face", () => {
it("Kimi-K2.5 - should return totalTokens equal to sum of components", { retry: 3, timeout: 60000 }, async () => {
const llm = getModel("huggingface", "moonshotai/Kimi-K2.5");
@@ -364,10 +308,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // z.ai
- // =========================================================================
-
describe.skipIf(!process.env.ZAI_API_KEY)("z.ai", () => {
it("should return totalTokens equal to sum of components", { retry: 3, timeout: 60000 }, async () => {
const llm = getZaiTestModel();
@@ -383,10 +323,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Mistral
- // =========================================================================
-
describe.skipIf(!process.env.MISTRAL_API_KEY)("Mistral", () => {
it("devstral-medium-latest - should return totalTokens equal to sum of components", {
retry: 3,
@@ -405,10 +341,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // MiniMax
- // =========================================================================
-
describe.skipIf(!process.env.MINIMAX_API_KEY)("MiniMax", () => {
it("MiniMax-M2.7 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -427,10 +359,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Xiaomi MiMo
- // =========================================================================
-
describe.skipIf(!process.env.XIAOMI_API_KEY)("Xiaomi MiMo (API billing)", () => {
it("mimo-v2.5-pro - should return totalTokens equal to sum of components", {
retry: 3,
@@ -449,10 +377,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Xiaomi MiMo Token Plan CN
- // =========================================================================
-
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_CN_API_KEY)("Xiaomi MiMo Token Plan (CN)", () => {
it("mimo-v2.5-pro - should return totalTokens equal to sum of components", {
retry: 3,
@@ -473,10 +397,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Xiaomi MiMo Token Plan AMS
- // =========================================================================
-
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_AMS_API_KEY)("Xiaomi MiMo Token Plan (AMS)", () => {
it("mimo-v2.5-pro - should return totalTokens equal to sum of components", {
retry: 3,
@@ -497,10 +417,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Xiaomi MiMo Token Plan SGP
- // =========================================================================
-
describe.skipIf(!process.env.XIAOMI_TOKEN_PLAN_SGP_API_KEY)("Xiaomi MiMo Token Plan (SGP)", () => {
it("mimo-v2.5-pro - should return totalTokens equal to sum of components", {
retry: 3,
@@ -521,10 +437,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Kimi For Coding
- // =========================================================================
-
describe.skipIf(!process.env.KIMI_API_KEY)("Kimi For Coding", () => {
it("should return totalTokens equal to sum of components", { retry: 3, timeout: 60000 }, async () => {
const llm = getKimiCodingTestModel();
@@ -540,10 +452,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // Vercel AI Gateway
- // =========================================================================
-
describe.skipIf(!process.env.AI_GATEWAY_API_KEY)("Vercel AI Gateway", () => {
it("google/gemini-2.5-flash - should return totalTokens equal to sum of components", {
retry: 3,
@@ -562,10 +470,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // OpenRouter - Multiple backend providers
- // =========================================================================
-
describe.skipIf(!process.env.OPENROUTER_API_KEY)("OpenRouter", () => {
it("anthropic/claude-sonnet-4 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -648,10 +552,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // GitHub Copilot (OAuth)
- // =========================================================================
-
describe("GitHub Copilot (OAuth)", () => {
it.skipIf(!githubCopilotToken)(
"gpt-5-mini - should return totalTokens equal to sum of components",
@@ -688,12 +588,6 @@ describe("totalTokens field", () => {
);
});
- // =========================================================================
- // =========================================================================
-
- // =========================================================================
- // =========================================================================
-
describe.skipIf(!hasBedrockCredentials())("Amazon Bedrock", () => {
it("claude-sonnet-4-5 - should return totalTokens equal to sum of components", {
retry: 3,
@@ -712,10 +606,6 @@ describe("totalTokens field", () => {
});
});
- // =========================================================================
- // OpenAI Codex (OAuth)
- // =========================================================================
-
describe("OpenAI Codex (OAuth)", () => {
it.skipIf(!openaiCodexToken)(
"gpt-5.2-codex - should return totalTokens equal to sum of components",
diff --git a/packages/ai/test/transform-messages-copilot-openai-to-anthropic.test.ts b/packages/ai/test/transform-messages-copilot-openai-to-anthropic.test.ts
index 7508e74b80..3fe07d4e15 100644
--- a/packages/ai/test/transform-messages-copilot-openai-to-anthropic.test.ts
+++ b/packages/ai/test/transform-messages-copilot-openai-to-anthropic.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import { transformMessages } from "../src/providers/transform-messages.js";
import type { AssistantMessage, Message, Model, ToolCall } from "../src/types.js";
-// Normalize function matching what anthropic.ts uses
function anthropicNormalizeToolCallId(
id: string,
_model: Model<"anthropic-messages">,
@@ -80,7 +79,6 @@ describe("OpenAI to Anthropic session migration for Copilot Claude", () => {
const result = transformMessages(messages, model, anthropicNormalizeToolCallId);
const assistantMsg = result.find((m) => m.role === "assistant") as AssistantMessage;
- // Thinking block should be converted to text since models differ
const textBlocks = assistantMsg.content.filter((b) => b.type === "text");
const thinkingBlocks = assistantMsg.content.filter((b) => b.type === "thinking");
expect(thinkingBlocks).toHaveLength(0);
diff --git a/packages/ai/test/unicode-surrogate.test.ts b/packages/ai/test/unicode-surrogate.test.ts
index 3d9945c981..f6ac63ed40 100644
--- a/packages/ai/test/unicode-surrogate.test.ts
+++ b/packages/ai/test/unicode-surrogate.test.ts
@@ -13,10 +13,8 @@ import { hasBedrockCredentials } from "./bedrock-utils.js";
import { hasCloudflareAiGatewayCredentials, hasCloudflareWorkersAICredentials } from "./cloudflare-utils.js";
import { resolveApiKey } from "./oauth.js";
-// Empty schema for test tools - must be proper OBJECT type for Cloud Code Assist
const emptySchema = Type.Object({});
-// Resolve OAuth tokens at module level (async, runs before tests)
const oauthTokens = await Promise.all([
resolveApiKey("anthropic"),
resolveApiKey("github-copilot"),
@@ -24,20 +22,8 @@ const oauthTokens = await Promise.all([
]);
const [anthropicOAuthToken, githubCopilotToken, openaiCodexToken] = oauthTokens;
-/**
- * Test for Unicode surrogate pair handling in tool results.
- *
- * Issue: When tool results contain emoji or other characters outside the Basic Multilingual Plane,
- * they may be incorrectly serialized as unpaired surrogates, causing "no low surrogate in string"
- * errors when sent to the API provider.
- *
- * Example error from Anthropic:
- * "The request body is not valid JSON: no low surrogate in string: line 1 column 197667"
- */
-
async function testEmojiInToolResults<TApi extends Api>(llm: Model<TApi>, options: StreamOptionsWithExtras = {}) {
const toolCallId = llm.provider === "mistral" ? "testtool1" : "test_1";
- // Simulate a tool that returns emoji
const context: Context = {
systemPrompt: "You are a helpful assistant.",
messages: [
@@ -80,7 +66,6 @@ async function testEmojiInToolResults<TApi extends Api>(llm: Model<TApi>, option
],
};
- // Add tool result with various problematic Unicode characters
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: toolCallId,
@@ -107,14 +92,12 @@ async function testEmojiInToolResults<TApi extends Api>(llm: Model<TApi>, option
context.messages.push(toolResult);
- // Add follow-up user message
context.messages.push({
role: "user",
content: "Summarize the tool result briefly.",
timestamp: Date.now(),
});
- // This should not throw a surrogate pair error
const response = await complete(llm, context, options);
expect(response.stopReason).not.toBe("error");
@@ -166,7 +149,6 @@ async function testRealWorldLinkedInData<TApi extends Api>(llm: Model<TApi>, opt
],
};
- // Real-world tool result from LinkedIn with emoji
const toolResult: ToolResultMessage = {
role: "toolResult",
toolCallId: toolCallId,
@@ -203,7 +185,6 @@ Unanswered Comments: 2
timestamp: Date.now(),
});
- // This should not throw a surrogate pair error
const response = await complete(llm, context, options);
expect(response.stopReason).not.toBe("error");
@@ -255,8 +236,6 @@ async function testUnpairedHighSurrogate<TApi extends Api>(llm: Model<TApi>, opt
],
};
- // Construct a string with an intentionally unpaired high surrogate
- // This simulates what might happen if text processing corrupts emoji
const unpairedSurrogate = String.fromCharCode(0xd83d); // High surrogate without low surrogate
const toolResult: ToolResultMessage = {
@@ -276,8 +255,6 @@ async function testUnpairedHighSurrogate<TApi extends Api>(llm: Model<TApi>, opt
timestamp: Date.now(),
});
- // This should not throw a surrogate pair error
- // The unpaired surrogate should be sanitized before sending to API
const response = await complete(llm, context, options);
expect(response.stopReason).not.toBe("error");
@@ -368,10 +345,6 @@ describe("AI Providers Unicode Surrogate Pair Tests", () => {
});
});
- // =========================================================================
- // OAuth-based providers (credentials from ~/.pi/agent/oauth.json)
- // =========================================================================
-
describe("Anthropic OAuth Provider Unicode Handling", () => {
const llm = getModel("anthropic", "claude-haiku-4-5");
diff --git a/packages/ai/test/xhigh.test.ts b/packages/ai/test/xhigh.test.ts
index ef487369f5..bb2eb2070d 100644
--- a/packages/ai/test/xhigh.test.ts
+++ b/packages/ai/test/xhigh.test.ts
@@ -17,7 +17,6 @@ function makeContext(): Context {
describe.skipIf(!process.env.OPENAI_API_KEY)("xhigh reasoning", () => {
describe("codex-max (supports xhigh)", () => {
- // Note: codex models only support the responses API, not chat completions
it("should work with openai-responses", async () => {
const model = getModel("openai", "gpt-5.1-codex-max");
const s = stream(model, makeContext(), { reasoningEffort: "xhigh" });
@@ -42,7 +41,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY)("xhigh reasoning", () => {
const s = stream(model, makeContext(), { reasoningEffort: "xhigh" });
for await (const _ of s) {
- // drain events
}
const response = await s.result();
@@ -60,7 +58,6 @@ describe.skipIf(!process.env.OPENAI_API_KEY)("xhigh reasoning", () => {
const s = stream(model, makeContext(), { reasoningEffort: "xhigh" });
for await (const _ of s) {
- // drain events
}
const response = await s.result();
diff --git a/packages/coding-agent/examples/extensions/auto-commit-on-exit.ts b/packages/coding-agent/examples/extensions/auto-commit-on-exit.ts
index 58063e95c2..39447204ff 100644
--- a/packages/coding-agent/examples/extensions/auto-commit-on-exit.ts
+++ b/packages/coding-agent/examples/extensions/auto-commit-on-exit.ts
@@ -9,15 +9,12 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.on("session_shutdown", async (_event, ctx) => {
- // Check for uncommitted changes
const { stdout: status, code } = await pi.exec("git", ["status", "--porcelain"]);
if (code !== 0 || status.trim().length === 0) {
- // Not a git repo or no changes
return;
}
- // Find the last assistant message for commit context
const entries = ctx.sessionManager.getEntries();
let lastAssistantText = "";
for (let i = entries.length - 1; i >= 0; i--) {
@@ -34,11 +31,9 @@ export default function (pi: ExtensionAPI) {
}
}
- // Generate a simple commit message
const firstLine = lastAssistantText.split("\n")[0] || "Work in progress";
const commitMessage = `[pi] ${firstLine.slice(0, 50)}${firstLine.length > 50 ? "..." : ""}`;
- // Stage and commit
await pi.exec("git", ["add", "-A"]);
const { code: commitCode } = await pi.exec("git", ["commit", "-m", commitMessage]);
diff --git a/packages/coding-agent/examples/extensions/bookmark.ts b/packages/coding-agent/examples/extensions/bookmark.ts
index 3854b86e0d..302d133d93 100644
--- a/packages/coding-agent/examples/extensions/bookmark.ts
+++ b/packages/coding-agent/examples/extensions/bookmark.ts
@@ -15,7 +15,6 @@ export default function (pi: ExtensionAPI) {
handler: async (args, ctx) => {
const label = args.trim() || `bookmark-${Date.now()}`;
- // Find the last assistant message entry
const entries = ctx.sessionManager.getEntries();
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
@@ -30,7 +29,6 @@ export default function (pi: ExtensionAPI) {
},
});
- // Remove bookmark
pi.registerCommand("unbookmark", {
description: "Remove bookmark from last labeled entry",
handler: async (_args, ctx) => {
diff --git a/packages/coding-agent/examples/extensions/dirty-repo-guard.ts b/packages/coding-agent/examples/extensions/dirty-repo-guard.ts
index 5357464ef1..86874afdac 100644
--- a/packages/coding-agent/examples/extensions/dirty-repo-guard.ts
+++ b/packages/coding-agent/examples/extensions/dirty-repo-guard.ts
@@ -12,11 +12,9 @@ async function checkDirtyRepo(
ctx: ExtensionContext,
action: string,
): Promise<{ cancel: boolean } | undefined> {
- // Check for uncommitted changes
const { stdout, code } = await pi.exec("git", ["status", "--porcelain"]);
if (code !== 0) {
- // Not a git repo, allow the action
return;
}
@@ -26,11 +24,9 @@ async function checkDirtyRepo(
}
if (!ctx.hasUI) {
- // In non-interactive mode, block by default
return { cancel: true };
}
- // Count changed files
const changedFiles = stdout.trim().split("\n").filter(Boolean).length;
const choice = await ctx.ui.select(`You have ${changedFiles} uncommitted file(s). ${action} anyway?`, [
diff --git a/packages/coding-agent/examples/extensions/message-renderer.ts b/packages/coding-agent/examples/extensions/message-renderer.ts
index 9183d1ec6d..b5e0b08ace 100644
--- a/packages/coding-agent/examples/extensions/message-renderer.ts
+++ b/packages/coding-agent/examples/extensions/message-renderer.ts
@@ -11,30 +11,25 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Box, Text } from "@earendil-works/pi-tui";
export default function (pi: ExtensionAPI) {
- // Register custom renderer for "status-update" messages
pi.registerMessageRenderer("status-update", (message, { expanded }, theme) => {
const details = message.details as { level: string; timestamp: number } | undefined;
const level = details?.level ?? "info";
- // Color based on level
const color = level === "error" ? "error" : level === "warn" ? "warning" : "success";
const prefix = theme.fg(color, `[${level.toUpperCase()}]`);
let text = `${prefix} ${message.content}`;
- // Show timestamp when expanded
if (expanded && details?.timestamp) {
const time = new Date(details.timestamp).toLocaleTimeString();
text += `\n${theme.fg("dim", ` at ${time}`)}`;
}
- // Use Box with customMessageBg for consistent styling
const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
box.addChild(new Text(text, 0, 0));
return box;
});
- // Command to send status messages
pi.registerCommand("status", {
description: "Send a status message (usage: /status [warn|error] message)",
handler: async (args, _ctx) => {
@@ -42,7 +37,6 @@ export default function (pi: ExtensionAPI) {
let level = "info";
let content = args.trim();
- // Check for level prefix
if (parts[0] === "warn" || parts[0] === "error") {
level = parts[0];
content = parts.slice(1).join(" ") || "Status update";
diff --git a/packages/coding-agent/examples/extensions/model-status.ts b/packages/coding-agent/examples/extensions/model-status.ts
index 7dfa18bbbe..27fa2f8b2e 100644
--- a/packages/coding-agent/examples/extensions/model-status.ts
+++ b/packages/coding-agent/examples/extensions/model-status.ts
@@ -13,19 +13,15 @@ export default function (pi: ExtensionAPI) {
pi.on("model_select", async (event, ctx) => {
const { model, previousModel, source } = event;
- // Format model identifiers
const next = `${model.provider}/${model.id}`;
const prev = previousModel ? `${previousModel.provider}/${previousModel.id}` : "none";
- // Show notification on change
if (source !== "restore") {
ctx.ui.notify(`Model: ${next}`, "info");
}
- // Update status bar with current model
ctx.ui.setStatus("model", `🤖 ${model.id}`);
- // Log change details (visible in debug output)
console.log(`[model_select] ${prev} → ${next} (${source})`);
});
}
diff --git a/packages/coding-agent/scripts/migrate-sessions.sh b/packages/coding-agent/scripts/migrate-sessions.sh
index 53f50e5532..b71e72f737 100755
--- a/packages/coding-agent/scripts/migrate-sessions.sh
+++ b/packages/coding-agent/scripts/migrate-sessions.sh
@@ -1,9 +1,6 @@
#!/usr/bin/env bash
#
# Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.
-# This fixes sessions created by the bug in v0.30.0 where sessions were
-# saved to ~/.pi/agent/ instead of ~/.pi/agent/sessions/<encoded-cwd>/.
-#
# Usage: ./migrate-sessions.sh [--dry-run]
#
diff --git a/packages/coding-agent/src/cli/config-selector.ts b/packages/coding-agent/src/cli/config-selector.ts
index cfd825835c..f7bc30ae47 100644
--- a/packages/coding-agent/src/cli/config-selector.ts
+++ b/packages/coding-agent/src/cli/config-selector.ts
@@ -1,7 +1,3 @@
-/**
- * TUI config selector for `pi config` command
- */
-
import { ProcessTerminal, TUI } from "@earendil-works/pi-tui";
import type { ResolvedPaths } from "../core/package-manager.js";
import type { SettingsManager } from "../core/settings-manager.js";
@@ -15,9 +11,7 @@ export interface ConfigSelectorOptions {
agentDir: string;
}
-/** Show TUI config selector and return when closed */
export async function selectConfig(options: ConfigSelectorOptions): Promise<void> {
- // Initialize theme before showing TUI
initTheme(options.settingsManager.getTheme(), true);
return new Promise((resolve) => {
diff --git a/packages/coding-agent/src/cli/file-processor.ts b/packages/coding-agent/src/cli/file-processor.ts
index c9ab54950a..418ad173cd 100644
--- a/packages/coding-agent/src/cli/file-processor.ts
+++ b/packages/coding-agent/src/cli/file-processor.ts
@@ -1,7 +1,3 @@
-/**
- * Process @file CLI arguments into text content and image attachments
- */
-
import { access, readFile, stat } from "node:fs/promises";
import type { ImageContent } from "@earendil-works/pi-ai";
import chalk from "chalk";
@@ -16,21 +12,17 @@ export interface ProcessedFiles {
}
export interface ProcessFileOptions {
- /** Whether to auto-resize images to 2000x2000 max. Default: true */
autoResizeImages?: boolean;
}
-/** Process @file arguments into text content and image attachments */
export async function processFileArguments(fileArgs: string[], options?: ProcessFileOptions): Promise<ProcessedFiles> {
const autoResizeImages = options?.autoResizeImages ?? true;
let text = "";
const images: ImageContent[] = [];
for (const fileArg of fileArgs) {
- // Expand and resolve path (handles ~ expansion and macOS screenshot Unicode spaces)
const absolutePath = resolve(resolveReadPath(fileArg, process.cwd()));
- // Check if file exists
try {
await access(absolutePath);
} catch {
@@ -38,17 +30,14 @@ export async function processFileArguments(fileArgs: string[], options?: Process
process.exit(1);
}
- // Check if file is empty
const stats = await stat(absolutePath);
if (stats.size === 0) {
- // Skip empty files
continue;
}
const mimeType = await detectSupportedImageMimeTypeFromFile(absolutePath);
if (mimeType) {
- // Handle image file
const content = await readFile(absolutePath);
const base64Content = content.toString("base64");
@@ -77,14 +66,12 @@ export async function processFileArguments(fileArgs: string[], options?: Process
images.push(attachment);
- // Add text reference to image with optional dimension note
if (dimensionNote) {
text += `<file name="${absolutePath}">${dimensionNote}</file>\n`;
} else {
text += `<file name="${absolutePath}"></file>\n`;
}
} else {
- // Handle text file
try {
const content = await readFile(absolutePath, "utf-8");
text += `<file name="${absolutePath}">\n${content}\n</file>\n`;
diff --git a/packages/coding-agent/src/cli/list-models.ts b/packages/coding-agent/src/cli/list-models.ts
index a3d04a480b..6228a0e10e 100644
--- a/packages/coding-agent/src/cli/list-models.ts
+++ b/packages/coding-agent/src/cli/list-models.ts
@@ -1,16 +1,9 @@
-/**
- * List available models with optional fuzzy search
- */
-
import type { Api, Model } from "@earendil-works/pi-ai";
import { fuzzyFilter } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { formatNoModelsAvailableMessage } from "../core/auth-guidance.js";
import type { ModelRegistry } from "../core/model-registry.js";
-/**
- * Format a number as human-readable (e.g., 200000 -> "200K", 1000000 -> "1M")
- */
function formatTokenCount(count: number): string {
if (count >= 1_000_000) {
const millions = count / 1_000_000;
@@ -23,9 +16,6 @@ function formatTokenCount(count: number): string {
return count.toString();
}
-/**
- * List available models, optionally filtered by search pattern
- */
export async function listModels(modelRegistry: ModelRegistry, searchPattern?: string): Promise<void> {
const loadError = modelRegistry.getError();
if (loadError) {
@@ -39,7 +29,6 @@ export async function listModels(modelRegistry: ModelRegistry, searchPattern?: s
return;
}
- // Apply fuzzy filter if search pattern provided
let filteredModels: Model<Api>[] = models;
if (searchPattern) {
filteredModels = fuzzyFilter(models, searchPattern, (m) => `${m.provider} ${m.id}`);
@@ -50,14 +39,12 @@ export async function listModels(modelRegistry: ModelRegistry, searchPattern?: s
return;
}
- // Sort by provider, then by model id
filteredModels.sort((a, b) => {
const providerCmp = a.provider.localeCompare(b.provider);
if (providerCmp !== 0) return providerCmp;
return a.id.localeCompare(b.id);
});
- // Calculate column widths
const rows = filteredModels.map((m) => ({
provider: m.provider,
model: m.id,
@@ -85,7 +72,6 @@ export async function listModels(modelRegistry: ModelRegistry, searchPattern?: s
images: Math.max(headers.images.length, ...rows.map((r) => r.images.length)),
};
- // Print header
const headerLine = [
headers.provider.padEnd(widths.provider),
headers.model.padEnd(widths.model),
@@ -96,7 +82,6 @@ export async function listModels(modelRegistry: ModelRegistry, searchPattern?: s
].join(" ");
console.log(headerLine);
- // Print rows
for (const row of rows) {
const line = [
row.provider.padEnd(widths.provider),
diff --git a/packages/coding-agent/src/config.ts b/packages/coding-agent/src/config.ts
index b709ab10e9..aff8d08395 100644
--- a/packages/coding-agent/src/config.ts
+++ b/packages/coding-agent/src/config.ts
@@ -422,21 +422,11 @@ export function getPackageJsonPath(): string {
return join(getPackageDir(), "package.json");
}
-/** Get path to README.md */
-export function getReadmePath(): string {
- return resolve(join(getPackageDir(), "README.md"));
-}
-
/** Get path to docs directory */
export function getDocsPath(): string {
return resolve(join(getPackageDir(), "docs"));
}
-/** Get path to examples directory */
-export function getExamplesPath(): string {
- return resolve(join(getPackageDir(), "examples"));
-}
-
/** Get path to CHANGELOG.md */
export function getChangelogPath(): string {
return resolve(join(getPackageDir(), "CHANGELOG.md"));
@@ -609,41 +599,21 @@ export function appendRotatingLog(logPath: string, message: string, maxBytes: nu
}
}
-/** Get path to models.json */
-export function getModelsPath(): string {
- return join(getAgentDir(), "models.json");
-}
-
/** Get path to auth.json */
export function getAuthPath(): string {
return join(getAgentDir(), "auth.json");
}
-/** Get path to settings.json */
-export function getSettingsPath(): string {
- return join(getAgentDir(), "settings.json");
-}
-
/** Get path to cron jobs store */
export function getCronJobsPath(agentDir: string = getAgentDir()): string {
return join(agentDir, "cron-jobs.json");
}
-/** Get path to tools directory */
-export function getToolsDir(): string {
- return join(getAgentDir(), "tools");
-}
-
/** Get path to managed binaries directory (fd, rg) */
export function getBinDir(): string {
return join(getAgentDir(), "bin");
}
-/** Get path to prompt templates directory */
-export function getPromptsDir(): string {
- return join(getAgentDir(), "prompts");
-}
-
/** Get path to sessions directory */
export function getSessionsDir(agentDir: string = getAgentDir()): string {
const envDir = getSessionDirEnvOverride();
diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.ts
index a030c98ef9..b2cc572a2d 100644
--- a/packages/coding-agent/src/core/agent-messages.ts
+++ b/packages/coding-agent/src/core/agent-messages.ts
@@ -141,9 +141,9 @@ export interface AgentSessionMessageReceipt {
message: string;
// Not named "status": the kernel host bridge envelope reserves that key.
deliveryStatus: AgentSessionMessageDeliveryStatus;
- /** Present when deliveryStatus is "delivered": the message reached the target's context. */
+ /** Present only for delivered messages: when the target context received it. */
deliveredAt?: string;
- /** Present when deliveryStatus is "queued": the message waits behind the target's current work. */
+ /** Present only for queued messages: when it was placed behind current work. */
queuedAt?: string;
deliveryMode?: "steer";
}
diff --git a/packages/coding-agent/src/core/agent-session-config.ts b/packages/coding-agent/src/core/agent-session-config.ts
index 79d8370149..40ed3a1702 100644
--- a/packages/coding-agent/src/core/agent-session-config.ts
+++ b/packages/coding-agent/src/core/agent-session-config.ts
@@ -35,9 +35,7 @@ export interface AgentSessionRuntimeConfig {
* so it survives the appMode="daemon" context switch.
*/
serializedRefine?: boolean;
- /** User-facing client mode that created this session. The daemon is transport, not an execution mode. */
executionMode?: AgentExecutionMode;
- /** Opt-out-only policy carried across daemon process boundaries. */
telemetryDisabled?: true;
/**
* Initial goal to seed when creating a new top-level session (rlmDepth 0).
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index 198b628f9b..6f1428474e 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -20,24 +20,11 @@ import { SessionManager } from "./session-manager.js";
export { SessionImportFileNotFoundError } from "./session-import-errors.js";
-/**
- * Result returned by runtime creation.
- *
- * The caller gets the created session, its cwd-bound services, and all
- * diagnostics collected during setup.
- */
export interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {
services: AgentSessionServices;
diagnostics: AgentSessionRuntimeDiagnostic[];
}
-/**
- * Creates a full runtime for a target cwd and session manager.
- *
- * The factory closes over process-global fixed inputs, recreates cwd-bound
- * services for the effective cwd, resolves session options against those
- * services, and finally creates the AgentSession.
- */
export type CreateAgentSessionRuntimeFactory = (options: {
cwd: string;
agentDir: string;
@@ -57,10 +44,8 @@ export interface AgentSessionRuntimeMetadata {
parentSessionFile?: string;
rlmChildId?: string;
rlmParentNodeId?: string;
- /** Runtime restored from an already-persisted completed registry entry. */
rehydratedCompleted?: boolean;
prompt?: string;
- /** Source of the IPython cell that spawned this subagent, for display. */
spawnCode?: string;
sessionDir?: string;
}
@@ -76,13 +61,6 @@ function extractUserMessageText(content: string | Array<{ type: string; text?: s
.join("");
}
-/**
- * Owns the current AgentSession plus its cwd-bound services.
- *
- * Session replacement methods tear down the current runtime first, then create
- * and apply the next runtime. If creation fails, the error is propagated to the
- * caller. The caller is responsible for user-facing error handling.
- */
export class AgentSessionRuntime implements SubagentRuntimeHost {
private rebindSession?: (session: AgentSession) => Promise<void>;
private readonly sessionReplacedListeners = new Set<(session: AgentSession) => void | Promise<void>>();
@@ -751,12 +729,6 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
}
}
-/**
- * Create the initial runtime from a runtime factory and initial session target.
- *
- * The same factory is stored on the returned AgentSessionRuntime and reused for
- * later /new, resume, /fork, and import flows.
- */
export async function createAgentSessionRuntime(
createRuntime: CreateAgentSessionRuntimeFactory,
options: {
diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.ts
index 1e9df16b20..20186b5102 100644
--- a/packages/coding-agent/src/core/agent-session-services.ts
+++ b/packages/coding-agent/src/core/agent-session-services.ts
@@ -20,25 +20,11 @@ import type { SessionManager } from "./session-manager.js";
import { SettingsManager } from "./settings-manager.js";
import { installAgentTelemetry, isTelemetryEnabled } from "./telemetry.js";
-/**
- * Non-fatal issues collected while creating services or sessions.
- *
- * Runtime creation returns diagnostics to the caller instead of printing or
- * exiting. The app layer decides whether warnings should be shown and whether
- * errors should abort startup.
- */
export interface AgentSessionRuntimeDiagnostic {
type: "info" | "warning" | "error";
message: string;
}
-/**
- * Inputs for creating cwd-bound runtime services.
- *
- * These services are recreated whenever the effective session cwd changes.
- * CLI-provided resource paths should be resolved to absolute paths before they
- * reach this function, so later cwd switches do not reinterpret them.
- */
export interface CreateAgentSessionServicesOptions {
cwd: string;
agentDir?: string;
@@ -54,14 +40,12 @@ export interface CreateAgentSessionServicesOptions {
* would release the pane while the parent is still running.
*/
noBuiltinHerdrReporter?: boolean;
- /** Explicit daemon-carried opt-out; cannot enable telemetry. */
telemetryDisabled?: true;
}
export interface AgentSessionCreationOptions {
model?: Model<any>;
thinkingLevel?: ThinkingLevel;
- /** Provider service tier. Fast mode uses "priority". */
serviceTier?: ServiceTier;
scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
tools?: string[];
@@ -82,34 +66,18 @@ export interface AgentSessionCreationOptions {
rlmHeartbeatController?: AgentRlmHeartbeatController;
prewarmIpythonKernel?: boolean;
autonomous?: AgentAutonomousConfig;
- /** Serialized refine mode for print/headless autonomous runs. */
serializedRefine?: boolean;
- /** User-facing client mode that created the top-level session. */
executionMode?: AgentExecutionMode;
- /** Explicit daemon-carried opt-out; cannot enable telemetry. */
telemetryDisabled?: true;
- /** Initial goal to seed at session creation (rlmDepth 0 only, idempotent). */
initialGoal?: { objective: string; tokenBudget?: number };
}
-/**
- * Inputs for creating an AgentSession from already-created services.
- *
- * Use this after services exist and any cwd-bound model/tool/session options
- * have been resolved against those services.
- */
export interface CreateAgentSessionFromServicesOptions extends AgentSessionCreationOptions {
services: AgentSessionServices;
sessionManager: SessionManager;
sessionStartEvent?: SessionStartEvent;
}
-/**
- * Coherent cwd-bound runtime services for one effective session cwd.
- *
- * This is infrastructure only. The AgentSession itself is created separately so
- * session options can be resolved against these services first.
- */
export interface AgentSessionServices {
cwd: string;
agentDir: string;
@@ -169,11 +137,6 @@ function applyExtensionFlagValues(
return diagnostics;
}
-/**
- * Create cwd-bound runtime services.
- *
- * Returns services plus diagnostics. It does not create an AgentSession.
- */
export async function createAgentSessionServices(
options: CreateAgentSessionServicesOptions,
): Promise<AgentSessionServices> {
@@ -254,13 +217,6 @@ export async function createAgentSessionServices(
};
}
-/**
- * Create an AgentSession from previously created services.
- *
- * This keeps session creation separate from service creation so callers can
- * resolve model, thinking, tools, and other session inputs against the target
- * cwd before constructing the session.
- */
export async function createAgentSessionFromServices(
options: CreateAgentSessionFromServicesOptions,
): Promise<CreateAgentSessionResult> {
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index a2f9c85b1e..d82129e2a7 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -1,18 +1,3 @@
-/**
- * AgentSession - Core abstraction for agent lifecycle and session management.
- *
- * This class is shared between all run modes (interactive, print, rpc).
- * It encapsulates:
- * - Agent state access
- * - Event subscription with automatic session persistence
- * - Model and thinking level management
- * - Compaction (manual and auto)
- * - Bash execution
- * - Session switching and branching
- *
- * Modes use this class and add their own I/O layer on top.
- */
-
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
@@ -291,31 +276,23 @@ export interface RlmChildAgentSnapshot {
id: string;
parentId?: string;
activeSessionId?: string;
- /** Stable daemon-visible session name for addressing/displaying the child. */
sessionName?: string;
- /** Exact provider/model selector used by the child. */
model?: string;
label: string;
status: RlmChildAgentStatus;
durationMs?: number;
answerPreview?: string;
- /** Number of tool executions the subagent has started so far. */
toolUseCount?: number;
- /** Context size (tokens) of the subagent's latest turn. */
tokenCount?: number;
- /** Latest recap of what the subagent is doing, from the summarizer. */
recap?: string;
sessionDir: string;
activity?: RlmChildAgentActivity;
- /** Child sent at least one explicit agent message since task admission. */
repliedSinceTask?: boolean;
- /** Failure reason when status is "error". */
error?: string;
}
export type CompactionReason = "manual" | "threshold" | "overflow" | "requested";
-/** Session-specific events that extend the core AgentEvent */
export type AgentSessionEvent =
| AgentEvent
| {
@@ -339,7 +316,6 @@ export type AgentSessionEvent =
aborted: boolean;
willRetry: boolean;
errorMessage?: string;
- /** "warning" for benign skips (nothing to compact), "error" for real failures */
errorSeverity?: "warning" | "error";
customInstructions?: string;
}
@@ -378,20 +354,15 @@ export type AgentSessionEvent =
cancelled: boolean;
truncated: boolean;
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 };
-/** Listener function for agent session events */
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
-/** Payload of the bash_end event for a user-initiated bash command */
type UserBashEndDetails = {
exitCode: number | undefined;
cancelled: boolean;
@@ -400,32 +371,20 @@ type UserBashEndDetails = {
errorMessage?: string;
};
-/** Thrown when compaction is skipped for a benign reason (surfaced as a warning, not an error) */
export class CompactionSkippedError extends Error {}
-// ============================================================================
-// Types
-// ============================================================================
-
export interface AgentSessionConfig {
agent: Agent;
sessionManager: SessionManager;
settingsManager: SettingsManager;
serviceTierPreference?: ServiceTier;
cwd: string;
- /** Config dir backing credentials (auth.json); exported to the kernel for skills. */
agentDir?: string;
- /** Models to cycle through with Ctrl+P (from --models flag) */
scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
- /** Resource loader for skills, prompts, themes, context files, system prompt */
resourceLoader: ResourceLoader;
- /** SDK custom tools registered outside extensions */
customTools?: ToolDefinition[];
- /** Model registry for API key resolution and model discovery */
modelRegistry: ModelRegistry;
- /** Initial active built-in tool names. Default: [ipython] */
initialActiveToolNames?: string[];
- /** Optional allowlist of tool names. When provided, only these tool names are exposed. */
allowedToolNames?: string[];
/**
* Whether the built-in long-running goals feature is available: the bundled
@@ -433,9 +392,7 @@ export interface AgentSessionConfig {
* Default: true.
*/
includeGoals?: boolean;
- /** Daemon-backed agent-to-agent messaging bridge. Omitted for local-only sessions. */
agentMessageController?: AgentSessionMessageController;
- /** Daemon-backed read-only active-session observation bridge. Omitted for local-only sessions. */
agentObserveController?: AgentObserveController;
/**
* Whether the bundled compact skill and its compact.* host handlers are
@@ -459,32 +416,16 @@ export interface AgentSessionConfig {
* a definition-first registry even when callers provide plain AgentTool instances.
*/
baseToolsOverride?: Record<string, AgentTool>;
- /** Mutable ref used by Agent to access the current ExtensionRunner */
extensionRunnerRef?: { current?: ExtensionRunner };
- /** Session start event metadata emitted when extensions bind to this runtime. */
sessionStartEvent?: SessionStartEvent;
- /** Current RLM recursion depth. Root sessions default to RLM_DEPTH or 0. */
rlmDepth?: number;
- /** Maximum RLM recursion depth. Defaults to RLM_MAX_DEPTH or 1. */
rlmMaxDepth?: number;
- /** Directory exposed to the kernel as RLM_SESSION_DIR. */
rlmSessionDir?: string;
- /** Node id for this session when it is itself an RLM child. */
rlmParentNodeId?: string;
- /** Parent agent name/id shown in child communication doctrine. */
rlmParentAgent?: string;
- /** Host responsible for creating RLM subagent runtimes. */
subagentRuntimeHost?: SubagentRuntimeHost;
- /** Host-side autonomous continuation policy. */
autonomous?: AgentAutonomousConfig;
- /**
- * Boot the IPython kernel in the background as soon as the session is created,
- * so the first ipython tool call doesn't pay the kernel cold start.
- *
- * Only applies to main agents (rlmDepth 0); subagent kernels stay lazy. Default: false.
- */
prewarmIpythonKernel?: boolean;
- /** Test/extension hook for automatic refine review decisions. Defaults to the model-backed review gate. */
autoRefineReviewer?: AutoRefineReviewer;
/**
* When true, auto-refine runs synchronously between turns at the
@@ -532,42 +473,26 @@ export type SerializedBackgroundPlanResult =
| { status: "invalidated"; branchVersion: number }
| {
status: "failure";
- /** True when the background plan was for an explicit refine.run (skipReview). */
explicit: boolean;
- /** Original options for the failed plan, to allow re-queue on explicit failure. */
options: { instructions?: string; rollbackId?: string; global?: boolean };
branchVersion: number;
};
export type AutoRefineReviewer = (request: AutoRefineReviewRequest, signal?: AbortSignal) => Promise<AutoRefineReview>;
-/** Options for AgentSession.prompt() */
export interface PromptOptions {
- /** Whether to expand file-based prompt templates (default: true) */
expandPromptTemplates?: boolean;
- /** Image attachments */
images?: ImageContent[];
- /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
streamingBehavior?: "steer" | "followUp";
- /** Coalesce follow-up queueing so only one pending follow-up exists for this key. */
followUpQueueKey?: string;
- /** Source of input for extension input event handlers. Defaults to "interactive". */
source?: InputSource;
- /** Internal hook used by RPC mode to observe prompt preflight acceptance or rejection. */
preflightResult?: (success: boolean, queued?: boolean) => void;
- /** Queue instead of starting immediately when the session is idle but already has queued work. */
queueIfBusy?: boolean;
- /** Start queued work when no agent turn is currently running. */
resumeIfIdle?: boolean;
- /** Host-generated prompt that must bypass extension/slash/template input interception. */
internalPrompt?: boolean;
- /** Prevent host-driven prompts from causing autonomous continuation injection. */
suppressAutonomousContinuation?: boolean;
- /** Skip extension input handlers for replaying already-accepted input. */
skipInputHandlers?: boolean;
- /** Cancel this prompt while it is waiting for direct-turn admission. */
signal?: AbortSignal;
- /** Internal host hook fired at the direct-turn ownership commit point. */
admissionCommitted?: () => void;
agentMessageId?: string;
content?: (TextContent | ImageContent)[];
@@ -668,13 +593,11 @@ type QueuedSessionAction = SessionAction<PreparedTurnPayload | PreparedCommandPa
interface PreparedPromptPreparation {
result: Awaited<ReturnType<ExtensionRunner["emitBeforeAgentStart"]>>;
- /** Base system prompt captured at emitBeforeAgentStart, for stale-base refresh at handoff. */
basePromptSnapshot: string;
}
class DeferredSessionInputError extends Error {}
-/** Wrap a preflight callback so only the first report wins. */
function oncePreflight(
preflightResult: ((success: boolean, queued?: boolean) => void) | undefined,
): (success: boolean, queued?: boolean) => void {
@@ -874,10 +797,6 @@ interface AgentMessageDeferred {
reject: (error: Error) => void;
}
-/**
- * Per-agent-message settlement record: `delivery` settles when the prompt reaches agent state,
- * `completion` when its turn (or command) finishes. Settled deferreds are removed immediately.
- */
interface AgentMessageOutcome {
delivery?: AgentMessageDeferred;
completion?: AgentMessageDeferred;
@@ -893,12 +812,10 @@ function createAgentMessageDeferred(): AgentMessageDeferred {
return deferred;
}
-/** Result from cycleModel() */
export interface ModelCycleResult {
model: Model<any>;
thinkingLevel: ThinkingLevel;
serviceTier: ServiceTier;
- /** Whether cycling through scoped models (--models flag) or all available */
isScoped: boolean;
}
@@ -942,15 +859,10 @@ interface RlmChildRun {
error?: string;
abort: () => void;
publication: AgentMessageDeferred;
- /** Child session, once its runtime exists. Used to cancel nested child runs. */
session?: AgentSession;
- /** True once the detached run task has finished its catch and cleanup paths. */
settled: boolean;
- /** Selector snapshot for a delete admitted while runtime startup was still pending. */
detachedDeletion?: RlmSubagentRegistryEntry;
- /** Re-emits the run's rlm_child_update snapshot with its current status. */
emitUpdate?: () => void;
- /** Idempotent child-event forwarder cleanup, once the child runtime exists. */
unsubscribe?: () => void;
}
@@ -958,14 +870,8 @@ interface RlmSubagentModelSelection {
model: Model<Api>;
}
-// ============================================================================
-// Constants
-// ============================================================================
-
-/** Standard thinking levels */
const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
-/** Cap on the post-compaction kernel namespace probe so a wedged kernel can't stall recovery. */
const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;
const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";
@@ -1077,10 +983,6 @@ function attributeChildUsage(parentUsage: Usage, childUsage: Usage): void {
parentUsage.totalTokens = parentContextTokens;
}
-// ============================================================================
-// AgentSession Class
-// ============================================================================
-
export class AgentSession {
readonly agent: Agent;
readonly sessionManager: SessionManager;
@@ -1092,7 +994,6 @@ export class AgentSession {
thinkingLevel?: ThinkingLevel;
}>;
- // Event subscription state
private _unsubscribeAgent?: () => void;
private _eventListeners: AgentSessionEventListener[] = [];
private _lastSessionActionSnapshot: SessionActionSnapshot = {
@@ -1105,7 +1006,6 @@ export class AgentSession {
/** Session-owned actions. Items are never fed into Agent.steer/followUp. */
private readonly _actionStore = new ActionStore<QueuedSessionAction>();
private _sessionInputPump: Promise<void> = Promise.resolve();
- // Coalesces wakes so overlapping submissions cannot start competing pumps.
private _sessionInputPumpRequested = false;
// Invalidates preparation when a branch pause starts and finishes before its next await resumes.
private _sessionInputPumpEpoch = 0;
@@ -1121,7 +1021,6 @@ export class AgentSession {
private readonly _sessionActionCommitDisposeAbortController = new AbortController();
// Checkpoint and handoff waiters share lifecycle-edge notifications to avoid polling.
private readonly _sessionInputCheckpointWaiters = new Set<() => void>();
- /** Messages queued to be included with the next user prompt as context ("asides"). */
private _pendingNextTurnMessages: CustomMessage[] = [];
private _goalState: GoalState = emptyGoalState();
@@ -1132,7 +1031,6 @@ export class AgentSession {
private _autonomousContinuationSuppressionDepth = 0;
private _autonomousContinuationSuppressedMessages = new WeakSet<AgentMessage>();
- // Compaction state
private _compactionAbortController: AbortController | undefined = undefined;
private _autoCompactionAbortController: AbortController | undefined = undefined;
private _compactionOperation: Promise<void> | undefined = undefined;
@@ -1142,11 +1040,9 @@ export class AgentSession {
private _pendingRequestedCompaction: { customInstructions?: string } | undefined;
private _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;
- // Branch summarization state
private _branchSummaryAbortController: AbortController | undefined = undefined;
private _branchSummaryOperation: Promise<void> | undefined = undefined;
- // Retry state
private _retryAbortController: AbortController | undefined = undefined;
private _retryAttempt = 0;
private _retryPromise: Promise<void> | undefined = undefined;
@@ -1157,13 +1053,11 @@ export class AgentSession {
/** Outcome disclosures whose session-file append failed; retained for context rebuilds. */
private readonly _unpersistedCompactionOutcomes: CustomMessage[] = [];
- // Bash execution state
private _bashAbortController: AbortController | undefined = undefined;
private _userBashRunning = false;
private _userBashAbortRequested = false;
private _pendingBashMessages: BashExecutionMessage[] = [];
- // Extension system
private _extensionRunner!: ExtensionRunner;
private _execEnvProvider?: () => Record<string, string | undefined> | undefined;
private _turnIndex = 0;
@@ -1237,16 +1131,13 @@ export class AgentSession {
/** Latest recap for this session, written by the daemon summarizer; read by a parent to label its child snapshots. */
private _currentRecap?: string;
- // Model registry for API key resolution
private _modelRegistry: ModelRegistry;
- // Tool registry for extension getTools/setTools
private _toolRegistry: Map<string, AgentTool> = new Map();
private _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();
private _toolPromptSnippets: Map<string, string> = new Map();
private _toolPromptGuidelines: Map<string, string[]> = new Map();
- // Base system prompt (without extension appends) - used to apply fresh appends each turn
private _baseSystemPrompt = "";
private _baseSystemPromptOptions!: BuildSystemPromptOptions;
private _assistantTurnsSinceAutoRefine = 0;
@@ -1269,17 +1160,9 @@ export class AgentSession {
private _autoRefineReviewAbort?: AbortController;
private _refineAbortController?: AbortController;
private readonly _autoRefineReviewer?: AutoRefineReviewer;
- /** When true, auto-refine runs synchronously between turns (serialized mode). */
private readonly _serializedRefine: boolean;
- /** Settles (never rejects) after a planned refine waits for idle and finishes applying. */
private _refineInFlight?: Promise<void>;
- /** Settles when the background planning LLM pass completes. Planning does not block turn entry points. */
private _refinePlanInFlight?: Promise<void>;
- /**
- * Settles when a serialized-mode background planning pass completes.
- * Planning starts at assistant message_end (overlapping tool execution)
- * and is awaited at shouldStopAfterTurn before applying.
- */
private _serializedPlanInFlight?: Promise<SerializedBackgroundPlanResult | undefined>;
private _serializedPlanClaim?: Promise<void>;
private _serializedExplicitRefineOptions?: {
@@ -1353,8 +1236,6 @@ export class AgentSession {
this._goalAccountingStartedAt = Date.now();
}
- // Always subscribe to agent events for internal handling
- // (session persistence, extensions, auto-compaction, retry logic)
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
this._installAgentToolHooks();
this._installAgentTurnHook();
@@ -1384,7 +1265,6 @@ export class AgentSession {
this.agent.state.systemPrompt = this._baseSystemPrompt;
}
- /** Model registry for API key resolution and model discovery */
get modelRegistry(): ModelRegistry {
return this._modelRegistry;
}
@@ -1484,11 +1364,6 @@ export class AgentSession {
this.agent.shouldStopAfterTurn = (context) => this._shouldStopAfterTurn(context);
}
- // =========================================================================
- // Event Subscription
- // =========================================================================
-
- /** Emit an event to all listeners */
private _emit(event: AgentSessionEvent): void {
for (const l of this._eventListeners) {
try {
@@ -2003,7 +1878,6 @@ export class AgentSession {
return true;
}
- /** Append custom messages returned by before_agent_start extension handlers. */
private _appendBeforeAgentStartMessages(
messages: AgentMessage[],
result: Awaited<ReturnType<ExtensionRunner["emitBeforeAgentStart"]>>,
@@ -2242,7 +2116,6 @@ export class AgentSession {
}
if (bgResult?.status === "plan") {
- // Fix 4: Validate branchVersion before applying the plan.
if (bgResult.branchVersion !== this._autoRefineBranchVersion) {
if (!this._pendingRequestedRefine) {
this._lastAutoRefineReviewAt = Date.now();
@@ -2276,9 +2149,8 @@ export class AgentSession {
}
if (bgResult?.status === "failure") {
- // Fix 3: Background review or planning failed. Stamp cooldown
- // without a synchronous retry (the discriminated contract says no duplicate boundary
- // model call). A separately queued refine.run may still be serviced below.
+ // Background review or planning failure stamps cooldown without a synchronous retry.
+ // A separately queued refine.run may still be serviced below.
if (branchVersion === this._autoRefineBranchVersion) {
this._lastAutoRefineReviewAt = Date.now();
}
@@ -2377,7 +2249,6 @@ export class AgentSession {
await this._runSerializedAutoRefineReview("turn_interval", branchVersion);
}
- /** Run automatic review and, when approved, refinement at a serialized turn boundary. */
private async _runSerializedAutoRefineReview(
reason: "compact" | "turn_interval",
branchVersion: number,
@@ -2494,7 +2365,7 @@ export class AgentSession {
return;
}
- // Bug 4 fix: Also start background planning for a pending agent-callable
+ // Start background planning for a pending agent-callable
// refine.run request, so its plan is ready at the shouldStopAfterTurn
// boundary. The pending request is consumed (cleared) here so the
// boundary doesn't re-plan it. Explicit refine.run skips the review gate.
@@ -3302,7 +3173,6 @@ export class AgentSession {
return autonomousMessage ? [autonomousMessage] : [];
}
- // Track last assistant message for auto-compaction check
private _lastAssistantMessage: AssistantMessage | undefined = undefined;
private _agentMessageOutcome(agentMessageId: string): AgentMessageOutcome {
@@ -3324,7 +3194,6 @@ export class AgentSession {
return outcome.delivery.promise;
}
- /** Resolve (no error) or reject an existing leg of an agent message outcome. */
private _settleAgentMessage(
agentMessageId: string | undefined,
leg: "delivery" | "completion",
@@ -3343,7 +3212,6 @@ export class AgentSession {
else deferred.resolve();
}
- /** Reject both currently registered legs of an agent message outcome. */
private _rejectAgentMessage(agentMessageId: string | undefined, error: Error): void {
if (agentMessageId === undefined) return;
this._settleAgentMessage(agentMessageId, "delivery", error);
@@ -3379,7 +3247,6 @@ export class AgentSession {
);
}
- /** Internal handler for agent events - shared by subscribe and reconnect */
private _handleAgentEvent = (event: AgentEvent): void => {
this._createRetryPromiseForAgentEnd(event);
if (event.type === "message_start" || event.type === "message_end") {
@@ -3536,7 +3403,6 @@ export class AgentSession {
this._overflowRecovery = "idle";
}
- // Emit to extensions first
await this._emitExtensionEvent(event);
if (event.type === "message_start" || event.type === "message_end") {
const cleared = this._capturingCancelledAction(event.message);
@@ -3549,14 +3415,10 @@ export class AgentSession {
this._addLoginGuidanceToAuthError(event);
- // Notify all listeners
this._emit(event);
- // Handle session persistence
if (event.type === "message_end") {
- // Check if this is a custom message from extensions
if (event.message.role === "custom") {
- // Persist as CustomMessageEntry
this.sessionManager.appendCustomMessageEntry(
event.message.customType,
event.message.content,
@@ -3568,12 +3430,9 @@ export class AgentSession {
event.message.role === "assistant" ||
event.message.role === "toolResult"
) {
- // Regular LLM message - persist as SessionMessageEntry
this.sessionManager.appendMessage(event.message);
}
- // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
- // Track assistant message for auto-compaction (checked on agent_end)
if (event.message.role === "assistant") {
this._lastAssistantMessage = event.message;
@@ -3623,7 +3482,6 @@ export class AgentSession {
return;
}
- // Check auto-retry and auto-compaction after agent completes
if (event.type === "agent_end") {
const msg =
this._lastAssistantMessage ??
@@ -3634,7 +3492,6 @@ export class AgentSession {
return;
}
- // Check for retryable errors first (overloaded, rate limit, server errors)
const concreteAuthFailure = this._isConcreteProviderAuthFailure(msg);
const retryConcreteAuthFailure =
concreteAuthFailure && !this._isStructuredPermanentProviderRetryExhausted(msg);
@@ -3677,7 +3534,6 @@ export class AgentSession {
);
}
- /** Resolve the pending retry promise */
private _resolveRetry(): void {
if (this._retryResolve) {
this._retryResolve();
@@ -3687,7 +3543,6 @@ export class AgentSession {
}
}
- /** Find the last assistant message in agent state (including aborted ones) */
private _findLastAssistantMessage(): AssistantMessage | undefined {
const messages = this.agent.state.messages;
for (let i = messages.length - 1; i >= 0; i--) {
@@ -3715,7 +3570,6 @@ export class AgentSession {
Object.assign(targetRecord, replacement);
}
- /** Emit extension events based on agent events */
private async _emitExtensionEvent(event: AgentEvent): Promise<void> {
if (event.type === "agent_start") {
this._turnIndex = 0;
@@ -3803,7 +3657,6 @@ export class AgentSession {
subscribe(listener: AgentSessionEventListener): () => void {
this._eventListeners.push(listener);
- // Return unsubscribe function for this specific listener
return () => {
const index = this._eventListeners.indexOf(listener);
if (index !== -1) {
@@ -3888,9 +3741,7 @@ export class AgentSession {
} else if (this._refinePlanInFlight) {
await this._refinePlanInFlight;
} else if (this._serializedPlanInFlight) {
- // Fix 5: Await the background plan and apply a ready "plan"
- // result before teardown so the refinement is persisted.
- // Do NOT discard a ready plan.
+ // Await the background plan and apply a ready "plan" result before teardown.
await this._consumeSerializedBackgroundPlan(async (bgResult) => {
if (bgResult?.status === "plan" && bgResult.branchVersion === this._autoRefineBranchVersion) {
try {
@@ -4108,21 +3959,14 @@ export class AgentSession {
this._disposeCallbacks.add(callback);
}
- // =========================================================================
- // Read-only State Access
- // =========================================================================
-
- /** Full agent state */
get state(): AgentState {
return this.agent.state;
}
- /** Current model (may be undefined if not yet selected) */
get model(): Model<any> | undefined {
return this.agent.state.model;
}
- /** Current thinking level */
get thinkingLevel(): ThinkingLevel {
return this.agent.state.thinkingLevel;
}
@@ -4131,32 +3975,22 @@ export class AgentSession {
return this.agent.state.serviceTier;
}
- /** Whether agent is currently streaming a response */
get isStreaming(): boolean {
return this.agent.state.isStreaming;
}
- /** Current effective system prompt (includes any per-turn extension modifications) */
get systemPrompt(): string {
return this.agent.state.systemPrompt;
}
- /** Current retry attempt (0 if not retrying) */
get retryAttempt(): number {
return this._retryAttempt;
}
- /**
- * Get the names of currently active tools.
- * Returns the names of tools currently set on the agent.
- */
getActiveToolNames(): string[] {
return this.agent.state.tools.map((t) => t.name);
}
- /**
- * Get all configured tools with name, description, parameter schema, and source metadata.
- */
getAllTools(): ToolInfo[] {
return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
name: definition.name,
@@ -4170,12 +4004,6 @@ export class AgentSession {
return this._toolDefinitions.get(name)?.definition;
}
- /**
- * Set active tools by name.
- * Only tools in the registry can be enabled. Unknown tool names are ignored.
- * Also rebuilds the system prompt to reflect the new tool set.
- * Changes take effect on the next agent turn.
- */
setActiveToolsByName(toolNames: string[]): void {
const tools: AgentTool[] = [];
const validToolNames: string[] = [];
@@ -4193,12 +4021,10 @@ export class AgentSession {
}
this.agent.state.tools = tools;
- // Rebuild base system prompt with new tool set
this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
this.agent.state.systemPrompt = this._baseSystemPrompt;
}
- /** Whether compaction or branch summarization is currently running */
get isCompacting(): boolean {
return (
this._autoCompactionAbortController !== undefined ||
@@ -4207,7 +4033,6 @@ export class AgentSession {
);
}
- /** All messages including custom types like BashExecutionMessage */
get messages(): AgentMessage[] {
return this.agent.state.messages;
}
@@ -4221,10 +4046,6 @@ export class AgentSession {
return context;
}
- /**
- * Merge disclosures whose session-file append failed into a rebuilt message
- * list at their timestamp position, where they appeared live.
- */
private _mergeUnpersistedCompactionOutcomes(messages: AgentMessage[]): void {
for (const outcome of this._unpersistedCompactionOutcomes) {
let insertAt = messages.length;
@@ -4235,37 +4056,30 @@ export class AgentSession {
}
}
- /** Current steering mode */
get steeringMode(): "all" | "one-at-a-time" {
return this.agent.steeringMode;
}
- /** Current follow-up mode */
get followUpMode(): "all" | "one-at-a-time" {
return this.agent.followUpMode;
}
- /** Current session file path, or undefined if sessions are disabled */
get sessionFile(): string | undefined {
return this.sessionManager.getSessionFile();
}
- /** Current session ID */
get sessionId(): string {
return this.sessionManager.getSessionId();
}
- /** Current RLM spawn depth for this session. */
get rlmDepth(): number {
return this._rlmDepth;
}
- /** Current absolute RLM spawn-depth cap. */
get rlmMaxDepth(): number {
return this._rlmMaxDepth;
}
- /** Current session display name, if set */
get sessionName(): string | undefined {
return this.sessionManager.getSessionName();
}
@@ -4301,7 +4115,6 @@ export class AgentSession {
this._autonomousContinuationSuppressedMessages.add(message);
}
- /** Scoped models for cycling (from --models flag) */
get scopedModels(): ReadonlyArray<{
model: Model<any>;
thinkingLevel?: ThinkingLevel;
@@ -4309,12 +4122,10 @@ export class AgentSession {
return this._scopedModels;
}
- /** Update scoped models for cycling */
setScopedModels(scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>): void {
this._scopedModels = scopedModels;
}
- /** File-based prompt templates */
get promptTemplates(): ReadonlyArray<PromptTemplate> {
return this._resourceLoader.getPrompts().prompts;
}
@@ -4384,10 +4195,6 @@ export class AgentSession {
return buildSystemPrompt(this._baseSystemPromptOptions);
}
- // =========================================================================
- // Prompting
- // =========================================================================
-
private _refreshExtensionSystemPrompt(extensionPrompt: string, baseSnapshot: string): string {
if (this._baseSystemPrompt === baseSnapshot) {
return extensionPrompt;
@@ -4524,7 +4331,6 @@ export class AgentSession {
return this._prompt(text, options);
}
- /** Resolve once the session has accepted ownership, before queued or active execution completes. */
async promptUntilAccepted(text: string, options?: PromptOptions): Promise<void> {
return this._prompt(text, { ...options, returnAfterAccepted: true });
}
@@ -4899,7 +4705,6 @@ export class AgentSession {
const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
return args ? `${skillBlock}\n\n${args}` : skillBlock;
} catch (err) {
- // Emit error like extension commands do
this._extensionRunner.emitError({
extensionPath: skill.filePath,
event: "skill_expansion",
@@ -5951,9 +5756,6 @@ export class AgentSession {
this._emit({ type: "message_end", message });
}
- /**
- * Throw an error if the text is an extension command.
- */
private _throwIfExtensionCommand(text: string): void {
const commandName = parseSlashCommand(text)?.name ?? "";
const command = this._extensionRunner.getCommand(commandName);
@@ -6049,7 +5851,6 @@ export class AgentSession {
content: string | (TextContent | ImageContent)[],
options?: { deliverAs?: "steer" | "followUp" },
): Promise<void> {
- // Normalize content to text string + optional images
let text: string;
let images: ImageContent[] | undefined;
@@ -6069,7 +5870,6 @@ export class AgentSession {
if (images.length === 0) images = undefined;
}
- // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
await this._prompt(text, {
expandPromptTemplates: false,
streamingBehavior: options?.deliverAs,
@@ -6079,11 +5879,6 @@ export class AgentSession {
});
}
- /**
- * Clear all queued messages and return them.
- * Useful for restoring to editor when user aborts.
- * @returns Object with steering and followUp arrays
- */
clearQueue(): { steering: string[]; followUp: string[] } {
const clearable = this._actionStore
.clearableActions()
@@ -6673,9 +6468,6 @@ export class AgentSession {
this.agent.abort();
}
- /**
- * Abort current operation and wait for agent to become idle.
- */
async abort(): Promise<void> {
const compactionOperation = this._compactionOperation;
const branchSummaryOperation = this._branchSummaryOperation;
@@ -6716,10 +6508,6 @@ export class AgentSession {
}
}
- // =========================================================================
- // Model Management
- // =========================================================================
-
private async _emitModelSelect(
nextModel: Model<any>,
previousModel: Model<any> | undefined,
@@ -6753,11 +6541,6 @@ export class AgentSession {
return promise;
}
- /**
- * Set model directly.
- * Validates that the model is available, saves to session and settings.
- * @throws Error if the model is not available
- */
async setModel(model: Model<any>, options: ModelSelectOptions = {}): Promise<void> {
if (!this._modelRegistry.hasConfiguredAuth(model)) {
throw new Error(`No API key for ${model.provider}/${model.id}`);
@@ -6773,7 +6556,6 @@ export class AgentSession {
this.sessionManager.appendModelChange(model.provider, model.id);
this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
- // Re-clamp thinking level for new model's capabilities
this.setThinkingLevel(thinkingLevel);
this._clampServiceTierForModel(serviceTier);
@@ -6807,12 +6589,6 @@ export class AgentSession {
return undefined;
}
- /**
- * Cycle to next/previous model.
- * Uses scoped models (from --models flag) if available, otherwise all available models.
- * @param direction - "forward" (default) or "backward"
- * @returns The new model info, or undefined if only one model available
- */
async cycleModel(
direction: "forward" | "backward" = "forward",
options: ModelSelectOptions = {},
@@ -6843,15 +6619,10 @@ export class AgentSession {
const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
const serviceTier = this._getServiceTierForModelSwitch();
- // Apply model
this.agent.state.model = next.model;
this.sessionManager.appendModelChange(next.model.provider, next.model.id);
this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
- // Apply thinking level.
- // - Explicit scoped model thinking level overrides current session level
- // - Undefined scoped model thinking level inherits the current session preference
- // setThinkingLevel clamps to model capabilities.
this.setThinkingLevel(thinkingLevel);
this._clampServiceTierForModel(serviceTier);
@@ -6891,7 +6662,6 @@ export class AgentSession {
this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
- // Re-clamp thinking level for new model's capabilities
this.setThinkingLevel(thinkingLevel);
this._clampServiceTierForModel(serviceTier);
@@ -6910,20 +6680,10 @@ export class AgentSession {
};
}
- // =========================================================================
- // Thinking Level Management
- // =========================================================================
-
- /**
- * Set thinking level.
- * Clamps to model capabilities based on available thinking levels.
- * Saves to session and settings only if the level actually changes.
- */
setThinkingLevel(level: ThinkingLevel): void {
const availableLevels = this.getAvailableThinkingLevels();
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
- // Only persist if actually changing
const previousLevel = this.agent.state.thinkingLevel;
const isChanging = effectiveLevel !== previousLevel;
@@ -6986,10 +6746,6 @@ export class AgentSession {
});
}
- /**
- * Cycle to next thinking level.
- * @returns New level, or undefined if model doesn't support thinking
- */
cycleThinkingLevel(): ThinkingLevel | undefined {
if (!this.supportsThinking()) return undefined;
@@ -7002,18 +6758,11 @@ export class AgentSession {
return nextLevel;
}
- /**
- * Get available thinking levels for current model.
- * The provider will clamp to what the specific model supports internally.
- */
getAvailableThinkingLevels(): ThinkingLevel[] {
if (!this.model) return THINKING_LEVELS;
return getSupportedThinkingLevels(this.model) as ThinkingLevel[];
}
- /**
- * Check if current model supports thinking/reasoning.
- */
supportsThinking(): boolean {
return !!this.model?.reasoning;
}
@@ -7032,14 +6781,9 @@ export class AgentSession {
return this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : "off";
}
- // Added to history (not a nextTurn message) so it also reaches the continue()-driven
- // auto-compaction resume, which never injects nextTurn messages.
private async _notifyKernelStateAfterCompaction(): Promise<void> {
const provisioner = this._ipythonKernelProvisioner;
- // No kernel means no state to remind about; only stay silent in that case.
if (!provisioner?.hasRunningKernel) return;
- // Bound the probe so a wedged kernel can't stall recovery, and abort it on timeout so
- // the kernel's serialized execution queue isn't left occupied by a never-resolving cell.
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), KERNEL_STATE_LISTING_TIMEOUT_MS);
if (typeof timer === "object" && "unref" in timer) timer.unref();
@@ -7049,8 +6793,6 @@ export class AgentSession {
} finally {
clearTimeout(timer);
}
- // null is a listing failure/timeout; only claim state survived if the kernel is still up
- // (it may have died in the window since the check above).
if (names === null && !provisioner.hasRunningKernel) return;
const detail =
names === null
@@ -7070,7 +6812,6 @@ export class AgentSession {
display: false,
timestamp: Date.now(),
} satisfies CustomMessage;
- // Insert before a trailing assistant error so overflow-retry cleanup can still strip it.
const messages = this.agent.state.messages;
const last = messages[messages.length - 1];
const insertBeforeError = last?.role === "assistant" && (last as AssistantMessage).stopReason === "error";
@@ -7084,11 +6825,6 @@ export class AgentSession {
this._emit({ type: "message_end", message });
}
- /**
- * Tell the model when a resumed session revived its IPython kernel state, so it
- * knows which variables are actually available instead of assuming the kernel is
- * the one it left. Delivered as context before the next turn.
- */
private _onIpythonStateRestored(result: RestoreResult): void {
const lines = ["<ipython_state_restored>"];
if (result.restored.length > 0) {
@@ -7117,37 +6853,16 @@ export class AgentSession {
).catch(() => {});
}
- // =========================================================================
- // Queue Mode Management
- // =========================================================================
-
- /**
- * Set steering message mode.
- * Saves to settings.
- */
setSteeringMode(mode: "all" | "one-at-a-time"): void {
this.agent.steeringMode = mode;
this.settingsManager.setSteeringMode(mode);
}
- /**
- * Set follow-up message mode.
- * Saves to settings.
- */
setFollowUpMode(mode: "all" | "one-at-a-time"): void {
this.agent.followUpMode = mode;
this.settingsManager.setFollowUpMode(mode);
}
- // =========================================================================
- // Compaction
- // =========================================================================
-
- /**
- * Manually compact the session context.
- * Aborts current agent operation first.
- * @param customInstructions Optional instructions for the compaction summary
- */
async compact(customInstructions?: string, options: { skipAbort?: boolean } = {}): Promise<CompactionResult> {
if (options.skipAbort && this.isStreaming) {
throw new Error("Cannot compact without aborting while the agent is running.");
@@ -7300,7 +7015,6 @@ export class AgentSession {
this._mergeUnpersistedCompactionOutcomes(this.agent.state.messages);
this._restoreLateIpythonSentAgentMessages();
- // Get the saved compaction entry for the extension event
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
| CompactionEntry
| undefined;
@@ -7324,9 +7038,6 @@ export class AgentSession {
await Promise.allSettled(childIds.map((childId) => this.deleteRlmSubagent(childId)));
}
- /**
- * Cancel in-progress compaction (manual or auto).
- */
abortCompaction(): void {
this._compactionAbortController?.abort();
this._autoCompactionAbortController?.abort();
@@ -7374,7 +7085,6 @@ export class AgentSession {
// _planRefine or _reviewAutoRefine call settles via signal abort
// rather than hanging forever.
this._refineAbortController?.abort();
- // Await and clear serialized background plan if in flight.
if (this._serializedPlanInFlight) {
await this._consumeSerializedBackgroundPlan(async () => false);
}
@@ -7455,7 +7165,6 @@ export class AgentSession {
}, 100);
}
- /** Whether any snapshot of scheduled continuation messages is still session-owned. */
private _sessionOwnsScheduledContinuations(continuationMessages: AgentMessage[]): boolean {
return continuationMessages.some((message) => this._postCompactionContinuationMessages.includes(message));
}
@@ -7784,7 +7493,6 @@ export class AgentSession {
const refineAbort = new AbortController();
this._refineAbortController = refineAbort;
- // Background planning phase — does NOT block turn entry points
const planRun = this._planRefine(options, refineAbort.signal);
const planSettled = planRun.then(
() => undefined,
@@ -8033,9 +7741,6 @@ export class AgentSession {
}
}
- /**
- * Cancel in-progress branch summarization.
- */
abortBranchSummary(): void {
this._branchSummaryAbortController?.abort();
}
@@ -8151,7 +7856,6 @@ export class AgentSession {
return await this._runAutoCompaction("overflow", true);
}
- // Case 2: Model-requested (compact skill); runs even with auto-compaction off.
if (this._pendingRequestedCompaction !== undefined) {
return await this._runAutoCompaction("requested", false);
}
@@ -8181,7 +7885,6 @@ export class AgentSession {
* Internal: Run automatic (threshold/overflow) or model-requested compaction
* with events.
*/
- /** Emit an unsuccessful compaction_end and durably record the outcome. */
private _endCompactionUnsuccessfully(
reason: CompactionOutcomeReason,
outcome: CompactionOutcome,
@@ -8374,14 +8077,10 @@ export class AgentSession {
}
}
- /**
- * Toggle auto-compaction setting.
- */
setAutoCompactionEnabled(enabled: boolean): void {
this.settingsManager.setCompactionEnabled(enabled);
}
- /** Whether auto-compaction is enabled */
get autoCompactionEnabled(): boolean {
return this.settingsManager.getCompactionEnabled();
}
@@ -8833,7 +8532,6 @@ export class AgentSession {
return skills;
}
- /** Typed handlers for host requests arriving from the IPython kernel comm bridge. */
private _createKernelHostHandlers(): HostRequestHandlers {
const handlers: HostRequestHandlers = {
"rlm.run": createRlmRunHostHandler(async ({ prompt, kwargs, cellSourceCode }) => ({
@@ -8949,7 +8647,6 @@ export class AgentSession {
// visible here so MCP skill gating sees the new credentials.
this._modelRegistry.authStorage.reload();
resetApiProviders();
- // Re-read mcpServers and re-register user MCP providers from the reloaded settings.
this._mcpManager?.refresh();
await this._resourceLoader.reload();
this._buildRuntime({
@@ -9056,7 +8753,6 @@ export class AgentSession {
return this._rlmSessionDir;
}
- /** Context size (tokens) of this session's latest assistant turn, for live subagent display. */
_contextTokensForCurrentMessages(): number | undefined {
const last = this._findLastAssistantMessage();
return last ? calculateContextTokens(last.usage) : undefined;
@@ -9211,7 +8907,6 @@ export class AgentSession {
return true;
}
- /** Status of a direct RLM child run, while the run is still tracked. */
getRlmChildRunStatus(childId: string): RlmChildAgentStatus | undefined {
return this._activeRlmChildRuns.get(childId)?.status;
}
@@ -9236,7 +8931,6 @@ export class AgentSession {
return run.session?.sessionId;
}
- /** Current direct-child registry for the model-facing rlm.list_subagents API. */
async listRlmSubagents(): Promise<RlmListSubagentsResult> {
return this._buildRlmSubagentList(await this._agentMessageController?.listAgents());
}
@@ -9340,7 +9034,6 @@ export class AgentSession {
return matches[0]!;
}
- /** Delete an inactive direct or nested child by its registry child id without affecting active runs. */
async deleteInactiveRlmSubagent(
childId: string,
isExternallyRunning: () => boolean = () => false,
@@ -9382,7 +9075,6 @@ export class AgentSession {
return result.outcome === "skipped_running" ? "running" : "deleted";
}
- /** Delete a running, retained, or passive direct child selected from this parent session's registry. */
async deleteRlmSubagent(target: string): Promise<RlmDeleteSubagentResult> {
const inFlight = [...this._deletingRlmChildren.values()].filter(({ subagent }) =>
this._rlmSubagentMatchesTarget(subagent, target),
@@ -9595,7 +9287,6 @@ export class AgentSession {
return true;
}
- /** Stop retaining an idle daemon child without deleting its durable registry row. */
releaseRlmChildSession(childId: string, session: AgentSession): (() => void) | false {
const run = this._activeRlmChildRuns.get(childId);
if (run?.session === session && run.status === "done") {
@@ -9630,7 +9321,6 @@ export class AgentSession {
return false;
}
- // Inline (non-daemon) mode only; daemon clients attach to the child session directly.
getRlmChildSession(childId: string): AgentSession | undefined {
const direct = this._activeRlmChildRuns.get(childId)?.session ?? this._rlmChildSessions.get(childId);
if (direct) {
@@ -9651,12 +9341,6 @@ export class AgentSession {
return undefined;
}
- /**
- * Cancel a single RLM child run by id, searching nested child sessions.
- *
- * @returns true when a running or queued run was cancelled; false when the
- * id is unknown or the run already finished.
- */
cancelRlmChildRun(childId: string, reason = "Cancelled by user"): boolean {
const run = this._activeRlmChildRuns.get(childId);
if (run) {
@@ -9667,7 +9351,6 @@ export class AgentSession {
return true;
}
}
- // A finished, retained child can still have a running nested subagent.
for (const retained of this._rlmChildSessions.values()) {
if (retained.cancelRlmChildRun(childId, reason)) {
return true;
@@ -10116,18 +9799,9 @@ export class AgentSession {
return this._startRlmChildRun(prompt, kwargs, spawnCode);
}
- // =========================================================================
- // Auto-Retry
- // =========================================================================
-
- /**
- * Check if an error is retryable (overloaded, rate limit, server errors).
- * Context overflow errors are NOT retryable (handled by compaction instead).
- */
private _isRetryableError(message: AssistantMessage): boolean {
if (message.stopReason !== "error" || !message.errorMessage) return false;
- // Context overflow is handled by compaction, not retry
const contextWindow = this.model?.contextWindow ?? 0;
if (isContextOverflow(message, contextWindow)) return false;
@@ -10292,10 +9966,6 @@ export class AgentSession {
this._retryAuthFailureSources = [];
}
- /**
- * Handle retryable errors with exponential backoff.
- * @returns true if retry was initiated, false if max retries exceeded or disabled
- */
private async _handleRetryableError(
message: AssistantMessage,
options?: {
@@ -10311,8 +9981,6 @@ export class AgentSession {
return false;
}
- // Retry promise is created synchronously in _handleAgentEvent for agent_end.
- // Keep a defensive fallback here in case a future refactor bypasses that path.
if (!this._retryPromise) {
this._retryPromise = new Promise((resolve) => {
this._retryResolve = resolve;
@@ -10323,7 +9991,6 @@ export class AgentSession {
if (this._retryAttempt > settings.maxRetries) {
this._markProviderAuthStaleForRetryFailure(message, options);
- // Max retries exceeded, emit final failure and reset
this._emit({
type: "auto_retry_end",
success: false,
@@ -10346,18 +10013,15 @@ export class AgentSession {
errorMessage: message.errorMessage || "Unknown error",
});
- // Remove error message from agent state (keep in session for history)
const messages = this.agent.state.messages;
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
this.agent.state.messages = messages.slice(0, -1);
}
- // Wait with exponential backoff (abortable)
this._retryAbortController = new AbortController();
try {
await sleep(delayMs, this._retryAbortController.signal);
} catch {
- // Aborted during sleep - emit end event so UI can clean up
const attempt = this._retryAttempt;
this._markProviderAuthStaleForRetryFailure(message, options);
this._retryAttempt = 0;
@@ -10374,19 +10038,13 @@ export class AgentSession {
}
this._retryAbortController = undefined;
- // Retry via continue() - use setTimeout to break out of event handler chain
setTimeout(() => {
- this.agent.continue().catch(() => {
- // Retry failed - will be caught by next agent_end
- });
+ this.agent.continue().catch(() => {});
}, 0);
return true;
}
- /**
- * Cancel in-progress retry.
- */
abortRetry(): void {
if (this._retryAbortController) {
this._retryAbortController.abort();
@@ -10407,10 +10065,6 @@ export class AgentSession {
this._resolveRetry();
}
- /**
- * Wait for any in-progress retry to complete.
- * Returns immediately if no retry is in progress.
- */
private async waitForRetry(): Promise<void> {
if (!this._retryPromise) {
return;
@@ -10420,12 +10074,10 @@ export class AgentSession {
await this.agent.waitForIdle();
}
- /** Whether auto-retry is currently in progress */
get isRetrying(): boolean {
return this._retryPromise !== undefined;
}
- /** Whether an accepted prompt is still running or waiting for retry completion. */
get hasAcceptedPromptInFlight(): boolean {
return this._actionStore
.unfinishedActions()
@@ -10437,22 +10089,14 @@ export class AgentSession {
);
}
- /** Whether auto-retry is enabled */
get autoRetryEnabled(): boolean {
return this.settingsManager.getRetryEnabled();
}
- /**
- * Toggle auto-retry setting.
- */
setAutoRetryEnabled(enabled: boolean): void {
this.settingsManager.setRetryEnabled(enabled);
}
- // =========================================================================
- // Bash Execution
- // =========================================================================
-
/**
* Execute a bash command.
* Adds result to agent context and session.
@@ -10472,7 +10116,6 @@ export class AgentSession {
): Promise<BashResult> {
this._bashAbortController = new AbortController();
- // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
const prefix = this.settingsManager.getShellCommandPrefix();
const shellPath = this.settingsManager.getShellPath();
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
@@ -10633,10 +10276,6 @@ export class AgentSession {
}
}
- /**
- * Record a bash execution result in session history.
- * Used by executeBash and by extensions that handle bash execution themselves.
- */
recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {
const bashMessage: BashExecutionMessage = {
role: "bashExecution",
@@ -10652,13 +10291,10 @@ export class AgentSession {
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
if (this.isStreaming) {
- // Queue for later - will be flushed on agent_end
this._pendingBashMessages.push(bashMessage);
} else {
- // Add to agent state immediately
this.agent.state.messages.push(bashMessage);
- // Save to session
this.sessionManager.appendMessage(bashMessage);
}
}
@@ -10675,7 +10311,6 @@ export class AgentSession {
this._bashAbortController?.abort();
}
- /** Whether a bash command is currently running */
get isBashRunning(): boolean {
return this._bashAbortController !== undefined || this._userBashRunning;
}
@@ -10693,26 +10328,18 @@ export class AgentSession {
if (this._pendingBashMessages.length === 0) return;
for (const bashMessage of this._pendingBashMessages) {
- // Add to agent state
this.agent.state.messages.push(bashMessage);
- // Save to session
this.sessionManager.appendMessage(bashMessage);
}
this._pendingBashMessages = [];
}
- // =========================================================================
- // Session Management
- // =========================================================================
-
- /** Current RLM max-depth value and the source that supplied it. */
getRlmMaxDepthStatus(): RlmMaxDepthStatus {
return { maxDepth: this._rlmMaxDepth, source: this._rlmMaxDepthSource };
}
- /** Persist and immediately apply a per-chat RLM max-depth override. */
async setRlmMaxDepth(maxDepth: number, options: { global?: boolean } = {}): Promise<SetRlmMaxDepthResult> {
if (!isNonNegativeInteger(maxDepth)) {
throw new Error("RLM max depth must be a non-negative integer.");
@@ -10745,7 +10372,6 @@ export class AgentSession {
};
}
- /** Set a display name for the current session. */
setSessionName(name: string): void {
this.sessionManager.appendSessionInfo(name);
this._emit({
@@ -10754,10 +10380,6 @@ export class AgentSession {
});
}
- // =========================================================================
- // Tree Navigation
- // =========================================================================
-
/**
* Navigate to a different node in the session tree.
* Unlike fork() which creates a new session file, this stays in the same file.
@@ -10812,7 +10434,6 @@ export class AgentSession {
aborted?: boolean;
summaryEntry?: BranchSummaryEntry;
}> {
- // Model required for summarization
if (options.summarize && !this.model) {
throw new Error("No model available for summarization");
}
@@ -10864,14 +10485,12 @@ export class AgentSession {
// about to persist harness/session entries for the current branch.
await this._invalidatePendingAutoRefineForBranchChange();
- // Collect entries to summarize (from old leaf to common ancestor)
const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
this.sessionManager,
oldLeafId,
targetId,
);
- // Prepare event data - mutable so extensions can override
let customInstructions = options.customInstructions;
let replaceInstructions = options.replaceInstructions;
let label = options.label;
@@ -10887,7 +10506,6 @@ export class AgentSession {
label,
};
- // Set up abort controller for summarization
this._branchSummaryAbortController = new AbortController();
let resolveBranchSummaryOperation: () => void = () => {};
const branchSummaryOperation = new Promise<void>((resolve) => {
@@ -10899,7 +10517,6 @@ export class AgentSession {
let extensionSummary: { summary: string; details?: unknown } | undefined;
let fromExtension = false;
- // Emit session_before_tree event
if (this._extensionRunner.hasHandlers("session_before_tree")) {
const result = (await this._extensionRunner.emit({
type: "session_before_tree",
@@ -10916,7 +10533,6 @@ export class AgentSession {
fromExtension = true;
}
- // Allow extensions to override instructions and label
if (result?.customInstructions !== undefined) {
customInstructions = result.customInstructions;
}
@@ -10928,7 +10544,6 @@ export class AgentSession {
}
}
- // Run default summarizer if needed
let summaryText: string | undefined;
let summaryDetails: unknown;
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
@@ -10960,16 +10575,13 @@ export class AgentSession {
summaryDetails = extensionSummary.details;
}
- // Determine the new leaf position based on target type
let newLeafId: string | null;
let editorText: string | undefined;
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
- // User message: leaf = parent (null if root), text goes to editor
newLeafId = targetEntry.parentId;
editorText = this._extractUserMessageText(targetEntry.message.content);
} else if (targetEntry.type === "custom_message") {
- // Custom message: leaf = parent (null if root), text goes to editor
newLeafId = targetEntry.parentId;
editorText =
typeof targetEntry.content === "string"
@@ -10979,15 +10591,11 @@ export class AgentSession {
.map((c) => c.text)
.join("");
} else {
- // Non-user message: leaf = selected node
newLeafId = targetId;
}
- // Switch leaf (with or without summary)
- // Summary is attached at the navigation target position (newLeafId), not the old branch
let summaryEntry: BranchSummaryEntry | undefined;
if (summaryText) {
- // Create summary at target position (can be null for root)
const summaryId = this.sessionManager.branchWithSummary(
newLeafId,
summaryText,
@@ -10996,24 +10604,19 @@ export class AgentSession {
);
summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
- // Attach label to the summary entry
if (label) {
this.sessionManager.appendLabelChange(summaryId, label);
}
} else if (newLeafId === null) {
- // No summary, navigating to root - reset leaf
this.sessionManager.resetLeaf();
} else {
- // No summary, navigating to non-root
this.sessionManager.branch(newLeafId);
}
- // Attach label to target entry when not summarizing (no summary entry to label)
if (label && !summaryText) {
this.sessionManager.appendLabelChange(targetId, label);
}
- // Update agent state
const sessionContext = this.sessionManager.buildSessionContext();
this.agent.state.messages = sessionContext.messages;
this._mergeUnpersistedCompactionOutcomes(this.agent.state.messages);
@@ -11022,7 +10625,6 @@ export class AgentSession {
this._reloadRlmMaxDepthFromBranch();
this._invalidateQueuedPromptPreparation();
- // Emit session_tree event
await this._extensionRunner.emit({
type: "session_tree",
newLeafId: this.sessionManager.getLeafId(),
@@ -11031,8 +10633,6 @@ export class AgentSession {
fromExtension: summaryText ? fromExtension : undefined,
});
- // Emit to custom tools
-
return { editorText, cancelled: false, summaryEntry };
} finally {
this._branchSummaryAbortController = undefined;
@@ -11043,9 +10643,6 @@ export class AgentSession {
}
}
- /**
- * Get all user messages from session for fork selector.
- */
getUserMessagesForForking(): Array<{ entryId: string; text: string }> {
const entries = this.sessionManager.getEntries();
const result: Array<{ entryId: string; text: string }> = [];
@@ -11074,9 +10671,6 @@ export class AgentSession {
return "";
}
- /**
- * Get session statistics.
- */
getSessionStats(): SessionStats {
const state = this.state;
const userMessages = state.messages.filter((m) => m.role === "user").length;
@@ -11168,7 +10762,6 @@ export class AgentSession {
};
}
- /** RLM session dir holding sub-* child sessions, without creating directories. */
private _rlmSessionDirForReading(): string | undefined {
return this._rlmSessionDir ?? this.sessionManager.getSessionArtifactDir();
}
@@ -11230,7 +10823,6 @@ export class AgentSession {
async exportToHtml(outputPath?: string): Promise<string> {
const themeName = this.settingsManager.getTheme();
- // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
const toolRenderer: ToolHtmlRenderer = createToolHtmlRenderer({
getToolDefinition: (name) => this.getToolDefinition(name),
theme,
@@ -11280,10 +10872,6 @@ export class AgentSession {
return filePath;
}
- // =========================================================================
- // Utilities
- // =========================================================================
-
/**
* Get text content of last assistant message.
* Useful for /copy command.
@@ -11327,16 +10915,10 @@ export class AgentSession {
return context;
}
- /**
- * Check if extensions have handlers for a specific event type.
- */
hasExtensionHandlers(eventType: string): boolean {
return this._extensionRunner.hasHandlers(eventType);
}
- /**
- * Get the extension runner (for setting UI context and error handlers).
- */
get extensionRunner(): ExtensionRunner {
return this._extensionRunner;
}
diff --git a/packages/coding-agent/src/core/auth-storage.ts b/packages/coding-agent/src/core/auth-storage.ts
index 493c9c964d..71a5b6fb3a 100644
--- a/packages/coding-agent/src/core/auth-storage.ts
+++ b/packages/coding-agent/src/core/auth-storage.ts
@@ -819,7 +819,7 @@ export class AuthStorage {
providerId: string,
options?: { includeFallback?: boolean },
): Promise<AuthApiKeyResult> {
- // Runtime override takes highest priority
+ // Runtime overrides take precedence over stored credentials and environment keys.
const runtimeCandidate = this.getRuntimeAuthCandidate(providerId);
const runtimeKey = this.runtimeOverrides.get(providerId);
if (runtimeKey && runtimeCandidate && !this.isAuthSourceStale(providerId, runtimeCandidate)) {
@@ -883,15 +883,12 @@ export class AuthStorage {
if (storedCandidate && !this.isAuthSourceStale(providerId, storedCandidate)) {
const provider = getOAuthProvider(providerId);
if (!provider) {
- // Unknown OAuth provider, can't get API key
return {};
}
-
- // Check if token needs refresh
+ // Lock refreshes so concurrent instances cannot race on the credential file.
const needsRefresh = Date.now() >= cred.expires;
if (needsRefresh) {
- // Use locked refresh to prevent race conditions
try {
const result = await this.refreshOAuthTokenWithLock(providerId);
if (result) {
@@ -905,12 +902,11 @@ export class AuthStorage {
}
} catch (error) {
this.recordError(error);
- // Refresh failed - re-read file to check if another instance succeeded
+ // A peer may have refreshed successfully; reload before treating this refresh as failed.
this.reload();
const updatedCred = this.data[providerId];
if (updatedCred?.type === "oauth" && Date.now() < updatedCred.expires) {
- // Another instance refreshed successfully, use those credentials
const updatedCandidate = this.getStoredAuthCandidate(providerId);
return {
apiKey: provider.getApiKey(updatedCred),
@@ -920,12 +916,10 @@ export class AuthStorage {
};
}
- // Refresh truly failed - return undefined so model discovery skips this provider
- // User can /login to re-authenticate (credentials preserved for retry)
+ // Preserve credentials for a later /login retry while discovery skips this provider.
return {};
}
} else {
- // Token not expired, use current access token
return {
apiKey: provider.getApiKey(cred),
sourceToken: this.getAuthSourceTokenForCandidate(providerId, storedCandidate),
@@ -933,8 +927,7 @@ export class AuthStorage {
}
}
}
-
- // Other providers preserve auth.json priority over environment variables.
+ // Stored auth wins over environment variables for non-Prime-Inference providers.
if (
providerId !== PRIME_INFERENCE_PROVIDER_ID &&
envKey &&
@@ -946,8 +939,6 @@ export class AuthStorage {
sourceToken: this.getAuthSourceTokenForCandidate(providerId, envCandidate),
};
}
-
- // Fall back to custom resolver (e.g., models.json custom providers)
if (options?.includeFallback !== false) {
const fallbackCandidate = this.getFallbackAuthCandidate(providerId);
if (fallbackCandidate && !this.isAuthSourceStale(providerId, fallbackCandidate)) {
diff --git a/packages/coding-agent/src/core/bash-executor.ts b/packages/coding-agent/src/core/bash-executor.ts
index ee55611e33..4103629493 100644
--- a/packages/coding-agent/src/core/bash-executor.ts
+++ b/packages/coding-agent/src/core/bash-executor.ts
@@ -14,11 +14,6 @@ import stripAnsi from "strip-ansi";
import { sanitizeBinaryOutput } from "../utils/shell.js";
import type { BashOperations } from "./tools/bash.js";
import { DEFAULT_MAX_BYTES, truncateTail } from "./tools/truncate.js";
-
-// ============================================================================
-// Types
-// ============================================================================
-
export interface BashExecutorOptions {
/** Callback for streaming output chunks (already sanitized) */
onChunk?: (chunk: string) => void;
@@ -38,11 +33,6 @@ export interface BashResult {
/** Path to temp file containing full output (if output exceeded truncation threshold) */
fullOutputPath?: string;
}
-
-// ============================================================================
-// Implementation
-// ============================================================================
-
/**
* Execute a bash command using custom BashOperations.
* Used for remote execution (SSH, containers, etc.).
@@ -77,11 +67,7 @@ export async function executeBashWithOperations(
const onData = (data: Buffer) => {
totalBytes += data.length;
-
- // Sanitize: strip ANSI, replace binary garbage, normalize newlines
const text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\r/g, "");
-
- // Start writing to temp file if exceeds threshold
if (totalBytes > DEFAULT_MAX_BYTES) {
ensureTempFile();
}
@@ -89,16 +75,12 @@ export async function executeBashWithOperations(
if (tempFileStream) {
tempFileStream.write(text);
}
-
- // Keep rolling buffer
outputChunks.push(text);
outputBytes += text.length;
while (outputBytes > maxOutputBytes && outputChunks.length > 1) {
const removed = outputChunks.shift()!;
outputBytes -= removed.length;
}
-
- // Stream to callback
if (options?.onChunk) {
options.onChunk(text);
}
@@ -128,7 +110,6 @@ export async function executeBashWithOperations(
fullOutputPath: tempFilePath,
};
} catch (err) {
- // Check if it was an abort
if (options?.signal?.aborted) {
const fullOutput = outputChunks.join("");
const truncationResult = truncateTail(fullOutput);
diff --git a/packages/coding-agent/src/core/compaction/branch-summarization.ts b/packages/coding-agent/src/core/compaction/branch-summarization.ts
index 2933e15787..a23f825f05 100644
--- a/packages/coding-agent/src/core/compaction/branch-summarization.ts
+++ b/packages/coding-agent/src/core/compaction/branch-summarization.ts
@@ -25,11 +25,6 @@ import {
SUMMARIZATION_SYSTEM_PROMPT,
serializeConversation,
} from "./utils.js";
-
-// ============================================================================
-// Types
-// ============================================================================
-
export interface BranchSummaryResult {
summary?: string;
readFiles?: string[];
@@ -78,11 +73,6 @@ export interface GenerateBranchSummaryOptions {
/** Tokens reserved for prompt + LLM response (default 16384) */
reserveTokens?: number;
}
-
-// ============================================================================
-// Entry Collection
-// ============================================================================
-
/**
* Collect entries that should be summarized when navigating from one position to another.
*
@@ -100,16 +90,11 @@ export function collectEntriesForBranchSummary(
oldLeafId: string | null,
targetId: string,
): CollectEntriesResult {
- // If no old position, nothing to summarize
if (!oldLeafId) {
return { entries: [], commonAncestorId: null };
}
-
- // Find common ancestor (deepest node that's on both paths)
const oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));
const targetPath = session.getBranch(targetId);
-
- // targetPath is root-first, so iterate backwards to find deepest common ancestor
let commonAncestorId: string | null = null;
for (let i = targetPath.length - 1; i >= 0; i--) {
if (oldPath.has(targetPath[i].id)) {
@@ -117,8 +102,6 @@ export function collectEntriesForBranchSummary(
break;
}
}
-
- // Collect entries from old leaf back to common ancestor
const entries: SessionEntry[] = [];
let current: string | null = oldLeafId;
@@ -128,17 +111,10 @@ export function collectEntriesForBranchSummary(
entries.push(entry);
current = entry.parentId;
}
-
- // Reverse to get chronological order
entries.reverse();
return { entries, commonAncestorId };
}
-
-// ============================================================================
-// Entry to Message Conversion
-// ============================================================================
-
/**
* Extract AgentMessage from a session entry.
* Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.
@@ -146,7 +122,7 @@ export function collectEntriesForBranchSummary(
function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
switch (entry.type) {
case "message":
- // Skip tool results - context is in assistant's tool call
+ // Tool-result context remains attached to its assistant tool call.
if (entry.message.role === "toolResult") return undefined;
return entry.message;
@@ -163,8 +139,6 @@ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
entry.timestamp,
entry.customInstructions,
);
-
- // These don't contribute to conversation content
case "thinking_level_change":
case "model_change":
case "custom":
@@ -202,35 +176,26 @@ export function prepareBranchEntries(entries: SessionEntry[], tokenBudget: numbe
for (const f of details.readFiles) fileOps.read.add(f);
}
if (Array.isArray(details.modifiedFiles)) {
- // Modified files go into both edited and written for proper deduplication
for (const f of details.modifiedFiles) {
fileOps.edited.add(f);
}
}
}
}
-
- // Second pass: walk from newest to oldest, adding messages until token budget
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
const message = getMessageFromEntry(entry);
if (!message) continue;
-
- // Extract file ops from assistant messages (tool calls)
extractFileOpsFromMessage(message, fileOps);
const tokens = estimateTokens(message);
-
- // Check budget before adding
if (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {
- // If this is a summary entry, try to fit it anyway as it's important context
if (entry.type === "compaction" || entry.type === "branch_summary") {
if (totalTokens < tokenBudget * 0.9) {
messages.unshift(message);
totalTokens += tokens;
}
}
- // Stop - we've hit the budget
break;
}
@@ -240,11 +205,6 @@ export function prepareBranchEntries(entries: SessionEntry[], tokenBudget: numbe
return { messages, fileOps, totalTokens };
}
-
-// ============================================================================
-// Summary Generation
-// ============================================================================
-
const BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.
Summary of that exploration:
@@ -290,23 +250,18 @@ export async function generateBranchSummary(
options: GenerateBranchSummaryOptions,
): Promise<BranchSummaryResult> {
const { model, apiKey, headers, signal, customInstructions, replaceInstructions, reserveTokens = 16384 } = options;
-
- // Token budget = context window minus reserved space for prompt + response
const contextWindow = model.contextWindow || 128000;
const tokenBudget = contextWindow - reserveTokens;
const { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);
+ // Nothing model-visible remains after filtering.
if (messages.length === 0) {
return { summary: "No content to summarize" };
}
-
- // Transform to LLM-compatible messages, then serialize to text
- // Serialization prevents the model from treating it as a conversation to continue
+ // Serialize before the LLM call so it summarizes rather than continues this branch.
const llmMessages = convertToLlm(messages);
const conversationText = serializeConversation(llmMessages);
-
- // Build prompt
let instructions: string;
if (replaceInstructions && customInstructions) {
instructions = customInstructions;
@@ -324,15 +279,11 @@ export async function generateBranchSummary(
timestamp: Date.now(),
},
];
-
- // Call LLM for summarization
const response = await completeSimple(
model,
{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },
{ apiKey, headers, signal, maxTokens: 2048 },
);
-
- // Check if aborted or errored
if (response.stopReason === "aborted") {
return { aborted: true };
}
@@ -344,11 +295,7 @@ export async function generateBranchSummary(
.filter((c): c is { type: "text"; text: string } => c.type === "text")
.map((c) => c.text)
.join("\n");
-
- // Prepend preamble to provide context about the branch summary
summary = BRANCH_SUMMARY_PREAMBLE + summary;
-
- // Compute file lists and append to summary
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
summary += formatFileOperations(readFiles, modifiedFiles);
diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts
index f1602cf822..5716c5e699 100644
--- a/packages/coding-agent/src/core/compaction/compaction.ts
+++ b/packages/coding-agent/src/core/compaction/compaction.ts
@@ -24,11 +24,6 @@ import {
SUMMARIZATION_SYSTEM_PROMPT,
serializeConversation,
} from "./utils.js";
-
-// ============================================================================
-// File Operation Tracking
-// ============================================================================
-
/** Details stored in CompactionEntry.details for file tracking */
export interface CompactionDetails {
readFiles: string[];
@@ -38,14 +33,13 @@ export interface CompactionDetails {
/**
* Extract file operations from messages and previous compaction entries.
*/
+/** Preserve file operations recorded by prior compactions and current tool calls. */
function extractFileOperations(
messages: AgentMessage[],
entries: SessionEntry[],
prevCompactionIndex: number,
): FileOperations {
const fileOps = createFileOps();
-
- // Collect from previous compaction's details (if pi-generated)
if (prevCompactionIndex >= 0) {
const prevCompaction = entries[prevCompactionIndex] as CompactionEntry;
if (!prevCompaction.fromHook && prevCompaction.details) {
@@ -59,19 +53,12 @@ function extractFileOperations(
}
}
}
-
- // Extract from tool calls in messages
for (const msg of messages) {
extractFileOpsFromMessage(msg, fileOps);
}
return fileOps;
}
-
-// ============================================================================
-// Message Extraction
-// ============================================================================
-
/**
* Extract AgentMessage from an entry if it produces one.
* Returns undefined for entries that don't contribute to LLM context.
@@ -112,11 +99,6 @@ export interface CompactionResult<T = unknown> {
/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
details?: T;
}
-
-// ============================================================================
-// Types
-// ============================================================================
-
export const COMPACT_SKILL_NAME = "compact";
export interface CompactionSettings {
@@ -130,11 +112,6 @@ export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {
reserveTokens: 16384,
keepRecentTokens: 20000,
};
-
-// ============================================================================
-// Token calculation
-// ============================================================================
-
/**
* Calculate total context tokens from usage.
* Uses the native totalTokens field when available, falls back to computing from components.
@@ -231,11 +208,6 @@ export function shouldCompact(contextTokens: number, contextWindow: number, sett
if (contextWindow <= 0) return false;
return contextTokens > contextWindow - settings.reserveTokens;
}
-
-// ============================================================================
-// Cut point detection
-// ============================================================================
-
/**
* Estimate token count for a message using chars/4 heuristic.
* This is conservative (overestimates tokens).
@@ -338,8 +310,7 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
case "session_info":
break;
}
-
- // branch_summary and custom_message are user-role messages, valid cut points
+ // Branch summaries and custom messages are user-role turn boundaries.
if (entry.type === "branch_summary" || entry.type === "custom_message") {
cutPoints.push(i);
}
@@ -355,7 +326,6 @@ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endInde
export function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {
for (let i = entryIndex; i >= startIndex; i--) {
const entry = entries[i];
- // branch_summary and custom_message are user-role messages, can start a turn
if (entry.type === "branch_summary" || entry.type === "custom_message") {
return i;
}
@@ -405,22 +375,15 @@ export function findCutPoint(
if (cutPoints.length === 0) {
return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
}
-
- // Walk backwards from newest, accumulating estimated message sizes
let accumulatedTokens = 0;
let cutIndex = cutPoints[0]; // Default: keep from first message (not header)
for (let i = endIndex - 1; i >= startIndex; i--) {
const entry = entries[i];
if (entry.type !== "message") continue;
-
- // Estimate this message's size
const messageTokens = estimateTokens(entry.message);
accumulatedTokens += messageTokens;
-
- // Check if we've exceeded the budget
if (accumulatedTokens >= keepRecentTokens) {
- // Find the closest valid cut point at or after this entry
for (let c = 0; c < cutPoints.length; c++) {
if (cutPoints[c] >= i) {
cutIndex = cutPoints[c];
@@ -430,25 +393,19 @@ export function findCutPoint(
break;
}
}
-
- // Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)
while (cutIndex > startIndex) {
const prevEntry = entries[cutIndex - 1];
- // Stop at session header or compaction boundaries
if (prevEntry.type === "compaction") {
break;
}
if (prevEntry.type === "message") {
- // Stop if we hit any message
break;
}
- // Include this non-message entry (bash, settings change, etc.)
cutIndex--;
}
-
- // Determine if this is a split turn
const cutEntry = entries[cutIndex];
const isUserMessage = cutEntry.type === "message" && cutEntry.message.role === "user";
+ // A cut in a non-user turn requires a prefix summary.
const turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
return {
@@ -457,11 +414,6 @@ export function findCutPoint(
isSplitTurn: !isUserMessage && turnStartIndex !== -1,
};
}
-
-// ============================================================================
-// Summarization
-// ============================================================================
-
const SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
Use this EXACT format:
@@ -567,13 +519,9 @@ export async function generateSummary(
const maxTokens = Math.floor(0.8 * reserveTokens);
const basePrompt = buildSummarizationPrompt(customInstructions, previousSummary);
-
- // Serialize conversation to text so model doesn't try to continue it
- // Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)
+ // Serialize before the LLM call so it summarizes rather than continues this conversation.
const llmMessages = convertToLlm(currentMessages);
const conversationText = serializeConversation(llmMessages);
-
- // Build the prompt with conversation wrapped in tags
let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
if (previousSummary) {
promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
@@ -610,11 +558,6 @@ export async function generateSummary(
return textContent;
}
-
-// ============================================================================
-// Compaction Preparation (for extensions)
-// ============================================================================
-
export interface CompactionPreparation {
/** UUID of first entry to keep */
firstKeptEntryId: string;
@@ -662,8 +605,6 @@ export function prepareCompaction(
const tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;
const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);
-
- // Get UUID of first kept entry
const firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];
if (!firstKeptEntry?.id) {
return undefined; // Session needs migration
@@ -671,15 +612,11 @@ export function prepareCompaction(
const firstKeptEntryId = firstKeptEntry.id;
const historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;
-
- // Messages to summarize (will be discarded after summary)
const messagesToSummarize: AgentMessage[] = [];
for (let i = boundaryStart; i < historyEnd; i++) {
const msg = getMessageFromEntryForCompaction(pathEntries[i]);
if (msg) messagesToSummarize.push(msg);
}
-
- // Messages for turn prefix summary (if splitting a turn)
const turnPrefixMessages: AgentMessage[] = [];
if (cutPoint.isSplitTurn) {
for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
@@ -688,16 +625,12 @@ export function prepareCompaction(
}
}
- // Everything fits in the keep-recent window and there is no previous summary
- // to carry forward — compacting would summarize an empty conversation.
+ // Avoid a compaction that would summarize no history.
if (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0 && !previousSummary) {
return undefined;
}
-
- // Extract file operations from messages and previous compaction
const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
-
- // Also extract file ops from turn prefix if splitting
+ // Split turns retain their suffix, but their prefix file operations still belong in the summary.
if (cutPoint.isSplitTurn) {
for (const msg of turnPrefixMessages) {
extractFileOpsFromMessage(msg, fileOps);
@@ -715,11 +648,6 @@ export function prepareCompaction(
settings,
};
}
-
-// ============================================================================
-// Main compaction function
-// ============================================================================
-
const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
Summarize the prefix to provide context for the retained suffix:
@@ -761,12 +689,9 @@ export async function compact(
fileOps,
settings,
} = preparation;
-
- // Generate summaries (can be parallel if both needed) and merge into one
let summary: string;
if (isSplitTurn && turnPrefixMessages.length > 0) {
- // Generate both summaries in parallel
const [historyResult, turnPrefixResult] = await Promise.all([
messagesToSummarize.length > 0
? generateSummary(
@@ -791,10 +716,8 @@ export async function compact(
thinkingLevel,
),
]);
- // Merge into single summary
summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
} else {
- // Just generate history summary
summary = await generateSummary(
messagesToSummarize,
model,
@@ -807,8 +730,6 @@ export async function compact(
thinkingLevel,
);
}
-
- // Compute file lists and append to summary
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
summary += formatFileOperations(readFiles, modifiedFiles);
diff --git a/packages/coding-agent/src/core/compaction/utils.ts b/packages/coding-agent/src/core/compaction/utils.ts
index 63b71803e5..72a764566d 100644
--- a/packages/coding-agent/src/core/compaction/utils.ts
+++ b/packages/coding-agent/src/core/compaction/utils.ts
@@ -4,11 +4,6 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { Message } from "@earendil-works/pi-ai";
-
-// ============================================================================
-// File Operation Tracking
-// ============================================================================
-
export interface FileOperations {
read: Set<string>;
written: Set<string>;
@@ -74,11 +69,6 @@ export function formatFileOperations(readFiles: string[], modifiedFiles: string[
if (sections.length === 0) return "";
return `\n\n${sections.join("\n\n")}`;
}
-
-// ============================================================================
-// Message Serialization
-// ============================================================================
-
/** Maximum characters for a tool result in serialized summaries. */
const TOOL_RESULT_MAX_CHARS = 2000;
@@ -154,11 +144,6 @@ export function serializeConversation(messages: Message[]): string {
return parts.join("\n\n");
}
-
-// ============================================================================
-// Summarization System Prompt
-// ============================================================================
-
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
diff --git a/packages/coding-agent/src/core/context-tree.ts b/packages/coding-agent/src/core/context-tree.ts
index 99f826a29a..6e744b9929 100644
--- a/packages/coding-agent/src/core/context-tree.ts
+++ b/packages/coding-agent/src/core/context-tree.ts
@@ -12,14 +12,10 @@ export type ContextWindowResolver = (provider: string, modelId: string) => numbe
/**
* One agent in the context overview: the main session or an RLM (sub-)agent.
- *
- * `ownUsage` excludes descendant usage (child usage attributions subtracted),
- * so own usage summed over a tree never double-counts. `totalUsage` is the
- * attributed aggregate: own plus all completed descendants, matching what
- * /usage reports for the session.
+ * `ownUsage` excludes descendants; `totalUsage` includes completed descendants, matching /usage.
*/
export interface ContextTreeNode {
- /** "root" for the session itself, the RLM child node id (sub-xxxx) otherwise. */
+ /** "root" for the session itself; sub-xxxx for an RLM child. */
id: string;
label: string;
status: "active" | RlmChildAgentStatus;
@@ -56,7 +52,6 @@ function readUserMessageText(content: unknown): string {
.join("\n");
}
-/** Compact a prompt into a one-line label, mirroring compactRlmText in agent-session.ts. */
function compactLabel(text: string, maxLength = 80): string {
const compact = text.replace(/\s+/g, " ").trim();
if (compact.length <= maxLength) {
diff --git a/packages/coding-agent/src/core/exec.ts b/packages/coding-agent/src/core/exec.ts
index bd62eb5a0e..c3cc408068 100644
--- a/packages/coding-agent/src/core/exec.ts
+++ b/packages/coding-agent/src/core/exec.ts
@@ -77,7 +77,6 @@ export async function execCommand(
if (!killed) {
killed = true;
proc.kill("SIGTERM");
- // Force kill after 5 seconds if SIGTERM doesn't work
forceKillTimeoutId = setTimeout(() => {
forceKillTimeoutId = undefined;
if (proc.exitCode === null && proc.signalCode === null) {
@@ -87,7 +86,6 @@ export async function execCommand(
}
};
- // Handle abort signal
if (options?.signal) {
if (options.signal.aborted) {
killProcess();
@@ -96,7 +94,6 @@ export async function execCommand(
}
}
- // Handle timeout
if (options?.timeout && options.timeout > 0) {
timeoutId = setTimeout(() => {
killProcess();
diff --git a/packages/coding-agent/src/core/export-html/ansi-to-html.ts b/packages/coding-agent/src/core/export-html/ansi-to-html.ts
index d675fd55b3..17afcec98e 100644
--- a/packages/coding-agent/src/core/export-html/ansi-to-html.ts
+++ b/packages/coding-agent/src/core/export-html/ansi-to-html.ts
@@ -11,7 +11,6 @@
* - Reset (0)
*/
-// Standard ANSI color palette (0-15)
const ANSI_COLORS = [
"#000000", // 0: black
"#800000", // 1: red
@@ -35,12 +34,10 @@ const ANSI_COLORS = [
* Convert 256-color index to hex.
*/
function color256ToHex(index: number): string {
- // Standard colors (0-15)
if (index < 16) {
return ANSI_COLORS[index];
}
- // Color cube (16-231): 6x6x6 = 216 colors
if (index < 232) {
const cubeIndex = index - 16;
const r = Math.floor(cubeIndex / 36);
@@ -51,7 +48,6 @@ function color256ToHex(index: number): string {
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
- // Grayscale (232-255): 24 shades
const gray = 8 + (index - 232) * 10;
const grayHex = gray.toString(16).padStart(2, "0");
return `#${grayHex}${grayHex}${grayHex}`;
@@ -113,7 +109,6 @@ function applySgrCode(params: number[], style: TextStyle): void {
const code = params[i];
if (code === 0) {
- // Reset all
style.fg = null;
style.bg = null;
style.bold = false;
@@ -129,7 +124,6 @@ function applySgrCode(params: number[], style: TextStyle): void {
} else if (code === 4) {
style.underline = true;
} else if (code === 22) {
- // Reset bold/dim
style.bold = false;
style.dim = false;
} else if (code === 23) {
@@ -137,16 +131,12 @@ function applySgrCode(params: number[], style: TextStyle): void {
} else if (code === 24) {
style.underline = false;
} else if (code >= 30 && code <= 37) {
- // Standard foreground colors
style.fg = ANSI_COLORS[code - 30];
} else if (code === 38) {
- // Extended foreground color
if (params[i + 1] === 5 && params.length > i + 2) {
- // 256-color: 38;5;N
style.fg = color256ToHex(params[i + 2]);
i += 2;
} else if (params[i + 1] === 2 && params.length > i + 4) {
- // RGB: 38;2;R;G;B
const r = params[i + 2];
const g = params[i + 3];
const b = params[i + 4];
@@ -154,19 +144,14 @@ function applySgrCode(params: number[], style: TextStyle): void {
i += 4;
}
} else if (code === 39) {
- // Default foreground
style.fg = null;
} else if (code >= 40 && code <= 47) {
- // Standard background colors
style.bg = ANSI_COLORS[code - 40];
} else if (code === 48) {
- // Extended background color
if (params[i + 1] === 5 && params.length > i + 2) {
- // 256-color: 48;5;N
style.bg = color256ToHex(params[i + 2]);
i += 2;
} else if (params[i + 1] === 2 && params.length > i + 4) {
- // RGB: 48;2;R;G;B
const r = params[i + 2];
const g = params[i + 3];
const b = params[i + 4];
@@ -174,22 +159,17 @@ function applySgrCode(params: number[], style: TextStyle): void {
i += 4;
}
} else if (code === 49) {
- // Default background
style.bg = null;
} else if (code >= 90 && code <= 97) {
- // Bright foreground colors
style.fg = ANSI_COLORS[code - 90 + 8];
} else if (code >= 100 && code <= 107) {
- // Bright background colors
style.bg = ANSI_COLORS[code - 100 + 8];
}
- // Ignore unrecognized codes
i++;
}
}
-// Match ANSI escape sequences: ESC[ followed by params and ending with 'm'
const ANSI_REGEX = /\x1b\[([\d;]*)m/g;
/**
@@ -201,31 +181,25 @@ export function ansiToHtml(text: string): string {
let lastIndex = 0;
let inSpan = false;
- // Reset regex state
ANSI_REGEX.lastIndex = 0;
let match = ANSI_REGEX.exec(text);
while (match !== null) {
- // Add text before this escape sequence
const beforeText = text.slice(lastIndex, match.index);
if (beforeText) {
result += escapeHtml(beforeText);
}
- // Parse SGR parameters
const paramStr = match[1];
const params = paramStr ? paramStr.split(";").map((p) => parseInt(p, 10) || 0) : [0];
- // Close existing span if we have one
if (inSpan) {
result += "</span>";
inSpan = false;
}
- // Apply the codes
applySgrCode(params, style);
- // Open new span if we have any styling
if (hasStyle(style)) {
result += `<span style="${styleToInlineCSS(style)}">`;
inSpan = true;
@@ -235,13 +209,11 @@ export function ansiToHtml(text: string): string {
match = ANSI_REGEX.exec(text);
}
- // Add remaining text
const remainingText = text.slice(lastIndex);
if (remainingText) {
result += escapeHtml(remainingText);
}
- // Close any open span
if (inSpan) {
result += "</span>";
}
diff --git a/packages/coding-agent/src/core/export-html/index.ts b/packages/coding-agent/src/core/export-html/index.ts
index e667366163..a6733fe9ac 100644
--- a/packages/coding-agent/src/core/export-html/index.ts
+++ b/packages/coding-agent/src/core/export-html/index.ts
@@ -113,8 +113,6 @@ function generateThemeVars(themeName?: string): string {
for (const [key, value] of Object.entries(colors)) {
lines.push(`--${key}: ${value};`);
}
-
- // Use explicit theme export colors if available, otherwise derive from userMessageBg
const themeExport = getThemeExportColors(themeName);
const userMessageBg = colors.userMessageBg || "#343541";
const derivedColors = deriveExportColors(userMessageBg);
@@ -154,11 +152,7 @@ function generateHtml(sessionData: SessionData, themeName?: string): string {
const bodyBg = themeExport.pageBg ?? derivedExportColors.pageBg;
const containerBg = themeExport.cardBg ?? derivedExportColors.cardBg;
const infoBg = themeExport.infoBg ?? derivedExportColors.infoBg;
-
- // Base64 encode session data to avoid escaping issues
const sessionDataBase64 = Buffer.from(JSON.stringify(sessionData)).toString("base64");
-
- // Build the CSS with theme variables injected
const css = templateCss
.replace("{{THEME_VARS}}", themeVars)
.replace("{{BODY_BG}}", bodyBg)
@@ -188,8 +182,6 @@ function preRenderCustomTools(
for (const entry of entries) {
if (entry.type !== "message") continue;
const msg = entry.message;
-
- // Find tool calls in assistant messages
if (msg.role === "assistant" && Array.isArray(msg.content)) {
for (const block of msg.content) {
if (block.type === "toolCall" && !TEMPLATE_RENDERED_TOOLS.has(block.name)) {
@@ -200,11 +192,8 @@ function preRenderCustomTools(
}
}
}
-
- // Find tool results
if (msg.role === "toolResult" && msg.toolCallId) {
const toolName = msg.toolName || "";
- // Only render if we have a pre-rendered call OR it's not template-rendered
const existing = renderedTools[msg.toolCallId];
if (existing || !TEMPLATE_RENDERED_TOOLS.has(toolName)) {
const rendered = toolRenderer.renderResult(
@@ -248,12 +237,9 @@ export async function exportSessionToHtml(
}
const entries = sm.getEntries();
-
- // Pre-render custom tools if a tool renderer is provided
let renderedTools: Record<string, RenderedToolHtml> | undefined;
if (opts.toolRenderer) {
renderedTools = preRenderCustomTools(entries, opts.toolRenderer);
- // Only include if we actually rendered something
if (Object.keys(renderedTools).length === 0) {
renderedTools = undefined;
}
diff --git a/packages/coding-agent/src/core/export-html/template.css b/packages/coding-agent/src/core/export-html/template.css
index c807161ee8..27c902d2ed 100644
--- a/packages/coding-agent/src/core/export-html/template.css
+++ b/packages/coding-agent/src/core/export-html/template.css
@@ -32,8 +32,6 @@
display: flex;
min-height: 100vh;
}
-
- /* Sidebar */
#sidebar {
width: var(--sidebar-width);
min-width: var(--sidebar-width);
@@ -242,8 +240,6 @@
color: var(--muted);
flex-shrink: 0;
}
-
- /* Main content */
#content {
flex: 1;
min-width: 0;
@@ -258,8 +254,6 @@
width: 100%;
max-width: 800px;
}
-
- /* Help bar */
.help-bar {
font-size: 11px;
color: var(--warning);
@@ -299,8 +293,6 @@
background: var(--hover);
border-color: var(--borderAccent);
}
-
- /* Header */
.header {
background: var(--container-bg);
border-radius: 4px;
@@ -338,8 +330,6 @@
color: var(--text);
flex: 1;
}
-
- /* Messages */
#messages {
display: flex;
flex-direction: column;
@@ -364,8 +354,6 @@
padding: 0;
position: relative;
}
-
- /* Copy link button - appears on hover */
.copy-link-btn {
position: absolute;
top: 8px;
@@ -403,8 +391,6 @@
color: white;
border-color: var(--success, #22c55e);
}
-
- /* Highlight effect for deep-linked messages */
.user-message.highlight,
.assistant-message.highlight {
animation: highlight-pulse 2s ease-out;
@@ -455,8 +441,6 @@
color: var(--thinkingText);
font-style: italic;
}
-
- /* Tool execution */
.tool-execution {
padding: var(--line-height);
border-radius: 4px;
@@ -576,8 +560,6 @@
.expand-hint {
color: var(--toolOutput);
}
-
- /* Diff */
.tool-diff {
font-size: 11px;
overflow-x: auto;
@@ -587,8 +569,6 @@
.diff-added { color: var(--toolDiffAdded); }
.diff-removed { color: var(--toolDiffRemoved); }
.diff-context { color: var(--toolDiffContext); }
-
- /* Model change */
.model-change {
padding: 0 var(--line-height);
color: var(--dim);
@@ -599,8 +579,6 @@
color: var(--borderAccent);
font-weight: bold;
}
-
- /* Compaction / Branch Summary - matches customMessage colors from TUI */
.compaction {
background: var(--customMessageBg);
border-radius: 4px;
@@ -631,8 +609,6 @@
.compaction.expanded .compaction-content {
display: block;
}
-
- /* System prompt */
.system-prompt {
background: var(--customMessageBg);
padding: var(--line-height);
@@ -691,8 +667,6 @@
color: var(--muted);
margin-top: 4px;
}
-
- /* Tools list */
.tools-list {
background: var(--customMessageBg);
padding: var(--line-height);
@@ -777,8 +751,6 @@
color: var(--dim);
margin-left: 8px;
}
-
- /* Hook/custom messages */
.hook-message {
background: var(--customMessageBg);
color: var(--customMessageText);
@@ -790,8 +762,6 @@
color: var(--customMessageLabel);
font-weight: bold;
}
-
- /* Skill invocation - matches compaction style (clickable, collapsed by default) */
.skill-invocation {
background: var(--customMessageBg);
border-radius: 4px;
@@ -829,8 +799,6 @@
.skill-user-entry {
position: relative;
}
-
- /* Branch summary */
.branch-summary {
background: var(--customMessageBg);
padding: var(--line-height);
@@ -841,8 +809,6 @@
font-weight: bold;
color: var(--borderAccent);
}
-
- /* Error */
.error-text {
color: var(--error);
padding: 0 var(--line-height);
@@ -850,8 +816,6 @@
.tool-error {
color: var(--error);
}
-
- /* Images */
.message-images {
margin-bottom: 12px;
}
@@ -862,8 +826,6 @@
border-radius: 4px;
margin: var(--line-height) 0;
}
-
- /* Markdown content */
.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
@@ -954,24 +916,18 @@
max-width: 100%;
border-radius: 4px;
}
-
- /* Syntax highlighting */
.hljs { background: transparent; color: var(--text); }
.hljs-comment, .hljs-quote { color: var(--syntaxComment); }
.hljs-keyword, .hljs-selector-tag { color: var(--syntaxKeyword); }
.hljs-number, .hljs-literal { color: var(--syntaxNumber); }
.hljs-string, .hljs-doctag { color: var(--syntaxString); }
- /* Function names: hljs v11 uses .hljs-title.function_ compound class */
.hljs-function, .hljs-title, .hljs-title.function_, .hljs-section, .hljs-name { color: var(--syntaxFunction); }
- /* Types: hljs v11 uses .hljs-title.class_ for class names */
.hljs-type, .hljs-class, .hljs-title.class_, .hljs-built_in { color: var(--syntaxType); }
.hljs-attr, .hljs-variable, .hljs-variable.language_, .hljs-params, .hljs-property { color: var(--syntaxVariable); }
.hljs-meta, .hljs-meta .hljs-keyword, .hljs-meta .hljs-string { color: var(--syntaxKeyword); }
.hljs-operator { color: var(--syntaxOperator); }
.hljs-punctuation { color: var(--syntaxPunctuation); }
.hljs-subst { color: var(--text); }
-
- /* Footer */
.footer {
margin-top: 48px;
padding: 20px;
@@ -979,8 +935,6 @@
color: var(--dim);
font-size: 10px;
}
-
- /* Mobile */
#hamburger {
display: none;
position: fixed;
diff --git a/packages/coding-agent/src/core/export-html/template.html b/packages/coding-agent/src/core/export-html/template.html
index c1d678a0a2..fa43ac0a5b 100644
--- a/packages/coding-agent/src/core/export-html/template.html
+++ b/packages/coding-agent/src/core/export-html/template.html
@@ -40,14 +40,8 @@
</div>
<script id="session-data" type="application/json">{{SESSION_DATA}}</script>
-
- <!-- Vendored libraries -->
<script>{{MARKED_JS}}</script>
-
- <!-- highlight.js -->
<script>{{HIGHLIGHT_JS}}</script>
-
- <!-- Main application code -->
<script>
{{JS}}
</script>
diff --git a/packages/coding-agent/src/core/export-html/template.js b/packages/coding-agent/src/core/export-html/template.js
index 68f2089c1d..ddeaaa5772 100644
--- a/packages/coding-agent/src/core/export-html/template.js
+++ b/packages/coding-agent/src/core/export-html/template.js
@@ -1,10 +1,5 @@
(function() {
'use strict';
-
- // ============================================================
- // DATA LOADING
- // ============================================================
-
const base64 = document.getElementById('session-data').textContent;
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
@@ -13,32 +8,17 @@
}
const data = JSON.parse(new TextDecoder('utf-8').decode(bytes));
const { header, entries, leafId: defaultLeafId, systemPrompt, tools, renderedTools } = data;
-
- // ============================================================
- // URL PARAMETER HANDLING
- // ============================================================
-
- // Parse URL parameters for deep linking: leafId and targetId
- // Check for injected params (when loaded in iframe via srcdoc) or use window.location
const injectedParams = document.querySelector('meta[name="pi-url-params"]');
const searchString = injectedParams ? injectedParams.content : window.location.search.substring(1);
const urlParams = new URLSearchParams(searchString);
const urlLeafId = urlParams.get('leafId');
const urlTargetId = urlParams.get('targetId');
- // Use URL leafId if provided, otherwise fall back to session default
const leafId = urlLeafId || defaultLeafId;
-
- // ============================================================
- // DATA STRUCTURES
- // ============================================================
-
- // Entry lookup by ID
const byId = new Map();
for (const entry of entries) {
byId.set(entry.id, entry);
}
- // Tool call lookup (toolCallId -> {name, arguments})
const toolCallMap = new Map();
for (const entry of entries) {
if (entry.type === 'message' && entry.message.role === 'assistant') {
@@ -53,19 +33,12 @@
}
}
- // Label lookup (entryId -> label string)
- // Labels are stored in 'label' entries that reference their target via targetId
const labelMap = new Map();
for (const entry of entries) {
if (entry.type === 'label' && entry.targetId && entry.label) {
labelMap.set(entry.targetId, entry.label);
}
}
-
- // ============================================================
- // TREE DATA PREPARATION (no DOM, pure data)
- // ============================================================
-
/**
* Build tree structure from flat entries.
* Returns array of root nodes, each with { entry, children, label }.
@@ -74,7 +47,6 @@
const nodeMap = new Map();
const roots = [];
- // Create nodes
for (const entry of entries) {
nodeMap.set(entry.id, {
entry,
@@ -83,7 +55,6 @@
});
}
- // Build parent-child relationships
for (const entry of entries) {
const node = nodeMap.get(entry.id);
if (entry.parentId === null || entry.parentId === undefined || entry.parentId === entry.id) {
@@ -98,7 +69,6 @@
}
}
- // Sort children by timestamp
function sortChildren(node) {
node.children.sort((a, b) =>
new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
@@ -118,7 +88,6 @@
let current = byId.get(targetId);
while (current) {
ids.add(current.id);
- // Stop if no parent or self-referencing (root)
if (!current.parentId || current.parentId === current.id) {
break;
}
@@ -135,7 +104,6 @@
let current = byId.get(targetId);
while (current) {
path.unshift(current);
- // Stop if no parent or self-referencing (root)
if (!current.parentId || current.parentId === current.id) {
break;
}
@@ -144,7 +112,6 @@
return path;
}
- // Tree node lookup for finding leaves
let treeNodeMap = null;
/**
@@ -153,7 +120,6 @@
* Children are sorted by timestamp, so the newest is always last.
*/
function findNewestLeaf(nodeId) {
- // Build tree node map lazily
if (!treeNodeMap) {
treeNodeMap = new Map();
const tree = buildTree();
@@ -167,7 +133,6 @@
const node = treeNodeMap.get(nodeId);
if (!node) return nodeId;
- // Follow the newest (last) child at each level
let current = node;
while (current.children.length > 0) {
current = current.children[current.children.length - 1];
@@ -184,7 +149,6 @@
const result = [];
const multipleRoots = roots.length > 1;
- // Mark which subtrees contain the active leaf
const containsActive = new Map();
function markActive(node) {
let has = activePathIds.has(node.entry.id);
@@ -196,10 +160,8 @@
}
roots.forEach(markActive);
- // Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
const stack = [];
- // Add roots (prioritize branch containing active leaf)
const orderedRoots = [...roots].sort((a, b) =>
Number(containsActive.get(b)) - Number(containsActive.get(a))
);
@@ -216,25 +178,19 @@
const children = node.children;
const multipleChildren = children.length > 1;
- // Order children (active branch first)
const orderedChildren = [...children].sort((a, b) =>
Number(containsActive.get(b)) - Number(containsActive.get(a))
);
- // Calculate child indent (matches tree-selector.ts)
let childIndent;
if (multipleChildren) {
- // Parent branches: children get +1
childIndent = indent + 1;
} else if (justBranched && indent > 0) {
- // First generation after a branch: +1 for visual grouping
childIndent = indent + 1;
} else {
- // Single-child chain: stay flat
childIndent = indent;
}
- // Build gutters for children
const connectorDisplayed = showConnector && !isVirtualRootChild;
const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
const connectorPosition = Math.max(0, currentDisplayIndent - 1);
@@ -242,7 +198,6 @@
? [...gutters, { position: connectorPosition, show: !isLast }]
: gutters;
- // Add children in reverse order for stack
for (let i = orderedChildren.length - 1; i >= 0; i--) {
const childIsLast = i === orderedChildren.length - 1;
stack.push([orderedChildren[i], childIndent, multipleChildren, multipleChildren, childIsLast, childGutters, false]);
@@ -284,11 +239,6 @@
}
return prefixChars.join('');
}
-
- // ============================================================
- // FILTERING (pure data)
- // ============================================================
-
let filterMode = 'default';
let searchQuery = '';
@@ -377,10 +327,8 @@
const label = flatNode.node.label;
const isCurrentLeaf = entry.id === currentLeafId;
- // Always show current leaf
if (isCurrentLeaf) return true;
- // Hide assistant messages with only tool calls (no text) unless error/aborted
if (entry.type === 'message' && entry.message.role === 'assistant') {
const msg = entry.message;
const hasText = hasTextContent(msg.content);
@@ -388,7 +336,6 @@
if (!hasText && !isErrorOrAborted) return false;
}
- // Apply filter mode
const isSettingsEntry = [
'label',
'custom',
@@ -418,7 +365,6 @@
if (!passesFilter) return false;
- // Apply search filter
if (searchTokens.length > 0) {
const nodeText = getSearchableText(entry, label);
if (!searchTokens.every(t => nodeText.includes(t))) return false;
@@ -427,7 +373,6 @@
return true;
});
- // Recalculate visual structure based on visible tree
recalculateVisualStructure(filtered, flatNodes);
return filtered;
@@ -444,13 +389,11 @@
const visibleIds = new Set(filteredNodes.map(n => n.node.entry.id));
- // Build entry map for parent lookup (using full tree)
const entryMap = new Map();
for (const flatNode of allFlatNodes) {
entryMap.set(flatNode.node.entry.id, flatNode);
}
- // Find nearest visible ancestor for a node
function findVisibleAncestor(nodeId) {
let currentId = entryMap.get(nodeId)?.node.entry.parentId;
while (currentId != null) {
@@ -462,7 +405,6 @@
return null;
}
- // Build visible tree structure
const visibleParent = new Map();
const visibleChildren = new Map();
visibleChildren.set(null, []); // root-level nodes
@@ -478,21 +420,16 @@
visibleChildren.get(ancestorId).push(nodeId);
}
- // Update multipleRoots based on visible roots
const visibleRootIds = visibleChildren.get(null);
const multipleRoots = visibleRootIds.length > 1;
- // Build a map for quick lookup: nodeId → FlatNode
const filteredNodeMap = new Map();
for (const flatNode of filteredNodes) {
filteredNodeMap.set(flatNode.node.entry.id, flatNode);
}
- // DFS traversal of visible tree, applying same indentation rules as flattenTree()
- // Stack items: [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
const stack = [];
- // Add visible roots in reverse order (to process in forward order via stack)
for (let i = visibleRootIds.length - 1; i >= 0; i--) {
const isLast = i === visibleRootIds.length - 1;
stack.push([
@@ -512,7 +449,6 @@
const flatNode = filteredNodeMap.get(nodeId);
if (!flatNode) continue;
- // Update this node's visual properties
flatNode.indent = indent;
flatNode.showConnector = showConnector;
flatNode.isLast = isLast;
@@ -520,14 +456,9 @@
flatNode.isVirtualRootChild = isVirtualRootChild;
flatNode.multipleRoots = multipleRoots;
- // Get visible children of this node
const children = visibleChildren.get(nodeId) || [];
const multipleChildren = children.length > 1;
- // Calculate child indent using same rules as flattenTree():
- // - Parent branches (multiple children): children get +1
- // - Just branched and indent > 0: children get +1 for visual grouping
- // - Single-child chain: stay flat
let childIndent;
if (multipleChildren) {
childIndent = indent + 1;
@@ -537,7 +468,6 @@
childIndent = indent;
}
- // Build gutters for children (same logic as flattenTree)
const connectorDisplayed = showConnector && !isVirtualRootChild;
const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
const connectorPosition = Math.max(0, currentDisplayIndent - 1);
@@ -545,7 +475,6 @@
? [...gutters, { position: connectorPosition, show: !isLast }]
: gutters;
- // Add children in reverse order (to process in forward order via stack)
for (let i = children.length - 1; i >= 0; i--) {
const childIsLast = i === children.length - 1;
stack.push([
@@ -560,11 +489,6 @@
}
}
}
-
- // ============================================================
- // TREE DISPLAY TEXT (pure data -> string)
- // ============================================================
-
function shortenPath(p) {
if (typeof p !== 'string') return '';
if (p.startsWith('/Users/')) {
@@ -697,11 +621,6 @@
return labelHtml + `<span class="tree-muted">[${escapeHtml(entry.type)}]</span>`;
}
}
-
- // ============================================================
- // TREE RENDERING (DOM manipulation)
- // ============================================================
-
let currentLeafId = leafId;
let currentTargetId = urlTargetId || leafId;
let treeRendered = false;
@@ -713,7 +632,6 @@
const filtered = filterNodes(flatNodes, currentLeafId);
const container = document.getElementById('tree-container');
- // Full render only on first call or when filter/search changes
if (!treeRendered) {
container.innerHTML = '';
@@ -744,7 +662,6 @@
div.appendChild(prefixSpan);
div.appendChild(marker);
div.appendChild(content);
- // Navigate to the newest leaf through this node, but scroll to the clicked node
div.addEventListener('click', () => {
if (window.getSelection().toString()) return;
const leafId = findNewestLeaf(entry.id);
@@ -756,7 +673,6 @@
treeRendered = true;
} else {
- // Just update markers and classes
const nodes = container.querySelectorAll('.tree-node');
for (const node of nodes) {
const id = node.dataset.id;
@@ -775,7 +691,6 @@
document.getElementById('tree-status').textContent = `${filtered.length} / ${flatNodes.length} entries`;
- // Scroll active node into view after layout
setTimeout(() => {
const activeNode = container.querySelector('.tree-node.active');
if (activeNode) {
@@ -788,11 +703,6 @@
treeRendered = false;
renderTree();
}
-
- // ============================================================
- // MESSAGE RENDERING
- // ============================================================
-
function formatTokens(count) {
if (count < 1000) return count.toString();
if (count < 10000) return (count / 1000).toFixed(1) + 'k';
@@ -874,7 +784,6 @@
return `<div class="tool-output"><pre><code class="hljs">${highlighted}</code></pre></div>`;
}
- // Plain text output
if (remaining > 0) {
let out = '<div class="tool-output expandable" onclick="if(window.getSelection().toString())return;this.classList.toggle(\'expanded\')">';
out += '<div class="output-preview">';
@@ -1018,10 +927,8 @@
break;
}
default: {
- // Check for pre-rendered custom tool HTML
const rendered = renderedTools?.[call.id];
if (rendered?.callHtml || rendered?.resultHtmlCollapsed || rendered?.resultHtmlExpanded) {
- // Custom tool with pre-rendered HTML from TUI renderer
if (rendered.callHtml) {
html += `<div class="tool-header ansi-rendered">${rendered.callHtml}</div>`;
} else {
@@ -1029,21 +936,17 @@
}
if (rendered.resultHtmlCollapsed && rendered.resultHtmlExpanded && rendered.resultHtmlCollapsed !== rendered.resultHtmlExpanded) {
- // Both collapsed and expanded differ - render expandable section
html += `<div class="tool-output expandable ansi-rendered" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
<div class="output-preview">${rendered.resultHtmlCollapsed}</div>
<div class="output-full">${rendered.resultHtmlExpanded}</div>
</div>`;
} else if (rendered.resultHtmlExpanded) {
- // Only expanded exists (or collapsed is identical) - show directly
html += `<div class="tool-output ansi-rendered">${rendered.resultHtmlExpanded}</div>`;
} else if (result) {
- // No pre-rendered result HTML - fallback to JSON
const output = getResultText();
if (output) html += formatExpandableOutput(output, 10);
}
} else {
- // Fallback to JSON display (existing behavior)
html += `<div class="tool-header"><span class="tool-name">${escapeHtml(name)}</span></div>`;
html += `<div class="tool-output"><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></div>`;
if (result) {
@@ -1063,7 +966,6 @@
* Reconstructs the original format: header line + entry lines.
*/
window.downloadSessionJson = function() {
- // Build JSONL content: header first, then all entries
const lines = [];
if (header) {
lines.push(JSON.stringify({ type: 'header', ...header }));
@@ -1073,7 +975,6 @@
}
const jsonlContent = lines.join('\n');
- // Create download
const blob = new Blob([jsonlContent], { type: 'application/x-ndjson' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -1090,25 +991,20 @@
* URL format: base?gistId&leafId=<leafId>&targetId=<entryId>
*/
function buildShareUrl(entryId) {
- // Check for injected base URL (used when loaded in iframe via srcdoc)
const baseUrlMeta = document.querySelector('meta[name="pi-share-base-url"]');
const baseUrl = baseUrlMeta ? baseUrlMeta.content : window.location.href.split('?')[0];
const url = new URL(window.location.href);
- // Find the gist ID (first query param without value, e.g., ?abc123)
const gistId = Array.from(url.searchParams.keys()).find(k => !url.searchParams.get(k));
- // Build the share URL
const params = new URLSearchParams();
params.set('leafId', currentLeafId);
params.set('targetId', entryId);
- // If we have an injected base URL (iframe context), use it directly
if (baseUrlMeta) {
return `${baseUrl}&${params.toString()}`;
}
- // Otherwise build from current location (direct file access)
url.search = gistId ? `?${gistId}&${params.toString()}` : `?${params.toString()}`;
return url.toString();
}
@@ -1125,10 +1021,8 @@
success = true;
}
} catch (err) {
- // Clipboard API failed, try fallback
}
- // Fallback for HTTP or when Clipboard API is unavailable
if (!success) {
try {
const textarea = document.createElement('textarea');
@@ -1183,19 +1077,16 @@
const skillBlock = parseSkillBlock(text);
if (skillBlock) {
- // Collect images from content array
const images = Array.isArray(content) ? content.filter(c => c.type === 'image') : [];
const hasUserContent = skillBlock.userMessage || images.length > 0;
let html = `<div class="skill-user-entry" id="${entryDomId}">${copyBtnHtml}${tsHtml}`;
- // Skill invocation (collapsed by default, click to expand)
html += `<div class="skill-invocation" onclick="if(window.getSelection().toString())return;this.classList.toggle('expanded')">
<div class="skill-invocation-label">[skill] ${escapeHtml(skillBlock.name)}</div>
<div class="skill-invocation-collapsed">${escapeHtml(skillBlock.name)} (click to expand)</div>
<div class="skill-invocation-content markdown-content">${safeMarkedParse(skillBlock.content)}</div>
</div>`;
- // User message (separate block if present)
if (hasUserContent) {
html += '<div class="user-message">';
if (images.length > 0) {
@@ -1215,7 +1106,6 @@
return html;
}
- // No skill block - normal user message
let html = `<div class="user-message" id="${entryDomId}">${copyBtnHtml}${tsHtml}`;
if (Array.isArray(content)) {
@@ -1311,11 +1201,6 @@
return '';
}
-
- // ============================================================
- // HEADER / STATS
- // ============================================================
-
function computeStats(entryList) {
let userMessages = 0, assistantMessages = 0, toolResults = 0;
let customMessages = 0, compactions = 0, branchSummaries = 0, toolCalls = 0;
@@ -1397,7 +1282,6 @@
</div>
</div>`;
- // Render system prompt (user's base prompt, applies to all providers)
if (systemPrompt) {
const lines = systemPrompt.split('\n');
const previewLines = 10;
@@ -1449,21 +1333,13 @@
return html;
}
-
- // ============================================================
- // NAVIGATION
- // ============================================================
-
- // Cache for rendered entry DOM nodes
const entryCache = new Map();
function renderEntryToNode(entry) {
- // Check cache first
if (entryCache.has(entry.id)) {
return entryCache.get(entry.id).cloneNode(true);
}
- // Render to HTML string, then parse to node
const html = renderEntry(entry);
if (!html) return null;
@@ -1471,7 +1347,6 @@
template.innerHTML = html;
const node = template.content.firstElementChild;
- // Cache the node
if (node) {
entryCache.set(entry.id, node.cloneNode(true));
}
@@ -1488,7 +1363,6 @@
document.getElementById('header-container').innerHTML = renderHeader();
attachHeaderHandlers();
- // Build messages using cached DOM nodes
const messagesEl = document.getElementById('messages');
const fragment = document.createDocumentFragment();
@@ -1502,7 +1376,6 @@
messagesEl.innerHTML = '';
messagesEl.appendChild(fragment);
- // Attach click handlers for copy-link buttons
messagesEl.querySelectorAll('.copy-link-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
@@ -1512,18 +1385,15 @@
});
});
- // Use setTimeout(0) to ensure DOM is fully laid out before scrolling
setTimeout(() => {
const content = document.getElementById('content');
if (scrollMode === 'bottom') {
content.scrollTop = content.scrollHeight;
} else if (scrollMode === 'target') {
- // If scrollToEntryId is provided, scroll to that specific entry
const scrollTargetId = scrollToEntryId || targetId;
const targetEl = document.getElementById(`entry-${scrollTargetId}`);
if (targetEl) {
targetEl.scrollIntoView({ block: 'center' });
- // Briefly highlight the target message
if (scrollToEntryId) {
targetEl.classList.add('highlight');
setTimeout(() => targetEl.classList.remove('highlight'), 2000);
@@ -1532,20 +1402,12 @@
}
}, 0);
}
-
- // ============================================================
- // INITIALIZATION
- // ============================================================
-
- // Configure marked with syntax highlighting and TUI-compatible HTML handling
const strictStrikethroughRegex = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
marked.use({
breaks: true,
gfm: true,
tokenizer: {
- // Treat HTML-like input as plain text so tags are shown verbatim,
- // matching the TUI markdown renderer.
html() {
return undefined;
},
@@ -1564,7 +1426,6 @@
}
},
renderer: {
- // Sanitize link URLs to prevent javascript:/vbscript:/data: XSS
link(token) {
const href = (token.href || '').trim();
if (/^\s*(javascript|vbscript|data):/i.test(href)) {
@@ -1577,7 +1438,6 @@
out += '>' + this.parser.parseInline(token.tokens) + '</a>';
return out;
},
- // Sanitize image src URLs
image(token) {
const href = (token.href || '').trim();
if (/^\s*(javascript|vbscript|data):/i.test(href)) {
@@ -1590,7 +1450,6 @@
out += '>';
return out;
},
- // Code blocks: syntax highlight, no HTML escaping
code(token) {
const code = token.text;
const lang = token.lang;
@@ -1602,7 +1461,6 @@
highlighted = escapeHtml(code);
}
} else {
- // Auto-detect language if not specified
try {
highlighted = hljs.highlightAuto(code).value;
} catch {
@@ -1611,26 +1469,22 @@
}
return `<pre><code class="hljs">${highlighted}</code></pre>`;
},
- // Inline code: escape HTML
codespan(token) {
return `<code>${escapeHtml(token.text)}</code>`;
}
}
});
- // Simple marked parse (escaping handled in renderers)
function safeMarkedParse(text) {
return marked.parse(text);
}
- // Search input
const searchInput = document.getElementById('tree-search');
searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value;
forceTreeRerender();
});
- // Filter buttons
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
@@ -1640,7 +1494,6 @@
});
});
- // Sidebar toggle
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('sidebar-overlay');
const hamburger = document.getElementById('hamburger');
@@ -1687,7 +1540,6 @@
try {
localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(Math.round(clampSidebarWidth(width))));
} catch {
- // Ignore storage failures (e.g. private browsing restrictions)
}
}
@@ -1767,7 +1619,6 @@
overlay.addEventListener('click', closeSidebar);
document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
- // Toggle states
let thinkingExpanded = true;
let toolOutputsExpanded = false;
@@ -1808,7 +1659,6 @@
return element.isContentEditable || Boolean(element.closest?.('[contenteditable="true"]'));
};
- // Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
searchInput.value = '';
@@ -1830,17 +1680,13 @@
}
});
- // Initial render
- // If URL has targetId, scroll to that specific message; otherwise stay at top
if (leafId) {
if (urlTargetId && byId.has(urlTargetId)) {
- // Deep link: navigate to leaf and scroll to target message
navigateTo(leafId, 'target', urlTargetId);
} else {
navigateTo(leafId, 'none');
}
} else if (entries.length > 0) {
- // Fallback: use last entry if no leafId
navigateTo(entries[entries.length - 1].id, 'none');
}
})();
diff --git a/packages/coding-agent/src/core/export-html/tool-renderer.ts b/packages/coding-agent/src/core/export-html/tool-renderer.ts
index 4f6d569efc..7ba99a1410 100644
--- a/packages/coding-agent/src/core/export-html/tool-renderer.ts
+++ b/packages/coding-agent/src/core/export-html/tool-renderer.ts
@@ -114,7 +114,6 @@ export function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRend
const lines = component.render(width);
return ansiLinesToHtml(lines);
} catch {
- // On error, return undefined so HTML export can fall back to structured result rendering
return undefined;
}
},
@@ -132,15 +131,12 @@ export function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRend
return undefined;
}
- // Build AgentToolResult from content array
- // Cast content since session storage uses generic object types
const agentToolResult = {
content: result as (TextContent | ImageContent)[],
details,
isError,
};
- // Render collapsed
const collapsedComponent = toolDef.renderResult(
agentToolResult,
{ expanded: false, isPartial: false },
@@ -150,7 +146,6 @@ export function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRend
renderedResultComponents.set(toolCallId, collapsedComponent);
const collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));
- // Render expanded
const expandedComponent = toolDef.renderResult(
agentToolResult,
{ expanded: true, isPartial: false },
@@ -165,7 +160,6 @@ export function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRend
expanded,
};
} catch {
- // On error, return undefined so HTML export can fall back to structured result rendering
return undefined;
}
},
diff --git a/packages/coding-agent/src/core/extensions/index.ts b/packages/coding-agent/src/core/extensions/index.ts
index 0ddadf4a1d..26ea3b2290 100644
--- a/packages/coding-agent/src/core/extensions/index.ts
+++ b/packages/coding-agent/src/core/extensions/index.ts
@@ -4,7 +4,6 @@
export type { SlashCommandInfo, SlashCommandSource } from "../slash-commands.js";
export type { SourceInfo } from "../source-info.js";
-// Built-in extensions
export {
createHerdrAgentStateExtension,
hasFileBasedHerdrIntegration,
@@ -29,14 +28,11 @@ export type {
AfterProviderResponseEvent,
AgentEndEvent,
AgentStartEvent,
- // Re-exports
AgentToolResult,
AgentToolUpdateCallback,
AppendEntryHandler,
- // App keybindings (for custom editors)
AppKeybinding,
AutocompleteProviderFactory,
- // Events - Tool (ToolCallEvent types)
BashToolCallEvent,
BashToolResultEvent,
BeforeAgentStartEvent,
@@ -44,11 +40,8 @@ export type {
BeforeProviderRequestEvent,
BeforeProviderRequestEventResult,
BuildSystemPromptOptions,
- // Context
CompactOptions,
- // Events - Agent
ContextEvent,
- // Event Results
ContextEventResult,
ContextUsage,
CustomToolCallEvent,
@@ -60,19 +53,16 @@ export type {
ExecResult,
Extension,
ExtensionActions,
- // API
ExtensionAPI,
ExtensionCommandContext,
ExtensionCommandContextActions,
ExtensionContext,
ExtensionContextActions,
- // Errors
ExtensionError,
ExtensionEvent,
ExtensionFactory,
ExtensionFlag,
ExtensionHandler,
- // Runtime
ExtensionRuntime,
ExtensionShortcut,
ExtensionUIContext,
@@ -82,7 +72,6 @@ export type {
GetAllToolsHandler,
GetCommandsHandler,
GetThinkingLevelHandler,
- // Events - Input
InputEvent,
InputEventResult,
InputSource,
@@ -90,26 +79,21 @@ export type {
IpythonToolResultEvent,
KeybindingsManager,
LoadExtensionsResult,
- // Events - Message
MessageEndEvent,
- // Message Rendering
MessageRenderer,
MessageRenderOptions,
MessageStartEvent,
MessageUpdateEvent,
ModelSelectEvent,
ModelSelectSource,
- // Provider Registration
ProviderConfig,
ProviderModelConfig,
RefineCompleteEvent,
- // Commands
RegisteredCommand,
RegisteredTool,
ReplacedSessionContext,
ReplayBuiltInToolName,
ResolvedCommand,
- // Events - Resources
ResourcesDiscoverEvent,
ResourcesDiscoverResult,
SendMessageHandler,
@@ -125,7 +109,6 @@ export type {
SessionCompactEvent,
SessionEvent,
SessionShutdownEvent,
- // Events - Session
SessionStartEvent,
SessionTreeEvent,
SetActiveToolsHandler,
@@ -133,14 +116,10 @@ export type {
SetModelHandler,
SetThinkingLevelHandler,
TerminalInputHandler,
- // Events - Tool
ToolCallEvent,
ToolCallEventResult,
- // Tools
ToolDefinition,
- // Events - Tool Execution
ToolExecutionEndEvent,
- // Tool execution mode
ToolExecutionMode,
ToolExecutionStartEvent,
ToolExecutionUpdateEvent,
@@ -151,13 +130,11 @@ export type {
TreePreparation,
TurnEndEvent,
TurnStartEvent,
- // Events - User Bash
UserBashEvent,
UserBashEventResult,
WidgetPlacement,
WorkingIndicatorOptions,
} from "./types.js";
-// Type guards
export {
defineTool,
isBashToolResult,
diff --git a/packages/coding-agent/src/core/extensions/loader.ts b/packages/coding-agent/src/core/extensions/loader.ts
index c22dc49628..2c7e81ad6b 100644
--- a/packages/coding-agent/src/core/extensions/loader.ts
+++ b/packages/coding-agent/src/core/extensions/loader.ts
@@ -172,7 +172,6 @@ function createExtensionAPI(
eventBus: EventBus,
): ExtensionAPI {
const api = {
- // Registration methods - write to extension
on(event: string, handler: HandlerFn): void {
runtime.assertActive();
const list = extension.handlers.get(event) ?? [];
@@ -225,14 +224,12 @@ function createExtensionAPI(
extension.messageRenderers.set(customType, renderer as MessageRenderer);
},
- // Flag access - checks extension registered it, reads from runtime
getFlag(name: string): boolean | string | undefined {
runtime.assertActive();
if (!extension.flags.has(name)) return undefined;
return runtime.flagValues.get(name);
},
- // Action methods - delegate to shared runtime
sendMessage(message, options): void {
runtime.assertActive();
runtime.sendMessage(message, options);
@@ -478,7 +475,6 @@ function isExtensionFile(name: string): boolean {
* Returns resolved paths or null if no entry points found.
*/
function resolveExtensionEntries(dir: string): string[] | null {
- // Check for package.json with "pi" field first
const packageJsonPath = path.join(dir, "package.json");
if (fs.existsSync(packageJsonPath)) {
const manifest = readPiManifest(packageJsonPath);
@@ -496,7 +492,6 @@ function resolveExtensionEntries(dir: string): string[] | null {
}
}
- // Check for index.ts or index.js
const indexTs = path.join(dir, "index.ts");
const indexJs = path.join(dir, "index.js");
if (fs.existsSync(indexTs)) {
@@ -532,13 +527,11 @@ function discoverExtensionsInDir(dir: string): string[] {
for (const entry of entries) {
const entryPath = path.join(dir, entry.name);
- // 1. Direct files: *.ts or *.js
if ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {
discovered.push(entryPath);
continue;
}
- // 2 & 3. Subdirectories
if (entry.isDirectory() || entry.isSymbolicLink()) {
const entries = resolveExtensionEntries(entryPath);
if (entries) {
@@ -575,25 +568,20 @@ export async function discoverAndLoadExtensions(
}
};
- // 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/
const localExtDir = path.join(cwd, CONFIG_DIR_NAME, "extensions");
addPaths(discoverExtensionsInDir(localExtDir));
- // 2. Global extensions: agentDir/extensions/
const globalExtDir = path.join(agentDir, "extensions");
addPaths(discoverExtensionsInDir(globalExtDir));
- // 3. Explicitly configured paths
for (const p of configuredPaths) {
const resolved = resolvePath(p, cwd);
if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
- // Check for package.json with pi manifest or index.ts
const entries = resolveExtensionEntries(resolved);
if (entries) {
addPaths(entries);
continue;
}
- // No explicit entries - discover individual files in directory
addPaths(discoverExtensionsInDir(resolved));
continue;
}
diff --git a/packages/coding-agent/src/core/extensions/runner.ts b/packages/coding-agent/src/core/extensions/runner.ts
index 21c739c16a..618aa19431 100644
--- a/packages/coding-agent/src/core/extensions/runner.ts
+++ b/packages/coding-agent/src/core/extensions/runner.ts
@@ -271,7 +271,6 @@ export class ExtensionRunner {
unregisterProvider?: (name: string) => void;
},
): void {
- // Copy actions into the shared runtime (all extension APIs reference this)
this.runtime.sendMessage = actions.sendMessage;
this.runtime.sendUserMessage = actions.sendUserMessage;
this.runtime.appendEntry = actions.appendEntry;
@@ -287,7 +286,6 @@ export class ExtensionRunner {
this.runtime.getThinkingLevel = actions.getThinkingLevel;
this.runtime.setThinkingLevel = actions.setThinkingLevel;
- // Context actions (required)
this.getModel = contextActions.getModel;
this.isIdleFn = contextActions.isIdle;
this.getSignalFn = contextActions.getSignal;
@@ -298,7 +296,6 @@ export class ExtensionRunner {
this.compactFn = contextActions.compact;
this.getSystemPromptFn = contextActions.getSystemPrompt;
- // Flush provider registrations queued during extension loading
for (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {
try {
if (providerActions?.registerProvider) {
@@ -316,9 +313,6 @@ export class ExtensionRunner {
}
}
this.runtime.pendingProviderRegistrations = [];
-
- // From this point on, provider registration/unregistration takes effect immediately
- // without requiring a /reload.
this.runtime.registerProvider = (name, config) => {
if (providerActions?.registerProvider) {
providerActions.registerProvider(name, config);
diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.ts
index 1dc4ee88cb..289405fdfc 100644
--- a/packages/coding-agent/src/core/extensions/types.ts
+++ b/packages/coding-agent/src/core/extensions/types.ts
@@ -73,11 +73,6 @@ export type { ExecOptions, ExecResult } from "../exec.js";
export type { AppKeybinding, KeybindingsManager } from "../keybindings.js";
export type { BuildSystemPromptOptions } from "../system-prompt.js";
export type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };
-
-// ============================================================================
-// UI Context
-// ============================================================================
-
/** Options for extension UI dialogs. */
export interface ExtensionUIDialogOptions {
/** AbortSignal to programmatically dismiss the dialog. */
@@ -266,11 +261,6 @@ export interface ExtensionUIContext {
/** Set tool output expansion state. */
setToolsExpanded(expanded: boolean): void;
}
-
-// ============================================================================
-// Extension Context
-// ============================================================================
-
export interface ContextUsage {
/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */
tokens: number | null;
@@ -372,11 +362,6 @@ export interface ReplacedSessionContext extends ExtensionCommandContext {
options?: { deliverAs?: "steer" | "followUp" },
): Promise<void>;
}
-
-// ============================================================================
-// Tool Types
-// ============================================================================
-
/** Rendering options for tool results */
export interface ToolRenderResultOptions {
/** Whether the result view is expanded */
@@ -487,11 +472,6 @@ export function defineTool<TParams extends TSchema, TDetails = unknown, TState =
): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {
return tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;
}
-
-// ============================================================================
-// Resource Events
-// ============================================================================
-
/** Fired after session_start to allow extensions to provide additional resource paths. */
export interface ResourcesDiscoverEvent {
type: "resources_discover";
@@ -505,11 +485,6 @@ export interface ResourcesDiscoverResult {
promptPaths?: string[];
themePaths?: string[];
}
-
-// ============================================================================
-// Session Events
-// ============================================================================
-
/** Fired when a session is started, loaded, or reloaded */
export interface SessionStartEvent {
type: "session_start";
@@ -597,11 +572,6 @@ export type SessionEvent =
| SessionShutdownEvent
| SessionBeforeTreeEvent
| SessionTreeEvent;
-
-// ============================================================================
-// Agent Events
-// ============================================================================
-
/** Fired before each LLM call. Can modify messages. */
export interface ContextEvent {
type: "context";
@@ -717,11 +687,6 @@ export interface ToolExecutionEndEvent {
result: any;
isError: boolean;
}
-
-// ============================================================================
-// Model Events
-// ============================================================================
-
export type ModelSelectSource = "set" | "cycle" | "restore";
/** Fired when a new model is selected */
@@ -738,11 +703,6 @@ export interface ThinkingLevelSelectEvent {
level: ThinkingLevel;
previousLevel: ThinkingLevel;
}
-
-// ============================================================================
-// User Bash Events
-// ============================================================================
-
/** Fired when user executes a bash command via ! or !! prefix */
export interface UserBashEvent {
type: "user_bash";
@@ -753,11 +713,6 @@ export interface UserBashEvent {
/** Current working directory */
cwd: string;
}
-
-// ============================================================================
-// Input Events
-// ============================================================================
-
/** Source of user input */
export type InputSource = "interactive" | "rpc" | "extension";
@@ -777,11 +732,6 @@ export type InputEventResult =
| { action: "continue" }
| { action: "transform"; text: string; images?: ImageContent[] }
| { action: "handled" };
-
-// ============================================================================
-// Tool Events
-// ============================================================================
-
interface ToolCallEventBase {
type: "tool_call";
toolCallId: string;
@@ -850,7 +800,6 @@ export type ToolResultEvent =
| IpythonToolResultEvent
| CustomToolResultEvent;
-// Type guards for ToolResultEvent
export function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {
return e.toolName === "bash";
}
@@ -917,11 +866,6 @@ export type ExtensionEvent =
| ToolCallEvent
| ToolResultEvent
| RefineCompleteEvent;
-
-// ============================================================================
-// Event Results
-// ============================================================================
-
export interface ContextEventResult {
messages?: AgentMessage[];
}
@@ -986,11 +930,6 @@ export interface SessionBeforeTreeResult {
/** Override label to attach to the branch summary entry */
label?: string;
}
-
-// ============================================================================
-// Message Rendering
-// ============================================================================
-
export interface MessageRenderOptions {
expanded: boolean;
}
@@ -1000,11 +939,6 @@ export type MessageRenderer<T = unknown> = (
options: MessageRenderOptions,
theme: Theme,
) => Component | undefined;
-
-// ============================================================================
-// Command Registration
-// ============================================================================
-
export interface RegisteredCommand {
name: string;
sourceInfo: SourceInfo;
@@ -1016,11 +950,6 @@ export interface RegisteredCommand {
export interface ResolvedCommand extends RegisteredCommand {
invocationName: string;
}
-
-// ============================================================================
-// Extension API
-// ============================================================================
-
/** Handler function type for events */
// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements
export type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;
@@ -1029,10 +958,6 @@ export type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContex
* ExtensionAPI passed to extension factory functions.
*/
export interface ExtensionAPI {
- // =========================================================================
- // Event Subscription
- // =========================================================================
-
on(event: "resources_discover", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;
on(event: "session_start", handler: ExtensionHandler<SessionStartEvent>): void;
on(
@@ -1072,20 +997,10 @@ export interface ExtensionAPI {
on(event: "user_bash", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;
on(event: "input", handler: ExtensionHandler<InputEvent, InputEventResult>): void;
on(event: "refine_complete", handler: ExtensionHandler<RefineCompleteEvent>): void;
-
- // =========================================================================
- // Tool Registration
- // =========================================================================
-
/** Register a tool that the LLM can call. */
registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(
tool: ToolDefinition<TParams, TDetails, TState>,
): void;
-
- // =========================================================================
- // Command, Shortcut, Flag Registration
- // =========================================================================
-
/** Register a custom command. */
registerCommand(name: string, options: Omit<RegisteredCommand, "name" | "sourceInfo">): void;
@@ -1110,18 +1025,8 @@ export interface ExtensionAPI {
/** Get the value of a registered CLI flag. */
getFlag(name: string): boolean | string | undefined;
-
- // =========================================================================
- // Message Rendering
- // =========================================================================
-
/** Register a custom renderer for CustomMessageEntry. */
registerMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;
-
- // =========================================================================
- // Actions
- // =========================================================================
-
/** Send a custom message to the session. */
sendMessage<T = unknown>(
message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
@@ -1139,11 +1044,6 @@ export interface ExtensionAPI {
/** Append a custom entry to the session for state persistence (not sent to LLM). */
appendEntry<T = unknown>(customType: string, data?: T): void;
-
- // =========================================================================
- // Session Metadata
- // =========================================================================
-
/** Set the session display name (shown in session selector). */
setSessionName(name: string): void | Promise<void>;
@@ -1167,11 +1067,6 @@ export interface ExtensionAPI {
/** Get available slash commands in the current session. */
getCommands(): SlashCommandInfo[];
-
- // =========================================================================
- // Model and Thinking Level
- // =========================================================================
-
/** Set the current model. Returns false if no API key available. */
setModel(model: Model<any>): Promise<boolean>;
@@ -1180,11 +1075,6 @@ export interface ExtensionAPI {
/** Set thinking level (clamped to model capabilities). */
setThinkingLevel(level: ThinkingLevel): void;
-
- // =========================================================================
- // Provider Registration
- // =========================================================================
-
/**
* Register or override a model provider.
*
@@ -1257,11 +1147,6 @@ export interface ExtensionAPI {
/** Shared event bus for extension communication. */
events: EventBus;
}
-
-// ============================================================================
-// Provider Registration Types
-// ============================================================================
-
/** Configuration for registering a provider via pi.registerProvider(). */
export interface ProviderConfig {
/** Display name for the provider in UI. */
@@ -1325,11 +1210,6 @@ export interface ProviderModelConfig {
/** Extension factory function type. Supports both sync and async initialization. */
export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;
-
-// ============================================================================
-// Loaded Extension Types
-// ============================================================================
-
export interface RegisteredTool {
definition: ToolDefinition;
sourceInfo: SourceInfo;
@@ -1510,11 +1390,6 @@ export interface LoadExtensionsResult {
/** Shared runtime - actions are throwing stubs until runner.initialize() */
runtime: ExtensionRuntime;
}
-
-// ============================================================================
-// Extension Error
-// ============================================================================
-
export interface ExtensionError {
extensionPath: string;
event: string;
diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.ts
index f7916eab85..d62c30fb1b 100644
--- a/packages/coding-agent/src/core/kernel/index.ts
+++ b/packages/coding-agent/src/core/kernel/index.ts
@@ -1,4 +1,3 @@
-// TODO: reconsider persistent kernel vs stateless `python -c` once RLM-1 weights land.
import { type ChildProcess, spawn } from "node:child_process";
import { createHmac, randomBytes } from "node:crypto";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
@@ -422,8 +421,6 @@ function createDeferred<T>(): Deferred<T> {
return { promise, resolve, reject };
}
-// ---- wire format ---------------------------------------------------------
-
function buildMessage(
msgType: string,
content: Record<string, unknown>,
@@ -477,8 +474,6 @@ function decode(frames: Buffer[]): JupyterMessage | null {
}
}
-// ---- connection setup ----------------------------------------------------
-
const CONNECTION_PORT_KEYS = ["shell_port", "iopub_port", "stdin_port", "control_port", "hb_port"] as const;
function hasResolvedPorts(info: ConnectionInfo): boolean {
@@ -543,8 +538,6 @@ function makeConnection(): { info: ConnectionInfo; path: string; tempDir: string
return { info, path, tempDir };
}
-// ---- process-wide cleanup -----------------------------------------------
-
const liveKernels = new Set<KernelManager>();
let signalHandlersInstalled = false;
@@ -582,8 +575,6 @@ function installSignalHandlersOnce(): void {
});
}
-// ---- kernel manager ------------------------------------------------------
-
export class KernelManager {
private readonly options: Pick<
KernelManagerOptions,
@@ -712,8 +703,9 @@ export class KernelManager {
try {
rmSync(connection.tempDir, { recursive: true, force: true });
} catch {
- // Leave the temp dir for OS tmp cleanup.
+ // Leave temporary kernel files for OS cleanup.
}
+ // A failed fork may leave stale ports; retry with a fresh connection file.
connection = makeConnection();
this.tempDir = connection.tempDir;
}
@@ -1385,7 +1377,7 @@ export class KernelManager {
process.kill(this.kernelPid, killSignal);
}
} catch {
- // Kernel already exited.
+ // The kernel has already exited.
}
this.kernel = undefined;
this.kernelPid = undefined;
@@ -1394,7 +1386,7 @@ export class KernelManager {
try {
rmSync(this.tempDir, { recursive: true, force: true });
} catch {
- // Leave the temp dir for OS tmp cleanup.
+ // Leave temporary kernel files for OS cleanup.
}
}
this.tempDir = undefined;
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index 1174bdb97a..7099c5eac6 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -185,7 +185,6 @@ export interface CompactionSummaryMessage {
timestamp: number;
}
-// Extend CustomAgentMessages via declaration merging
declare module "@earendil-works/pi-agent-core" {
interface CustomAgentMessages {
bashExecution: BashExecutionMessage;
@@ -432,7 +431,6 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
.map((m): Message | undefined => {
switch (m.role) {
case "bashExecution":
- // Skip messages excluded from context (!! prefix)
if (m.excludeFromContext) {
return undefined;
}
diff --git a/packages/coding-agent/src/core/model-registry.ts b/packages/coding-agent/src/core/model-registry.ts
index 89885d4350..0bd646d229 100644
--- a/packages/coding-agent/src/core/model-registry.ts
+++ b/packages/coding-agent/src/core/model-registry.ts
@@ -43,7 +43,6 @@ import {
resolveHeadersOrThrow,
} from "./resolve-config-value.js";
-// Schema for OpenRouter routing preferences
const PercentileCutoffsSchema = Type.Object({
p50: Type.Optional(Type.Number()),
p75: Type.Optional(Type.Number()),
@@ -83,13 +82,11 @@ const OpenRouterRoutingSchema = Type.Object({
preferred_max_latency: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),
});
-// Schema for Vercel AI Gateway routing preferences
const VercelGatewayRoutingSchema = Type.Object({
only: Type.Optional(Type.Array(Type.String())),
order: Type.Optional(Type.Array(Type.String())),
});
-// Schema for thinking level support and provider-specific values
const ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]);
const ThinkingLevelMapSchema = Type.Object({
off: Type.Optional(ThinkingLevelMapValueSchema),
@@ -144,7 +141,6 @@ const ProviderCompatSchema = Type.Union([
AnthropicMessagesCompatSchema,
]);
-// Schema for custom model definition
// Most fields are optional with sensible defaults for local models (Ollama, LM Studio, etc.)
const ModelDefinitionSchema = Type.Object({
id: Type.String({ minLength: 1 }),
@@ -168,7 +164,6 @@ const ModelDefinitionSchema = Type.Object({
compat: Type.Optional(ProviderCompatSchema),
});
-// Schema for per-model overrides (all fields optional, merged with built-in model)
const ModelOverrideSchema = Type.Object({
name: Type.Optional(Type.String({ minLength: 1 })),
reasoning: Type.Optional(Type.Boolean()),
@@ -331,7 +326,6 @@ function mergeCompat(
function applyModelOverride(model: Model<Api>, override: ModelOverride): Model<Api> {
const result = { ...model };
- // Simple field overrides
if (override.name !== undefined) result.name = override.name;
if (override.reasoning !== undefined) result.reasoning = override.reasoning;
if (override.thinkingLevelMap !== undefined) {
@@ -341,7 +335,6 @@ function applyModelOverride(model: Model<Api>, override: ModelOverride): Model<A
if (override.contextWindow !== undefined) result.contextWindow = override.contextWindow;
if (override.maxTokens !== undefined) result.maxTokens = override.maxTokens;
- // Merge cost (partial override)
if (override.cost) {
result.cost = {
input: override.cost.input ?? model.cost.input,
@@ -351,7 +344,6 @@ function applyModelOverride(model: Model<Api>, override: ModelOverride): Model<A
};
}
- // Deep merge compat
result.compat = mergeCompat(model.compat, override.compat);
return result;
@@ -496,8 +488,6 @@ export class ModelRegistry {
// Credentials may have been written by another process (e.g. the UI
// process saving a login while the session lives in the daemon).
this.authStorage.reload();
-
- // Ensure dynamic API/OAuth registrations are rebuilt from current provider state.
resetApiProviders();
resetOAuthProviders();
// reset drops everything but model-provider built-ins; re-add MCP integrations
@@ -525,7 +515,6 @@ export class ModelRegistry {
}
private loadModels(): void {
- // Load custom models and overrides from models.json
const {
models: customModels,
overrides,
@@ -535,7 +524,6 @@ export class ModelRegistry {
if (error) {
this.loadError = error;
- // Keep built-in models even if custom models failed to load
}
this.explicitPrivatePrimeInferenceModelIds = new Set(
@@ -544,7 +532,6 @@ export class ModelRegistry {
const builtInModels = [...this.loadBuiltInModels(overrides, modelOverrides), ...getPrivatePrimeInferenceModels()];
let combined = this.mergeCustomModels(builtInModels, customModels);
- // Let OAuth providers modify their models (e.g., update baseUrl)
for (const oauthProvider of this.authStorage.getOAuthProviders()) {
const cred = this.authStorage.get(oauthProvider.id);
if (cred?.type === "oauth" && oauthProvider.modifyModels) {
@@ -568,7 +555,6 @@ export class ModelRegistry {
return models.map((m) => {
let model = m;
- // Apply provider-level baseUrl/headers/compat override
if (providerOverride) {
model = {
...model,
@@ -577,7 +563,6 @@ export class ModelRegistry {
};
}
- // Apply per-model override
const modelOverride = perModelOverrides?.get(m.id);
if (modelOverride) {
model = applyModelOverride(model, modelOverride);
@@ -636,7 +621,6 @@ export class ModelRegistry {
const config = parsed as ModelsConfig;
- // Additional validation
this.validateConfig(config);
const overrides = new Map<string, ProviderOverride>();
@@ -682,14 +666,12 @@ export class ModelRegistry {
providerConfig.modelOverrides && Object.keys(providerConfig.modelOverrides).length > 0;
if (models.length === 0) {
- // Override-only config: needs baseUrl, headers, compat, modelOverrides, or some combination.
if (!providerConfig.baseUrl && !providerConfig.headers && !providerConfig.compat && !hasModelOverrides) {
throw new Error(
`Provider ${providerName}: must specify "baseUrl", "headers", "compat", "modelOverrides", or "models".`,
);
}
} else if (!isBuiltIn) {
- // Non-built-in providers with custom models require endpoint + auth.
if (!providerConfig.baseUrl) {
throw new Error(`Provider ${providerName}: "baseUrl" is required when defining custom models.`);
}
@@ -697,7 +679,6 @@ export class ModelRegistry {
throw new Error(`Provider ${providerName}: "apiKey" is required when defining custom models.`);
}
}
- // Built-in providers with custom models: baseUrl/apiKey/api are optional,
// inherited from built-in models. Auth comes from env vars / auth storage.
for (const modelDef of models) {
@@ -708,10 +689,8 @@ export class ModelRegistry {
`Provider ${providerName}, model ${modelDef.id}: no "api" specified. Set at provider or model level.`,
);
}
- // For built-in providers, api is optional — inherited from built-in models.
if (!modelDef.id) throw new Error(`Provider ${providerName}: model missing "id"`);
- // Validate contextWindow/maxTokens only if provided (they have defaults)
if (modelDef.contextWindow !== undefined && modelDef.contextWindow <= 0)
throw new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);
if (modelDef.maxTokens !== undefined && modelDef.maxTokens <= 0)
@@ -724,7 +703,6 @@ export class ModelRegistry {
const models: Model<Api>[] = [];
const builtInProviders = new Set<string>(getProviders());
- // Cache built-in defaults (api, baseUrl) per provider, extracted from first model.
const builtInDefaultsCache = new Map<string, { api: string; baseUrl: string }>();
const getBuiltInDefaults = (providerName: string): { api: string; baseUrl: string } | undefined => {
if (!builtInProviders.has(providerName)) return undefined;
@@ -894,7 +872,7 @@ export class ModelRegistry {
this.authorizedPrivatePrimeInferenceTeamId = teamId;
this.writePrivatePrimeAuthorizationCache({ fingerprint, modelIds: authorizedIds, refreshedAt: Date.now() });
} catch {
- // Keep the cached ids.
+ // Keep the cached authorization.
}
};
const pending = this.backgroundPrivatePrimeAuthorization?.promise;
@@ -956,7 +934,7 @@ export class ModelRegistry {
writeFileSync(tmpPath, JSON.stringify({ ...cache, modelIds: [...cache.modelIds] }), { mode: 0o600 });
renameSync(tmpPath, cachePath);
} catch {
- // Caching is best effort; a failed write just means the next startup refetches.
+ // A failed cache write only requires a later refetch.
}
}
@@ -1526,9 +1504,7 @@ export class ModelRegistry {
}
private applyProviderConfig(providerName: string, config: ProviderConfigInput): void {
- // Register OAuth provider if provided
if (config.oauth) {
- // Ensure the OAuth provider ID matches the provider name
const oauthProvider: OAuthProviderInterface = {
...config.oauth,
id: providerName,
@@ -1551,10 +1527,8 @@ export class ModelRegistry {
this.storeProviderRequestConfig(providerName, config);
if (config.models && config.models.length > 0) {
- // Full replacement: remove existing models for this provider
this.models = this.models.filter((m) => m.provider !== providerName);
- // Parse and add new models
for (const modelDef of config.models) {
const api = modelDef.api || config.api;
this.storeModelHeaders(providerName, modelDef.id, modelDef.headers);
@@ -1575,8 +1549,6 @@ export class ModelRegistry {
compat: modelDef.compat,
} as Model<Api>);
}
-
- // Apply OAuth modifyModels if credentials exist (e.g., to update baseUrl)
if (config.oauth?.modifyModels) {
const cred = this.authStorage.get(providerName);
if (cred?.type === "oauth") {
@@ -1584,7 +1556,6 @@ export class ModelRegistry {
}
}
} else if (config.baseUrl || config.headers) {
- // Override-only: update baseUrl for existing models. Request headers are resolved per request.
this.models = this.models.map((m) => {
if (m.provider !== providerName) return m;
return {
diff --git a/packages/coding-agent/src/core/model-resolver.ts b/packages/coding-agent/src/core/model-resolver.ts
index d8c0ea5f25..cb47c46a99 100644
--- a/packages/coding-agent/src/core/model-resolver.ts
+++ b/packages/coding-agent/src/core/model-resolver.ts
@@ -63,10 +63,7 @@ export interface ScopedModel {
* Dates are typically in format: -20241022 or -20250929
*/
function isAlias(id: string): boolean {
- // Check if ID ends with -latest
if (id.endsWith("-latest")) return true;
-
- // Check if ID ends with a date pattern (-YYYYMMDD)
const datePattern = /-\d{8}$/;
return !datePattern.test(id);
}
@@ -129,8 +126,6 @@ function tryMatchModel(modelPattern: string, availableModels: Model<Api>[]): Mod
if (exactMatch) {
return exactMatch;
}
-
- // No exact match - fall back to partial matching
const matches = availableModels.filter(
(m) =>
m.id.toLowerCase().includes(modelPattern.toLowerCase()) ||
@@ -140,17 +135,13 @@ function tryMatchModel(modelPattern: string, availableModels: Model<Api>[]): Mod
if (matches.length === 0) {
return undefined;
}
-
- // Separate into aliases and dated versions
const aliases = matches.filter((m) => isAlias(m.id));
const datedVersions = matches.filter((m) => !isAlias(m.id));
if (aliases.length > 0) {
- // Prefer alias - if multiple aliases, pick the one that sorts highest
aliases.sort((a, b) => b.id.localeCompare(a.id));
return aliases[0];
} else {
- // No alias found, pick latest dated version
datedVersions.sort((a, b) => b.id.localeCompare(a.id));
return datedVersions[0];
}
@@ -216,16 +207,12 @@ export function parseModelPattern(
availableModels: Model<Api>[],
options?: { allowInvalidThinkingLevelFallback?: boolean },
): ParsedModelResult {
- // Try exact match first
const exactMatch = tryMatchModel(pattern, availableModels);
if (exactMatch) {
return { model: exactMatch, thinkingLevel: undefined, warning: undefined };
}
-
- // No match - try splitting on last colon if present
const lastColonIndex = pattern.lastIndexOf(":");
if (lastColonIndex === -1) {
- // No colons, pattern simply doesn't match any model
return { model: undefined, thinkingLevel: undefined, warning: undefined };
}
@@ -233,10 +220,8 @@ export function parseModelPattern(
const suffix = pattern.substring(lastColonIndex + 1);
if (isValidThinkingLevel(suffix)) {
- // Valid thinking level - recurse on prefix and use this level
const result = parseModelPattern(prefix, availableModels, options);
if (result.model) {
- // Only use this thinking level if no warning from inner recursion
return {
model: result.model,
thinkingLevel: result.warning ? undefined : suffix,
@@ -245,15 +230,12 @@ export function parseModelPattern(
}
return result;
} else {
- // Invalid suffix
const allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;
if (!allowFallback) {
// In strict mode (CLI --model parsing), treat it as part of the model id and fail.
// This avoids accidentally resolving to a different model.
return { model: undefined, thinkingLevel: undefined, warning: undefined };
}
-
- // Scope mode: recurse on prefix and warn
const result = parseModelPattern(prefix, availableModels, options);
if (result.model) {
return {
@@ -281,9 +263,7 @@ export function resolveModelScopeFromModels(patterns: string[], availableModels:
const scopedModels: ScopedModel[] = [];
for (const pattern of patterns) {
- // Check if pattern contains glob characters
if (pattern.includes("*") || pattern.includes("?") || pattern.includes("[")) {
- // Extract optional thinking level suffix (e.g., "provider/*:high")
const colonIdx = pattern.lastIndexOf(":");
let globPattern = pattern;
let thinkingLevel: ThinkingLevel | undefined;
@@ -295,8 +275,6 @@ export function resolveModelScopeFromModels(patterns: string[], availableModels:
globPattern = pattern.substring(0, colonIdx);
}
}
-
- // Match against "provider/modelId" format OR just model ID
// This allows "*sonnet*" to match without requiring "anthropic/*sonnet*"
const matchingModels = availableModels.filter((m) => {
const fullId = `${m.provider}/${m.id}`;
@@ -329,8 +307,6 @@ export function resolveModelScopeFromModels(patterns: string[], availableModels:
console.warn(chalk.yellow(`Warning: No models match pattern "${pattern}"`));
continue;
}
-
- // Avoid duplicates
if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {
scopedModels.push({ model, thinkingLevel });
}
@@ -387,8 +363,6 @@ export function resolveCliModel(options: {
error: "No models available. Check your installation or add models to models.json.",
};
}
-
- // Build canonical provider lookup (case-insensitive)
const providerMap = new Map<string, string>();
for (const m of availableModels) {
providerMap.set(m.provider.toLowerCase(), m.provider);
@@ -465,7 +439,6 @@ export function resolveCliModel(options: {
if (exact) {
return { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };
}
- // Also try parseModelPattern on the full input against all models
const fallback = parseModelPattern(cliModel, availableModels, {
allowInvalidThinkingLevelFallback: false,
});
@@ -540,8 +513,6 @@ export async function findInitialModel(options: {
cachedAvailableModels ??= await modelRegistry.refreshAvailableModels();
return cachedAvailableModels;
};
-
- // 1. CLI args take priority
if (cliProvider && cliModel) {
const resolved = resolveCliModel({
cliProvider,
@@ -570,8 +541,6 @@ export async function findInitialModel(options: {
return { model: resolvedModel, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
}
}
-
- // 2. Use first model from scoped models (skip if continuing/resuming)
if (scopedModels.length > 0 && !isContinuing) {
return {
model: scopedModels[0].model,
@@ -580,8 +549,6 @@ export async function findInitialModel(options: {
};
}
const availableModels = await getAvailableModels();
-
- // 3. Try saved default from settings
if (defaultProvider && defaultModelId) {
// Rebuild from the provider template when the saved id is missing from this
// build's snapshot (e.g. prime-inference catalog churn), so it survives updates.
@@ -600,19 +567,13 @@ export async function findInitialModel(options: {
return { model, thinkingLevel, fallbackMessage: undefined };
}
}
-
- // 4. Try first available model with valid API key
if (availableModels.length > 0) {
const defaultModel = findPreferredDefaultModel(availableModels);
if (defaultModel) {
return { model: defaultModel, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
}
-
- // If no default found, use first available
return { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
}
-
- // 5. No model found
return { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
}
@@ -637,8 +598,6 @@ export async function restoreModelFromSession(
}
return { model: restoredModel, fallbackMessage: undefined };
}
-
- // Model not found or no API key - fall back
const registeredModel = modelRegistry.find(savedProvider, savedModelId);
const reason = !registeredModel
? "model no longer exists"
@@ -650,8 +609,6 @@ export async function restoreModelFromSession(
if (shouldPrintMessages) {
console.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));
}
-
- // If we already have a model, use it as fallback
const availableCurrentModel = currentModel
? availableModels.find((candidate) => modelsAreEqual(candidate, currentModel))
: undefined;
@@ -668,8 +625,6 @@ export async function restoreModelFromSession(
fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackCurrentModel.provider}/${fallbackCurrentModel.id}.`,
};
}
-
- // Try to find any available model
if (availableModels.length > 0) {
const fallbackModel = findPreferredDefaultModel(availableModels) ?? availableModels[0];
@@ -682,7 +637,5 @@ export async function restoreModelFromSession(
fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,
};
}
-
- // No models available
return { model: undefined, fallbackMessage: undefined };
}
diff --git a/packages/coding-agent/src/core/package-manager.ts b/packages/coding-agent/src/core/package-manager.ts
index fd818595f3..eaca1c746d 100644
--- a/packages/coding-agent/src/core/package-manager.ts
+++ b/packages/coding-agent/src/core/package-manager.ts
@@ -330,7 +330,7 @@ function collectFiles(
}
}
} catch {
- // Ignore errors
+ // Ignore unreadable directories during file discovery.
}
return files;
@@ -406,7 +406,7 @@ function collectSkillEntries(
entries.push(...collectSkillEntries(fullPath, mode, ig, root));
}
} catch {
- // Ignore errors
+ // Ignore unreadable directories during skill discovery.
}
return entries;
@@ -482,7 +482,7 @@ function collectAutoPromptEntries(dir: string): string[] {
}
}
} catch {
- // Ignore errors
+ // Ignore unreadable directories during prompt discovery.
}
return entries;
@@ -519,7 +519,7 @@ function collectAutoThemeEntries(dir: string): string[] {
}
}
} catch {
- // Ignore errors
+ // Ignore unreadable directories during theme discovery.
}
return entries;
@@ -568,14 +568,10 @@ function resolveExtensionEntries(dir: string): string[] | null {
function collectAutoExtensionEntries(dir: string): string[] {
const entries: string[] = [];
if (!existsSync(dir)) return entries;
-
- // First check if this directory itself has explicit extension entries (package.json or index)
const rootEntries = resolveExtensionEntries(dir);
if (rootEntries) {
return rootEntries;
}
-
- // Otherwise, discover extensions from directory contents
const ig = ignore();
addIgnoreRules(ig, dir, dir);
@@ -613,7 +609,7 @@ function collectAutoExtensionEntries(dir: string): string[] {
}
}
} catch {
- // Ignore errors
+ // Ignore unreadable directories during extension discovery.
}
return entries;
@@ -734,21 +730,16 @@ function applyPatterns(allPaths: string[], patterns: string[], baseDir: string):
includes.push(p);
}
}
-
- // Step 1: Apply includes (or all if no includes)
+ // Apply patterns in order: includes, excludes, force-includes, then force-excludes.
let result: string[];
if (includes.length === 0) {
result = [...allPaths];
} else {
result = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir));
}
-
- // Step 2: Apply excludes
if (excludes.length > 0) {
result = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir));
}
-
- // Step 3: Force-include (add back from allPaths, overriding exclusions)
if (forceIncludes.length > 0) {
for (const filePath of allPaths) {
if (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {
@@ -756,8 +747,6 @@ function applyPatterns(allPaths: string[], patterns: string[], baseDir: string):
}
}
}
-
- // Step 4: Force-exclude (remove even if included or force-included)
if (forceExcludes.length > 0) {
result = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir));
}
@@ -867,8 +856,7 @@ export class DefaultPackageManager implements PackageManager {
const accumulator = this.createAccumulator();
const globalSettings = this.settingsManager.getGlobalSettings();
const projectSettings = this.settingsManager.getProjectSettings();
-
- // Collect all packages with scope (project first so cwd resources win collisions)
+ // Project resources win collisions with global resources.
const allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];
for (const pkg of projectSettings.packages ?? []) {
allPackages.push({ pkg, scope: "project" });
@@ -876,8 +864,7 @@ export class DefaultPackageManager implements PackageManager {
for (const pkg of globalSettings.packages ?? []) {
allPackages.push({ pkg, scope: "user" });
}
-
- // Dedupe: project scope wins over global for same package identity
+ // Deduplicate by package identity after recording project precedence.
const packageSources = this.dedupePackages(allPackages);
await this.resolvePackageSources(packageSources, accumulator, onMissing);
@@ -1109,7 +1096,7 @@ export class DefaultPackageManager implements PackageManager {
const latestVersion = await this.getLatestNpmVersion(source.name);
return latestVersion !== installedVersion;
} catch {
- // Preserve existing update behavior when version lookup fails.
+ // Preserve the existing update policy when version lookup fails.
return true;
}
}
@@ -1397,8 +1384,6 @@ export class DefaultPackageManager implements PackageManager {
if (isLocalPath(source)) {
return { type: "local", path: source };
}
-
- // Try parsing as git URL
const gitParsed = parseGitUrl(source);
if (gitParsed) {
return gitParsed;
@@ -1651,11 +1636,8 @@ export class DefaultPackageManager implements PackageManager {
if (!existing) {
seen.set(identity, entry);
} else if (entry.scope === "project" && existing.scope === "user") {
- // Project wins over user
seen.set(identity, entry);
}
- // If existing is project and new is global, keep existing (project)
- // If both are same scope, keep first one
}
return Array.from(seen.values());
@@ -1753,7 +1735,6 @@ export class DefaultPackageManager implements PackageManager {
const target = await this.getLocalGitUpdateTarget(targetDir);
- // Fetch only the ref we will reset to, avoiding unrelated branch/tag noise.
await this.runCommand("git", target.fetchArgs, { cwd: targetDir });
const localHead = await this.runCommandCapture("git", ["rev-parse", "HEAD"], {
@@ -1770,7 +1751,7 @@ export class DefaultPackageManager implements PackageManager {
await this.runCommand("git", ["reset", "--hard", target.ref], { cwd: targetDir });
- // Clean untracked files (extensions should be pristine)
+ // Extension checkouts must be pristine after an update.
await this.runCommand("git", ["clean", "-fdx"], { cwd: targetDir });
const packageJsonPath = join(targetDir, "package.json");
@@ -1788,7 +1769,7 @@ export class DefaultPackageManager implements PackageManager {
await this.updateGit(source, "temporary");
});
} catch {
- // Keep cached temporary checkout if refresh fails.
+ // Keep the cached temporary checkout if refresh fails.
}
}
@@ -1972,7 +1953,6 @@ export class DefaultPackageManager implements PackageManager {
for (const resourceType of RESOURCE_TYPES) {
const dir = join(packageRoot, resourceType);
if (existsSync(dir)) {
- // Collect all files from the directory (all enabled by default)
const files = collectResourceFiles(dir, resourceType);
for (const f of files) {
this.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true);
@@ -1997,7 +1977,6 @@ export class DefaultPackageManager implements PackageManager {
}
const dir = join(packageRoot, resourceType);
if (existsSync(dir)) {
- // Collect all files from the directory (all enabled by default)
const files = collectResourceFiles(dir, resourceType);
for (const f of files) {
this.addResource(target, f, metadata, true);
@@ -2014,15 +1993,13 @@ export class DefaultPackageManager implements PackageManager {
): void {
const { allFiles } = this.collectManifestFiles(packageRoot, resourceType);
+ // An explicit empty list disables this resource type.
if (userPatterns.length === 0) {
- // Empty array explicitly disables all resources of this type
for (const f of allFiles) {
this.addResource(target, f, metadata, false);
}
return;
}
-
- // Apply user patterns
const enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot);
for (const f of allFiles) {
@@ -2118,16 +2095,10 @@ export class DefaultPackageManager implements PackageManager {
baseDir: string,
): void {
if (entries.length === 0) return;
-
- // Collect all files from plain entries (non-pattern entries)
const { plain, patterns } = splitPatterns(entries);
const resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir));
const allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType);
-
- // Determine which files are enabled based on patterns
const enabledPaths = applyPatterns(allFiles, patterns, baseDir);
-
- // Add all files with their enabled state
for (const f of allFiles) {
this.addResource(target, f, metadata, enabledPaths.has(f));
}
@@ -2252,9 +2223,7 @@ export class DefaultPackageManager implements PackageManager {
baseDir: this.bundledSkillsDir,
};
const builtinEntries = collectAutoSkillEntries(this.bundledSkillsDir, "pi");
- // Built-in skills (edit, goal, …) are expected to ship with the package. A
- // packaging slip that drops the skills/ dir from the build output would
- // otherwise degrade silently to zero skills (ENG-4220); surface it loudly.
+ // Bundled skills must ship with the package; warn instead of silently exposing none.
if (builtinEntries.length === 0) {
accumulator.diagnostics.push({
type: "warning",
@@ -2266,9 +2235,9 @@ export class DefaultPackageManager implements PackageManager {
}
const builtinSkillOverrides = [
...userOverrides.skills,
- // Disable the bundled websearch skill unless explicitly enabled…
+ // Web search stays disabled until explicitly enabled.
...(this.settingsManager.getBundledWebsearchEnabled() ? [] : ["-websearch/SKILL.md"]),
- // …and disable any MCP integration the user hasn't logged into.
+ // MCP integration skills stay disabled until their authentication is available.
...this.extraBuiltinSkillOverrides(),
];
addResources("skills", builtinEntries, builtinMetadata, builtinSkillOverrides, this.bundledSkillsDir);
@@ -2302,7 +2271,7 @@ export class DefaultPackageManager implements PackageManager {
files.push(...collectResourceFiles(p, resourceType));
}
} catch {
- // Ignore errors
+ // Ignore inaccessible resource paths.
}
}
return files;
diff --git a/packages/coding-agent/src/core/resolve-config-value.ts b/packages/coding-agent/src/core/resolve-config-value.ts
index 646042e1c9..ffff420893 100644
--- a/packages/coding-agent/src/core/resolve-config-value.ts
+++ b/packages/coding-agent/src/core/resolve-config-value.ts
@@ -6,7 +6,6 @@
import { execSync, spawnSync } from "child_process";
import { getShellConfig } from "../utils/shell.js";
-// Cache for shell command results (persists for process lifetime)
const commandResultCache = new Map<string, string | undefined>();
/**
diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.ts
index e89472fce0..55585d8107 100644
--- a/packages/coding-agent/src/core/rlm-runtime.ts
+++ b/packages/coding-agent/src/core/rlm-runtime.ts
@@ -4,10 +4,10 @@ import type { AgentSession } from "./agent-session.js";
import type { ToolDefinition } from "./extensions/index.js";
import type { HostRequestHandler } from "./kernel/index.js";
+/** Request emitted by `rlm.run`; cellSourceCode preserves the spawning cell for display. */
export interface RlmRunRequest {
prompt: string;
kwargs: Record<string, unknown>;
- /** Source of the IPython cell that issued this rlm.run call, when available. */
cellSourceCode?: string;
}
@@ -148,7 +148,7 @@ export function findRlmModelMatches(query: string, models: Model<Api>[], limit:
}));
}
-/** Adapt an RlmRunHandler into the typed "rlm.run" handler for the kernel host bridge. */
+/** Adapt an RlmRunHandler into the typed `rlm.run` kernel host handler. */
export function createRlmRunHostHandler(handler: RlmRunHandler): HostRequestHandler {
return async (payload) => {
if (typeof payload.prompt !== "string") {
@@ -179,7 +179,7 @@ export function createRlmFindModelsHostHandler(handler: RlmFindModelsHandler): H
};
}
-/** Expose the current parent session's RLM child registry to its kernel. */
+/** Expose the current parent session's direct RLM child registry to its kernel. */
export function createRlmListSubagentsHostHandler(handler: RlmListSubagentsHandler): HostRequestHandler {
return async () => {
const { subagents } = await handler();
diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.ts
index 70c9fc502b..e8ffda2f19 100644
--- a/packages/coding-agent/src/core/sdk.ts
+++ b/packages/coding-agent/src/core/sdk.ts
@@ -84,8 +84,6 @@ export interface CreateAgentSessionResult {
modelFallbackMessage?: string;
}
-// Re-exports
-
export type { AgentSessionRuntimeConfig } from "./agent-session-config.js";
export * from "./agent-session-runtime.js";
export type { AgentSessionCreationOptions } from "./agent-session-services.js";
@@ -103,15 +101,7 @@ export type { CreateRlmSubagentRuntimeOptions, RlmSubagentRuntime, SubagentRunti
export type { Skill } from "./skills.js";
export type { Tool } from "./tools/index.js";
-export {
- createBashTool,
- createEditTool,
- // Tool factories (for custom cwd)
- createIpythonTool,
- withFileMutationQueue,
-};
-
-// Helper Functions
+export { createBashTool, createEditTool, createIpythonTool, withFileMutationQueue };
function getDefaultAgentDir(): string {
return getAgentDir();
@@ -157,7 +147,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
const agentDir = options.agentDir ?? getDefaultAgentDir();
let resourceLoader = options.resourceLoader;
- // Use provided or create AuthStorage and ModelRegistry
const authPath = options.agentDir ? join(agentDir, "auth.json") : undefined;
const modelsPath = options.agentDir ? join(agentDir, "models.json") : undefined;
const authStorage = options.authStorage ?? AuthStorage.create(authPath);
@@ -183,7 +172,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
time("resourceLoader.reload");
}
- // Check if session has existing data to restore
const existingSession = sessionManager.buildSessionContext();
const hasExistingSession = existingSession.messages.length > 0;
const hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change");
@@ -192,7 +180,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
let model = options.model;
let modelFallbackMessage: string | undefined;
- // If session has data, try to restore model from it
if (!model && hasExistingSession && existingSession.model) {
const restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);
if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {
@@ -203,7 +190,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
}
}
- // If still no model, use findInitialModel (checks settings default, then provider defaults)
if (!model) {
const result = await findInitialModel({
scopedModels: [],
@@ -223,19 +209,16 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
let thinkingLevel = options.thinkingLevel;
- // If session has data, restore thinking level from it
if (thinkingLevel === undefined && hasExistingSession) {
thinkingLevel = hasThinkingEntry
? (existingSession.thinkingLevel as ThinkingLevel)
: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);
}
- // Fall back to settings default
if (thinkingLevel === undefined) {
thinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
}
- // Clamp to model capabilities
if (!model) {
thinkingLevel = "off";
} else {
@@ -255,14 +238,11 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
let agent: Agent;
- // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)
const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {
const converted = convertToLlm(messages);
- // Check setting dynamically so mid-session changes take effect
if (!settingsManager.getBlockImages()) {
return converted;
}
- // Filter out ImageContent from all messages, replacing with text placeholder
return converted.map((msg) => {
if (msg.role === "user" || msg.role === "toolResult") {
const content = msg.content;
@@ -275,7 +255,6 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
)
.filter(
(c, i, arr) =>
- // Dedupe consecutive "Image reading is disabled." texts
!(
c.type === "text" &&
c.text === "Image reading is disabled." &&
@@ -349,14 +328,12 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,
});
- // Restore messages if session has existing data
if (hasExistingSession) {
agent.state.messages = existingSession.messages;
if (!hasThinkingEntry) {
sessionManager.appendThinkingLevelChange(thinkingLevel);
}
} else {
- // Save initial configuration for new sessions so it can be restored on resume.
if (model) {
sessionManager.appendModelChange(model.provider, model.id);
}
diff --git a/packages/coding-agent/src/core/session-import-errors.ts b/packages/coding-agent/src/core/session-import-errors.ts
index f917b8f018..00cb1a81fd 100644
--- a/packages/coding-agent/src/core/session-import-errors.ts
+++ b/packages/coding-agent/src/core/session-import-errors.ts
@@ -1,6 +1,3 @@
-/**
- * Thrown when /import references a JSONL file path that does not exist.
- */
export class SessionImportFileNotFoundError extends Error {
readonly filePath: string;
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index edc5aff0f0..cd6e486deb 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -79,7 +79,6 @@ export interface SessionHeader {
timestamp: string;
cwd: string;
parentSession?: string;
- /** RLM spawn depth. Optional for backward compatibility. Forks preserve the source depth. */
rlmDepth?: number;
git?: GitContext;
}
@@ -87,7 +86,6 @@ export interface SessionHeader {
export interface NewSessionOptions {
id?: string;
parentSession?: string;
- /** Explicit RLM spawn depth. An explicitly undefined value suppresses parent derivation. */
rlmDepth?: number;
}
@@ -128,11 +126,8 @@ export interface CompactionEntry<T = unknown> extends SessionEntryBase {
summary: string;
firstKeptEntryId: string;
tokensBefore: number;
- /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
details?: T;
- /** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
fromHook?: boolean;
- /** User instructions that guided the summary (from `/compact <instructions>`) */
customInstructions?: string;
}
@@ -140,22 +135,10 @@ export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
type: "branch_summary";
fromId: string;
summary: string;
- /** Extension-specific data (not sent to LLM) */
details?: T;
- /** True if generated by an extension, false if pi-generated */
fromHook?: boolean;
}
-/**
- * Custom entry for extensions to store extension-specific data in the session.
- * Use customType to identify your extension's entries.
- *
- * Purpose: Persist extension state across session reloads. On reload, extensions can
- * scan entries for their customType and reconstruct internal state.
- *
- * Does NOT participate in LLM context (ignored by buildSessionContext).
- * For injecting content into context, see CustomMessageEntry.
- */
export interface CustomEntry<T = unknown> extends SessionEntryBase {
type: "custom";
customType: string;
@@ -175,68 +158,46 @@ export interface ChildUsageAttributionEntry extends SessionEntryBase {
origin?: "spawn_task" | "agent_message" | "direct_user";
}
-/** Label entry for user-defined bookmarks/markers on entries. */
export interface LabelEntry extends SessionEntryBase {
type: "label";
targetId: string;
label: string | undefined;
}
-/** Session metadata entry (e.g., user-defined display name). */
export interface SessionInfoEntry extends SessionEntryBase {
type: "session_info";
name?: string;
}
-// On-disk lifecycle. "archived" replaces legacy "sleep" (normalized on read).
-// "crash" is read-only back-compat; no longer written.
export type SessionStateStatus = "active" | "archived" | "crash";
export interface SessionState {
status: SessionStateStatus;
}
-/** Session lifecycle state entry (e.g., inactive status for daemon-managed sessions). */
export interface SessionStateEntry extends SessionEntryBase {
type: "session_state";
state: SessionState;
}
-/** Whether an idle agent's turn left the task complete or awaiting more input. */
export type AgentTaskState = "needs_input" | "completed";
-/** Latest short status for an agent, shown in the agents view. */
export interface AgentStatus {
summary: string;
taskState?: AgentTaskState;
- /** Message count this status was derived from, used to skip redundant work. */
basedOnMessageCount: number;
}
-/** Append-only status entry; ignored by buildSessionContext and other readers. */
export interface AgentStatusEntry extends SessionEntryBase {
type: "agent_status";
status: AgentStatus;
}
-/** Append-only repo-state entry; ignored by buildSessionContext and other readers. */
export interface GitStateEntry extends SessionEntryBase {
type: "git_state";
git: GitContext;
}
-/**
- * Custom message entry for extensions to inject messages into LLM context.
- * Use customType to identify your extension's entries.
- *
- * Unlike CustomEntry, this DOES participate in LLM context.
- * The content is converted to a user message in buildSessionContext().
- * Use details for extension-specific metadata (not sent to LLM).
- *
- * display controls TUI rendering:
- * - false: hidden entirely
- * - true: rendered with distinct styling (different from user messages)
- */
export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
type: "custom_message";
customType: string;
@@ -245,7 +206,6 @@ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
display: boolean;
}
-/** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
export type SessionEntry =
| SessionMessageEntry
| ThinkingLevelChangeEntry
@@ -262,15 +222,11 @@ export type SessionEntry =
| AgentStatusEntry
| GitStateEntry;
-/** Raw file entry (includes header) */
export type FileEntry = SessionHeader | SessionEntry;
-/** Tree node for getTree() - defensive copy of session structure */
export interface SessionTreeFlatNode {
entry: SessionEntry;
- /** Resolved label for this entry, if any */
label?: string;
- /** Timestamp of the latest label change for this entry, if any */
labelTimestamp?: string;
}
@@ -288,22 +244,16 @@ export interface SessionContext {
export interface SessionInfo {
path: string;
id: string;
- /** Working directory where the session was started. Empty string for old sessions. */
cwd: string;
- /** User-defined display name from session_info entries. */
name?: string;
- /** Latest persisted lifecycle state from session_state entries. */
state?: SessionState;
- /** Path to the parent session (if this session was forked). */
parentSessionPath?: string;
- /** Resolved RLM spawn depth. */
rlmDepth: number;
created: Date;
modified: Date;
messageCount: number;
firstMessage: string;
allMessagesText: string;
- /** Latest persisted recap/verdict, so off-daemon sessions keep their status. */
agentStatus?: AgentStatus;
}
@@ -343,32 +293,26 @@ function createUniqueSessionFileTarget(sessionDir: string): { sessionId: string;
throw new Error("Unable to create a unique session file");
}
-/** Root of the artifact tree next to a sessions dir: `<dirname(sessionDir)>/session-artifacts`. */
export function getSessionArtifactsRoot(sessionDir: string): string {
return join(dirname(sessionDir), "session-artifacts");
}
-/** A session's artifact directory: `<dirname(sessionDir)>/session-artifacts/<sessionId>`. */
export function getSessionArtifactPath(sessionDir: string, sessionId: string): string {
return join(getSessionArtifactsRoot(sessionDir), sessionId);
}
-/** {@link getSessionArtifactPath} from a session file; the id defaults to basename minus `.jsonl`. */
export function getSessionArtifactPathForFile(sessionFile: string, sessionId?: string): string {
return getSessionArtifactPath(dirname(sessionFile), sessionId ?? basename(sessionFile).replace(/\.jsonl$/, ""));
}
-/** Generate a unique short ID (8 hex chars, collision-checked) */
function generateId(byId: { has(id: string): boolean }): string {
for (let i = 0; i < 100; i++) {
const id = randomUUID().slice(0, 8);
if (!byId.has(id)) return id;
}
- // Fallback to full UUID if somehow we have collisions
return randomUUID();
}
-/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
function migrateV1ToV2(entries: FileEntry[]): void {
const ids = new Set<string>();
let prevId: string | null = null;
@@ -383,7 +327,6 @@ function migrateV1ToV2(entries: FileEntry[]): void {
entry.parentId = prevId;
prevId = entry.id;
- // Convert firstKeptEntryIndex to firstKeptEntryId for compaction
if (entry.type === "compaction") {
const comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };
if (typeof comp.firstKeptEntryIndex === "number") {
@@ -397,7 +340,6 @@ function migrateV1ToV2(entries: FileEntry[]): void {
}
}
-/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
function migrateV2ToV3(entries: FileEntry[]): void {
for (const entry of entries) {
if (entry.type === "session") {
@@ -405,7 +347,6 @@ function migrateV2ToV3(entries: FileEntry[]): void {
continue;
}
- // Update message entries with hookMessage role
if (entry.type === "message") {
const msgEntry = entry as SessionMessageEntry;
if (msgEntry.message && (msgEntry.message as { role: string }).role === "hookMessage") {
@@ -415,10 +356,6 @@ function migrateV2ToV3(entries: FileEntry[]): void {
}
}
-/**
- * Run all necessary migrations to bring entries to current version.
- * Mutates entries in place. Returns true if any migration was applied.
- */
function migrateToCurrentVersion(entries: FileEntry[]): boolean {
const header = entries.find((e) => e.type === "session") as SessionHeader | undefined;
const version = header?.version ?? 1;
@@ -431,12 +368,10 @@ function migrateToCurrentVersion(entries: FileEntry[]): boolean {
return true;
}
-/** Exported for testing */
export function migrateSessionEntries(entries: FileEntry[]): void {
migrateToCurrentVersion(entries);
}
-/** Exported for compaction.test.ts */
export function parseSessionEntries(content: string): FileEntry[] {
const entries: FileEntry[] = [];
const lines = content.trim().split("\n");
@@ -447,7 +382,7 @@ export function parseSessionEntries(content: string): FileEntry[] {
const entry = JSON.parse(line) as FileEntry;
entries.push(entry);
} catch {
- // Skip malformed lines
+ // Skip malformed lines.
}
}
@@ -480,17 +415,11 @@ export function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEnt
return null;
}
-/**
- * Build the session context from entries using tree traversal.
- * If leafId is provided, walks from that entry to root.
- * Handles compaction and branch summaries along the path.
- */
export function buildSessionContext(
entries: SessionEntry[],
leafId?: string | null,
byId?: Map<string, SessionEntry>,
): SessionContext {
- // Build uuid index if not available
if (!byId) {
byId = new Map<string, SessionEntry>();
for (const entry of entries) {
@@ -498,17 +427,14 @@ export function buildSessionContext(
}
}
- // Find leaf
let leaf: SessionEntry | undefined;
if (leafId === null) {
- // Explicitly null - return no messages (navigated to before first entry)
return { messages: [], thinkingLevel: "off", serviceTier: "default", model: null };
}
if (leafId) {
leaf = byId.get(leafId);
}
if (!leaf) {
- // Fallback to last entry (when leafId is undefined)
leaf = entries[entries.length - 1];
}
@@ -525,7 +451,6 @@ export function buildSessionContext(
}
path.reverse();
- // Extract settings and find compaction
let thinkingLevel = "off";
let serviceTier: ServiceTier = "default";
let model: { provider: string; modelId: string } | null = null;
@@ -563,7 +488,6 @@ export function buildSessionContext(
};
if (compaction) {
- // Find compaction index in path
const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
// Collect kept messages (before compaction, starting from firstKeptEntryId).
@@ -592,13 +516,11 @@ export function buildSessionContext(
...retainedMessages,
);
- // Emit messages after compaction
for (let i = compactionIdx + 1; i < path.length; i++) {
const entry = path[i];
appendMessage(entry);
}
} else {
- // No compaction - emit all messages, handle branch summaries and custom messages
for (const entry of path) {
appendMessage(entry);
}
@@ -607,10 +529,6 @@ export function buildSessionContext(
return { messages, thinkingLevel, serviceTier, model };
}
-/**
- * Compute the default session directory for a cwd.
- * Returns the configured session root.
- */
export function getDefaultSessionDir(_cwd: string, agentDir: string = getDefaultAgentDir()): string {
const sessionDir = getSessionsDir(agentDir);
if (!existsSync(sessionDir)) {
@@ -670,7 +588,6 @@ function finalizeLoadedEntries(entries: FileEntry[]): FileEntry[] {
return entries;
}
-/** Exported for testing */
export function loadEntriesFromFile(filePath: string): FileEntry[] {
if (!existsSync(filePath)) return [];
return finalizeLoadedEntries(parseEntriesFromBuffer(readFileSync(filePath)));
@@ -796,7 +713,6 @@ function isValidSessionFile(filePath: string): boolean {
}
}
-/** Exported for testing */
export function findMostRecentSession(sessionDir: string): string | null {
try {
const files = readdirSync(sessionDir)
@@ -869,8 +785,6 @@ function extractTextContent(message: Message): string {
.join(" ");
}
-// Legacy "hidden" and "sleep" statuses (written by older versions) both map to
-// the current "archived".
function normalizeSessionStateStatus(value: unknown): SessionStateStatus | undefined {
if (value === "active" || value === "archived" || value === "crash") {
return value;
@@ -1066,11 +980,9 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
try {
entry = JSON.parse(trimmed) as FileEntry;
} catch {
- // Skip malformed lines
continue;
}
- // Extract session name (use latest, including explicit clears)
if (entry.type === "session_info") {
const infoEntry = entry as SessionInfoEntry;
name = infoEntry.name?.trim() || undefined;
@@ -1163,7 +1075,6 @@ async function listSessionsFromDir(
const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
const total = progressTotal ?? files.length;
- // drop cache entries for deleted files so it stays bounded
const present = new Set(files);
for (const key of sessionInfoCache.keys()) {
if (dirname(key) === dir && !present.has(key)) {
@@ -1182,23 +1093,12 @@ async function listSessionsFromDir(
}
}
} catch {
- // Return empty list on error
+ // Return no sessions when the directory cannot be read.
}
return sessions;
}
-/**
- * Manages conversation sessions as append-only trees stored in JSONL files.
- *
- * Each session entry has an id and parentId forming a tree structure. The "leaf"
- * pointer tracks the current position. Appending creates a child of the current leaf.
- * Branching moves the leaf to an earlier entry, allowing new branches without
- * modifying history.
- *
- * Use buildSessionContext() to get the resolved message list for the LLM, which
- * handles compaction summaries and follows the path from root to current leaf.
- */
export class SessionManager {
private sessionId: string = "";
private sessionFile: string | undefined;
@@ -1285,7 +1185,7 @@ export class SessionManager {
try {
parentHeader = readSessionHeader(options.parentSession);
} catch {
- // Legacy-invalid or unavailable parents leave the child depth unknown.
+ // Unavailable parent metadata leaves the child depth unknown.
}
}
if (this.persist) {
@@ -1470,7 +1370,6 @@ export class SessionManager {
const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
const shouldPersistWithoutAssistant = entry.type === "session_state" || entry.type === "session_info";
if (!hasAssistant && !shouldPersistWithoutAssistant) {
- // Mark as not flushed so when assistant arrives, all entries get written
this.flushed = false;
return;
}
@@ -1492,12 +1391,6 @@ export class SessionManager {
this._persist(entry);
}
- /** Append a message as child of current leaf, then advance leaf. Returns entry id.
- * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
- * Reason: we want these to be top-level entries in the session, not message session entries,
- * so it is easier to find them.
- * These need to be appended via appendCompaction() and appendBranchSummary() methods.
- */
appendMessage(message: Message | CustomMessage | BashExecutionMessage): string {
const entry: SessionMessageEntry = {
type: "message",
@@ -1510,7 +1403,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
appendThinkingLevelChange(thinkingLevel: string): string {
const entry: ThinkingLevelChangeEntry = {
type: "thinking_level_change",
@@ -1523,7 +1415,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a service tier change as child of current leaf, then advance leaf. Returns entry id. */
appendServiceTierChange(serviceTier: ServiceTier): string {
const entry: ServiceTierChangeEntry = {
type: "service_tier_change",
@@ -1536,7 +1427,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */
appendModelChange(provider: string, modelId: string): string {
const entry: ModelChangeEntry = {
type: "model_change",
@@ -1550,7 +1440,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
appendCompaction<T = unknown>(
summary: string,
firstKeptEntryId: string,
@@ -1575,7 +1464,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
appendCustomEntry(customType: string, data?: unknown): string {
const entry: CustomEntry = {
type: "custom",
@@ -1589,12 +1477,10 @@ export class SessionManager {
return entry.id;
}
- /** Append a custom entry and undo its in-memory index if persistence fails. */
appendCustomEntryWithRollback(customType: string, data?: unknown): string {
return this._appendEntryWithRollback(() => this.appendCustomEntry(customType, data));
}
- /** Append an RLM child usage attribution and update the parent assistant aggregate in memory. */
appendChildUsageAttribution(
targetId: string,
childUsage: Usage,
@@ -1621,7 +1507,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a session info entry (e.g., display name). Returns entry id. */
appendSessionInfo(name: string): string {
const entry: SessionInfoEntry = {
type: "session_info",
@@ -1634,7 +1519,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a session lifecycle state entry. Returns entry id. */
appendSessionState(state: SessionState): string {
const entry: SessionStateEntry = {
type: "session_state",
@@ -1647,10 +1531,7 @@ export class SessionManager {
return entry.id;
}
- /** Get the current session name from the latest session_info entry, if any. */
getSessionName(): string | undefined {
- // Walk entries in reverse to find the latest session_info entry.
- // Empty names explicitly clear the session title.
const entries = this.getEntries();
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
@@ -1661,7 +1542,6 @@ export class SessionManager {
return undefined;
}
- /** Get the current session lifecycle state from the latest session_state entry, if any. */
getSessionState(): SessionState | undefined {
const entries = this.getEntries();
for (let i = entries.length - 1; i >= 0; i--) {
@@ -1702,7 +1582,6 @@ export class SessionManager {
return contentEntries.length > start;
}
- /** Append the latest agent status (summary + completion judgment). Returns entry id. */
appendAgentStatus(status: AgentStatus): string {
const entry: AgentStatusEntry = {
type: "agent_status",
@@ -1719,7 +1598,6 @@ export class SessionManager {
return entry.id;
}
- /** Append a git state entry as child of current leaf, then advance leaf. Returns entry id. */
appendGitState(git: GitContext): string {
const entry: GitStateEntry = {
type: "git_state",
@@ -1741,7 +1619,6 @@ export class SessionManager {
return this.appendGitState(git);
}
- /** Active-branch git: nearest git_state from leaf to root, else the header snapshot. */
private getActiveGitContext(): GitContext | undefined {
let current = this.leafId ? this.byId.get(this.leafId) : undefined;
while (current) {
@@ -1752,7 +1629,6 @@ export class SessionManager {
return header?.type === "session" ? header.git : undefined;
}
- /** Get the latest agent status from the most recent agent_status entry, if any. */
getLatestAgentStatus(): AgentStatus | undefined {
// Walk the current leaf to root so we only read status on the active branch,
// not a sibling branch's status that happens to sit later in the file.
@@ -1766,14 +1642,6 @@ export class SessionManager {
return undefined;
}
- /**
- * Append a custom message entry (for extensions) that participates in LLM context.
- * @param customType Extension identifier for filtering on reload
- * @param content Message content (string or TextContent/ImageContent array)
- * @param display Whether to show in TUI (true = styled display, false = hidden)
- * @param details Optional extension-specific metadata (not sent to LLM)
- * @returns Entry id
- */
appendCustomMessageEntry<T = unknown>(
customType: string,
content: string | (TextContent | ImageContent)[],
@@ -1833,10 +1701,6 @@ export class SessionManager {
}
}
- // =========================================================================
- // Tree Traversal
- // =========================================================================
-
getLeafId(): string | null {
return this.leafId;
}
@@ -1849,9 +1713,6 @@ export class SessionManager {
return this.byId.get(id);
}
- /**
- * Get all direct children of an entry.
- */
getChildren(parentId: string): SessionEntry[] {
const children: SessionEntry[] = [];
for (const entry of this.byId.values()) {
@@ -1862,18 +1723,10 @@ export class SessionManager {
return children;
}
- /**
- * Get the label for an entry, if any.
- */
getLabel(id: string): string | undefined {
return this.labelsById.get(id);
}
- /**
- * Set or clear a label on an entry.
- * Labels are user-defined markers for bookmarking/navigation.
- * Pass undefined or empty string to clear the label.
- */
appendLabelChange(targetId: string, label: string | undefined): string {
if (!this.byId.has(targetId)) {
throw new Error(`Entry ${targetId} not found`);
@@ -1897,11 +1750,6 @@ export class SessionManager {
return entry.id;
}
- /**
- * Walk from entry to root, returning all entries in path order.
- * Includes all entry types (messages, compaction, model changes, etc.).
- * Use buildSessionContext() to get the resolved messages for the LLM.
- */
getBranch(fromId?: string): SessionEntry[] {
// push+reverse, not unshift-per-entry: unshift is O(n), which makes this O(n^2) on long sessions.
const path: SessionEntry[] = [];
@@ -1915,10 +1763,6 @@ export class SessionManager {
return path;
}
- /**
- * Build the session context (what gets sent to the LLM).
- * Uses tree traversal from current leaf.
- */
buildSessionContext(): SessionContext {
// Pass fileEntries directly rather than getEntries(): the resolved context
// is computed from the leaf-to-root walk over byId (which already excludes
@@ -1928,28 +1772,15 @@ export class SessionManager {
return buildSessionContext(this.fileEntries as SessionEntry[], this.leafId, this.byId);
}
- /**
- * Get session header.
- */
getHeader(): SessionHeader | null {
const h = this.fileEntries.find((e) => e.type === "session");
return h ? (h as SessionHeader) : null;
}
- /**
- * Get all session entries (excludes header). Returns a shallow copy.
- * The session is append-only: use appendXXX() to add entries, branch() to
- * change the leaf pointer. Entries cannot be modified or deleted.
- */
getEntries(): SessionEntry[] {
return this.fileEntries.filter((e): e is SessionEntry => e.type !== "session");
}
- /**
- * Get the session as a tree structure. Returns a shallow defensive copy of all entries.
- * A well-formed session has exactly one root (first entry with parentId === null).
- * Orphaned entries (broken parent chain) are also returned as roots.
- */
getFlatTree(): SessionTreeFlatNode[] {
return this.getEntries().map((entry) => ({
entry,
@@ -1963,12 +1794,10 @@ export class SessionManager {
const nodeMap = new Map<string, SessionTreeNode>();
const roots: SessionTreeNode[] = [];
- // Create nodes with resolved labels
for (const flatNode of entries) {
nodeMap.set(flatNode.entry.id, { ...flatNode, children: [] });
}
- // Build tree
for (const flatNode of entries) {
const entry = flatNode.entry;
const node = nodeMap.get(entry.id)!;
@@ -1979,7 +1808,6 @@ export class SessionManager {
if (parent) {
parent.children.push(node);
} else {
- // Orphan - treat as root
roots.push(node);
}
}
@@ -1997,16 +1825,6 @@ export class SessionManager {
return roots;
}
- // =========================================================================
- // Branching
- // =========================================================================
-
- /**
- * Start a new branch from an earlier entry.
- * Moves the leaf pointer to the specified entry. The next appendXXX() call
- * will create a child of that entry, forming a new branch. Existing entries
- * are not modified or deleted.
- */
branch(branchFromId: string): void {
if (!this.byId.has(branchFromId)) {
throw new Error(`Entry ${branchFromId} not found`);
@@ -2014,20 +1832,10 @@ export class SessionManager {
this.leafId = branchFromId;
}
- /**
- * Reset the leaf pointer to null (before any entries).
- * The next appendXXX() call will create a new root entry (parentId = null).
- * Use this when navigating to re-edit the first user message.
- */
resetLeaf(): void {
this.leafId = null;
}
- /**
- * Start a new branch with a summary of the abandoned path.
- * Same as branch(), but also appends a branch_summary entry that captures
- * context from the abandoned conversation path.
- */
branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean): string {
if (branchFromId !== null && !this.byId.has(branchFromId)) {
throw new Error(`Entry ${branchFromId} not found`);
@@ -2047,11 +1855,6 @@ export class SessionManager {
return entry.id;
}
- /**
- * Create a new session file containing only the path from root to the specified leaf.
- * Useful for extracting a single conversation path from a branched session.
- * Returns the new session file path, or undefined if not persisting.
- */
createBranchedSession(leafId: string): string | undefined {
const previousSessionFile = this.sessionFile;
const path = this.getBranch(leafId);
@@ -2059,7 +1862,6 @@ export class SessionManager {
throw new Error(`Entry ${leafId} not found`);
}
- // Filter out LabelEntry from path - we'll recreate them from the resolved map
const pathWithoutLabels = path.filter((e) => e.type !== "label");
const target = this.persist
@@ -2080,7 +1882,6 @@ export class SessionManager {
git: this.persist ? (captureGitContext(this.cwd) ?? undefined) : undefined,
};
- // Collect labels for entries in the path
const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));
const labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];
for (const [targetId, label] of this.labelsById) {
@@ -2090,7 +1891,6 @@ export class SessionManager {
}
if (this.persist) {
- // Build label entries
const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
let parentId = lastEntryId;
const labelEntries: LabelEntry[] = [];
@@ -2129,7 +1929,6 @@ export class SessionManager {
return newSessionFile;
}
- // In-memory mode: replace current session with the path + labels
const labelEntries: LabelEntry[] = [];
let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
@@ -2150,22 +1949,11 @@ export class SessionManager {
return undefined;
}
- /**
- * Create a new session.
- * @param cwd Working directory (stored in session header)
- * @param sessionDir Optional session directory. If omitted, uses the configured session root.
- */
static create(cwd: string, sessionDir?: string): SessionManager {
const dir = sessionDir ?? getDefaultSessionDir(cwd);
return new SessionManager(cwd, dir, undefined, true);
}
- /**
- * Open a specific session file.
- * @param path Path to session file
- * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
- * @param cwdOverride Optional cwd override instead of the session header cwd.
- */
static open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {
// Only the header's cwd is needed to construct the manager; the constructor
// (setSessionFile) performs the full parse. Read just the first line here
@@ -2189,22 +1977,15 @@ export class SessionManager {
}
cwd = header?.cwd;
}
- // If no sessionDir provided, derive from file's parent directory
const dir = sessionDir ?? resolve(path, "..");
return new SessionManager(cwd ?? process.cwd(), dir, path, true);
}
- /**
- * Non-blocking open() for the daemon: parses off the event loop so a large load
- * doesn't freeze other sessions. Falls back to open() for any non-happy path so
- * behavior is identical to it.
- */
static async openAsync(path: string, sessionDir?: string, cwdOverride?: string): Promise<SessionManager> {
if (!existsSync(path)) {
return SessionManager.open(path, sessionDir, cwdOverride);
}
const entries = await loadEntriesFromFileAsync(path);
- // empty/corrupt: defer to open() (finalizeLoadedEntries guarantees entries[0] is a valid header otherwise)
if (entries.length === 0) {
return SessionManager.open(path, sessionDir, cwdOverride);
}
@@ -2213,11 +1994,6 @@ export class SessionManager {
return new SessionManager(cwd ?? process.cwd(), dir, path, true, entries);
}
- /**
- * Continue the most recent session, or create new if none.
- * @param cwd Working directory
- * @param sessionDir Optional session directory. If omitted, uses the configured session root.
- */
static continueRecent(cwd: string, sessionDir?: string): SessionManager {
const dir = sessionDir ?? getDefaultSessionDir(cwd);
const mostRecent = findMostRecentSessionForCwd(dir, cwd);
@@ -2227,18 +2003,10 @@ export class SessionManager {
return new SessionManager(cwd, dir, undefined, true);
}
- /** Create an in-memory session (no file persistence) */
static inMemory(cwd: string = process.cwd(), sessionDir = ""): SessionManager {
return new SessionManager(cwd, sessionDir, undefined, false);
}
- /**
- * Fork a session from another project directory into the current project.
- * Creates a new session in the target cwd with the full history from the source session.
- * @param sourcePath Path to the source session file
- * @param targetCwd Target working directory (where the new session will be stored)
- * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.
- */
static forkFrom(sourcePath: string, targetCwd: string, sessionDir?: string): SessionManager {
const sourceEntries = loadEntriesFromFile(sourcePath);
if (sourceEntries.length === 0) {
@@ -2256,13 +2024,11 @@ export class SessionManager {
mkdirSync(dir, { recursive: true });
}
- // Create new session file with new ID but forked content
const target = createUniqueSessionFileTarget(dir);
const newSessionId = target.sessionId;
const timestamp = new Date().toISOString();
const newSessionFile = target.sessionFile;
- // Write new header pointing to source as parent, with updated cwd
const newHeader: SessionHeader = {
type: "session",
version: CURRENT_SESSION_VERSION,
@@ -2296,12 +2062,6 @@ export class SessionManager {
return new SessionManager(targetCwd, dir, newSessionFile, true);
}
- /**
- * List all sessions for a directory.
- * @param cwd Working directory (used to compute default session directory)
- * @param sessionDir Optional session directory. If omitted, uses the configured session root.
- * @param callbacks Optional callbacks for progress and discovered sessions
- */
static async list(cwd: string, sessionDir?: string, callbacks?: SessionListCallbacks): Promise<SessionInfo[]> {
const dir = sessionDir ?? getDefaultSessionDir(cwd);
const matchesCwd = (session: SessionInfo) => sessionInfoMatchesCwd(session, cwd);
@@ -2321,11 +2081,6 @@ export class SessionManager {
return sessions;
}
- /**
- * List all sessions across all project directories.
- * @param callbacks Optional callbacks for progress and discovered sessions
- * @param sessionDir Optional session root. If omitted, uses the configured session root.
- */
static async listAll(callbacks?: SessionListCallbacks, sessionDir?: string): Promise<SessionInfo[]> {
const sessionsDir = sessionDir ?? getSessionsDir();
const sessions = await listSessionsFromDir(sessionsDir, callbacks);
diff --git a/packages/coding-agent/src/core/session-stats.ts b/packages/coding-agent/src/core/session-stats.ts
index 27997307e3..bff8c91922 100644
--- a/packages/coding-agent/src/core/session-stats.ts
+++ b/packages/coding-agent/src/core/session-stats.ts
@@ -1,6 +1,5 @@
import type { ContextUsage } from "./extensions/index.js";
-/** Session statistics for the /session command and connection snapshots. */
export interface SessionStats {
sessionFile: string | undefined;
sessionId: string;
diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts
index d221ccc7e5..30f759bab3 100644
--- a/packages/coding-agent/src/core/settings-manager.ts
+++ b/packages/coding-agent/src/core/settings-manager.ts
@@ -186,8 +186,6 @@ function deepMergeSettings(base: Settings, overrides: Settings): Settings {
if (overrideValue === undefined) {
continue;
}
-
- // For nested objects, merge recursively
if (
typeof overrideValue === "object" &&
overrideValue !== null &&
@@ -198,7 +196,6 @@ function deepMergeSettings(base: Settings, overrides: Settings): Settings {
) {
(result as Record<string, unknown>)[key] = { ...baseValue, ...overrideValue };
} else {
- // For primitives and arrays, override value wins
(result as Record<string, unknown>)[key] = overrideValue;
}
}
@@ -259,7 +256,6 @@ export class FileSettingsStorage implements SettingsStorage {
let release: (() => void) | undefined;
try {
- // Only create directory and lock if file exists or we need to write
const fileExists = existsSync(path);
if (fileExists) {
release = this.acquireLockSyncWithRetry(path);
@@ -267,7 +263,6 @@ export class FileSettingsStorage implements SettingsStorage {
const current = fileExists ? readFileSync(path, "utf-8") : undefined;
const next = fn(current);
if (next !== undefined) {
- // Only create directory when we actually need to write
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
@@ -396,19 +391,14 @@ export class SettingsManager {
/** Migrate old settings format to new format */
private static migrateSettings(settings: Record<string, unknown>): Settings {
- // Migrate queueMode -> steeringMode
if ("queueMode" in settings && !("steeringMode" in settings)) {
settings.steeringMode = settings.queueMode;
delete settings.queueMode;
}
-
- // Migrate legacy websockets boolean -> transport enum
if (!("transport" in settings) && typeof settings.websockets === "boolean") {
settings.transport = settings.websockets ? "websocket" : "sse";
delete settings.websockets;
}
-
- // Migrate old skills object format to new array format
if (
"skills" in settings &&
typeof settings.skills === "object" &&
@@ -428,8 +418,6 @@ export class SettingsManager {
delete settings.skills;
}
}
-
- // Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs
if (
"retry" in settings &&
typeof settings.retry === "object" &&
@@ -1120,7 +1108,6 @@ export class SettingsManager {
}
getClearOnShrink(): boolean {
- // Settings takes precedence, then env var, then default false
if (this.settings.terminal?.clearOnShrink !== undefined) {
return this.settings.terminal.clearOnShrink;
}
@@ -1137,7 +1124,6 @@ export class SettingsManager {
}
getFullscreen(): boolean {
- // Env var overrides the setting (both directions) for one-off runs
if (process.env.PI_FULLSCREEN !== undefined) {
return process.env.PI_FULLSCREEN === "1";
}
diff --git a/packages/coding-agent/src/core/skills.ts b/packages/coding-agent/src/core/skills.ts
index 0872e818aa..9ed0875628 100644
--- a/packages/coding-agent/src/core/skills.ts
+++ b/packages/coding-agent/src/core/skills.ts
@@ -332,14 +332,12 @@ function loadSkillsFromDirInternal(
continue;
}
- // Skip node_modules to avoid scanning dependencies
if (entry.name === "node_modules") {
continue;
}
const fullPath = join(dir, entry.name);
- // For symlinks, check if they point to a directory and follow them
let isDirectory = entry.isDirectory();
let isFile = entry.isFile();
if (entry.isSymbolicLink()) {
@@ -348,7 +346,6 @@ function loadSkillsFromDirInternal(
isDirectory = stats.isDirectory();
isFile = stats.isFile();
} catch {
- // Broken symlink, skip it
continue;
}
}
@@ -398,22 +395,18 @@ function loadSkillFromFile(
const skillDir = dirname(filePath);
const parentDirName = basename(skillDir);
- // Validate description
const descErrors = validateDescription(frontmatter.description);
for (const error of descErrors) {
diagnostics.push({ type: "warning", message: error, path: filePath });
}
- // Use name from frontmatter, or fall back to parent directory name
const name = frontmatter.name || parentDirName;
- // Validate name
const nameErrors = validateName(name, parentDirName);
for (const error of nameErrors) {
diagnostics.push({ type: "warning", message: error, path: filePath });
}
- // Still load the skill even with warnings (unless description is completely missing)
if (!frontmatter.description || frontmatter.description.trim() === "") {
return { skill: null, diagnostics };
}
@@ -520,7 +513,6 @@ function resolveSkillPath(p: string, cwd: string): string {
export function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {
const { cwd, agentDir, skillPaths, includeDefaults } = options;
- // Resolve agentDir - if not provided, use default from config
const resolvedAgentDir = agentDir ?? getAgentDir();
const skillMap = new Map<string, Skill>();
@@ -533,10 +525,8 @@ export function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {
function addSkills(result: LoadSkillsResult) {
allDiagnostics.push(...result.diagnostics);
for (const skill of result.skills) {
- // Resolve symlinks to detect duplicate files
const realPath = canonicalizePath(skill.filePath);
- // Skip silently if we've already loaded this exact file (via symlink)
if (realPathSet.has(realPath)) {
continue;
}
diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.ts
index 8329572ce7..1541063491 100644
--- a/packages/coding-agent/src/core/tools/bash.ts
+++ b/packages/coding-agent/src/core/tools/bash.ts
@@ -81,17 +81,14 @@ export function createLocalBashOperations(options?: { shellPath?: string }): Bas
if (child.pid) trackDetachedChildPid(child.pid);
let timedOut = false;
let timeoutHandle: NodeJS.Timeout | undefined;
- // Set timeout if provided.
if (timeout !== undefined && timeout > 0) {
timeoutHandle = setTimeout(() => {
timedOut = true;
if (child.pid) killProcessTree(child.pid);
}, timeout * 1000);
}
- // Stream stdout and stderr.
child.stdout?.on("data", onData);
child.stderr?.on("data", onData);
- // Handle abort signal by killing the entire process tree.
const onAbort = () => {
if (child.pid) killProcessTree(child.pid);
};
diff --git a/packages/coding-agent/src/core/tools/edit-diff.ts b/packages/coding-agent/src/core/tools/edit-diff.ts
index 6d9bb05d4d..a1fe118647 100644
--- a/packages/coding-agent/src/core/tools/edit-diff.ts
+++ b/packages/coding-agent/src/core/tools/edit-diff.ts
@@ -32,26 +32,15 @@ export function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string
* - Normalize special Unicode spaces to regular space
*/
export function normalizeForFuzzyMatch(text: string): string {
- return (
- text
- .normalize("NFKC")
- // Strip trailing whitespace per line
- .split("\n")
- .map((line) => line.trimEnd())
- .join("\n")
- // Smart single quotes → '
- .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
- // Smart double quotes → "
- .replace(/[\u201C\u201D\u201E\u201F]/g, '"')
- // Various dashes/hyphens → -
- // U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,
- // U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus
- .replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-")
- // Special spaces → regular space
- // U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,
- // U+205F medium math space, U+3000 ideographic space
- .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")
- );
+ return text
+ .normalize("NFKC")
+ .split("\n")
+ .map((line) => line.trimEnd())
+ .join("\n")
+ .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
+ .replace(/[\u201C\u201D\u201E\u201F]/g, '"')
+ .replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-")
+ .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ");
}
export interface FuzzyMatchResult {
@@ -94,7 +83,6 @@ export interface AppliedEditsResult {
* Unicode quotes/dashes normalized to ASCII).
*/
export function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {
- // Try exact match first
const exactIndex = content.indexOf(oldText);
if (exactIndex !== -1) {
return {
@@ -106,7 +94,6 @@ export function fuzzyFindText(content: string, oldText: string): FuzzyMatchResul
};
}
- // Try fuzzy match - work entirely in normalized space
const fuzzyContent = normalizeForFuzzyMatch(content);
const fuzzyOldText = normalizeForFuzzyMatch(oldText);
const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);
@@ -274,7 +261,6 @@ export function generateDiffString(
const oldLines = oldContent.split("\n");
const newLines = newContent.split("\n");
- // Offset by startLine so a snippet shows absolute file line numbers.
const maxLineNum = startLine - 1 + Math.max(oldLines.length, newLines.length);
const lineNumWidth = String(maxLineNum).length;
@@ -291,19 +277,16 @@ export function generateDiffString(
}
if (part.added || part.removed) {
- // Capture the first changed line (in the new file)
if (firstChangedLine === undefined) {
firstChangedLine = newLineNum;
}
- // Show the change
for (const line of raw) {
if (part.added) {
const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
output.push(`+${lineNum} ${line}`);
newLineNum++;
} else {
- // removed
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
output.push(`-${lineNum} ${line}`);
oldLineNum++;
@@ -311,7 +294,6 @@ export function generateDiffString(
}
lastWasChange = true;
} else {
- // Context lines - only show a few before/after changes
const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
const hasLeadingChange = lastWasChange;
const hasTrailingChange = nextPartIsChange;
@@ -378,7 +360,6 @@ export function generateDiffString(
newLineNum++;
}
} else {
- // Skip these context lines entirely
oldLineNum += raw.length;
newLineNum += raw.length;
}
@@ -411,7 +392,6 @@ export async function computeEditsDiff(
const absolutePath = resolveToCwd(path, cwd);
try {
- // Check if file exists and is readable
try {
await access(absolutePath, constants.R_OK);
} catch (error: unknown) {
@@ -419,15 +399,11 @@ export async function computeEditsDiff(
return { error: `Could not edit file: ${path}. ${errorMessage}.` };
}
- // Read the file
const rawContent = await readFile(absolutePath, "utf-8");
-
- // Strip BOM before matching (LLM won't include invisible BOM in oldText)
const { text: content } = stripBom(rawContent);
const normalizedContent = normalizeToLF(content);
const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);
- // Generate the diff
return generateDiffString(baseContent, newContent);
} catch (err) {
return { error: err instanceof Error ? err.message : String(err) };
diff --git a/packages/coding-agent/src/core/tools/edit.ts b/packages/coding-agent/src/core/tools/edit.ts
index e0eb0502f0..df71f893f4 100644
--- a/packages/coding-agent/src/core/tools/edit.ts
+++ b/packages/coding-agent/src/core/tools/edit.ts
@@ -105,7 +105,7 @@ function prepareEditArguments(input: unknown): EditToolInput {
const parsed = JSON.parse(args.edits);
if (Array.isArray(parsed)) args.edits = parsed;
} catch {
- // Not JSON: leave as-is for schema validation to reject.
+ // Leave non-JSON input for schema validation to reject.
}
}
@@ -365,7 +365,6 @@ export function createEditToolDefinition(
content: Array<{ type: "text"; text: string }>;
details: EditToolDetails | undefined;
}>((resolve, reject) => {
- // Check if already aborted.
if (signal?.aborted) {
reject(new Error("Operation aborted"));
return;
@@ -373,7 +372,6 @@ export function createEditToolDefinition(
let aborted = false;
- // Set up abort handler.
const onAbort = () => {
aborted = true;
reject(new Error("Operation aborted"));
@@ -383,10 +381,8 @@ export function createEditToolDefinition(
signal.addEventListener("abort", onAbort, { once: true });
}
- // Perform the edit operation.
void (async () => {
try {
- // Check if file exists.
try {
await ops.access(absolutePath);
} catch (error: unknown) {
@@ -399,16 +395,13 @@ export function createEditToolDefinition(
return;
}
- // Check if aborted before reading.
if (aborted) {
return;
}
- // Read the file.
const buffer = await ops.readFile(absolutePath);
const rawContent = buffer.toString("utf-8");
- // Check if aborted after reading.
if (aborted) {
return;
}
@@ -423,7 +416,6 @@ export function createEditToolDefinition(
path,
);
- // Check if aborted before writing.
if (aborted) {
return;
}
@@ -431,12 +423,10 @@ export function createEditToolDefinition(
const finalContent = bom + restoreLineEndings(newContent, originalEnding);
await ops.writeFile(absolutePath, finalContent);
- // Check if aborted after writing.
if (aborted) {
return;
}
- // Clean up abort handler.
if (signal) {
signal.removeEventListener("abort", onAbort);
}
@@ -452,7 +442,6 @@ export function createEditToolDefinition(
details: { diff: diffResult.diff, firstChangedLine: diffResult.firstChangedLine },
});
} catch (error: unknown) {
- // Clean up abort handler.
if (signal) {
signal.removeEventListener("abort", onAbort);
}
diff --git a/packages/coding-agent/src/core/tools/index.ts b/packages/coding-agent/src/core/tools/index.ts
index b9dd19237c..f846d0bf68 100644
--- a/packages/coding-agent/src/core/tools/index.ts
+++ b/packages/coding-agent/src/core/tools/index.ts
@@ -39,43 +39,18 @@ export {
import type { AgentTool } from "@earendil-works/pi-agent-core";
import type { ToolDefinition } from "../extensions/types.js";
-import { createIpythonTool, createIpythonToolDefinition, type IpythonToolOptions } from "./ipython.js";
+import { createIpythonToolDefinition, type IpythonToolOptions } from "./ipython.js";
export type Tool = AgentTool<any>;
export type ToolDef = ToolDefinition<any, any>;
export type ToolName = "ipython";
-export const allToolNames: Set<ToolName> = new Set(["ipython"]);
export interface ToolsOptions {
ipython?: IpythonToolOptions;
}
-export function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef {
- switch (toolName) {
- case "ipython":
- return createIpythonToolDefinition(cwd, options?.ipython);
- default:
- throw new Error(`Unknown tool name: ${toolName}`);
- }
-}
-
-export function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool {
- switch (toolName) {
- case "ipython":
- return createIpythonTool(cwd, options?.ipython);
- default:
- throw new Error(`Unknown tool name: ${toolName}`);
- }
-}
-
export function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record<ToolName, ToolDef> {
return {
ipython: createIpythonToolDefinition(cwd, options?.ipython),
};
}
-
-export function createAllTools(cwd: string, options?: ToolsOptions): Record<ToolName, Tool> {
- return {
- ipython: createIpythonTool(cwd, options?.ipython),
- };
-}
diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.ts
index 1be4321d5b..affb252ebd 100644
--- a/packages/coding-agent/src/core/tools/ipython.ts
+++ b/packages/coding-agent/src/core/tools/ipython.ts
@@ -1,4 +1,3 @@
-// TODO: reconsider whether the persistent kernel is needed once RLM-1 weights land.
import { existsSync } from "node:fs";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
diff --git a/packages/coding-agent/src/core/tools/path-utils.ts b/packages/coding-agent/src/core/tools/path-utils.ts
index 0c10b52ecb..e1e121f3c6 100644
--- a/packages/coding-agent/src/core/tools/path-utils.ts
+++ b/packages/coding-agent/src/core/tools/path-utils.ts
@@ -66,25 +66,21 @@ export function resolveReadPath(filePath: string, cwd: string): string {
return resolved;
}
- // Try macOS AM/PM variant (narrow no-break space before AM/PM)
const amPmVariant = tryMacOSScreenshotPath(resolved);
if (amPmVariant !== resolved && fileExists(amPmVariant)) {
return amPmVariant;
}
- // Try NFD variant (macOS stores filenames in NFD form)
const nfdVariant = tryNFDVariant(resolved);
if (nfdVariant !== resolved && fileExists(nfdVariant)) {
return nfdVariant;
}
- // Try curly quote variant (macOS uses U+2019 in screenshot names)
const curlyVariant = tryCurlyQuoteVariant(resolved);
if (curlyVariant !== resolved && fileExists(curlyVariant)) {
return curlyVariant;
}
- // Try combined NFD + curly quote (for French macOS screenshots like "Capture d'écran")
const nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);
if (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {
return nfdCurlyVariant;
diff --git a/packages/coding-agent/src/core/tools/render-utils.ts b/packages/coding-agent/src/core/tools/render-utils.ts
index 81d057583a..19893aa50e 100644
--- a/packages/coding-agent/src/core/tools/render-utils.ts
+++ b/packages/coding-agent/src/core/tools/render-utils.ts
@@ -23,10 +23,6 @@ export function replaceTabs(text: string): string {
return text.replace(/\t/g, " ");
}
-export function normalizeDisplayText(text: string): string {
- return text.replace(/\r/g, "");
-}
-
export interface TextOutputOptions {
/** Whether image fallbacks should parse image dimensions from base64 data. */
includeImageDimensions?: boolean;
diff --git a/packages/coding-agent/src/core/tools/truncate.ts b/packages/coding-agent/src/core/tools/truncate.ts
index 18ac5d74d2..a770db881f 100644
--- a/packages/coding-agent/src/core/tools/truncate.ts
+++ b/packages/coding-agent/src/core/tools/truncate.ts
@@ -72,7 +72,6 @@ export function truncateHead(content: string, options: TruncationOptions = {}):
const lines = content.split("\n");
const totalLines = lines.length;
- // Check if no truncation needed
if (totalLines <= maxLines && totalBytes <= maxBytes) {
return {
content,
@@ -89,7 +88,6 @@ export function truncateHead(content: string, options: TruncationOptions = {}):
};
}
- // Check if first line alone exceeds byte limit
const firstLineBytes = Buffer.byteLength(lines[0], "utf-8");
if (firstLineBytes > maxBytes) {
return {
@@ -107,7 +105,6 @@ export function truncateHead(content: string, options: TruncationOptions = {}):
};
}
- // Collect complete lines that fit
const outputLinesArr: string[] = [];
let outputBytesCount = 0;
let truncatedBy: "lines" | "bytes" = "lines";
@@ -125,7 +122,6 @@ export function truncateHead(content: string, options: TruncationOptions = {}):
outputBytesCount += lineBytes;
}
- // If we exited due to line limit
if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
truncatedBy = "lines";
}
@@ -162,7 +158,6 @@ export function truncateTail(content: string, options: TruncationOptions = {}):
const lines = content.split("\n");
const totalLines = lines.length;
- // Check if no truncation needed
if (totalLines <= maxLines && totalBytes <= maxBytes) {
return {
content,
@@ -179,7 +174,6 @@ export function truncateTail(content: string, options: TruncationOptions = {}):
};
}
- // Work backwards from the end
const outputLinesArr: string[] = [];
let outputBytesCount = 0;
let truncatedBy: "lines" | "bytes" = "lines";
@@ -206,7 +200,6 @@ export function truncateTail(content: string, options: TruncationOptions = {}):
outputBytesCount += lineBytes;
}
- // If we exited due to line limit
if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
truncatedBy = "lines";
}
@@ -239,7 +232,6 @@ function truncateStringToBytesFromEnd(str: string, maxBytes: number): string {
return str;
}
- // Start from the end, skip maxBytes back
let start = buf.length - maxBytes;
// Find a valid UTF-8 boundary (start of a character)
diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.ts
index eed228ae08..4228c5ed8e 100644
--- a/packages/coding-agent/src/modes/acp/acp-mode.ts
+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts
@@ -16,19 +16,6 @@ import { type AcpEventMappingState, acpUpdatesForSessionEvent } from "./acp-even
import { primeAgentMeta } from "./acp-meta.js";
import { type AcpStopReason, acpStopReason } from "./acp-stop-reason.js";
-/**
- * ACP (Agent Client Protocol) mode.
- *
- * prime-agent acts as an ACP agent over NDJSON on stdio, driving an
- * `AgentConnection` in-process. It deliberately does not shell out to RPC mode
- * and translate: prime-agent's differentiators (IPython-only tools, subagents,
- * autonomous gates) are visible as first-class events here, and a translating
- * adapter is exactly what flattens them away.
- *
- * Capabilities ACP has no native concept for travel in a reverse-domain
- * `_meta` envelope, which vanilla ACP clients ignore.
- */
-
/**
* ACP frames must reach real stdout.
*
@@ -383,8 +370,6 @@ export async function runAcpModeWithConnection(
}
})
.onRequest("session/close", async (ctx: any) => {
- // Releasing the subscription matters: it is the only thing that stops
- // forwarding events, and closing frees the connection for a new session.
const params = ctx.params as { sessionId: string };
if (session?.id !== params.sessionId) {
throw new Error(`Unknown ACP session: ${params.sessionId}`);
diff --git a/packages/coding-agent/src/modes/agent-connection/snapshot.ts b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
index 2c397645e0..d772c76d26 100644
--- a/packages/coding-agent/src/modes/agent-connection/snapshot.ts
+++ b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
@@ -54,7 +54,7 @@ export function createAgentConnectionState(
})),
activeToolNames: session.getActiveToolNames(),
contextUsage: session.getContextUsage(),
- // Baseline recap; the daemon overlays the live summary on attach.
+ // Baseline recap; the daemon overlays the live summary when attaching.
recap: persistedRecap(sessionManager),
};
}
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 7e98f96681..a5e8ea699c 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -297,12 +297,12 @@ export interface AgentConnectionParentMetadata {
export interface AgentConnectionSnapshot {
state: AgentConnectionState;
messages: AgentMessage[];
- /** In-flight assistant message, kept separate from finalized transcript messages. */
+ /** In-flight assistant message, separate from finalized transcript messages. */
streamingMessage?: AgentMessage;
sessionContext?: AgentConnectionSessionContext;
sessionTree?: { tree: AgentConnectionSessionTreeNode[]; leafId: string | null };
parent?: AgentConnectionParentMetadata;
- /** Live RLM child agents (including grandchildren) known to the host at snapshot time. */
+ /** Live RLM children, including descendants, known to the host at snapshot time. */
children?: AgentConnectionRlmChildAgentSnapshot[];
lastEventSequence?: number;
lastEventCursor?: AgentConnectionEventCursor;
@@ -348,7 +348,7 @@ export interface AgentConnectionState {
scopedModels: AgentConnectionScopedModel[];
activeToolNames: string[];
contextUsage: SessionStats["contextUsage"];
- /** One-line recap of the agent's recent work, shown above the prompt. */
+ /** One-line recent-work recap for the prompt UI. */
recap?: string;
}
@@ -434,7 +434,7 @@ export interface AgentConnectionToolDefinition {
replayBuiltInToolName?: ReplayBuiltInToolName;
}
-/** Prompt admission failure; only a confirmed cancellation is retry-safe. */
+/** Only confirmed cancellation makes prompt-admission failure retry-safe. */
export class AgentConnectionPromptAdmissionError extends Error {
readonly cancelled: boolean;
@@ -454,7 +454,7 @@ export interface AgentConnectionPromptOptions {
streamingBehavior?: "steer" | "followUp";
queueIfBusy?: boolean;
source?: InputSource;
- /** Cancel admission while it is still waiting; accepted prompts remain session-owned. */
+ /** Cancels only while admission waits; accepted prompts remain session-owned. */
signal?: AbortSignal;
}
@@ -473,7 +473,7 @@ export interface AgentConnectionSideQuestionTurn {
export interface AgentConnectionExecuteBashOptions {
excludeFromContext?: boolean;
- /** Run without recording into the session (side-conversation bash). */
+ /** Side-conversation bash is not recorded into the session. */
transient?: boolean;
/**
* Caller-generated id echoed on the run's bash_start/bash_end events, so the
@@ -520,7 +520,7 @@ export interface AgentConnectionQueueState {
export type AgentConnectionQueuedMessageLane = QueuedMessageLane;
export type AgentConnectionQueuedMessageMutation = QueuedMessageMutation;
-/** "unsupported" is returned only by remote connections whose daemon predates queued-message mutation. */
+/** `unsupported` means an older remote daemon lacks queued-message mutation. */
export type AgentConnectionQueuedMessageMutationStatus = QueuedMessageMutationStatus | "unsupported";
export interface AgentConnectionHeartbeat {
@@ -547,9 +547,9 @@ export interface AgentConnectionRlmChildAgentActivity {
export interface AgentConnectionRlmChildAgentSnapshot {
id: string;
parentId?: string;
- /** The child's own daemon active-session id, for attaching to it directly. */
+ /** Child daemon active-session id, for direct attachment. */
activeSessionId?: string;
- /** Stable daemon-visible session name for addressing/displaying the child. */
+ /** Stable daemon-visible child name for addressing and display. */
sessionName?: string;
/** Exact provider/model selector used by the child. */
model?: string;
@@ -558,15 +558,11 @@ export interface AgentConnectionRlmChildAgentSnapshot {
durationMs?: number;
answerPreview?: string;
repliedSinceTask?: boolean;
- /** Number of tool executions the subagent has started so far. */
toolUseCount?: number;
- /** Context size (tokens) of the subagent's latest turn. */
tokenCount?: number;
- /** Latest recap of what the subagent is doing. */
recap?: string;
sessionDir: string;
activity?: AgentConnectionRlmChildAgentActivity;
- /** Failure reason when status is "error". */
error?: string;
}
@@ -589,7 +585,6 @@ export type AgentConnectionSessionEvent =
aborted: boolean;
willRetry: boolean;
errorMessage?: string;
- /** "warning" for benign skips (nothing to compact), "error" for real failures */
errorSeverity?: "warning" | "error";
customInstructions?: string;
}
@@ -607,11 +602,8 @@ export type AgentConnectionSessionEvent =
cancelled: boolean;
truncated: boolean;
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 }
@@ -684,7 +676,6 @@ export interface AgentConnection {
clearAgentMessages(): Promise<number>;
getUserMessagesForForking(): Promise<AgentConnectionUserMessage[]>;
getLastAssistantText(): Promise<string | undefined>;
- /** The system prompt currently in effect for the model (with any per-turn extension changes). */
getSystemPrompt(): Promise<string>;
getToolDefinition(name: string): Promise<AgentConnectionToolDefinition | undefined>;
setSessionEntryLabel(entryId: string, label: string | undefined): Promise<void>;
@@ -696,7 +687,6 @@ export interface AgentConnection {
abortSideQuestion(id: string): Promise<boolean>;
steer(message: string, images?: ImageContent[]): Promise<void>;
followUp(message: string, images?: ImageContent[]): Promise<void>;
- /** Request cancellation of the active turn and return once the request is accepted. */
abort(): Promise<void>;
cancelRlmChild(childId: string): Promise<boolean>;
waitForIdle(): Promise<void>;
@@ -746,7 +736,7 @@ export interface AgentConnection {
renameSavedSession(sessionPath: string, name: string): Promise<void>;
deleteSavedSession(sessionPath: string): Promise<DeleteSessionFileResult>;
- /** Read-only watcher on another live session (a subagent); undefined if the transport can't reach it. */
+ /** Read-only live-session watcher; unavailable transports return undefined. */
watchSession(activeSessionId: string): Promise<AgentConnectionSessionWatcher | undefined>;
dispose(): Promise<void>;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index 4569e22252..ba650be09b 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -111,8 +111,6 @@ const RESUME_PROMPT_PLACEHOLDER = "Write a prompt to resume this session";
const COMPLETED_ROW_ICON = "✓";
const NEEDS_INPUT_ROW_ICON = "●";
const SELECTED_ROW_MARKER = "\0agents-view-selected-row\0";
-// Tags a spawn-code line so finalize can wrap the whole row in a panel
-// background, visually segmenting the program from the agent rows.
const CODE_ROW_MARKER = "\0agents-view-code-row\0";
export interface AgentsViewModeOptions {
@@ -159,7 +157,6 @@ export type AgentsViewPersistentState = {
// Ancestor chain to re-expand on return to a nested agent. Kept by sessionId,
// not row identity, so it survives an active→persisted identity flip.
pendingExpandedAncestorSessionIds?: string[];
- // Shared with each view instance so in-place expansion mutations survive remounts.
expandedSubagentParents?: Set<string>;
programShownParents?: Set<string>;
statusMessage?: string;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
index aabe580008..9a69e1ebff 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
@@ -56,14 +56,10 @@ function deserializeSessionInfo(session: SessionInfoWire): SessionInfo {
};
}
-/** @internal Exported to pin catalog selector semantics without spawning a catalog process. */
export function resolveCatalogSessionMatch(
sessions: readonly SessionInfo[],
selector: string,
): SessionInfo | undefined {
- // Deliberate broadening for create/resume as well as a2a wake: exact names
- // participate alongside id prefixes. Therefore a name that collides with an
- // id prefix is now ambiguous instead of the id-prefix match winning.
const matches = sessions.filter((session) => session.id.startsWith(selector) || session.name === selector);
if (matches.length > 1) {
throw new Error(`Ambiguous session selector "${selector}"`);
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index d7f5c099cd..90c448b47d 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -448,15 +448,6 @@ export async function runDaemonMode(options: DaemonModeOptions): Promise<never>
return new Promise(() => {});
}
-export function isTerminalRemoteAgentMessageError(error: unknown): error is Error {
- return (
- error instanceof Error &&
- (error.message.startsWith("Unknown active session:") ||
- error.message.startsWith("Ambiguous") ||
- error.message === AGENT_FAMILY_REACH_ERROR)
- );
-}
-
export class AgentDaemon {
private server?: Server;
private shuttingDown = false;
@@ -5874,6 +5865,7 @@ export class AgentDaemon {
type: "session_detached",
activeSessionId: state.activeSessionId,
});
+ // Discard an abandoned empty draft rather than retaining an empty session file.
// Abandoned new-chat: discard it so it doesn't linger in memory or leave an
// empty file. Replaces the old DeferredAgentConnection.
if (this.isDiscardableDraft(state)) {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts
index 154be07162..01c130514f 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor-ownership.ts
@@ -319,6 +319,7 @@ function defaultDaemonSupervisorRegistryDir(environment: NodeJS.ProcessEnv = pro
return environment[DAEMON_SUPERVISOR_REGISTRY_DIR_ENV] ?? join(homedir(), ".prime", "supervisor-owners");
}
+/** Read-only legacy registry location, disabled when the registry is overridden. */
/**
* Pre-move registry location under $TMPDIR, consulted READ-ONLY while daemons
* from before the ~/.prime move may still be running; gated off whenever the
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index ec3711c2b7..ad61fc57b7 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -2041,8 +2041,6 @@ export class DaemonSupervisor {
if (existing && !(await this.reclaimStaleWorkerRegistration(existing.worker))) {
return this.reuseWorkerForCreate(existing.worker, ownerClientId, sessionPath);
}
- // A passive child from a stopped worker reopens as top-level here (pre-existing behavior);
- // the recursive-harness residency/eviction PR will revisit it.
}
const key = createCommand.sessionPath
? canonicalSessionPath(createCommand.sessionPath)
diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
index 6adb2357e9..b3e01b95ee 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
@@ -196,7 +196,7 @@ export class DaemonWorkerClient {
}
}
} catch {
- // The malformed frame eventually fails the hello timeout.
+ // Invalid hello payloads are rejected by the timeout.
}
}
for (const listener of this.frameListeners) {
diff --git a/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts b/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts
index f3a0a8cd9c..7f03cb5c87 100644
--- a/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts
+++ b/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts
@@ -51,7 +51,6 @@ function isRlmSubagentDisplayEntry(value: unknown): value is RlmSubagentDisplayE
);
}
-/** Atomic write (temp + rename). Throws on failure; callers decide severity. */
export function writeRlmSubagentDisplayEntry(entry: RlmSubagentDisplayEntry): void {
const path = rlmSubagentDisplayPath(entry.sessionDir);
mkdirSync(entry.sessionDir, { recursive: true });
@@ -72,7 +71,6 @@ export function writeRlmSubagentDisplayEntry(entry: RlmSubagentDisplayEntry): vo
}
}
-/** Tolerant read: undefined for a missing, malformed, or invalid file. */
export async function readRlmSubagentDisplayEntry(sessionDir: string): Promise<RlmSubagentDisplayEntry | undefined> {
let contents: string;
try {
diff --git a/packages/coding-agent/src/modes/interactive/agent-activity.ts b/packages/coding-agent/src/modes/interactive/agent-activity.ts
index 703cdabad2..fd2d65c442 100644
--- a/packages/coding-agent/src/modes/interactive/agent-activity.ts
+++ b/packages/coding-agent/src/modes/interactive/agent-activity.ts
@@ -5,9 +5,7 @@ export type AgentActivity = "waiting" | "thinking" | "writing" | "writing-code"
export interface AgentActivityStatus {
activity: AgentActivity;
- /** "down" while receiving model output, "up" while sending (request in flight or tool executing). */
direction: "down" | "up";
- /** Output tokens accumulated since the user's last message. */
tokens: number;
}
@@ -19,14 +17,8 @@ export const AGENT_ACTIVITY_LABELS: Record<AgentActivity, string> = {
executing: "Executing",
};
-/** Fallback estimate for providers that only report usage when the message completes. */
const CHARS_PER_TOKEN_ESTIMATE = 4;
-/**
- * Derives what the agent is doing right now (and how many output tokens it has
- * produced since the user's last message) from the session event stream, so the
- * working loader can show more than a static "Working...".
- */
export class AgentActivityTracker {
private activity: AgentActivity = "waiting";
private completedTokens = 0;
@@ -134,7 +126,6 @@ export class AgentActivityTracker {
}
}
-// Same tiers as the token formatter in the pre-fork footer (removed in #21).
export function formatTokenCount(count: number): string {
if (count < 1000) return count.toString();
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.ts
index 238d06f0e3..80e7b2378e 100644
--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts
+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts
@@ -1,12 +1,3 @@
-/**
- * Provider authentication flows (login/logout dialogs and selectors).
- *
- * Extracted from InteractiveMode so any TUI surface that owns a `TUI` and a
- * `ModelRegistry` (interactive sessions, the agents view) can run the same
- * auth UI. Host-specific side effects (footer refresh, billing warnings) hang
- * off the small host interface instead of the flows themselves.
- */
-
import * as path from "node:path";
import { getProviders, type OAuthProviderId, type OAuthSelectPrompt } from "@earendil-works/pi-ai";
import type { OverlayHandle, TUI } from "@earendil-works/pi-tui";
@@ -61,7 +52,6 @@ function isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {
return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat");
}
-/** Returns the extra-usage warning when the given model would run on Anthropic subscription auth. */
export async function getAnthropicSubscriptionAuthWarning(
modelRegistry: ModelRegistry,
model: { provider: string } | undefined,
@@ -120,10 +110,10 @@ export interface ProviderLoginOptions {
initialCategory?: AuthSelectorCategory;
}
+/** Shared auth dialogs: host-specific refresh and billing effects remain outside the flow. */
export class ProviderAuthFlows {
constructor(private readonly host: ProviderAuthFlowsHost) {}
- /** Runs the provider selector followed by the matching login dialog. */
/**
* Run the OAuth login flow for an MCP integration server.
*
@@ -194,8 +184,6 @@ export class ProviderAuthFlows {
return this.showApiKeyLoginDialog(providerOption.id, providerOption.name, kind);
}
- /** Shows the stored-credential selector and removes the chosen credential. */
- /** Returns the provider id that was logged out, or null if nothing changed (cancelled / none). */
runLogout(): Promise<string | null> {
const providerOptions = this.getLogoutProviderOptions();
if (providerOptions.length === 0) {
@@ -365,15 +353,7 @@ export class ProviderAuthFlows {
}
private async showBedrockSetupDialog(providerId: string, providerName: string): Promise<AuthenticationResult> {
- const dialog = new LoginDialogComponent(
- this.host.ui,
- providerId,
- () => {
- // Completion handled below.
- },
- providerName,
- "Amazon Bedrock setup",
- );
+ const dialog = new LoginDialogComponent(this.host.ui, providerId, () => {}, providerName, "Amazon Bedrock setup");
const handle = showFullPaneOverlay(this.host.ui, dialog, 88);
const closeDialog = () => {
handle.hide();
@@ -532,9 +512,7 @@ export class ProviderAuthFlows {
const dialog = new LoginDialogComponent(
this.host.ui,
PRIME_INFERENCE_PROVIDER_ID,
- (_success, _message) => {
- // Completion handled below.
- },
+ (_success, _message) => {},
PRIME_INFERENCE_PROVIDER_NAME,
);
@@ -651,9 +629,7 @@ export class ProviderAuthFlows {
const dialog = new LoginDialogComponent(
this.host.ui,
PRIME_AGENT_TRACES_PROVIDER_ID,
- (_success, _message) => {
- // Completion handled below.
- },
+ (_success, _message) => {},
PRIME_AGENT_TRACES_PROVIDER_NAME,
);
@@ -758,14 +734,7 @@ export class ProviderAuthFlows {
providerName: string,
kind: "provider" | "service" = "provider",
): Promise<AuthenticationResult> {
- const dialog = new LoginDialogComponent(
- this.host.ui,
- providerId,
- (_success, _message) => {
- // Completion handled below
- },
- providerName,
- );
+ const dialog = new LoginDialogComponent(this.host.ui, providerId, (_success, _message) => {}, providerName);
const handle = showFullPaneOverlay(this.host.ui, dialog, 88);
@@ -832,25 +801,15 @@ export class ProviderAuthFlows {
.getOAuthProviders()
.find((provider) => provider.id === providerId);
- // Providers that use callback servers (can paste redirect URL)
const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
- // Create login dialog component
- const dialog = new LoginDialogComponent(
- this.host.ui,
- providerId,
- (_success, _message) => {
- // Completion handled below
- },
- providerName,
- );
+ const dialog = new LoginDialogComponent(this.host.ui, providerId, (_success, _message) => {}, providerName);
const dialogHandle = showFullPaneOverlay(this.host.ui, dialog, {
maxContentWidth: 88,
suspendFullscreenMouse: true,
});
- // Promise for manual code input (racing with callback server)
let manualCodeResolve: ((code: string) => void) | undefined;
let manualCodeReject: ((err: Error) => void) | undefined;
const manualCodePromise = new Promise<string>((resolve, reject) => {
@@ -858,7 +817,6 @@ export class ProviderAuthFlows {
manualCodeReject = reject;
});
- // Close dialog overlay helper.
const closeDialog = () => {
dialogHandle.hide();
this.host.ui.requestRender();
@@ -870,7 +828,6 @@ export class ProviderAuthFlows {
dialog.showAuth(info.url, info.instructions);
if (usesCallbackServer) {
- // Show input for manual paste, racing with callback
dialog
.showManualInput("Paste redirect URL below, or complete login in browser:")
.then((value) => {
@@ -886,10 +843,8 @@ export class ProviderAuthFlows {
}
});
} else if (providerId === "github-copilot") {
- // GitHub Copilot polls after onAuth
dialog.showWaiting("Waiting for browser authentication...");
}
- // For Anthropic: onPrompt is called immediately after
},
onPrompt: async (prompt: { message: string; placeholder?: string }) => {
@@ -907,7 +862,6 @@ export class ProviderAuthFlows {
signal: dialog.signal,
});
- // Success
closeDialog();
return await this.completeProviderAuthentication(providerId, providerName, "oauth", undefined, kind);
} catch (error: unknown) {
diff --git a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
index 661bbfe8c6..2026e3fec9 100644
--- a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
+++ b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts
@@ -1,7 +1,3 @@
-/**
- * Component for displaying bash command execution with streaming output.
- */
-
import { Container, Loader, Spacer, Text, type TUI } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import {
@@ -15,7 +11,6 @@ import { DynamicBorder } from "./dynamic-border.js";
import { expandCollapseHint, keyText } from "./keybinding-hints.js";
import { truncateToVisualLines } from "./visual-truncate.js";
-// Preview line limit when not expanded (matches tool execution behavior)
const PREVIEW_LINES = 20;
export class BashExecutionComponent extends Container {
@@ -41,18 +36,14 @@ export class BashExecutionComponent extends Container {
// Keep tool activity tight against a preceding agent-message notification.
if (!options.suppressLeadingSpace) this.addChild(new Spacer(1));
- // Top border
this.addChild(new DynamicBorder(borderColor));
- // Content container (holds dynamic content between borders)
this.contentContainer = new Container();
this.addChild(this.contentContainer);
- // Command header
const header = new Text(theme.fg(colorKey, theme.bold(`$ ${command}`)), 1, 0);
this.contentContainer.addChild(header);
- // Loader
this.loader = new Loader(
ui,
(spinner) => theme.fg("muted", spinner),
@@ -61,7 +52,6 @@ export class BashExecutionComponent extends Container {
);
this.contentContainer.addChild(this.loader);
- // Bottom border
this.addChild(new DynamicBorder(borderColor));
}
@@ -79,14 +69,11 @@ export class BashExecutionComponent extends Container {
}
appendOutput(chunk: string): void {
- // Strip ANSI codes and normalize line endings
// Note: binary data is already sanitized in tui-renderer.ts executeBashCommand
const clean = stripAnsi(chunk).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
- // Append to output lines
const newLines = clean.split("\n");
if (this.outputLines.length > 0 && newLines.length > 0) {
- // Append first chunk to last line (incomplete line continuation)
this.outputLines[this.outputLines.length - 1] += newLines[0];
this.outputLines.push(...newLines.slice(1));
} else {
@@ -111,7 +98,6 @@ export class BashExecutionComponent extends Container {
this.truncationResult = truncationResult;
this.fullOutputPath = fullOutputPath;
- // Stop loader
this.loader.stop();
this.updateDisplay();
@@ -133,24 +119,19 @@ export class BashExecutionComponent extends Container {
maxBytes: DEFAULT_MAX_BYTES,
});
- // Get the lines to potentially display (after context truncation)
+ // Recompute wrapping from the render width so resizes and split panes cannot use stale columns.
const availableLines = contextTruncation.content ? contextTruncation.content.split("\n") : [];
- // Apply preview truncation based on expanded state
const previewLogicalLines = availableLines.slice(-PREVIEW_LINES);
const hiddenLineCount = availableLines.length - previewLogicalLines.length;
- // Rebuild content container
this.contentContainer.clear();
- // Command header
const header = new Text(theme.fg("bashMode", theme.bold(`$ ${this.command}`)), 1, 0);
this.contentContainer.addChild(header);
- // Output
if (availableLines.length > 0) {
if (this.expanded) {
- // Show all lines
const displayText = availableLines.map((line) => theme.fg("muted", line)).join("\n");
this.contentContainer.addChild(new Text(`\n${displayText}`, 1, 0));
} else {
@@ -176,13 +157,11 @@ export class BashExecutionComponent extends Container {
}
}
- // Loader or status
if (this.status === "running") {
this.contentContainer.addChild(this.loader);
} else {
const statusParts: string[] = [];
- // Show how many lines are hidden (collapsed preview)
if (hiddenLineCount > 0) {
if (this.expanded) {
statusParts.push(expandCollapseHint("app.tools.expand", true));
diff --git a/packages/coding-agent/src/modes/interactive/components/bordered-loader.ts b/packages/coding-agent/src/modes/interactive/components/bordered-loader.ts
index ebe7094eea..916e4af5d2 100644
--- a/packages/coding-agent/src/modes/interactive/components/bordered-loader.ts
+++ b/packages/coding-agent/src/modes/interactive/components/bordered-loader.ts
@@ -3,7 +3,6 @@ import type { Theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
import { keyHint } from "./keybinding-hints.js";
-/** Loader wrapped with borders for extension UI */
export class BorderedLoader extends Container {
private loader: CancellableLoader | Loader;
private cancellable: boolean;
diff --git a/packages/coding-agent/src/modes/interactive/components/countdown-timer.ts b/packages/coding-agent/src/modes/interactive/components/countdown-timer.ts
index ac730644e6..43d07f3116 100644
--- a/packages/coding-agent/src/modes/interactive/components/countdown-timer.ts
+++ b/packages/coding-agent/src/modes/interactive/components/countdown-timer.ts
@@ -1,7 +1,3 @@
-/**
- * Reusable countdown timer for dialog components.
- */
-
import type { TUI } from "@earendil-works/pi-tui";
export class CountdownTimer {
diff --git a/packages/coding-agent/src/modes/interactive/components/custom-message.ts b/packages/coding-agent/src/modes/interactive/components/custom-message.ts
index 5cf6bbe20c..a6840c347b 100644
--- a/packages/coding-agent/src/modes/interactive/components/custom-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/custom-message.ts
@@ -5,10 +5,6 @@ import type { MessageRenderer } from "../../../core/extensions/types.js";
import type { CustomMessage } from "../../../core/messages.js";
import { getMarkdownTheme, theme } from "../theme/theme.js";
-/**
- * Component that renders a custom message entry from extensions.
- * Uses distinct styling to differentiate from user messages.
- */
export class CustomMessageComponent extends Container {
private message: CustomMessage<unknown>;
private customRenderer?: MessageRenderer;
@@ -29,7 +25,6 @@ export class CustomMessageComponent extends Container {
this.addChild(new Spacer(1));
- // Create box with purple background (used for default rendering)
this.box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
this.rebuild();
@@ -48,38 +43,32 @@ export class CustomMessageComponent extends Container {
}
private rebuild(): void {
- // Remove previous content component
if (this.customComponent) {
this.removeChild(this.customComponent);
this.customComponent = undefined;
}
this.removeChild(this.box);
- // Try custom renderer first - it handles its own styling
if (this.customRenderer) {
try {
const component = this.customRenderer(this.message, { expanded: this._expanded }, theme);
if (component) {
- // Custom renderer provides its own styled component
this.customComponent = component;
this.addChild(component);
return;
}
} catch {
- // Fall through to default rendering
+ // Fall back to the default renderer.
}
}
- // Default rendering uses our box
this.addChild(this.box);
this.box.clear();
- // Default rendering: label + content
const label = theme.fg("customMessageLabel", `\x1b[1m[${this.message.customType}]\x1b[22m`);
this.box.addChild(new Text(label, 0, 0));
this.box.addChild(new Spacer(1));
- // Extract text content
let text: string;
if (typeof this.message.content === "string") {
text = this.message.content;
diff --git a/packages/coding-agent/src/modes/interactive/components/extension-editor.ts b/packages/coding-agent/src/modes/interactive/components/extension-editor.ts
index e1134ce964..e0cf071db3 100644
--- a/packages/coding-agent/src/modes/interactive/components/extension-editor.ts
+++ b/packages/coding-agent/src/modes/interactive/components/extension-editor.ts
@@ -1,8 +1,3 @@
-/**
- * Multi-line editor component for extensions.
- * Supports Ctrl+G for external editor.
- */
-
import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
@@ -54,20 +49,16 @@ export class ExtensionEditorComponent extends Container implements Focusable {
this.onSubmitCallback = onSubmit;
this.onCancelCallback = onCancel;
- // Add top border
this.addChild(new DynamicBorder());
this.addChild(new Spacer(1));
- // Add title
this.addChild(new Text(theme.fg("accent", title), 1, 0));
this.addChild(new Spacer(1));
- // Create editor
this.editor = new Editor(tui, getEditorTheme(), options);
if (prefill) {
this.editor.setText(prefill);
}
- // Wire up Enter to submit (Shift+Enter for newlines, like the main editor)
this.editor.onSubmit = (text: string) => {
this.onSubmitCallback(text);
};
@@ -75,7 +66,6 @@ export class ExtensionEditorComponent extends Container implements Focusable {
this.addChild(new Spacer(1));
- // Add hint
const hasExternalEditor = !!(process.env.VISUAL || process.env.EDITOR);
const hint =
keyHint("tui.select.confirm", "submit") +
@@ -88,25 +78,21 @@ export class ExtensionEditorComponent extends Container implements Focusable {
this.addChild(new Spacer(1));
- // Add bottom border
this.addChild(new DynamicBorder());
}
handleInput(keyData: string): void {
const kb = getKeybindings();
- // Escape or Ctrl+C to cancel
if (kb.matches(keyData, "tui.select.cancel")) {
this.onCancelCallback();
return;
}
- // External editor (app keybinding)
if (this.keybindings.matches(keyData, "app.editor.external")) {
this.openExternalEditor();
return;
}
- // Forward to editor
this.editor.handleInput(keyData);
}
diff --git a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
index 5cd527fa0d..7ea9ec50aa 100644
--- a/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/oauth-selector.ts
@@ -51,13 +51,10 @@ const PROVIDER_LIST_RESERVED_ROWS = 7;
const TAB_BAR_RESERVED_ROWS = 2;
const PROVIDER_SCROLL_INDICATOR_ROWS = 1;
-/**
- * Component that renders an auth provider selector
- */
export class OAuthSelectorComponent extends Container implements Focusable {
private searchInput: MenuSearchInput;
- // Focusable implementation - propagate to search input for IME cursor positioning
+ // Delegate focus to the search input so its IME cursor remains positioned correctly.
private _focused = false;
get focused(): boolean {
return this._focused;
@@ -146,11 +143,9 @@ export class OAuthSelectorComponent extends Container implements Focusable {
panel.addChild(this.searchInput);
panel.addChild(new Spacer(1));
- // Create list container
this.listContainer = new MenuList({ compact: () => this.listLayout.compact });
panel.addChild(this.listContainer);
- // Initial render
this.filterProviders("");
}
@@ -312,7 +307,6 @@ export class OAuthSelectorComponent extends Container implements Focusable {
this.listContainer.addChild(new TruncatedText(scrollInfo, 1, 0));
}
- // Show "no providers" if empty
if (this.filteredProviders.length === 0) {
const message =
this.allProviders.length === 0
@@ -368,14 +362,11 @@ export class OAuthSelectorComponent extends Container implements Focusable {
handleInput(keyData: string): void {
const kb = getKeybindings();
- // Up arrow
if (kb.matches(keyData, "tui.select.up")) {
if (this.filteredProviders.length === 0) return;
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
this.updateList();
- }
- // Down arrow
- else if (kb.matches(keyData, "tui.select.down")) {
+ } else if (kb.matches(keyData, "tui.select.down")) {
if (this.filteredProviders.length === 0) return;
this.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1);
this.updateList();
@@ -394,20 +385,14 @@ export class OAuthSelectorComponent extends Container implements Focusable {
kb.matches(keyData, "tui.editor.cursorRight")
) {
this.switchCategory(1);
- }
- // Enter
- else if (kb.matches(keyData, "tui.select.confirm")) {
+ } else if (kb.matches(keyData, "tui.select.confirm")) {
const selectedProvider = this.filteredProviders[this.selectedIndex];
if (selectedProvider) {
this.onSelectCallback(selectedProvider);
}
- }
- // Escape or Ctrl+C
- else if (kb.matches(keyData, "tui.select.cancel")) {
+ } else if (kb.matches(keyData, "tui.select.cancel")) {
this.onCancelCallback();
- }
- // Pass everything else to search input
- else {
+ } else {
this.searchInput.handleInput(keyData);
this.filterProviders(this.searchInput.getValue());
}
diff --git a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
index 193d473258..0a08f669ab 100644
--- a/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/scoped-models-selector.ts
@@ -14,7 +14,6 @@ import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
import { keyText } from "./keybinding-hints.js";
-// EnabledIds: null = all enabled (no filter), string[] = explicit ordered list
type EnabledIds = string[] | null;
function isEnabled(enabledIds: EnabledIds, id: string): boolean {
@@ -83,10 +82,6 @@ export interface ModelsCallbacks {
onCancel: () => void;
}
-/**
- * Component for enabling/disabling models for Ctrl+P cycling.
- * Changes are session-only until explicitly persisted with Ctrl+S.
- */
export class ScopedModelsSelectorComponent extends Container implements Focusable {
private modelsById: Map<string, Model<any>> = new Map();
private allIds: string[] = [];
@@ -96,7 +91,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
private searchQuery = "";
private searchInput: Input;
- // Focusable implementation - propagate to searchInput for IME cursor positioning
private _focused = false;
get focused(): boolean {
return this._focused;
@@ -124,7 +118,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
this.enabledIds = config.enabledModelIds === null ? null : [...config.enabledModelIds];
this.filteredItems = this.buildItems();
- // Header
this.addChild(new DynamicBorder());
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("accent", theme.bold("Model Configuration")), 0, 0));
@@ -133,16 +126,13 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
);
this.addChild(new Spacer(1));
- // Search input
this.searchInput = new Input();
this.addChild(this.searchInput);
this.addChild(new Spacer(1));
- // List container
this.listContainer = new Container();
this.addChild(this.listContainer);
- // Footer hint
this.addChild(new Spacer(1));
this.footerText = new Text(this.getFooterText(), 0, 0);
this.addChild(this.footerText);
@@ -220,7 +210,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
this.listContainer.addChild(new Text(`${prefix}${modelText}${providerBadge}${status}`, 0, 0));
}
- // Add scroll indicator if needed
if (startIndex > 0 || endIndex < this.filteredItems.length) {
this.listContainer.addChild(
new Text(theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredItems.length})`), 0, 0),
@@ -237,7 +226,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
handleInput(data: string): void {
const kb = getKeybindings();
- // Navigation
if (kb.matches(data, "tui.select.up")) {
if (this.filteredItems.length === 0) return;
this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
@@ -251,7 +239,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Reorder enabled models
const reorderUp = kb.matches(data, "app.models.reorderUp");
const reorderDown = kb.matches(data, "app.models.reorderDown");
if (reorderUp || reorderDown) {
@@ -261,7 +248,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
const delta = reorderUp ? -1 : 1;
const currentIndex = this.enabledIds.indexOf(item.fullId);
const newIndex = currentIndex + delta;
- // Only move if within bounds
if (newIndex >= 0 && newIndex < this.enabledIds.length) {
this.enabledIds = move(this.enabledIds, item.fullId, delta);
this.isDirty = true;
@@ -273,7 +259,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Toggle on Enter
if (kb.matches(data, "tui.select.confirm")) {
const item = this.filteredItems[this.selectedIndex];
if (item) {
@@ -285,7 +270,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Enable all (filtered if search active, otherwise all)
if (kb.matches(data, "app.models.enableAll")) {
const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;
this.enabledIds = enableAll(this.enabledIds, this.allIds, targetIds);
@@ -295,7 +279,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Clear all (filtered if search active, otherwise all)
if (kb.matches(data, "app.models.clearAll")) {
const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;
this.enabledIds = clearAll(this.enabledIds, this.allIds, targetIds);
@@ -305,7 +288,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Toggle provider of current item
if (kb.matches(data, "app.models.toggleProvider")) {
const item = this.filteredItems[this.selectedIndex];
if (item) {
@@ -322,7 +304,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Save/persist to settings
if (kb.matches(data, "app.models.save")) {
this.callbacks.onPersist(this.enabledIds === null ? null : [...this.enabledIds]);
this.isDirty = false;
@@ -330,7 +311,6 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Ctrl+C - clear search or cancel if empty
if (matchesKey(data, Key.ctrl("c"))) {
if (this.searchInput.getValue()) {
this.searchInput.setValue("");
@@ -341,13 +321,11 @@ export class ScopedModelsSelectorComponent extends Container implements Focusabl
return;
}
- // Escape - cancel
if (matchesKey(data, Key.escape)) {
this.callbacks.onCancel();
return;
}
- // Pass everything else to search input
this.searchInput.handleInput(data);
this.refresh();
}
diff --git a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
index 3805cc4228..786b834996 100644
--- a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts
@@ -84,9 +84,6 @@ export interface SettingsCallbacks {
onCancel: () => void;
}
-/**
- * A submenu component for selecting from a list of options.
- */
class WarningSettingsSubmenu extends Container {
private settingsList: SettingsList;
private state: WarningSettings;
@@ -143,19 +140,15 @@ class SelectSubmenu extends Container {
) {
super();
- // Title
this.addChild(new Text(theme.bold(theme.fg("accent", title)), 0, 0));
- // Description
if (description) {
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("muted", description), 0, 0));
}
- // Spacer
this.addChild(new Spacer(1));
- // Select list
this.selectList = new SelectList(
options,
Math.min(options.length, 10),
@@ -163,7 +156,6 @@ class SelectSubmenu extends Container {
SETTINGS_SUBMENU_SELECT_LIST_LAYOUT,
);
- // Pre-select current value
const currentIndex = options.findIndex((o) => o.value === currentValue);
if (currentIndex !== -1) {
this.selectList.setSelectedIndex(currentIndex);
@@ -183,7 +175,6 @@ class SelectSubmenu extends Container {
this.addChild(this.selectList);
- // Hint
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("dim", " Enter to select · esc to go back"), 0, 0));
}
@@ -193,9 +184,6 @@ class SelectSubmenu extends Container {
}
}
-/**
- * Main settings selector component.
- */
export class SettingsSelectorComponent extends Container {
private settingsList: SettingsList;
@@ -443,7 +431,6 @@ export class SettingsSelectorComponent extends Container {
values: ["true", "false"],
});
- // Add borders
this.addChild(new DynamicBorder());
this.settingsList = new SettingsList(
diff --git a/packages/coding-agent/src/modes/interactive/components/show-images-selector.ts b/packages/coding-agent/src/modes/interactive/components/show-images-selector.ts
index 7e37cb7124..f7c1c03358 100644
--- a/packages/coding-agent/src/modes/interactive/components/show-images-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/show-images-selector.ts
@@ -7,9 +7,6 @@ const SHOW_IMAGES_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
maxPrimaryColumnWidth: 32,
};
-/**
- * Component that renders a show images selector with borders
- */
export class ShowImagesSelectorComponent extends Container {
private selectList: SelectList;
@@ -21,13 +18,10 @@ export class ShowImagesSelectorComponent extends Container {
{ value: "no", label: "No", description: "Show text placeholder instead" },
];
- // Add top border
this.addChild(new DynamicBorder());
- // Create selector
this.selectList = new SelectList(items, 5, getSelectListTheme(), SHOW_IMAGES_SELECT_LIST_LAYOUT);
- // Preselect current value
this.selectList.setSelectedIndex(currentValue ? 0 : 1);
this.selectList.onSelect = (item) => {
@@ -40,7 +34,6 @@ export class ShowImagesSelectorComponent extends Container {
this.addChild(this.selectList);
- // Add bottom border
this.addChild(new DynamicBorder());
}
diff --git a/packages/coding-agent/src/modes/interactive/components/theme-selector.ts b/packages/coding-agent/src/modes/interactive/components/theme-selector.ts
index 29e6e77919..6b5fcedd1b 100644
--- a/packages/coding-agent/src/modes/interactive/components/theme-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/theme-selector.ts
@@ -7,9 +7,6 @@ const THEME_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
maxPrimaryColumnWidth: 32,
};
-/**
- * Component that renders a theme selector
- */
export class ThemeSelectorComponent extends Container {
private selectList: SelectList;
private onPreview: (themeName: string) => void;
@@ -23,7 +20,6 @@ export class ThemeSelectorComponent extends Container {
super();
this.onPreview = onPreview;
- // Get available themes and create select items
const themes = getAvailableThemes();
const themeItems: SelectItem[] = themes.map((name) => ({
value: name,
@@ -31,13 +27,10 @@ export class ThemeSelectorComponent extends Container {
description: name === currentTheme ? "(current)" : undefined,
}));
- // Add top border
this.addChild(new DynamicBorder());
- // Create selector
this.selectList = new SelectList(themeItems, 10, getSelectListTheme(), THEME_SELECT_LIST_LAYOUT);
- // Preselect current theme
const currentIndex = themes.indexOf(currentTheme);
if (currentIndex !== -1) {
this.selectList.setSelectedIndex(currentIndex);
@@ -57,7 +50,6 @@ export class ThemeSelectorComponent extends Container {
this.addChild(this.selectList);
- // Add bottom border
this.addChild(new DynamicBorder());
}
diff --git a/packages/coding-agent/src/modes/interactive/components/thinking-selector.ts b/packages/coding-agent/src/modes/interactive/components/thinking-selector.ts
index 05ccdd55d3..bcc5701011 100644
--- a/packages/coding-agent/src/modes/interactive/components/thinking-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/thinking-selector.ts
@@ -18,9 +18,6 @@ const LEVEL_DESCRIPTIONS: Record<ThinkingLevel, string> = {
max: "Maximum reasoning",
};
-/**
- * Component that renders a thinking level selector with borders
- */
export class ThinkingSelectorComponent extends Container {
private selectList: SelectList;
@@ -38,10 +35,8 @@ export class ThinkingSelectorComponent extends Container {
description: LEVEL_DESCRIPTIONS[level],
}));
- // Add top border
this.addChild(new DynamicBorder());
- // Create selector
this.selectList = new SelectList(
thinkingLevels,
thinkingLevels.length,
@@ -49,7 +44,6 @@ export class ThinkingSelectorComponent extends Container {
THINKING_SELECT_LIST_LAYOUT,
);
- // Preselect current level
const currentIndex = thinkingLevels.findIndex((item) => item.value === currentLevel);
if (currentIndex !== -1) {
this.selectList.setSelectedIndex(currentIndex);
@@ -65,7 +59,6 @@ export class ThinkingSelectorComponent extends Container {
this.addChild(this.selectList);
- // Add bottom border
this.addChild(new DynamicBorder());
}
diff --git a/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts b/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
index 6cf4223ab0..7dae13e12f 100644
--- a/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/user-message-selector.ts
@@ -3,32 +3,26 @@ import { theme } from "../theme/theme.js";
import { DynamicBorder } from "./dynamic-border.js";
interface UserMessageItem {
- id: string; // Entry ID in the session
- text: string; // The message text
- timestamp?: string; // Optional timestamp if available
+ id: string;
+ text: string;
+ timestamp?: string;
}
-/**
- * Custom user message list component with selection
- */
class UserMessageList implements Component {
private messages: UserMessageItem[] = [];
private selectedIndex: number = 0;
public onSelect?: (entryId: string) => void;
public onCancel?: () => void;
- private maxVisible: number = 10; // Max messages visible
+ private maxVisible: number = 10;
constructor(messages: UserMessageItem[], initialSelectedId?: string) {
- // Store messages in chronological order (oldest to newest)
+ // Session history is chronological; default to the latest fork point.
this.messages = messages;
const initialIndex = initialSelectedId ? messages.findIndex((message) => message.id === initialSelectedId) : -1;
- // Start with selected message if provided, else default to the most recent
this.selectedIndex = initialIndex >= 0 ? initialIndex : Math.max(0, messages.length - 1);
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(width: number): string[] {
const lines: string[] = [];
@@ -38,38 +32,32 @@ class UserMessageList implements Component {
return lines;
}
- // Calculate visible range with scrolling
const startIndex = Math.max(
0,
Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),
);
const endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);
- // Render visible messages (2 lines per message + blank line)
for (let i = startIndex; i < endIndex; i++) {
const message = this.messages[i];
const isSelected = i === this.selectedIndex;
- // Normalize message to single line
const normalizedMessage = message.text.replace(/\n/g, " ").trim();
- // First line: cursor + message
const cursor = isSelected ? theme.fg("accent", "› ") : " ";
- const maxMsgWidth = width - 2; // Account for cursor (2 chars)
+ const maxMsgWidth = width - 2;
const truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);
const messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);
lines.push(messageLine);
- // Second line: metadata (position in history)
const position = i + 1;
const metadata = ` Message ${position} of ${this.messages.length}`;
const metadataLine = theme.fg("muted", metadata);
lines.push(metadataLine);
- lines.push(""); // Blank line between messages
+ lines.push("");
}
- // Add scroll indicator if needed
if (startIndex > 0 || endIndex < this.messages.length) {
const scrollInfo = theme.fg("muted", ` (${this.selectedIndex + 1}/${this.messages.length})`);
lines.push(scrollInfo);
@@ -80,23 +68,16 @@ class UserMessageList implements Component {
handleInput(keyData: string): void {
const kb = getKeybindings();
- // Up arrow - go to previous (older) message, wrap to bottom when at top
if (kb.matches(keyData, "tui.select.up")) {
this.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;
- }
- // Down arrow - go to next (newer) message, wrap to top when at bottom
- else if (kb.matches(keyData, "tui.select.down")) {
+ } else if (kb.matches(keyData, "tui.select.down")) {
this.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;
- }
- // Enter - select message and branch
- else if (kb.matches(keyData, "tui.select.confirm")) {
+ } else if (kb.matches(keyData, "tui.select.confirm")) {
const selected = this.messages[this.selectedIndex];
if (selected && this.onSelect) {
this.onSelect(selected.id);
}
- }
- // Escape - cancel
- else if (kb.matches(keyData, "tui.select.cancel")) {
+ } else if (kb.matches(keyData, "tui.select.cancel")) {
if (this.onCancel) {
this.onCancel();
}
@@ -104,9 +85,6 @@ class UserMessageList implements Component {
}
}
-/**
- * Component that renders a user message selector for branching
- */
export class UserMessageSelectorComponent extends Container {
private messageList: UserMessageList;
@@ -118,7 +96,6 @@ export class UserMessageSelectorComponent extends Container {
) {
super();
- // Add header
this.addChild(new Spacer(1));
this.addChild(new Text(theme.bold("Fork from Message"), 1, 0));
this.addChild(
@@ -132,18 +109,15 @@ export class UserMessageSelectorComponent extends Container {
this.addChild(new DynamicBorder());
this.addChild(new Spacer(1));
- // Create message list
this.messageList = new UserMessageList(messages, initialSelectedId);
this.messageList.onSelect = onSelect;
this.messageList.onCancel = onCancel;
this.addChild(this.messageList);
- // Add bottom border
this.addChild(new Spacer(1));
this.addChild(new DynamicBorder());
- // Auto-cancel if no messages
if (messages.length === 0) {
setTimeout(() => onCancel(), 100);
}
diff --git a/packages/coding-agent/src/modes/interactive/components/user-message.ts b/packages/coding-agent/src/modes/interactive/components/user-message.ts
index 2674f52b31..58b8766378 100644
--- a/packages/coding-agent/src/modes/interactive/components/user-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/user-message.ts
@@ -53,9 +53,6 @@ class SlashCommandMarkdown implements Component {
}
}
-/**
- * Component that renders a user message
- */
export class UserMessageComponent extends Container {
private contentBox: Box;
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index e1321507a0..02c64a8d4d 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -1,8 +1,3 @@
-/**
- * Interactive mode for the coding agent.
- * Handles TUI rendering and user interaction, delegating agent execution to AgentConnection.
- */
-
import { randomUUID } from "node:crypto";
import * as fs from "node:fs";
import * as os from "node:os";
@@ -266,7 +261,6 @@ import {
} from "./theme/theme.js";
import { setWorkingPulseFrame, WORKING_ICON_INTERVAL_MS } from "./theme/working-icon.js";
-/** Interface for components that can be expanded/collapsed */
interface Expandable {
setExpanded(expanded: boolean): void;
}
@@ -771,9 +765,6 @@ export function resolveInteractiveUpdateDaemonSocketPath(
return socketFlagIndex === -1 ? activeDaemonSocketPath : (args[socketFlagIndex + 1] ?? activeDaemonSocketPath);
}
-/**
- * Options for InteractiveMode initialization.
- */
export interface InteractiveInitialPrompt {
text: string;
images?: ImageContent[];
@@ -923,13 +914,11 @@ export class InteractiveMode {
private escapeRepeatTimer: ReturnType<typeof setTimeout> | undefined = undefined;
private anthropicSubscriptionWarningShown = false;
- // Status line tracking (for mutating immediately-sequential status updates)
private lastStatusSpacer: Spacer | undefined = undefined;
private lastStatusText: Text | undefined = undefined;
private lastGoalAnnouncement: GoalAnnouncementSnapshot | undefined = undefined;
private goalTrayTimer: NodeJS.Timeout | undefined = undefined;
- // Streaming message tracking
private streamingComponent: AssistantMessageComponent | undefined = undefined;
private streamingMessage: AssistantMessage | undefined = undefined;
private sideQuestionComponent: SideQuestionComponent | undefined;
@@ -958,7 +947,6 @@ export class InteractiveMode {
private sessionEventGeneration = 0;
private fastModeToggleQueue: Promise<void> = Promise.resolve();
- // Tool execution tracking: toolCallId -> component
private pendingTools = new Map<string, ToolExecutionComponent>();
private ipythonToolComponents = new Map<string, ToolExecutionComponent>();
private lateIpythonSentAgentMessages = new Map<string, KernelSentAgentMessage[]>();
@@ -973,15 +961,12 @@ export class InteractiveMode {
private subagentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();
private rlmNodeId: string | undefined;
- // Tool output expansion state
private toolOutputExpanded = false;
private agentMessagesExpanded = false;
private editDiffsExpanded = false;
- // Thinking block visibility state
private hideThinkingBlock = false;
- // Skill commands: command name -> skill file path
private skillCommands = new Map<string, string>();
private connectionCommands: AgentConnectionSlashCommand[] = [];
private connectionModels: AgentConnectionModel[] = [];
@@ -1009,14 +994,11 @@ export class InteractiveMode {
private pastedImages = new Map<number, ImageContent>();
private nextImageMarkerId = 1;
- // Agent subscription unsubscribe function
private unsubscribe?: () => void;
private signalCleanupHandlers: Array<() => void> = [];
- // Auto-compaction state
private autoCompactionLoader: Loader | undefined = undefined;
- // Auto-retry state
private retryLoader: Loader | undefined = undefined;
private retryCountdown: CountdownTimer | undefined = undefined;
private traceUploadAllAbortController: AbortController | undefined = undefined;
@@ -1028,17 +1010,14 @@ export class InteractiveMode {
private queueMutationChain: Promise<void> = Promise.resolve();
private pendingQueueEdit: symbol | undefined;
- // Shutdown state
private shutdownRequested = false;
- // Extension UI state
private extensionSelector: ExtensionSelectorComponent | undefined = undefined;
private extensionInput: ExtensionInputComponent | undefined = undefined;
private extensionEditor: ExtensionEditorComponent | undefined = undefined;
private extensionTerminalInputUnsubscribers = new Set<() => void>();
private activeConnectionExtensionUiRequests = new Map<string, { cancelLocal: () => void }>();
- // Extension widgets (components rendered above/below the editor)
private extensionWidgetsAbove = new Map<string, Component & { dispose?(): void }>();
private extensionWidgetsBelow = new Map<string, Component & { dispose?(): void }>();
private widgetContainerAbove!: Container;
@@ -1048,16 +1027,12 @@ export class InteractiveMode {
private recapContainer!: Container;
private sessionRecap: string | undefined;
- // Custom footer from extension (undefined = use built-in footer)
private customFooter: (Component & { dispose?(): void }) | undefined = undefined;
- // Header container that holds the built-in or custom header
private headerContainer: Container;
- // Built-in header (logo + keybinding hints)
private builtInHeader: Component | undefined = undefined;
- // Custom header from extension (undefined = use built-in header)
private customHeader: (Component & { dispose?(): void }) | undefined = undefined;
private getLocalSessionHost(): InteractiveModeLocalSessionHost {
@@ -1149,10 +1124,8 @@ export class InteractiveMode {
this.footer.setAutoCompactEnabled(this.settingsManager.getCompactionEnabled());
this.setGoalAnnouncementBaseline(emptyGoalState());
- // Load hide thinking block setting
this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
- // Register themes from resource loader and initialize
setRegisteredThemes(this.uiServices.getThemes());
initTheme(this.settingsManager.getTheme(), true);
}
@@ -1280,7 +1253,6 @@ export class InteractiveMode {
}
private createBaseAutocompleteProvider(): AutocompleteProvider {
- // Define commands for autocomplete
const slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.filter(
(command) => command.name !== "fast" || this.currentModelSupportsFastMode(),
).map((command) => ({
@@ -1323,7 +1295,6 @@ export class InteractiveMode {
...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),
}));
- // Convert extension commands to SlashCommand format
const extensionCommands: SlashCommand[] = connectionCommands
.filter((cmd) => cmd.source === "extension")
.filter((cmd) => !isBuiltinSlashCommandName(cmd.name))
@@ -1336,7 +1307,6 @@ export class InteractiveMode {
: undefined,
}));
- // Build skill commands from session.skills (if enabled)
this.skillCommands.clear();
const skillCommandList: SlashCommand[] = [];
if (this.settingsManager.getEnableSkillCommands()) {
@@ -1383,7 +1353,6 @@ export class InteractiveMode {
this.showWarning(formatMissingRipgrepMessage(rgResult));
}
- // Add header container as first child
this.ui.addChild(this.headerContainer);
// Brand splash: side-panel layout with structured runtime metadata on the right.
@@ -1457,7 +1426,6 @@ export class InteractiveMode {
this.setupKeyHandlers();
this.setupEditorSubmitHandler();
- // Start the UI before initializing extensions so session_start handlers can use interactive dialogs
this.ui.start();
this.fullscreenEnabled =
(this.options.forceFullscreen === true || this.settingsManager.getFullscreen()) &&
@@ -1467,31 +1435,23 @@ export class InteractiveMode {
}
this.isInitialized = true;
- // Initialize extensions first so resources are shown before messages
await this.rebindCurrentSession();
- // Render initial messages AFTER showing loaded resources
await this.renderInitialMessages();
- // Set up theme file watcher
onThemeChange(() => {
this.ui.invalidate();
this.updateEditorBorderColor();
this.ui.requestRender();
});
- // Set up git branch watcher (uses provider instead of footer)
this.footerDataProvider.onBranchChange(() => {
this.ui.requestRender();
});
- // Initialize available provider count for footer display
await this.updateAvailableProviderCount();
}
- /**
- * Update terminal title with session name and cwd.
- */
private updateTerminalTitle(): void {
const cwdBasename = path.basename(this.getCurrentCwd());
const sessionName = this.getCurrentSessionName();
@@ -1502,10 +1462,6 @@ export class InteractiveMode {
}
}
- /**
- * Run the interactive mode. This is the main entry point.
- * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.
- */
async run(): Promise<InteractiveModeRunResult> {
await this.init();
@@ -1525,7 +1481,6 @@ export class InteractiveMode {
: undefined;
const tmuxKeyboardWarningPromise = ownsGlobalStartupNotices ? checkTmuxKeyboardSetup() : undefined;
- // Show startup warnings
const {
migratedProviders,
modelFallbackMessage,
@@ -1832,10 +1787,6 @@ export class InteractiveMode {
};
}
- // =========================================================================
- // Extension System
- // =========================================================================
-
private formatDisplayPath(p: string): string {
const home = os.homedir();
let result = p;
@@ -1869,9 +1820,6 @@ export class InteractiveMode {
return this.options.verbose || this.toolOutputExpanded;
}
- /**
- * Get a short path relative to the package root for display.
- */
private getShortPath(fullPath: string, sourceInfo?: AgentConnectionSourceInfo): string {
const baseDir = sourceInfo?.baseDir;
if (baseDir && this.isPackageSource(sourceInfo)) {
@@ -3110,14 +3058,10 @@ export class InteractiveMode {
);
}
- /**
- * Set up keyboard shortcuts registered by extensions.
- */
private setupExtensionShortcuts(extensionRunner: ExtensionRunner): void {
const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
if (shortcuts.size === 0) return;
- // Create a context for shortcut handlers
const localSessionHost = this.getLocalSessionHost();
const createContext = (): ExtensionContext => ({
ui: this.createExtensionUIContext(),
@@ -3148,12 +3092,9 @@ export class InteractiveMode {
getSystemPrompt: () => localSessionHost.getSystemPrompt(),
});
- // Set up the extension shortcut handler on the default editor
this.defaultEditor.onExtensionShortcut = (data: string) => {
for (const [shortcutStr, shortcut] of shortcuts) {
- // Cast to KeyId - extension shortcuts use the same format
if (matchesKey(data, shortcutStr as KeyId)) {
- // Run handler async, don't block input
Promise.resolve(shortcut.handler(createContext())).catch((err) => {
this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);
});
@@ -3164,9 +3105,6 @@ export class InteractiveMode {
};
}
- /**
- * Set extension status text in the footer.
- */
private setExtensionStatus(key: string, text: string | undefined): void {
this.footerDataProvider.setExtensionStatus(key, text);
this.ui.requestRender();
@@ -3492,9 +3430,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Set an extension widget (string array or custom component).
- */
private setExtensionWidget(
key: string,
content: string[] | ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined,
@@ -3518,7 +3453,6 @@ export class InteractiveMode {
let component: Component & { dispose?(): void };
if (Array.isArray(content)) {
- // Wrap string array in a Container with Text components
const container = new Container();
for (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {
container.addChild(new Text(line, 1, 0));
@@ -3528,7 +3462,6 @@ export class InteractiveMode {
}
component = container;
} else {
- // Factory function - create component
component = content(this.ui, theme);
}
@@ -3582,12 +3515,8 @@ export class InteractiveMode {
this.setHiddenThinkingLabel();
}
- // Maximum total widget lines to prevent viewport overflow
private static readonly MAX_WIDGET_LINES = 10;
- /**
- * Render all extension widgets to the widget container.
- */
private renderWidgets(): void {
if (!this.widgetContainerAbove || !this.widgetContainerBelow) return;
this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);
@@ -3637,15 +3566,11 @@ export class InteractiveMode {
}
}
- /**
- * Set a custom footer component, or restore the built-in footer.
- */
private setExtensionFooter(
factory:
| ((tui: TUI, thm: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })
| undefined,
): void {
- // Dispose existing custom footer
if (this.customFooter?.dispose) {
this.customFooter.dispose();
}
@@ -3667,16 +3592,12 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Set a custom header component, or restore the built-in header.
- */
private setExtensionHeader(factory: ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined): void {
// Header may not be initialized yet if called during early initialization
if (!this.builtInHeader) {
return;
}
- // Dispose existing custom header
if (this.customHeader?.dispose) {
this.customHeader.dispose();
}
@@ -3686,7 +3607,6 @@ export class InteractiveMode {
const index = this.headerContainer.children.indexOf(currentHeader);
if (factory) {
- // Create and add custom header
this.customHeader = factory(this.ui, theme);
if (isExpandable(this.customHeader)) {
this.customHeader.setExpanded(this.toolOutputExpanded);
@@ -3698,7 +3618,6 @@ export class InteractiveMode {
this.headerContainer.children.unshift(this.customHeader);
}
} else {
- // Restore built-in header
this.customHeader = undefined;
if (isExpandable(this.builtInHeader)) {
this.builtInHeader.setExpanded(this.toolOutputExpanded);
@@ -3729,9 +3648,6 @@ export class InteractiveMode {
this.extensionTerminalInputUnsubscribers.clear();
}
- /**
- * Create the ExtensionUIContext for extensions.
- */
private createExtensionUIContext(): ExtensionUIContext {
return {
select: (title, options, opts) => this.showExtensionSelector(title, options, opts),
@@ -3789,9 +3705,6 @@ export class InteractiveMode {
};
}
- /**
- * Show a selector for extensions.
- */
private showExtensionSelector(
title: string,
options: string[],
@@ -3832,9 +3745,6 @@ export class InteractiveMode {
});
}
- /**
- * Hide the extension selector.
- */
private hideExtensionSelector(): void {
this.extensionSelector?.dispose();
this.editorContainer.clear();
@@ -3844,9 +3754,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Show a confirmation dialog for extensions.
- */
private async showExtensionConfirm(
title: string,
message: string,
@@ -3864,9 +3771,6 @@ export class InteractiveMode {
return confirmed ? error.issue.fallbackCwd : undefined;
}
- /**
- * Show a text input for extensions.
- */
private showExtensionInput(
title: string,
placeholder?: string,
@@ -3907,9 +3811,6 @@ export class InteractiveMode {
});
}
- /**
- * Hide the extension input.
- */
private hideExtensionInput(): void {
this.extensionInput?.dispose();
this.editorContainer.clear();
@@ -3919,9 +3820,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Show a multi-line editor for extensions (with Ctrl+G support).
- */
private showExtensionEditor(title: string, prefill?: string): Promise<string | undefined> {
return new Promise((resolve) => {
this.extensionEditor = new ExtensionEditorComponent(
@@ -3946,9 +3844,6 @@ export class InteractiveMode {
});
}
- /**
- * Hide the extension editor.
- */
private hideExtensionEditor(): void {
this.editorContainer.clear();
this.editorContainer.addChild(this.editor);
@@ -3957,10 +3852,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Set a custom editor component from an extension.
- * Pass undefined to restore the default editor.
- */
private setCustomEditorComponent(factory: EditorFactory | undefined): void {
this.editorComponentFactory = factory;
// Snapshot the current editor before replacing it. Paste markers are only
@@ -4057,9 +3948,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Show a notification for extensions.
- */
private showExtensionNotify(message: string, type?: "info" | "warning" | "error"): void {
if (type === "error") {
this.showError(message);
@@ -4170,10 +4058,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- // =========================================================================
- // Key Handlers
- // =========================================================================
-
private setupKeyHandlers(): void {
this.defaultEditor.getHeaderLine = () => this.getQueueSelectionHeader();
// Set up handlers on defaultEditor - they use this.editor for text access
@@ -4182,7 +4066,6 @@ export class InteractiveMode {
this.handleEscape();
};
- // Register app action handlers
this.defaultEditor.onAction("app.clear", () => this.handleCtrlC());
this.defaultEditor.onAction("app.interrupt", () => this.handleInterruptKey());
this.defaultEditor.onAction("app.shortcuts", () => this.showShortcutGuide());
@@ -4234,7 +4117,6 @@ export class InteractiveMode {
}
};
- // Handle clipboard image paste (triggered on Ctrl+V)
this.defaultEditor.onPasteImage = () => {
this.handleClipboardImagePaste();
};
@@ -4696,7 +4578,6 @@ export class InteractiveMode {
}).catch(() => {});
}
- // Handle commands
if (commandName === "btw") {
this.editor.setText("");
await this.handleSideQuestion(commandArgs);
@@ -5686,7 +5567,6 @@ export class InteractiveMode {
}
case "auto_retry_start": {
- // Show retry indicator
this.stopWorkingLoader();
this.statusContainer.clear();
this.retryCountdown?.dispose();
@@ -5718,7 +5598,6 @@ export class InteractiveMode {
this.retryCountdown.dispose();
this.retryCountdown = undefined;
}
- // Stop loader
if (this.retryLoader) {
this.retryLoader.stop();
this.retryLoader = undefined;
@@ -6158,7 +6037,6 @@ export class InteractiveMode {
return `${hours}h ${remainingMinutes.toString().padStart(2, "0")}m`;
}
- /** Extract text content from a user message */
private getUserMessageText(message: Message): string {
if (message.role !== "user") return "";
const textBlocks =
@@ -6377,14 +6255,12 @@ export class InteractiveMode {
}
const skillBlock = parseSkillBlock(textContent);
if (skillBlock) {
- // Render skill block (collapsible)
const component = new SkillInvocationMessageComponent(
skillBlock,
this.getMarkdownThemeWithSettings(),
);
component.setExpanded(this.toolOutputExpanded);
this.chatContainer.addChild(component);
- // Render user message separately if present
if (skillBlock.userMessage) {
const userComponent = new UserMessageComponent(
skillBlock.userMessage,
@@ -6424,7 +6300,6 @@ export class InteractiveMode {
break;
}
case "toolResult": {
- // Tool results are rendered inline with tool calls, handled separately
break;
}
default: {
@@ -6652,10 +6527,6 @@ export class InteractiveMode {
await this.renderSessionContext(context, { clearChat: true });
}
- // =========================================================================
- // Key handlers
- // =========================================================================
-
private handleEscape(): void {
this.clearCtrlCExitHint();
if (this.sideQuestionEvent) {
@@ -6783,7 +6654,6 @@ export class InteractiveMode {
}
private handleCtrlD(): void {
- // Only called when editor is empty (enforced by CustomEditor)
void this.shutdown();
}
@@ -7407,10 +7277,6 @@ export class InteractiveMode {
}
}
- // =========================================================================
- // UI helpers
- // =========================================================================
-
private clearInputBar(): void {
this.clearEscapeRepeat();
this.clearCtrlCExitHint({ render: false });
@@ -7442,7 +7308,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /** Get all queued messages from the session-owned connection queue. */
private getAllQueuedMessages(): { steering: string[]; followUp: string[] } {
return {
steering: [...this.connectionQueue.steering],
@@ -7486,7 +7351,6 @@ export class InteractiveMode {
}
}
- /** Move pending bash components from pending area to chat */
private flushPendingBashComponents(): void {
for (const component of this.pendingBashComponents) {
this.pendingMessagesContainer.removeChild(component);
@@ -7495,10 +7359,6 @@ export class InteractiveMode {
this.pendingBashComponents = [];
}
- // =========================================================================
- // Selectors
- // =========================================================================
-
/**
* Shows a selector component in place of the editor.
* @param create Factory that receives a `done` callback and returns the component and focus target
@@ -7915,7 +7775,6 @@ export class InteractiveMode {
return scopedModels;
}
- /** Update the footer's available provider count from current model candidates */
private async updateAvailableProviderCount(): Promise<void> {
const models = await this.getModelCandidates();
const uniqueProviders = new Set(models.map((m) => m.provider));
@@ -8728,10 +8587,6 @@ export class InteractiveMode {
}
}
- // =========================================================================
- // Command handlers
- // =========================================================================
-
private async handleUpdateCommand(args: string): Promise<void> {
const entrypoint = process.argv[1];
if (!entrypoint) {
@@ -9724,9 +9579,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Capitalize keybinding for display (e.g., "ctrl+c" -> "Ctrl+C").
- */
private capitalizeKey(key: string): string {
return key
.split("/")
@@ -9739,16 +9591,10 @@ export class InteractiveMode {
.join("/");
}
- /**
- * Get capitalized display string for an app keybinding action.
- */
private getAppKeyDisplay(action: AppKeybinding): string {
return this.capitalizeKey(keyText(action));
}
- /**
- * Get capitalized display string for an editor keybinding action.
- */
private getEditorKeyDisplay(action: Keybinding): string {
return this.capitalizeKey(keyText(action));
}
diff --git a/packages/coding-agent/src/modes/interactive/resume-hint.ts b/packages/coding-agent/src/modes/interactive/resume-hint.ts
index d6082e8340..a3918fdda1 100644
--- a/packages/coding-agent/src/modes/interactive/resume-hint.ts
+++ b/packages/coding-agent/src/modes/interactive/resume-hint.ts
@@ -1,7 +1,3 @@
-/**
- * Post-exit hint telling the user how to resume the session they just left.
- */
-
import { existsSync } from "node:fs";
import chalk from "chalk";
import { APP_NAME } from "../../config.js";
@@ -9,13 +5,7 @@ import type { SessionStats } from "../../core/session-stats.js";
export type ResumeHintStats = Pick<SessionStats, "sessionId" | "sessionFile" | "userMessages">;
-/**
- * Format the resume hint printed to stdout after the TUI exits.
- *
- * Returns undefined when there is nothing to resume: ephemeral sessions
- * (--no-session) have no session file, and sessions without any user
- * messages may never have been flushed to disk.
- */
+/** Omit ephemeral and unflushed empty sessions because neither can be resumed. */
export function formatResumeHint(stats: ResumeHintStats | undefined): string | undefined {
if (!stats?.sessionFile || stats.userMessages === 0) return undefined;
// Persistence is lazy: nothing is written until the first assistant message
diff --git a/packages/coding-agent/src/utils/clipboard-image.ts b/packages/coding-agent/src/utils/clipboard-image.ts
index 4cf44908f8..653bf8cb5f 100644
--- a/packages/coding-agent/src/utils/clipboard-image.ts
+++ b/packages/coding-agent/src/utils/clipboard-image.ts
@@ -27,21 +27,6 @@ function baseMimeType(mimeType: string): string {
return mimeType.split(";")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();
}
-export function extensionForImageMimeType(mimeType: string): string | null {
- switch (baseMimeType(mimeType)) {
- case "image/png":
- return "png";
- case "image/jpeg":
- return "jpg";
- case "image/webp":
- return "webp";
- case "image/gif":
- return "gif";
- default:
- return null;
- }
-}
-
function selectPreferredImageMimeType(mimeTypes: string[]): string | null {
const normalized = mimeTypes
.map((t) => t.trim())
diff --git a/packages/coding-agent/test/acp-events.test.ts b/packages/coding-agent/test/acp-events.test.ts
index f922183aa5..5ead194aaf 100644
--- a/packages/coding-agent/test/acp-events.test.ts
+++ b/packages/coding-agent/test/acp-events.test.ts
@@ -60,8 +60,6 @@ describe("ACP session event mapping", () => {
});
it("carries rich IPython output from the fields the tool actually reports", () => {
- // The ipython tool reports media/diffs under `details`, so the mapping must
- // read those exact fields rather than an invented MIME bundle.
const updates = acpUpdatesForSessionEvent({
type: "tool_execution_end",
toolCallId: "call-1",
@@ -120,7 +118,6 @@ describe("ACP session event mapping", () => {
{ type: "bash_start", command: "ls", excludeFromContext: false, runId: "r1" } as AgentConnectionSessionEvent,
state,
);
- // bash_output carries no runId, so the mapping must remember the active run.
const mid = acpUpdatesForSessionEvent(
{ type: "bash_output", chunk: "a.ts\n" } as AgentConnectionSessionEvent,
state,
diff --git a/packages/coding-agent/test/acp-stop-reason.test.ts b/packages/coding-agent/test/acp-stop-reason.test.ts
index 2504f0c6cb..16a278b165 100644
--- a/packages/coding-agent/test/acp-stop-reason.test.ts
+++ b/packages/coding-agent/test/acp-stop-reason.test.ts
@@ -36,8 +36,6 @@ describe("ACP stop reasons", () => {
});
it("never reports a stopped autonomous run as a clean end_turn", () => {
- // A wall-clock timeout is not a successful completion; reporting end_turn
- // would make it indistinguishable from finishing the work.
const timedOut = status({ startedAt: Date.now() - 60 * 60 * 1000 });
expect(acpStopReason({ cancelled: false, autonomous: timedOut })).toBe("max_turn_requests");
expect(acpStopReason({ cancelled: false, autonomous: status({ turnsUsed: 100 }) })).toBe("max_turn_requests");
diff --git a/packages/coding-agent/test/agent-activity.test.ts b/packages/coding-agent/test/agent-activity.test.ts
index ee5f309324..2e71e954b7 100644
--- a/packages/coding-agent/test/agent-activity.test.ts
+++ b/packages/coding-agent/test/agent-activity.test.ts
@@ -73,7 +73,6 @@ describe("AgentActivityTracker", () => {
});
test("updates live from the character estimate when streamed usage is stale", () => {
- // Anthropic reports usage at message start (~1 token) and then again only at the end.
const tracker = new AgentActivityTracker();
const message = createAssistantMessage(1);
tracker.handleEvent({ type: "message_start", message });
diff --git a/packages/coding-agent/test/agent-session-concurrent.test.ts b/packages/coding-agent/test/agent-session-concurrent.test.ts
index 3321b7c35f..41f9cd7d89 100644
--- a/packages/coding-agent/test/agent-session-concurrent.test.ts
+++ b/packages/coding-agent/test/agent-session-concurrent.test.ts
@@ -1,7 +1,3 @@
-/**
- * Tests for AgentSession concurrent prompt guard.
- */
-
import { existsSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -24,7 +20,6 @@ import { SettingsManager } from "../src/core/settings-manager.js";
import type { BuildSystemPromptOptions } from "../src/core/system-prompt.js";
import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.js";
-// Mock stream that mimics AssistantMessageEventStream
class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
constructor() {
super(
@@ -82,7 +77,6 @@ describe("AgentSession concurrent prompt guard", () => {
const model = getModel("anthropic", "claude-sonnet-4-5")!;
let abortSignal: AbortSignal | undefined;
- // Use a stream function that responds to abort
const agent = new Agent({
getApiKey: () => "test-key",
initialState: {
@@ -112,7 +106,6 @@ describe("AgentSession concurrent prompt guard", () => {
const settingsManager = SettingsManager.create(tempDir, tempDir);
const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
const modelRegistry = ModelRegistry.create(authStorage, tempDir);
- // Set a runtime API key so validation passes
authStorage.setRuntimeApiKey("anthropic", "test-key");
session = new AgentSession({
@@ -195,37 +188,27 @@ describe("AgentSession concurrent prompt guard", () => {
it("should throw when prompt() called while streaming", async () => {
createSession();
- // Start first prompt (don't await, it will block until abort)
const firstPrompt = session.prompt("First message");
-
- // Wait a tick for isStreaming to be set
await new Promise((resolve) => setTimeout(resolve, 10));
-
- // Verify we're streaming
expect(session.isStreaming).toBe(true);
- // Second prompt should reject
await expect(session.prompt("Second message")).rejects.toThrow(
"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
);
- // Cleanup
await session.abort();
- await firstPrompt.catch(() => {}); // Ignore abort error
+ await firstPrompt.catch(() => {});
});
it("should allow steer() while streaming", async () => {
createSession();
- // Start first prompt
const firstPrompt = session.prompt("First message");
await new Promise((resolve) => setTimeout(resolve, 10));
- // steer should work while streaming
expect(() => session.steer("Steering message")).not.toThrow();
expect(session.queuedActionCount).toBe(1);
- // Cleanup
await session.abort();
await firstPrompt.catch(() => {});
});
@@ -233,15 +216,12 @@ describe("AgentSession concurrent prompt guard", () => {
it("should allow followUp() while streaming", async () => {
createSession();
- // Start first prompt
const firstPrompt = session.prompt("First message");
await new Promise((resolve) => setTimeout(resolve, 10));
- // followUp should work while streaming
expect(() => session.followUp("Follow-up message")).not.toThrow();
expect(session.queuedActionCount).toBe(1);
- // Cleanup
await session.abort();
await firstPrompt.catch(() => {});
});
@@ -488,7 +468,6 @@ describe("AgentSession concurrent prompt guard", () => {
});
it("should allow prompt() after previous completes", async () => {
- // Create session with a stream that completes immediately
const model = getModel("anthropic", "claude-sonnet-4-5")!;
const agent = new Agent({
getApiKey: () => "test-key",
@@ -522,13 +501,8 @@ describe("AgentSession concurrent prompt guard", () => {
resourceLoader: createTestResourceLoader(),
});
- // First prompt completes
await session.prompt("First message");
-
- // Should not be streaming anymore
expect(session.isStreaming).toBe(false);
-
- // Second prompt should work
await expect(session.prompt("Second message")).resolves.not.toThrow();
});
diff --git a/packages/coding-agent/test/agent-traces-git-context.test.ts b/packages/coding-agent/test/agent-traces-git-context.test.ts
index 6d30b0884e..db24e956e7 100644
--- a/packages/coding-agent/test/agent-traces-git-context.test.ts
+++ b/packages/coding-agent/test/agent-traces-git-context.test.ts
@@ -31,7 +31,6 @@ describe("activeGitContext", () => {
});
it("ignores a git_state on a sibling branch and uses the active leaf's path", () => {
- // m1 -> g1(bbb) is one branch; m1 -> m2 -> g2(ccc) is the active branch (g2 is last in file).
const body = jsonl(
{ type: "message", id: "m1", parentId: null, timestamp: "t", message: {} },
{ type: "git_state", id: "g1", parentId: "m1", timestamp: "t", git: { commit: "bbb", branch: "old" } },
@@ -42,7 +41,6 @@ describe("activeGitContext", () => {
});
it("falls back to the header when the active path has no git_state", () => {
- // Active leaf m2 descends only from the header; g1 lives on an abandoned sibling.
const body = jsonl(
{ type: "message", id: "m1", parentId: null, timestamp: "t", message: {} },
{ type: "git_state", id: "g1", parentId: "m1", timestamp: "t", git: { commit: "bbb", branch: "old" } },
diff --git a/packages/coding-agent/test/agents-view-missing-cwd.test.ts b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
index 8d7894ddd8..57f7ed8579 100644
--- a/packages/coding-agent/test/agents-view-missing-cwd.test.ts
+++ b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
@@ -30,7 +30,6 @@ describe("agents view open with a missing session cwd", () => {
throw new Error("runtime factory should not be reached when the cwd is missing");
};
- // With cwd stripped, the session resolves against its deleted cwd and throws.
const stripped = await SessionManager.openAsync(sessionFile, sessionDir);
const suppliedLease = new SessionLease(sessionFile, join(root, "missing-cwd-lease"), "lease-token");
const releaseLease = vi.spyOn(suppliedLease, "release");
@@ -66,7 +65,6 @@ describe("agents view open with a missing session cwd", () => {
const overridden = await SessionManager.openAsync(sessionFile, sessionDir, resumeConfig.cwd);
expect(overridden.getCwd()).toBe(launchCwd);
- // The override gets the build past the cwd guard and into the factory.
let factoryCwd: string | undefined;
const okFactory = async (opts: { cwd: string }) => {
factoryCwd = opts.cwd;
diff --git a/packages/coding-agent/test/auth-storage.test.ts b/packages/coding-agent/test/auth-storage.test.ts
index c2f368a833..677d771b99 100644
--- a/packages/coding-agent/test/auth-storage.test.ts
+++ b/packages/coding-agent/test/auth-storage.test.ts
@@ -181,7 +181,6 @@ describe("AuthStorage", () => {
});
test("apiKey as literal value is used directly when not an env var", async () => {
- // Make sure this isn't an env var
delete process.env.literal_api_key_value;
writeAuthJson({
@@ -797,7 +796,6 @@ describe("AuthStorage", () => {
describe("caching", () => {
test("command is only executed once per process", async () => {
- // Use a command that writes to a file to count invocations
const counterFile = join(tempDir, "counter");
writeFileSync(counterFile, "0");
@@ -809,12 +807,10 @@ describe("AuthStorage", () => {
authStorage = AuthStorage.create(authJsonPath);
- // Call multiple times
await authStorage.getApiKey("anthropic");
await authStorage.getApiKey("anthropic");
await authStorage.getApiKey("anthropic");
- // Command should have only run once
const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
expect(count).toBe(1);
});
@@ -829,14 +825,12 @@ describe("AuthStorage", () => {
anthropic: { type: "api_key", key: command },
});
- // Create multiple AuthStorage instances
const storage1 = AuthStorage.create(authJsonPath);
await storage1.getApiKey("anthropic");
const storage2 = AuthStorage.create(authJsonPath);
await storage2.getApiKey("anthropic");
- // Command should still have only run once
const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
expect(count).toBe(1);
});
@@ -854,11 +848,9 @@ describe("AuthStorage", () => {
authStorage = AuthStorage.create(authJsonPath);
await authStorage.getApiKey("anthropic");
- // Clear cache and call again
clearConfigValueCache();
await authStorage.getApiKey("anthropic");
- // Command should have run twice
const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
expect(count).toBe(2);
});
@@ -890,14 +882,12 @@ describe("AuthStorage", () => {
authStorage = AuthStorage.create(authJsonPath);
- // Call multiple times - all should return undefined
const key1 = await authStorage.getApiKey("anthropic");
const key2 = await authStorage.getApiKey("anthropic");
expect(key1).toBeUndefined();
expect(key2).toBeUndefined();
- // Command should have only run once despite failures
const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
expect(count).toBe(1);
});
@@ -918,7 +908,6 @@ describe("AuthStorage", () => {
const key1 = await authStorage.getApiKey("anthropic");
expect(key1).toBe("first-value");
- // Change env var
process.env[envVarName] = "second-value";
const key2 = await authStorage.getApiKey("anthropic");
@@ -992,7 +981,6 @@ describe("AuthStorage", () => {
authStorage = AuthStorage.create(authJsonPath);
- // Simulate external edit while process is running
writeAuthJson({
anthropic: { type: "api_key", key: "old-anthropic" },
openai: { type: "api_key", key: "openai-key" },
@@ -1015,7 +1003,6 @@ describe("AuthStorage", () => {
authStorage = AuthStorage.create(authJsonPath);
- // Simulate external edit while process is running
writeAuthJson({
anthropic: { type: "api_key", key: "anthropic-key" },
openai: { type: "api_key", key: "openai-key" },
@@ -1055,7 +1042,6 @@ describe("AuthStorage", () => {
authStorage.reload();
- // Keeps previous in-memory data on reload failure
expect(authStorage.get("anthropic")).toEqual({ type: "api_key", key: "anthropic-key" });
const firstDrain = authStorage.drainErrors();
diff --git a/packages/coding-agent/test/bash-close-hang-windows.test.ts b/packages/coding-agent/test/bash-close-hang-windows.test.ts
index 10ae6414e5..2795be7ff3 100644
--- a/packages/coding-agent/test/bash-close-hang-windows.test.ts
+++ b/packages/coding-agent/test/bash-close-hang-windows.test.ts
@@ -35,7 +35,7 @@ function cleanupDetachedChild(pidFile: string): void {
try {
execFileSync("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore" });
} catch {
- // Process may have already exited.
+ // The detached Windows child may already have exited.
}
}
}
diff --git a/packages/coding-agent/test/bash-execution-width.test.ts b/packages/coding-agent/test/bash-execution-width.test.ts
index e3d5d47992..e0f98cfa73 100644
--- a/packages/coding-agent/test/bash-execution-width.test.ts
+++ b/packages/coding-agent/test/bash-execution-width.test.ts
@@ -1,7 +1,3 @@
-/**
- * Test that BashExecutionComponent's collapsed output respects the render-time width,
- * not a stale captured width. Regression test for #2569.
- */
import { visibleWidth } from "@earendil-works/pi-tui";
import { beforeAll, describe, expect, it } from "vitest";
import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";
@@ -27,6 +23,7 @@ function createTuiStub(columns: number): { columns: number; stub: any } {
return { columns: state.columns, stub };
}
+/** Collapsed output must wrap at render-time width after a resize or split. */
describe("BashExecutionComponent width handling (#2569)", () => {
beforeAll(() => {
initTheme(undefined, false);
@@ -43,7 +40,6 @@ describe("BashExecutionComponent width handling (#2569)", () => {
const longLine = "x".repeat(150);
component.appendOutput(`${longLine}\n${longLine}\n`);
- // Complete the command so it enters collapsed mode
component.setComplete(0, false);
// Render at the narrow width (simulating a resize or split pane)
diff --git a/packages/coding-agent/test/block-images.test.ts b/packages/coding-agent/test/block-images.test.ts
index 009707eee6..f00b019b32 100644
--- a/packages/coding-agent/test/block-images.test.ts
+++ b/packages/coding-agent/test/block-images.test.ts
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { processFileArguments } from "../src/cli/file-processor.js";
import { SettingsManager } from "../src/core/settings-manager.js";
-// 1x1 red PNG image as base64 (smallest valid PNG)
const TINY_PNG_BASE64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";
@@ -54,7 +53,6 @@ describe("blockImages setting", () => {
});
it("should always process images (filtering happens at convertToLlm layer)", async () => {
- // Create test image
const imagePath = join(testDir, "test.png");
writeFileSync(imagePath, Buffer.from(TINY_PNG_BASE64, "base64"));
@@ -65,7 +63,6 @@ describe("blockImages setting", () => {
});
it("should process text files normally", async () => {
- // Create test text file
const textPath = join(testDir, "test.txt");
writeFileSync(textPath, "Hello, world!");
diff --git a/packages/coding-agent/test/builtin-skills.test.ts b/packages/coding-agent/test/builtin-skills.test.ts
index 44eddc6884..8272ff0ca1 100644
--- a/packages/coding-agent/test/builtin-skills.test.ts
+++ b/packages/coding-agent/test/builtin-skills.test.ts
@@ -294,10 +294,7 @@ describe("builtin skills", () => {
});
});
- // The bundled skills only reach a deployed agent if the build/release scripts
- // copy skills/ into the shipped layout. A regression here resolves zero
- // built-in skills at runtime even though the source tree looks correct
- // (ENG-4220), so assert each shipping path still copies skills.
+ // Verify every shipping path includes bundled skills; source-only success would hide a release packaging regression.
describe("packaging ships bundled skills", () => {
const packageRoot = join(__dirname, "..");
const repoRoot = join(packageRoot, "..", "..");
diff --git a/packages/coding-agent/test/centered-overlay.test.ts b/packages/coding-agent/test/centered-overlay.test.ts
index 33a8a5c1ad..09969dcdb6 100644
--- a/packages/coding-agent/test/centered-overlay.test.ts
+++ b/packages/coding-agent/test/centered-overlay.test.ts
@@ -6,9 +6,7 @@ class TestComponent implements Component, Focusable {
focused = false;
readonly inputs: string[] = [];
- invalidate(): void {
- // Test component has no cached render state.
- }
+ invalidate(): void {}
render(width: number): string[] {
return [`content ${width}`, "second row"];
diff --git a/packages/coding-agent/test/child-process.test.ts b/packages/coding-agent/test/child-process.test.ts
index 6a807f32fc..08a87793f2 100644
--- a/packages/coding-agent/test/child-process.test.ts
+++ b/packages/coding-agent/test/child-process.test.ts
@@ -25,13 +25,11 @@ describe("process liveness", () => {
it("treats an exited process as dead", async () => {
const child = spawn(process.execPath, ["--eval", "process.exit(0)"], { stdio: "ignore" });
await new Promise<void>((resolveExit) => child.once("exit", () => resolveExit()));
- // Node reaps its own children on exit, so the pid is fully gone.
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
expect(isProcessAlive(child.pid!)).toBe(false);
});
it.skipIf(process.platform === "win32")("treats a zombie process as dead", async () => {
- // A parent that forks and never reaps leaves the child as a zombie.
const parent = spawn(
"perl",
["-e", '$| = 1; my $pid = fork(); if ($pid) { print "$pid\\n"; sleep 30 } else { exit 0 }'],
diff --git a/packages/coding-agent/test/code-preview.test.ts b/packages/coding-agent/test/code-preview.test.ts
index 3ec121ae74..fcf9c4df51 100644
--- a/packages/coding-agent/test/code-preview.test.ts
+++ b/packages/coding-agent/test/code-preview.test.ts
@@ -122,7 +122,6 @@ PY`;
const command = `./script.sh <<'EOF'
hello world
EOF`;
- // The .sh suffix must not trigger the bash-interpreter branch; preview the body.
expect(previewBashCommand(command)).toEqual({ language: "bash", text: "hello world" });
});
diff --git a/packages/coding-agent/test/compaction-extensions-example.test.ts b/packages/coding-agent/test/compaction-extensions-example.test.ts
index 4f5e33597a..47d3aca752 100644
--- a/packages/coding-agent/test/compaction-extensions-example.test.ts
+++ b/packages/coding-agent/test/compaction-extensions-example.test.ts
@@ -1,23 +1,15 @@
-/**
- * Verify the documentation example from extensions.md compiles and works.
- */
-
import { describe, expect, it } from "vitest";
import type { ExtensionAPI, SessionBeforeCompactEvent, SessionCompactEvent } from "../src/core/extensions/index.js";
describe("Documentation example", () => {
it("custom compaction example should type-check correctly", () => {
- // This is the example from extensions.md - verify it compiles
const exampleExtension = (pi: ExtensionAPI) => {
pi.on("session_before_compact", async (event: SessionBeforeCompactEvent, ctx) => {
- // All these should be accessible on the event
const { preparation, branchEntries } = event;
- // sessionManager, modelRegistry, and model come from ctx
const { sessionManager, modelRegistry } = ctx;
const { messagesToSummarize, turnPrefixMessages, tokensBefore, firstKeptEntryId, isSplitTurn } =
preparation;
- // Verify types
expect(Array.isArray(messagesToSummarize)).toBe(true);
expect(Array.isArray(turnPrefixMessages)).toBe(true);
expect(typeof isSplitTurn).toBe("boolean");
@@ -32,7 +24,6 @@ describe("Documentation example", () => {
.map((m) => `- ${typeof m.content === "string" ? m.content.slice(0, 100) : "[complex]"}`)
.join("\n");
- // Extensions return compaction content - SessionManager adds id/parentId
return {
compaction: {
summary: `User requests:\n${summary}`,
@@ -43,14 +34,12 @@ describe("Documentation example", () => {
});
};
- // Just verify the function exists and is callable
expect(typeof exampleExtension).toBe("function");
});
it("compact event should have correct fields", () => {
const checkCompactEvent = (pi: ExtensionAPI) => {
pi.on("session_compact", async (event: SessionCompactEvent) => {
- // These should all be accessible
const entry = event.compactionEntry;
const fromExtension = event.fromExtension;
diff --git a/packages/coding-agent/test/compaction-serialization.test.ts b/packages/coding-agent/test/compaction-serialization.test.ts
index f15a8b790a..75ceea1b16 100644
--- a/packages/coding-agent/test/compaction-serialization.test.ts
+++ b/packages/coding-agent/test/compaction-serialization.test.ts
@@ -21,7 +21,6 @@ describe("serializeConversation", () => {
expect(result).toContain("[Tool result]:");
expect(result).toContain("[... 3000 more characters truncated]");
expect(result).not.toContain("x".repeat(3000));
- // First 2000 chars should be present
expect(result).toContain("x".repeat(2000));
});
diff --git a/packages/coding-agent/test/daemon-client-env.test.ts b/packages/coding-agent/test/daemon-client-env.test.ts
index 4e1162a418..3c9edf570b 100644
--- a/packages/coding-agent/test/daemon-client-env.test.ts
+++ b/packages/coding-agent/test/daemon-client-env.test.ts
@@ -31,7 +31,6 @@ describe("withClientEnv", () => {
});
expect(seenPane).toBe("w2:p1");
expect(seenTab).toBe("t1");
- // The daemon's ambient value must not mix into a partial client env.
expect(seenWorkspace).toBeUndefined();
expect(process.env.HERDR_PANE_ID).toBe("original");
expect(process.env.HERDR_TAB_ID).toBeUndefined();
@@ -90,10 +89,7 @@ describe("withClientEnv", () => {
it("execEnvForSession pins keys independent of active env windows", async () => {
const baseline = execEnvForSession();
await withClientEnv({ HERDR_PANE_ID: "window-only" }, async () => {
- // An env-less session's exec env is the daemon's startup base, not
- // whatever another session's window put in process.env.
expect(execEnvForSession()).toStrictEqual(baseline);
- // A session with env gets exactly its values; missing keys are unset.
expect(execEnvForSession({ HERDR_PANE_ID: "w9:p9" })).toStrictEqual({
HERDR_ENV: undefined,
HERDR_PANE_ID: "w9:p9",
diff --git a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
index e7f7ae0442..c14c2a8a19 100644
--- a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
+++ b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
@@ -84,7 +84,6 @@ describe("DaemonSessionSummarizer lifecycle", () => {
await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
expect(state.summaryState).toMatchObject({ summary: "", taskState: "needs_input" });
- // A blank recap still owes a summary, so a later sweep retries and records it.
summarizer.notifyActivity(state);
await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
expect(generate).toHaveBeenCalledTimes(2);
@@ -131,14 +130,12 @@ describe("DaemonSessionSummarizer lifecycle", () => {
summarizer.notifyActivity(state);
await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
expect(generate).toHaveBeenCalledOnce();
- // Aborted → nothing written to the disposed session.
expect(state.summaryState).toBeUndefined();
});
test("discards a verdict when a new turn arrives during the model call", async () => {
vi.useFakeTimers();
const state = makeState({ working: false });
- // The model "responds" only after the session has moved on to a new turn.
const generate = vi.fn().mockImplementation(async () => {
(state.runtime.session.messages as unknown[]).push({ role: "user", content: "another task" });
return { summary: "Stale summary for the old turn", taskState: "completed" };
@@ -148,7 +145,6 @@ describe("DaemonSessionSummarizer lifecycle", () => {
summarizer.notifyActivity(state);
await vi.advanceTimersByTimeAsync(SETTLE_MS + 500);
expect(generate).toHaveBeenCalledOnce();
- // Result is for an outdated turn → dropped, nothing persisted.
expect(state.summaryState).toBeUndefined();
});
diff --git a/packages/coding-agent/test/daemon-supervisor-ownership.test.ts b/packages/coding-agent/test/daemon-supervisor-ownership.test.ts
index 6cacc933da..c89e5c03f5 100644
--- a/packages/coding-agent/test/daemon-supervisor-ownership.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-ownership.test.ts
@@ -101,12 +101,9 @@ describe("daemon supervisor ownership registry", () => {
await persistDaemonStartupFenceFromOwner(paths.socketPath, hello, paths.registryDir, legacyDir);
- // The fence lands in the NEW registry; the legacy record is untouched.
expect(readdirSync(join(paths.registryDir, "startup-fences"))).toHaveLength(1);
expect(readFileSync(legacyOwnerPath, "utf8")).toBe(legacyBytes);
- // Without a legacy dir the same scan fails: the fallback never fires for
- // an explicitly provided registry.
await expect(persistDaemonStartupFenceFromOwner(paths.socketPath, hello, paths.registryDir)).rejects.toThrow(
/does not match/,
);
@@ -136,7 +133,6 @@ describe("daemon supervisor ownership registry", () => {
assertDaemonSupervisorOwnerCurrent(identity, undefined, paths.registryDir, legacyDir),
).resolves.toEqual(expect.any(String));
- // Without the injected legacy dir, an explicit registry never falls back.
await expect(assertDaemonSupervisorOwnerCurrent(identity, undefined, paths.registryDir)).rejects.toMatchObject({
code: "supervisor_generation_stale",
});
@@ -190,7 +186,6 @@ describe("daemon supervisor ownership registry", () => {
realpath: false,
lockfilePath: join(paths.registryDir, ".guard"),
});
- // The direct renew is now queued behind the held guard.
const pending = admission.assertOrRenew();
pending.catch(() => undefined);
const releasing = admission.release();
diff --git a/packages/coding-agent/test/edit-summary.test.ts b/packages/coding-agent/test/edit-summary.test.ts
index 0f2aab8537..94330bd64e 100644
--- a/packages/coding-agent/test/edit-summary.test.ts
+++ b/packages/coding-agent/test/edit-summary.test.ts
@@ -149,7 +149,6 @@ describe("formatFileChangeSummaryLine", () => {
const expanded = formatFileChangeSummaryLine(path, undefined, change, true, width);
const collapsed = formatFileChangeSummaryLine(path, undefined, change, false, width);
expect(stripAnsi(expanded)).toContain("…");
- // "to expand" vs "to collapse" differ in width; the path must not re-truncate.
expect(pathPart(expanded)).toBe(pathPart(collapsed));
});
});
diff --git a/packages/coding-agent/test/export-html-xss.test.ts b/packages/coding-agent/test/export-html-xss.test.ts
index d19d9fed56..403ec53168 100644
--- a/packages/coding-agent/test/export-html-xss.test.ts
+++ b/packages/coding-agent/test/export-html-xss.test.ts
@@ -5,7 +5,6 @@ describe("export HTML markdown link sanitization", () => {
const templateJs = readFileSync(new URL("../src/core/export-html/template.js", import.meta.url), "utf-8");
it("overrides the marked link renderer to block javascript: protocol", () => {
- // The custom link renderer must check for dangerous protocols
expect(templateJs).toMatch(/link\s*\(\s*token\s*\)/);
expect(templateJs).toMatch(/javascript/i);
expect(templateJs).toMatch(/vbscript/i);
@@ -16,24 +15,20 @@ describe("export HTML markdown link sanitization", () => {
});
it("escapes href attributes in the custom link renderer", () => {
- // The link renderer must escape href values to prevent attribute breakout
expect(templateJs).toMatch(/escapeHtml\(href\)/);
});
it("escapes image mimeType attributes", () => {
- // Image mimeType must be escaped to prevent attribute breakout
expect(templateJs).not.toMatch(/\$\{img\.mimeType\}/);
expect(templateJs).toMatch(/escapeHtml\(img\.mimeType/);
});
it("escapes image data attributes", () => {
- // Image data is embedded in src attributes and must not allow attribute breakout.
expect(templateJs).not.toMatch(/;base64,\$\{img\.data\}"/);
expect(templateJs).toMatch(/;base64,\$\{escapeHtml\(img\.data \|\| (?:''|"")\)\}"/);
});
it("escapes entry IDs before inserting them into attributes", () => {
- // Session entry IDs are embedded in id and data-entry-id attributes.
expect(templateJs).not.toMatch(/id="\$\{entryId\}"/);
expect(templateJs).not.toMatch(/data-entry-id="\$\{entryId\}"/);
expect(templateJs).toMatch(/entry-\$\{escapeHtml\(entry\.id\)\}/);
@@ -41,7 +36,6 @@ describe("export HTML markdown link sanitization", () => {
});
it("escapes tree metadata rendered from session fields", () => {
- // The tree renders session metadata via innerHTML, so dynamic fields must be escaped.
expect(templateJs).not.toMatch(/\[\$\{msg\.toolName \|\| 'tool'\}\]/);
expect(templateJs).not.toMatch(/\[\$\{msg\.role\}\]/);
expect(templateJs).not.toMatch(/\[model: \$\{entry\.modelId\}\]/);
@@ -57,7 +51,6 @@ describe("export HTML markdown link sanitization", () => {
});
it("escapes model names in the exported header", () => {
- // Assistant message provider/model values are collected from the session and rendered with innerHTML.
expect(templateJs).not.toMatch(/\$\{globalStats\.models\.join\(', '\) \|\| 'unknown'\}/);
expect(templateJs).toMatch(/\$\{escapeHtml\(globalStats\.models\.join\(', '\) \|\| 'unknown'\)\}/);
});
diff --git a/packages/coding-agent/test/extension-tool-wrapper-rebind.test.ts b/packages/coding-agent/test/extension-tool-wrapper-rebind.test.ts
index e074ddea40..efee04b05b 100644
--- a/packages/coding-agent/test/extension-tool-wrapper-rebind.test.ts
+++ b/packages/coding-agent/test/extension-tool-wrapper-rebind.test.ts
@@ -5,8 +5,6 @@ import { wrapRegisteredTools } from "../src/core/extensions/wrapper.js";
const STALE = "This extension ctx is stale after session replacement or reload.";
-// Minimal stand-in for a runner whose createContext() throws once invalidated,
-// mirroring assertActive() on the real ExtensionRunner's guarded ctx getters.
function makeRunner(id: string): ExtensionRunner & { invalidate(): void } {
let stale = false;
return {
@@ -43,7 +41,6 @@ describe("wrapRegisteredTools runner rebinding", () => {
const first = await tool.execute("c1", {}, new AbortController().signal);
expect((first.content[0] as { text: string }).text).toBe("first");
- // Session rebuild: old runner invalidated, a fresh one takes its place.
runner.invalidate();
runner = makeRunner("second");
@@ -58,8 +55,6 @@ describe("wrapRegisteredTools runner rebinding", () => {
await expect(tool.execute("c1", {}, new AbortController().signal)).resolves.toBeTruthy();
runner.invalidate();
- // The ctx is resolved synchronously as an execute() argument, so a stale runner
- // throws at call time rather than rejecting.
expect(() => tool.execute("c2", {}, new AbortController().signal)).toThrow(STALE);
});
});
diff --git a/packages/coding-agent/test/extensions-discovery.test.ts b/packages/coding-agent/test/extensions-discovery.test.ts
index 52029d2cfa..b60d011a17 100644
--- a/packages/coding-agent/test/extensions-discovery.test.ts
+++ b/packages/coding-agent/test/extensions-discovery.test.ts
@@ -164,7 +164,6 @@ describe("extensions discovery", () => {
expect(result.errors).toHaveLength(0);
expect(result.extensions).toHaveLength(1);
expect(result.extensions[0].path).toContain("custom.ts");
- // Verify the right tool was registered
expect(result.extensions[0].tools.has("from-custom")).toBe(true);
expect(result.extensions[0].tools.has("from-index")).toBe(false);
});
@@ -206,7 +205,6 @@ describe("extensions discovery", () => {
fs.mkdirSync(subdir);
fs.mkdirSync(nested);
fs.writeFileSync(path.join(nested, "index.ts"), extensionCode);
- // No index.ts or package.json in container/
const result = await discoverAndLoadExtensions([], tempDir, tempDir);
@@ -215,15 +213,12 @@ describe("extensions discovery", () => {
});
it("handles mixed direct files and subdirectories", async () => {
- // Direct file
fs.writeFileSync(path.join(extensionsDir, "direct.ts"), extensionCode);
- // Subdirectory with index
const subdir1 = path.join(extensionsDir, "with-index");
fs.mkdirSync(subdir1);
fs.writeFileSync(path.join(subdir1, "index.ts"), extensionCode);
- // Subdirectory with package.json
const subdir2 = path.join(extensionsDir, "with-manifest");
fs.mkdirSync(subdir2);
fs.writeFileSync(path.join(subdir2, "entry.ts"), extensionCode);
@@ -298,7 +293,6 @@ describe("extensions discovery", () => {
});
it("resolves dependencies from extension's own node_modules", async () => {
- // Load extension that has its own package.json and node_modules with 'ms' package
const extPath = path.resolve(__dirname, "../examples/extensions/with-deps");
const result = await discoverAndLoadExtensions([extPath], tempDir, tempDir);
@@ -306,7 +300,6 @@ describe("extensions discovery", () => {
expect(result.errors).toHaveLength(0);
expect(result.extensions).toHaveLength(1);
expect(result.extensions[0].path).toContain("with-deps");
- // The extension registers a 'parse_duration' tool
expect(result.extensions[0].tools.has("parse_duration")).toBe(true);
});
@@ -432,14 +425,11 @@ describe("extensions discovery", () => {
});
it("loadExtensions only loads explicit paths without discovery", async () => {
- // Create discoverable extensions (would be found by discoverAndLoadExtensions)
fs.writeFileSync(path.join(extensionsDir, "discovered.ts"), extensionCodeWithTool("discovered"));
- // Create explicit extension outside discovery path
const explicitPath = path.join(tempDir, "explicit.ts");
fs.writeFileSync(explicitPath, extensionCodeWithTool("explicit"));
- // Use loadExtensions directly to skip discovery
const { loadExtensions } = await import("../src/core/extensions/loader.js");
const result = await loadExtensions([explicitPath], tempDir);
@@ -450,10 +440,8 @@ describe("extensions discovery", () => {
});
it("loadExtensions with no paths loads nothing", async () => {
- // Create discoverable extensions (would be found by discoverAndLoadExtensions)
fs.writeFileSync(path.join(extensionsDir, "discovered.ts"), extensionCode);
- // Use loadExtensions directly with empty paths
const { loadExtensions } = await import("../src/core/extensions/loader.js");
const result = await loadExtensions([], tempDir);
diff --git a/packages/coding-agent/test/extensions-input-event.test.ts b/packages/coding-agent/test/extensions-input-event.test.ts
index 5c08fd2ceb..723d00f111 100644
--- a/packages/coding-agent/test/extensions-input-event.test.ts
+++ b/packages/coding-agent/test/extensions-input-event.test.ts
@@ -16,14 +16,12 @@ describe("Input Event", () => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-input-test-"));
extensionsDir = path.join(tempDir, "extensions");
fs.mkdirSync(extensionsDir);
- // Clean globalThis test vars
delete (globalThis as any).testVar;
});
afterEach(() => fs.rmSync(tempDir, { recursive: true, force: true }));
async function createRunner(...extensions: string[]) {
- // Clear and recreate extensions dir for clean state
fs.rmSync(extensionsDir, { recursive: true, force: true });
fs.mkdirSync(extensionsDir);
for (let i = 0; i < extensions.length; i++) fs.writeFileSync(path.join(extensionsDir, `e${i}.ts`), extensions[i]);
@@ -34,12 +32,9 @@ describe("Input Event", () => {
}
it("returns continue when no handlers, undefined return, or explicit continue", async () => {
- // No handlers
expect((await (await createRunner()).emitInput("x", undefined, "interactive")).action).toBe("continue");
- // Returns undefined
let r = await createRunner(`export default p => p.on("input", async () => {});`);
expect((await r.emitInput("x", undefined, "interactive")).action).toBe("continue");
- // Returns explicit continue
r = await createRunner(`export default p => p.on("input", async () => ({ action: "continue" }));`);
expect((await r.emitInput("x", undefined, "interactive")).action).toBe("continue");
});
diff --git a/packages/coding-agent/test/git-update.test.ts b/packages/coding-agent/test/git-update.test.ts
index 5c184f38d0..eb50d6003c 100644
--- a/packages/coding-agent/test/git-update.test.ts
+++ b/packages/coding-agent/test/git-update.test.ts
@@ -1,11 +1,3 @@
-/**
- * Tests for git-based extension updates, specifically handling force-push scenarios.
- *
- * These tests verify that DefaultPackageManager.update() handles:
- * - Normal git updates (no force-push)
- * - Force-pushed remotes gracefully (currently fails, fix needed)
- */
-
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
@@ -15,7 +7,6 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { DefaultPackageManager } from "../src/core/package-manager.js";
import { SettingsManager } from "../src/core/settings-manager.js";
-// Helper to run git commands in a directory
function git(args: string[], cwd: string): string {
const result = spawnSync("git", args, {
cwd,
@@ -33,7 +24,6 @@ function initGitRepo(repoDir: string): void {
git(["config", "--local", "user.name", "Test"], repoDir);
}
-// Helper to create a commit with a file
function createCommit(repoDir: string, filename: string, content: string, message: string): string {
writeFileSync(join(repoDir, filename), content);
git(["add", filename], repoDir);
@@ -41,12 +31,10 @@ function createCommit(repoDir: string, filename: string, content: string, messag
return git(["rev-parse", "HEAD"], repoDir);
}
-// Helper to get current commit hash
function getCurrentCommit(repoDir: string): string {
return git(["rev-parse", "HEAD"], repoDir);
}
-// Helper to get file content
function getFileContent(repoDir: string, filename: string): string {
return readFileSync(join(repoDir, filename), "utf-8");
}
@@ -59,9 +47,6 @@ describe("DefaultPackageManager git update", () => {
let settingsManager: SettingsManager;
let packageManager: DefaultPackageManager;
- // Git source that maps to our installed directory structure.
- // Must use "git:" prefix so parseSource() treats it as a git source
- // (bare "github.com/..." is not recognized as a git URL).
const gitSource = "git:github.com/test/extension";
beforeEach(() => {
@@ -70,7 +55,6 @@ describe("DefaultPackageManager git update", () => {
remoteDir = join(tempDir, "remote");
agentDir = join(tempDir, "agent");
- // This matches the path structure: agentDir/git/<host>/<path>
installedDir = join(agentDir, "git", "github.com", "test", "extension");
mkdirSync(agentDir, { recursive: true });
@@ -89,24 +73,16 @@ describe("DefaultPackageManager git update", () => {
}
});
- /**
- * Sets up a "remote" repository and clones it to the installed directory.
- * This simulates what packageManager.install() would do.
- * @param sourceOverride Optional source string to use instead of gitSource (e.g., with @ref for pinned tests)
- */
function setupRemoteAndInstall(sourceOverride?: string): void {
- // Create "remote" repository
mkdirSync(remoteDir, { recursive: true });
initGitRepo(remoteDir);
createCommit(remoteDir, "extension.ts", "// v1", "Initial commit");
- // Clone to installed directory (simulating what install() does)
mkdirSync(join(agentDir, "git", "github.com", "test"), { recursive: true });
git(["clone", remoteDir, installedDir], tempDir);
git(["config", "--local", "user.email", "[email protected]"], installedDir);
git(["config", "--local", "user.name", "Test"], installedDir);
- // Add to global packages so update() processes this source
settingsManager.setPackages([sourceOverride ?? gitSource]);
}
@@ -155,13 +131,10 @@ describe("DefaultPackageManager git update", () => {
setupRemoteAndInstall();
expect(getFileContent(installedDir, "extension.ts")).toBe("// v1");
- // Add a new commit to remote
const newCommit = createCommit(remoteDir, "extension.ts", "// v2", "Second commit");
- // Update via package manager (no args = uses settings)
await packageManager.update();
- // Verify update succeeded
expect(getCurrentCommit(installedDir)).toBe(newCommit);
expect(getFileContent(installedDir, "extension.ts")).toBe("// v2");
});
@@ -169,7 +142,6 @@ describe("DefaultPackageManager git update", () => {
it("should handle multiple commits ahead", async () => {
setupRemoteAndInstall();
- // Add multiple commits to remote
createCommit(remoteDir, "extension.ts", "// v2", "Second commit");
createCommit(remoteDir, "extension.ts", "// v3", "Third commit");
const latestCommit = createCommit(remoteDir, "extension.ts", "// v4", "Fourth commit");
@@ -218,18 +190,14 @@ describe("DefaultPackageManager git update", () => {
setupRemoteAndInstall();
const initialCommit = getCurrentCommit(remoteDir);
- // Add commit to remote
createCommit(remoteDir, "extension.ts", "// v2", "Commit to keep");
- // Update to get the new commit
await packageManager.update();
expect(getFileContent(installedDir, "extension.ts")).toBe("// v2");
- // Now force-push to rewrite history on remote
git(["reset", "--hard", initialCommit], remoteDir);
const rewrittenCommit = createCommit(remoteDir, "extension.ts", "// v2-rewritten", "Rewritten commit");
- // Update should succeed despite force-push
await packageManager.update();
expect(getCurrentCommit(installedDir)).toBe(rewrittenCommit);
@@ -239,19 +207,15 @@ describe("DefaultPackageManager git update", () => {
it("should recover when local commit no longer exists in remote", async () => {
setupRemoteAndInstall();
- // Add commits to remote
createCommit(remoteDir, "extension.ts", "// v2", "Commit A");
createCommit(remoteDir, "extension.ts", "// v3", "Commit B");
- // Update to get all commits
await packageManager.update();
expect(getFileContent(installedDir, "extension.ts")).toBe("// v3");
- // Force-push remote to remove commits A and B
git(["reset", "--hard", "HEAD~2"], remoteDir);
const newCommit = createCommit(remoteDir, "extension.ts", "// v2-new", "New commit replacing A and B");
- // Update should succeed - the commits we had locally no longer exist
await packageManager.update();
expect(getCurrentCommit(installedDir)).toBe(newCommit);
@@ -261,19 +225,16 @@ describe("DefaultPackageManager git update", () => {
it("should handle complete history rewrite", async () => {
setupRemoteAndInstall();
- // Remote gets several commits
createCommit(remoteDir, "extension.ts", "// v2", "v2");
createCommit(remoteDir, "extension.ts", "// v3", "v3");
await packageManager.update();
expect(getFileContent(installedDir, "extension.ts")).toBe("// v3");
- // Maintainer force-pushes completely different history
git(["reset", "--hard", "HEAD~2"], remoteDir);
createCommit(remoteDir, "extension.ts", "// rewrite-a", "Rewrite A");
const finalCommit = createCommit(remoteDir, "extension.ts", "// rewrite-b", "Rewrite B");
- // Should handle this gracefully
await packageManager.update();
expect(getCurrentCommit(installedDir)).toBe(finalCommit);
@@ -283,28 +244,22 @@ describe("DefaultPackageManager git update", () => {
describe("pinned sources", () => {
it("should not update pinned git sources (with @ref)", async () => {
- // Create remote repo first to get the initial commit
mkdirSync(remoteDir, { recursive: true });
initGitRepo(remoteDir);
const initialCommit = createCommit(remoteDir, "extension.ts", "// v1", "Initial commit");
- // Install with pinned ref from the start - full clone to ensure commit is available
mkdirSync(join(agentDir, "git", "github.com", "test"), { recursive: true });
git(["clone", remoteDir, installedDir], tempDir);
git(["checkout", initialCommit], installedDir);
git(["config", "--local", "user.email", "[email protected]"], installedDir);
git(["config", "--local", "user.name", "Test"], installedDir);
- // Add to global packages with pinned ref
settingsManager.setPackages([`${gitSource}@${initialCommit}`]);
- // Add new commit to remote
createCommit(remoteDir, "extension.ts", "// v2", "Second commit");
- // Update should be skipped for pinned sources
await packageManager.update();
- // Should still be on initial commit
expect(getCurrentCommit(installedDir)).toBe(initialCommit);
expect(getFileContent(installedDir, "extension.ts")).toBe("// v1");
});
@@ -392,19 +347,15 @@ describe("DefaultPackageManager git update", () => {
it("should not install locally when source is only registered globally", async () => {
setupRemoteAndInstall();
- // Add a new commit to remote
createCommit(remoteDir, "extension.ts", "// v2", "Second commit");
- // The project-scope install path should not exist before or after update
const projectGitDir = join(tempDir, ".prime", "agent", "git", "github.com", "test", "extension");
expect(existsSync(projectGitDir)).toBe(false);
await packageManager.update(gitSource);
- // Global install should be updated
expect(getFileContent(installedDir, "extension.ts")).toBe("// v2");
- // Project-scope directory should NOT have been created
expect(existsSync(projectGitDir)).toBe(false);
});
});
diff --git a/packages/coding-agent/test/herdr-agent-state.test.ts b/packages/coding-agent/test/herdr-agent-state.test.ts
index 41a2423cbd..6c3f5909ff 100644
--- a/packages/coding-agent/test/herdr-agent-state.test.ts
+++ b/packages/coding-agent/test/herdr-agent-state.test.ts
@@ -218,7 +218,6 @@ describe("herdrAgentStateExtension", () => {
});
it("reports lifecycle state to the herdr socket", async () => {
- // Unix socket paths must stay under ~104 chars; use a short base dir.
const tempDir = join(tmpdir(), `hrd-${Math.random().toString(36).slice(2, 8)}`);
mkdirSync(tempDir, { recursive: true });
cleanupPaths.push(tempDir);
@@ -231,7 +230,6 @@ describe("herdrAgentStateExtension", () => {
process.env.HERDR_SOCKET_PATH = socketPath;
process.env.HERDR_PANE_ID = "w1:p1";
process.env.HERDR_PI_IDLE_DEBOUNCE_MS = "10";
- // Isolate from any real agent dir that may contain the file-based integration.
process.env.PRIME_AGENT_CODING_AGENT_DIR = tempDir;
const { pi, handlers } = createMockPi();
@@ -265,8 +263,6 @@ describe("herdrAgentStateExtension", () => {
await waitForRequests(3);
expect(requests[2]?.params.state).toBe("idle");
- // Session replacement must not release: the successor session re-reports,
- // and a racing release could clear the successor's fresh report.
await handlers.get("session_shutdown")?.[0]?.({ type: "session_shutdown", reason: "new" }, ctx);
await new Promise((resolve) => setTimeout(resolve, 50));
expect(requests).toHaveLength(3);
@@ -295,8 +291,6 @@ describe("herdrAgentStateExtension", () => {
expect(busHandlers.get("herdr:blocked")).toHaveLength(1);
const ctx = { sessionManager: { getSessionFile: () => undefined, getSessionId: () => "s" } };
- // Replacement shutdowns must also unsubscribe, or every /reload and /new
- // stacks another live listener on the shared bus.
await handlers.get("session_shutdown")?.[0]?.({ type: "session_shutdown", reason: "new" }, ctx);
expect(busHandlers.get("herdr:blocked")).toHaveLength(0);
});
@@ -318,7 +312,6 @@ describe("herdrAgentStateExtension", () => {
const { pi, handlers } = createMockPi();
herdrAgentStateExtension(pi);
- // Reload mid-turn: the fresh reporter's session_start sees a busy session.
const ctx = {
sessionManager: { getSessionFile: () => undefined, getSessionId: () => "s" },
isIdle: () => false,
@@ -327,7 +320,6 @@ describe("herdrAgentStateExtension", () => {
await waitForRequests(1);
expect(requests[0]?.params.state).toBe("working");
- // The turn's real end must still be honored (agentActive was seeded).
handlers.get("agent_end")?.[0]?.({ type: "agent_end", messages: [] }, ctx);
await waitForRequests(2);
expect(requests[1]?.params.state).toBe("idle");
@@ -353,7 +345,6 @@ describe("herdrAgentStateExtension", () => {
const ctx = { sessionManager: { getSessionFile: () => undefined, getSessionId: () => "s" } };
handlers.get("session_start")?.[0]?.({ type: "session_start", reason: "startup" }, ctx);
handlers.get("agent_start")?.[0]?.({ type: "agent_start" }, ctx);
- // End with a retryable provider error: enters the retry hold (working).
handlers.get("agent_end")?.[0]?.(
{
type: "agent_end",
@@ -397,9 +388,6 @@ describe("herdrAgentStateExtension", () => {
const ctx = { sessionManager: { getSessionFile: () => undefined, getSessionId: () => "s" } };
handlers.get("session_start")?.[0]?.({ type: "session_start", reason: "startup" }, ctx);
handlers.get("agent_start")?.[0]?.({ type: "agent_start" }, ctx);
- // The agent's auto-retry classifies almost every provider error as
- // retryable, so an error the old pattern list missed must still hold
- // working (not flip idle) while a retry may be pending.
handlers.get("agent_end")?.[0]?.(
{
type: "agent_end",
@@ -408,8 +396,6 @@ describe("herdrAgentStateExtension", () => {
ctx,
);
- // No retry arrives: after the grace window the pane settles to blocked
- // with the error message, never reporting idle in between.
await waitForRequests(3);
expect(requests.map((r) => r.params.state)).toEqual(["idle", "working", "blocked"]);
expect(requests.at(-1)?.params.message).toContain("unexpected provider failure");
@@ -434,8 +420,6 @@ describe("herdrAgentStateExtension", () => {
const ctx = { sessionManager: { getSessionFile: () => undefined, getSessionId: () => "s" } };
handlers.get("session_start")?.[0]?.({ type: "session_start", reason: "startup" }, ctx);
handlers.get("agent_start")?.[0]?.({ type: "agent_start" }, ctx);
- // Quit while the working report may still be in flight; the release must
- // be the final write, with no report reclaiming the pane afterwards.
await handlers.get("session_shutdown")?.[0]?.({ type: "session_shutdown", reason: "quit" }, ctx);
handlers.get("agent_start")?.[0]?.({ type: "agent_start" }, ctx);
@@ -468,9 +452,6 @@ describe("herdrAgentStateExtension", () => {
handlers.get("session_start")?.[0]?.({ type: "session_start", reason: "startup" }, ctx);
await waitForRequests(1);
- // Replacement shutdown: no release (the successor re-reports), and the
- // old instance must go quiet - a late report with its process-wide seq
- // would outrank and stomp the successor's state.
await handlers.get("session_shutdown")?.[0]?.({ type: "session_shutdown", reason: "new" }, ctx);
handlers.get("agent_start")?.[0]?.({ type: "agent_start" }, ctx);
await new Promise((resolve) => setTimeout(resolve, 100));
diff --git a/packages/coding-agent/test/image-markers.test.ts b/packages/coding-agent/test/image-markers.test.ts
index 32070278ab..752b814f81 100644
--- a/packages/coding-agent/test/image-markers.test.ts
+++ b/packages/coding-agent/test/image-markers.test.ts
@@ -34,7 +34,6 @@ describe("image markers", () => {
[1, "first"],
[2, "second"],
]);
- // Markers appear reversed in the text, but paste order is preserved.
expect(collectMarkedImages(pending, "[image #2] then [image #1]")).toEqual(["first", "second"]);
});
@@ -58,8 +57,6 @@ describe("image markers", () => {
test("a restored marker still resolves its image (undo-safe)", () => {
const pending = new Map([[1, "a"]]);
- // Marker deleted then brought back (e.g. via editor undo). Because images are
- // never pruned mid-edit, the restored marker still resolves at submit time.
expect(collectMarkedImages(pending, "no marker")).toEqual([]);
expect(collectMarkedImages(pending, "back [image #1]")).toEqual(["a"]);
});
@@ -73,7 +70,6 @@ describe("image markers", () => {
[3, "cccc"],
]);
evictImagesToBudget(images, size, 8, new Set());
- // Oldest (1) evicted; 2 and 3 (8 bytes) fit.
expect([...images.keys()]).toEqual([2, 3]);
});
@@ -83,7 +79,6 @@ describe("image markers", () => {
[2, "bbbb"],
[3, "cccc"],
]);
- // id 1 is live (kept) so it survives; 2 is evicted to get under budget.
evictImagesToBudget(images, size, 8, new Set([1]));
expect([...images.keys()]).toEqual([1, 3]);
});
diff --git a/packages/coding-agent/test/image-processing.test.ts b/packages/coding-agent/test/image-processing.test.ts
index 4dba6f2d94..9f3f45eabd 100644
--- a/packages/coding-agent/test/image-processing.test.ts
+++ b/packages/coding-agent/test/image-processing.test.ts
@@ -1,24 +1,16 @@
-/**
- * Tests for image processing utilities using Photon.
- */
-
import { describe, expect, it } from "vitest";
import { convertToPng } from "../src/utils/image-convert.js";
import { formatDimensionNote, resizeImage } from "../src/utils/image-resize.js";
-// Small 2x2 red PNG image (base64) - generated with ImageMagick
const TINY_PNG =
"iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAGUExURf8AAP///0EdNBEAAAABYktHRAH/Ai3eAAAAB3RJTUUH6gEOADM5Ddoh/wAAAAxJREFUCNdjYGBgAAAABAABJzQnCgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyNi0wMS0xNFQwMDo1MTo1NyswMDowMOnKzHgAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjYtMDEtMTRUMDA6NTE6NTcrMDA6MDCYl3TEAAAAKHRFWHRkYXRlOnRpbWVzdGFtcAAyMDI2LTAxLTE0VDAwOjUxOjU3KzAwOjAwz4JVGwAAAABJRU5ErkJggg==";
-// Small 2x2 blue JPEG image (base64) - generated with ImageMagick
const TINY_JPEG =
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAACAAIDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAVAQEBAAAAAAAAAAAAAAAAAAAGCf/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AD3VTB3/2Q==";
-// 100x100 gray PNG
const MEDIUM_PNG_100x100 =
"iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAAAAABVicqIAAAAAmJLR0QA/4ePzL8AAAAHdElNRQfqAQ4AMzkN2iH/AAAAP0lEQVRo3u3NQQEAAAQEMASXXYrz2gqst/Lm4ZBIJBKJRCKRSCQSiUQikUgkEolEIpFIJBKJRCKRSCQSiSTsAP1cAUZeKtreAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDI2LTAxLTE0VDAwOjUxOjU3KzAwOjAw6crMeAAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyNi0wMS0xNFQwMDo1MTo1NyswMDowMJiXdMQAAAAodEVYdGRhdGU6dGltZXN0YW1wADIwMjYtMDEtMTRUMDA6NTE6NTcrMDA6MDDPglUbAAAAAElFTkSuQmCC";
-// 200x200 colored PNG
const LARGE_PNG_200x200 =
"iVBORw0KGgoAAAANSUhEUgAAAMgAAADIEAIAAAByquWKAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAGYktHRP///////wlY99wAAAAHdElNRQfqAQ4AMzqU03BFAAAEEElEQVR42u3dvWqUURSF4XXMRAyIhSAWQvwnWtjaWusFx9bW1kKD/wELESxEiBjDjJdwysOC57mCXW32+zGcGbtdACpsdi+T8Xz1GABzm91xMl6sHgNgblzcT/Y+rh4DYG6cv0/2H64eA2BOEgI1fHQHaoyzbXIwVo8BMCcJgRqSEKgxft9Lrn5aPQbA3Ph1klw7Wj0GwJwkBGpYWECN8fMiub63egyAORcWUMPCAmqMH3eTG59XjwEwN76/S24+Wj0GwJwkBGpYWECN8e1fcmuzegyAORcWUMPCAmqM09vJ4dfVYwDMjS9vkzuPV48BMCcJgRqeSAZqjA/nyYP91WMAzElCoIYkBGqMk8Pk6HT1GABzm+3L5JIkBApIQqCGj+5AjfHmb/Lk8uoxAOYkIVBDEgI1LCygxmZ7nFyShEABFxZQw8ICaozXf5KnV1aPATDnwgJqWFhADQsLqOFnDUANFxZQw8ICaoxXZ8mzg9VjAMy5sIAaFhZQw3tYQA1/QgHUkIRADUkI1JCEQA1JCNSQhEANFxZQwzcsoIYkBGpIQqCGJARqSEKghiQEalhYQA1/QgHUcGEBNSwsoIYkBGq4sIAaFhZQw8ICaviGBdRwYQE1LCyghiQEariwgBoWFlDDe1hADS+OAjUkIVBDEgI1JCFQQxICNSQhUMOFBdTwDQuoIQmBGpIQqCEJgRqSEKghCYEaFhZQw4ujQA0XFlDDwgJqSEKghgsLqGFhATUsLKCGb1hADRcWUMPCAmpIQqCGCwuoYWEBNbyHBdTw4ihQQxICNSQhUEMSAjUkIVBDEgI1XFhADd+wgBqSEKghCYEakhCoIQmBGpIQqGFhATW8OArUcGEBNSwsoIYkBGq4sIAaFhZQw8ICaviGBdRwYQE1LCyghiQEariwgBoWFlDDe1hADS+OAjUkIVBDEgI1JCFQQxICNSQhUMOFBdTwDQuoIQmBGpIQqCEJgRqSEKghCYEa49lB8ups9RgAc14cBWpIQqCGhQXUkIRADRcWUMPCAmqMp1eS139WjwEw5xsWUEMSAjUsLKCGJARquLCAGhYWUGM8uZy8+bt6DIA5L44CNSQhUMMTyUCNcXSanByuHgNgThICNSQhUGM82E8+nK8eA2DOzxqAGpIQqDHuPE6+vF09BsDcOPyanN5ePQbAnCQEavgdFlBj3Nok3/6tHgNgzoujQA1JCNQYNx8l39+tHgNgbtz4nPy4u3oMgDlJCNSwsIAa4/pe8vNi9RgAc37WANSQhECNce0o+XWyegyAuXH1U/L73uoxAOYkIVDDwgJqjIORnG1XjwEw508ogBqSEKgx9h8m5+9XjwEwN/Y+Jhf3V48BMCcJgRpjPE+2x6vHAJgbSbLbrR4DYO4/GqiSgXN+ksgAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjYtMDEtMTRUMDA6NTE6NTcrMDA6MDDpysx4AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDI2LTAxLTE0VDAwOjUxOjU3KzAwOjAwmJd0xAAAACh0RVh0ZGF0ZTp0aW1lc3RhbXAAMjAyNi0wMS0xNFQwMDo1MTo1NyswMDowMM+CVRsAAAAASUVORK5CYII=";
@@ -34,9 +26,7 @@ describe("convertToPng", () => {
const result = await convertToPng(TINY_JPEG, "image/jpeg");
expect(result).not.toBeNull();
expect(result!.mimeType).toBe("image/png");
- // Result should be valid base64
expect(() => Buffer.from(result!.data, "base64")).not.toThrow();
- // PNG magic bytes
const buffer = Buffer.from(result!.data, "base64");
expect(buffer[0]).toBe(0x89);
expect(buffer[1]).toBe(0x50); // 'P'
@@ -79,13 +69,11 @@ describe("resizeImage", () => {
const originalBuffer = Buffer.from(LARGE_PNG_200x200, "base64");
const originalSize = originalBuffer.length;
- // Set maxBytes to less than the original encoded image size
const result = await resizeImage(
{ type: "image", data: LARGE_PNG_200x200, mimeType: "image/png" },
{ maxWidth: 2000, maxHeight: 2000, maxBytes: Math.floor(LARGE_PNG_200x200.length * 0.9) },
);
- // Should have tried to reduce size
expect(result).not.toBeNull();
const resultBuffer = Buffer.from(result!.data, "base64");
expect(resultBuffer.length).toBeLessThan(originalSize);
diff --git a/packages/coding-agent/test/interactive-mode-effort-command.test.ts b/packages/coding-agent/test/interactive-mode-effort-command.test.ts
index 12a7e5a2c2..2fd0ae6b0d 100644
--- a/packages/coding-agent/test/interactive-mode-effort-command.test.ts
+++ b/packages/coding-agent/test/interactive-mode-effort-command.test.ts
@@ -284,7 +284,6 @@ describe("InteractiveMode /effort", () => {
expect(patch.serviceTier).toBe("priority");
expect(patch.availableThinkingLevels).toContain("high");
expect(patch.availableThinkingLevels.length).toBeGreaterThan(1);
- // Provider rebuild keeps the /effort argument hint in sync with the model.
expect(setupAutocompleteProvider).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/coding-agent/test/ipython-cell-diff.test.ts b/packages/coding-agent/test/ipython-cell-diff.test.ts
index 1492f4a0fb..6441b7d8ed 100644
--- a/packages/coding-agent/test/ipython-cell-diff.test.ts
+++ b/packages/coding-agent/test/ipython-cell-diff.test.ts
@@ -47,7 +47,6 @@ describe("IPythonCellComponent diff rendering", () => {
details: {
status: "ok",
durationMs: 12,
- // IPython reprs the returned string, so the confirmation arrives quoted.
result: "'Edited sample.py'",
diffs: [{ path: "sample.py", oldStr: "alpha\ngamma\ndelta", newStr: "alpha\nGAMMA\ndelta", startLine: 10 }],
},
@@ -57,17 +56,13 @@ describe("IPythonCellComponent diff rendering", () => {
editDiffsExpanded: true,
});
- // Header carries the path (no "edit" label) and the +/- line counts.
expect(out).toContain("sample.py");
expect(out).not.toMatch(/edit sample\.py/);
expect(out).toMatch(/\+1\s+-1/);
- // Removed line keeps the old line number; added line the new one.
expect(out).toMatch(/11 - .*gamma/);
expect(out).toMatch(/11 \+ .*GAMMA/);
expect(out).toMatch(/10 .*alpha/);
- // The redundant "Edited sample.py" confirmation must not render as its own line.
expect(out.split("\n").some((line) => /^\s*'?Edited sample\.py'?\s*$/.test(line.trim()))).toBe(false);
- // Expanded edit cells still show the full source that produced the diff.
expect(out).toContain('await edit(path="sample.py", old_str="gamma", new_str="GAMMA")');
});
@@ -88,7 +83,6 @@ describe("IPythonCellComponent diff rendering", () => {
const collapsedWithDiffs = renderCell({ ...state, expanded: false, editDiffsExpanded: true });
expect(collapsedWithDiffs).toMatch(/11 - .*gamma/);
expect(collapsedWithDiffs).toMatch(/11 \+ .*GAMMA/);
- // The cell stays collapsed otherwise: no code body beyond the summary preview, no stdout.
expect(collapsedWithDiffs).not.toContain('print("edit-done-marker")');
expect(collapsedWithDiffs).not.toContain("unrelated stdout line");
@@ -116,7 +110,6 @@ describe("IPythonCellComponent diff rendering", () => {
}).render(width);
const diffRows = lines.filter((line) => /alpha|gamma|GAMMA/.test(stripAnsi(line)));
expect(diffRows.length).toBeGreaterThan(0);
- // Each changed row is a background block spanning the full width.
expect(diffRows.every((line) => visibleWidth(line) === width)).toBe(true);
expect(diffRows.some(hasBackground)).toBe(true);
});
@@ -134,8 +127,6 @@ describe("IPythonCellComponent diff rendering", () => {
const hiddenSummary = hidden.find((l) => l.includes("╰─ a.ts"));
expect(hiddenSummary).toMatch(/^ {4}╰─ a\.ts \+1 -1 · .*to expand\)$/);
- // The ctrl+j hint is not owned by the latest tool row: it stays visible
- // on rows whose ctrl+o hint is suppressed (showExpandHint=false).
const notLatest = renderCell({ ...state, editDiffsExpanded: false, showExpandHint: false }).split("\n");
expect(notLatest.find((l) => l.includes("╰─ a.ts"))).toMatch(/to expand\)$/);
expect(hidden.some((l) => /1 - .*x/.test(l))).toBe(false);
@@ -143,7 +134,6 @@ describe("IPythonCellComponent diff rendering", () => {
const shown = renderCell({ ...state, editDiffsExpanded: true }).split("\n");
const summary = shown.find((l) => l.includes("╰─ a.ts"));
expect(summary).toMatch(/^ {4}╰─ a\.ts \+1 -1 · .*to collapse\)$/);
- // Diff rows align with the summary's text column (after the ` ╰─ ` gutter).
const textColumn = (summary ?? "").indexOf("a.ts");
const removed = shown.find((l) => /1 - .*x/.test(l));
const added = shown.find((l) => /1 \+ .*X/.test(l));
@@ -152,7 +142,6 @@ describe("IPythonCellComponent diff rendering", () => {
for (const row of [removed ?? "", added ?? ""]) {
expect(row.startsWith(" ".repeat(textColumn))).toBe(true);
}
- // Toggling only adds the diff rows underneath; the summary line is stable.
expect(shown.filter((l) => !/\d+ [-+ ] /.test(l) && !l.includes("⋮")).length).toBe(hidden.length);
});
@@ -202,7 +191,6 @@ describe("IPythonCellComponent diff rendering", () => {
expanded: false,
editDiffsExpanded: false,
});
- // Same cwd-relative output the built-in edit tool's formatFileChangePath gives.
expect(out).toContain("╰─ same.ts +1 -1");
} finally {
rmSync(root, { recursive: true, force: true });
@@ -221,13 +209,10 @@ describe("IPythonCellComponent diff rendering", () => {
editDiffsExpanded: true,
}).render(width);
- // No rendered row may exceed the terminal width (the TUI throws if one does).
expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
- // The full content survives across the wrapped rows (nothing truncated away).
const joined = lines.map(stripAnsi).join("");
expect(joined).toContain("arg0");
expect(joined).toContain("arg29");
- // The added line spilled onto at least one continuation row.
expect(lines.filter((line) => /arg\d/.test(stripAnsi(line))).length).toBeGreaterThan(1);
});
@@ -245,7 +230,6 @@ describe("IPythonCellComponent diff rendering", () => {
expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
const summary = lines.map(stripAnsi).find((line) => line.includes("…"));
expect(summary).toBeDefined();
- // The +/- counts and hint survive truncation; only the path is shortened.
expect(summary).toMatch(/\+1 -1 · /);
});
@@ -266,7 +250,6 @@ describe("IPythonCellComponent diff rendering", () => {
}).render(120);
const plain = lines.map(stripAnsi);
const hinted = plain.filter((line) => line.includes("to collapse") && /[+]\d+ -\d+/.test(line));
- // Exactly one file row (the last file's) carries the ctrl+j cue.
expect(hinted).toHaveLength(1);
expect(hinted[0]).toContain("b.ts");
});
@@ -376,7 +359,6 @@ describe("IPythonCellComponent diff rendering", () => {
argsComplete: true,
expanded: false,
});
- // No diffs → the collapsed view stays a single line; output hides behind expand.
expect(collapsed.split("\n")).toHaveLength(1);
expect(collapsed).toContain("to expand");
expect(collapsed).not.toContain("world");
@@ -398,10 +380,8 @@ describe("IPythonCellComponent diff rendering", () => {
executionStarted: true,
argsComplete: true,
});
- // One consolidated header for the file, with summed counts.
expect(out.split("\n").filter((l) => l.includes("app.py")).length).toBe(1);
expect(out).toMatch(/app\.py\s+\+3\s+-3/);
- // Hunks are separated by the vertical-ellipsis marker.
expect((out.match(/⋮/g) ?? []).length).toBe(2);
});
@@ -416,18 +396,14 @@ describe("IPythonCellComponent diff rendering", () => {
const collapsed = new IPythonCellComponent({ ...state, expanded: false }).render(80);
const expanded = new IPythonCellComponent({ ...state, expanded: true }).render(80);
- // Top line is unchanged through the duration; only the trailing hint flips
- // "to expand" → "to collapse", so nothing before it can shift.
expect(stripAnsi(collapsed[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · \(.*to expand\)$/);
expect(stripAnsi(expanded[0])).toMatch(/^ ✓ python · .* · ↑ 1 ↓ 1 lines · 780\.0s · \(.*to collapse\)$/);
const upToHint = (line: string) => stripAnsi(line).replace(/· \([^·]*to (expand|collapse)\)$/, "");
expect(upToHint(expanded[0])).toBe(upToHint(collapsed[0]));
- // No separate "python · done · 780.0s" header line below the top line.
const stripped = expanded.map(stripAnsi);
expect(stripped.filter((l) => /python · done/.test(l)).length).toBe(0);
- // Expanding only attaches code + output below, backgroundless like the top.
expect(stripped.join("\n")).toContain("print(55)");
expect(stripped.join("\n")).toContain("55");
expect(expanded.some(hasBackground)).toBe(false);
diff --git a/packages/coding-agent/test/ipython-cell-wrap.test.ts b/packages/coding-agent/test/ipython-cell-wrap.test.ts
index b9c0fb1ce9..d70cef26d8 100644
--- a/packages/coding-agent/test/ipython-cell-wrap.test.ts
+++ b/packages/coding-agent/test/ipython-cell-wrap.test.ts
@@ -5,7 +5,6 @@ import { initTheme } from "../src/modes/interactive/theme/theme.js";
type CellState = ConstructorParameters<typeof IPythonCellComponent>[0];
-// True when `line` ends with a foreground color still open (a leak into the padding).
function foregroundLeftOpen(line: string): boolean {
let fg = false;
for (const match of line.matchAll(/\x1b\[([0-9;]*)m/g)) {
@@ -15,7 +14,6 @@ function foregroundLeftOpen(line: string): boolean {
if (code === 0 || code === 39) {
fg = false;
} else if (code === 38) {
- // Skip the color data of 38;5;n / 38;2;r;g;b so a component isn't read as a code.
fg = true;
const mode = Number(params[i + 1]);
i += mode === 2 ? 4 : mode === 5 ? 2 : 1;
diff --git a/packages/coding-agent/test/kernel-attach-image-skill.test.ts b/packages/coding-agent/test/kernel-attach-image-skill.test.ts
index b47be17c3a..6ece9e3ba2 100644
--- a/packages/coding-agent/test/kernel-attach-image-skill.test.ts
+++ b/packages/coding-agent/test/kernel-attach-image-skill.test.ts
@@ -6,7 +6,6 @@ import { getBundledSkillsDir } from "../src/config.js";
import type { PythonSkillRuntimeInfo } from "../src/core/skills.js";
import { IpythonKernelProvisioner, imageBlocksFromAttachments } from "../src/core/tools/ipython.js";
-// 1x1 transparent PNG.
const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";
function bundledAttachImageSkill(): PythonSkillRuntimeInfo {
@@ -263,7 +262,6 @@ except ValueError as error:
it("fails the cell loudly when an emitted attachment exceeds the size cap", async () => {
provisioner = new IpythonKernelProvisioner(tempDir, { pythonSkills: [] });
const manager = await provisioner.ensure();
- // Emit an oversized attachment directly, bypassing the skill's own cap.
const result = await manager.execute(`
from IPython.display import display
display({"application/vnd.prime-agent.attachment+json": {"mime_type": "image/png", "data": "A" * 10_000_001}}, raw=True)
diff --git a/packages/coding-agent/test/kernel-fork-server.test.ts b/packages/coding-agent/test/kernel-fork-server.test.ts
index 2fd472593c..4310326cab 100644
--- a/packages/coding-agent/test/kernel-fork-server.test.ts
+++ b/packages/coding-agent/test/kernel-fork-server.test.ts
@@ -26,8 +26,6 @@ describe("fork-server gating", () => {
it("degrades to ForkServerUnavailable when the interpreter can't start", async () => {
if (process.platform !== "linux") return;
- // The spawn errors immediately (ENOENT), so markDead fails the ready promise
- // fast rather than waiting out the ready timeout.
await expect(
forkKernel("/nonexistent/python-binary", { connectionPath: "/tmp/nope/connection.json" }),
).rejects.toBeInstanceOf(ForkServerUnavailable);
diff --git a/packages/coding-agent/test/kernel-goal-skill.test.ts b/packages/coding-agent/test/kernel-goal-skill.test.ts
index 239ffa3518..8aef83c0de 100644
--- a/packages/coding-agent/test/kernel-goal-skill.test.ts
+++ b/packages/coding-agent/test/kernel-goal-skill.test.ts
@@ -113,7 +113,6 @@ except RuntimeError as error:
'RuntimeError: host request type "goal.get" is not available in this session',
);
- // A "type" key smuggled into the payload must not reroute the request.
const reroute = await manager.execute(`
import rlm as _rlm
try:
diff --git a/packages/coding-agent/test/kernel-state-roundtrip.test.ts b/packages/coding-agent/test/kernel-state-roundtrip.test.ts
index b4d767c4a2..a4dcce3514 100644
--- a/packages/coding-agent/test/kernel-state-roundtrip.test.ts
+++ b/packages/coding-agent/test/kernel-state-roundtrip.test.ts
@@ -5,7 +5,6 @@ import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { KernelManager } from "../src/core/kernel/index.js";
-/** Find a python that can launch an ipykernel and has dill, or null to skip. */
function resolveKernelPython(): string | null {
const candidates = [
process.env.PRIME_AGENT_KERNEL_PYTHON,
@@ -98,8 +97,6 @@ describeIfKernel("kernel state snapshot round-trip (real kernel)", { tags: ["ker
const cfg = { path, manifestPath: join(dir, "shadow.json") };
const writer = new KernelManager({ python: python as string, cwd: dir, snapshot: cfg });
try {
- // Shadow builtins the snapshot helper itself relies on (list/print) plus a
- // plain builtin-named var (id); the helper must still run and capture them.
await writer.execute("list = [10, 20]\nprint = 'shadowed'\nid = 99");
const snap = await writer.snapshotState();
expect(snap).not.toBeNull();
@@ -127,11 +124,9 @@ describeIfKernel("kernel state snapshot round-trip (real kernel)", { tags: ["ker
snapshot: { path: badPath, manifestPath: join(badDir, "corrupt.json") },
});
try {
- // A valid dill file that deserializes to a list, not the expected name->bytes dict.
await manager.execute(`import dill\nopen(${JSON.stringify(badPath)}, "wb").write(dill.dumps([1, 2, 3]))`);
const restore = await manager.restoreState();
expect(restore).toBeNull();
- // The kernel must still be usable after a failed restore.
const echo = await manager.execute("print('alive')");
expect(echo.stdout.trim()).toBe("alive");
} finally {
@@ -144,12 +139,10 @@ describeIfKernel("kernel state snapshot round-trip (real kernel)", { tags: ["ker
const listDir = mkdtempSync(join(tmpdir(), "prime-agent-state-list-"));
const manager = new KernelManager({ python: python as string, cwd: listDir });
try {
- // A fresh, unstarted kernel reports no names.
expect(await manager.listNamespaceNames()).toBeNull();
await manager.execute("alpha = 1\ndef helper(n):\n return n\n_hidden = 2\nrlm = object()");
const names = await manager.listNamespaceNames();
expect(names).toEqual(expect.arrayContaining(["alpha", "helper"]));
- // Underscore-prefixed names and the live rlm handle must be filtered out.
expect(names).not.toContain("_hidden");
expect(names).not.toContain("rlm");
} finally {
diff --git a/packages/coding-agent/test/kernel-state-snapshot.test.ts b/packages/coding-agent/test/kernel-state-snapshot.test.ts
index 5aee07f717..7f2719d025 100644
--- a/packages/coding-agent/test/kernel-state-snapshot.test.ts
+++ b/packages/coding-agent/test/kernel-state-snapshot.test.ts
@@ -10,7 +10,6 @@ import {
snapshotPathIn,
} from "../src/core/kernel/state-snapshot.js";
-// Kept in sync with the marker the Python helpers print.
const MARKER = "__PRIME_AGENT_KERNEL_STATE__";
describe("kernel state snapshot paths", () => {
@@ -95,7 +94,6 @@ describe("buildSnapshotCode", () => {
it("uses dill, an atomic write, and skips internal handles", () => {
expect(code).toContain("import dill");
expect(code).toContain("os.replace");
- // rlm and the IPython display names must never be serialized.
expect(code).toContain('"rlm"');
expect(code).toContain(`print(${JSON.stringify(MARKER)}`);
});
diff --git a/packages/coding-agent/test/legacy-rlm-host-types.d.ts b/packages/coding-agent/test/legacy-rlm-host-types.d.ts
index 0c8b103f35..efbcb347ab 100644
--- a/packages/coding-agent/test/legacy-rlm-host-types.d.ts
+++ b/packages/coding-agent/test/legacy-rlm-host-types.d.ts
@@ -2,7 +2,6 @@ import type { CreateRlmSubagentRuntimeOptions, RlmSubagentRuntime } from "../src
declare module "../src/core/rlm-runtime.js" {
interface SubagentRuntimeHost {
- /** Compile-time compatibility for pre-fire-and-forget tests only. */
releaseRlmSubagentRuntime?: (
runtime: RlmSubagentRuntime,
options: CreateRlmSubagentRuntimeOptions,
diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.ts
index e4c45dd8a6..c328106e2e 100644
--- a/packages/coding-agent/test/marquee-components.test.ts
+++ b/packages/coding-agent/test/marquee-components.test.ts
@@ -91,7 +91,6 @@ describe("marquee TUI components", () => {
const component = new IPythonCellComponent(state);
const collapsed = await renderInVirtualTerminal(component);
- // Collapsed: marker + the bash command + duration + error name, on one line.
expect(collapsed).toContain("bash");
expect(collapsed).toContain("echo hi");
expect(collapsed).not.toContain("%%bash");
@@ -228,7 +227,6 @@ describe("marquee TUI components", () => {
const component = new IPythonCellComponent(state);
const collapsed = stripAnsi(component.render(100).join("\n"));
- // Collapsed python shows a one-line preview, the input line count, and the expand hint.
expect(collapsed).toContain("line_0 = 0");
expect(collapsed).not.toContain("line_7 = 7");
expect(collapsed).toContain("↑ 8");
@@ -253,7 +251,6 @@ describe("marquee TUI components", () => {
});
const collapsed = stripAnsi(component.render(100).join("\n"));
- // A single status line carries both counts and exactly one expand hint.
expect(collapsed).toContain("↑ 8 ↓ 8 lines");
expect(collapsed.match(/to expand/g)?.length).toBe(1);
});
@@ -270,7 +267,6 @@ describe("marquee TUI components", () => {
details: { status: "ok", durationMs: 15 },
executionStarted: true,
argsComplete: true,
- // Expanded so the long code/output lines wrap and reflow with width.
expanded: true,
};
const component = new IPythonCellComponent(state);
@@ -422,8 +418,6 @@ describe("marquee TUI components", () => {
isError: false,
});
- // Collapsed: routed through the cell renderer (a status line), not the
- // generic JSON arg dump.
const collapsedLines = component.render(100);
const collapsed = stripAnsi(collapsedLines.join("\n"));
expect(collapsed).toContain("python");
@@ -432,8 +426,6 @@ describe("marquee TUI components", () => {
expect(collapsed).not.toContain("ipython");
expect(collapsed).not.toContain('"code"');
- // Expanded keeps the same status content while updating the toggle hint,
- // then attaches the code and output below it, backgroundless like the top line.
component.setExpanded(true);
const expandedLines = component.render(100);
const expanded = stripAnsi(expandedLines.join("\n"));
diff --git a/packages/coding-agent/test/mcp-manager.test.ts b/packages/coding-agent/test/mcp-manager.test.ts
index 366a207ee5..92953fb396 100644
--- a/packages/coding-agent/test/mcp-manager.test.ts
+++ b/packages/coding-agent/test/mcp-manager.test.ts
@@ -77,8 +77,6 @@ describe("McpManager", () => {
const handlers = manager.hostHandlers();
expect(Object.keys(handlers).sort()).toEqual(["mcp.config", "mcp.refresh"]);
- // refresh with no credentials fails (so the kernel reports a refresh error,
- // not a false success), and a missing server arg is rejected.
await expect(handlers["mcp.refresh"]({ server: "linear" })).rejects.toThrow("Could not refresh");
await expect(handlers["mcp.refresh"]({})).rejects.toThrow("requires a server");
});
@@ -113,7 +111,6 @@ describe("McpManager", () => {
});
it("does not treat an oauth override of a catalog name as authed via the official stored cred", () => {
- // Pre-existing official Linear cred from a prior login.
authStorage.set("mcp:linear", {
type: "oauth",
access: "official",
@@ -124,7 +121,6 @@ describe("McpManager", () => {
authStorage,
getUserServers: () => ({ linear: { type: "http", url: "https://proxy.test/mcp", oauth: true } }),
});
- // Must NOT be enabled — else the official token would be sent to the override URL.
expect(manager.listStatus().find((s) => s.server === "linear")?.enabled).toBe(false);
});
@@ -161,7 +157,6 @@ describe("McpManager", () => {
getUserServers: () => ({ linear: { type: "http", url: "https://proxy.test/mcp" } }),
});
void manager;
- // Built-in linear provider must be gone so we don't send the official token to the override URL.
expect(getOAuthProvider("mcp:linear")).toBeUndefined();
});
diff --git a/packages/coding-agent/test/model-registry.test.ts b/packages/coding-agent/test/model-registry.test.ts
index dc9ec2b43a..4add0e701b 100644
--- a/packages/coding-agent/test/model-registry.test.ts
+++ b/packages/coding-agent/test/model-registry.test.ts
@@ -27,7 +27,6 @@ describe("ModelRegistry", () => {
clearApiKeyCache();
});
- /** Create minimal provider config */
function providerConfig(
baseUrl: string,
models: Array<{ id: string; name?: string }>,
@@ -61,12 +60,10 @@ describe("ModelRegistry", () => {
return value.replace(/\\/g, "/").replace(/"/g, '\\"');
}
- /** Create a baseUrl-only override (no custom models) */
function overrideConfig(baseUrl: string, headers?: Record<string, string>) {
return { baseUrl, ...(headers && { headers }) };
}
- /** Write raw providers config (for mixed override/replacement scenarios) */
function writeRawModelsJson(providers: Record<string, unknown>) {
writeFileSync(modelsJsonPath, JSON.stringify({ providers }));
}
@@ -97,7 +94,6 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
const anthropicModels = getModelsForProvider(registry, "anthropic");
- // Should have multiple built-in models, not just one
expect(anthropicModels.length).toBeGreaterThan(1);
expect(anthropicModels.some((m) => m.id.includes("claude"))).toBe(true);
});
@@ -110,7 +106,6 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
const anthropicModels = getModelsForProvider(registry, "anthropic");
- // All models should have the new baseUrl
for (const model of anthropicModels) {
expect(model.baseUrl).toBe("https://my-proxy.example.com/v1");
}
@@ -186,16 +181,13 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
const googleModels = getModelsForProvider(registry, "google");
- // Google models should still have their original baseUrl
expect(googleModels.length).toBeGreaterThan(0);
expect(googleModels[0].baseUrl).not.toBe("https://my-proxy.example.com/v1");
});
test("can mix baseUrl override and models merge", () => {
writeRawModelsJson({
- // baseUrl-only for anthropic
anthropic: overrideConfig("https://anthropic-proxy.example.com/v1"),
- // Add custom model for google (merged with built-ins)
google: providerConfig(
"https://google-proxy.example.com/v1",
[{ id: "gemini-custom" }],
@@ -205,12 +197,10 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
- // Anthropic: multiple built-in models with new baseUrl
const anthropicModels = getModelsForProvider(registry, "anthropic");
expect(anthropicModels.length).toBeGreaterThan(1);
expect(anthropicModels[0].baseUrl).toBe("https://anthropic-proxy.example.com/v1");
- // Google: built-ins plus custom model
const googleModels = getModelsForProvider(registry, "google");
expect(googleModels.length).toBeGreaterThan(1);
expect(googleModels.some((m) => m.id === "gemini-custom")).toBe(true);
@@ -224,7 +214,6 @@ describe("ModelRegistry", () => {
expect(getModelsForProvider(registry, "anthropic")[0].baseUrl).toBe("https://first-proxy.example.com/v1");
- // Update and refresh
writeRawModelsJson({
anthropic: overrideConfig("https://second-proxy.example.com/v1"),
});
@@ -236,8 +225,6 @@ describe("ModelRegistry", () => {
describe("custom models merge behavior", () => {
test("built-in provider custom models inherit api and baseUrl without explicit fields", () => {
- // Built-in providers already have api/baseUrl on every model, and auth
- // comes from env vars / auth storage. No need to specify them.
writeRawModelsJson({
openrouter: {
models: [
@@ -590,7 +577,6 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
expect(getModelsForProvider(registry, "anthropic").some((m) => m.id === "claude-custom")).toBe(true);
- // Update and refresh
writeModelsJson({
anthropic: providerConfig("https://second-proxy.example.com/v1", [{ id: "claude-custom-2" }]),
});
@@ -609,7 +595,6 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
expect(getModelsForProvider(registry, "anthropic").some((m) => m.id === "claude-custom")).toBe(true);
- // Remove custom models and refresh
writeModelsJson({});
registry.refresh();
@@ -637,7 +622,6 @@ describe("ModelRegistry", () => {
const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
expect(sonnet?.name).toBe("Custom Sonnet Name");
- // Other models should be unchanged
const opus = models.find((m) => m.id === "anthropic/claude-opus-4");
expect(opus?.name).not.toBe("Custom Sonnet Name");
});
@@ -680,7 +664,6 @@ describe("ModelRegistry", () => {
const models = getModelsForProvider(registry, "openrouter");
const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
- // Should have both the new routing AND preserve other compat settings
const compat = sonnet?.compat as OpenAICompletionsCompat | undefined;
expect(compat?.openRouterRouting).toEqual({ order: ["anthropic", "together"] });
});
@@ -727,11 +710,9 @@ describe("ModelRegistry", () => {
const models = getModelsForProvider(registry, "openrouter");
const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
- // Both overrides should apply
expect(sonnet?.baseUrl).toBe("https://my-proxy.example.com/v1");
expect(sonnet?.name).toBe("Proxied Sonnet");
- // Other models should have the baseUrl but not the name override
const opus = models.find((m) => m.id === "anthropic/claude-opus-4");
expect(opus?.baseUrl).toBe("https://my-proxy.example.com/v1");
expect(opus?.name).not.toBe("Proxied Sonnet");
@@ -751,9 +732,7 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
const models = getModelsForProvider(registry, "openrouter");
- // Should not create a new model
expect(models.find((m) => m.id === "nonexistent/model-id")).toBeUndefined();
- // Should not crash or show error
expect(registry.getError()).toBeUndefined();
});
@@ -772,9 +751,7 @@ describe("ModelRegistry", () => {
const models = getModelsForProvider(registry, "openrouter");
const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
- // Input cost should be overridden
expect(sonnet?.cost.input).toBe(99);
- // Other cost fields should be preserved from built-in
expect(sonnet?.cost.output).toBeGreaterThan(0);
});
@@ -817,7 +794,6 @@ describe("ModelRegistry", () => {
getModelsForProvider(registry, "openrouter").find((m) => m.id === "anthropic/claude-sonnet-4")?.name,
).toBe("First Name");
- // Update and refresh
writeRawModelsJson({
openrouter: {
modelOverrides: {
@@ -851,7 +827,6 @@ describe("ModelRegistry", () => {
)?.name;
expect(customName).toBe("Custom Name");
- // Remove override and refresh
writeRawModelsJson({});
registry.refresh();
@@ -1159,7 +1134,6 @@ describe("ModelRegistry", () => {
const registry = ModelRegistry.create(authStorage, modelsJsonPath);
expect(registry.getAvailable().some((m) => m.provider === "prime-inference")).toBe(false);
- // Simulate the UI process saving a login while this registry lives in the daemon.
const otherProcessAuth = AuthStorage.create(join(tempDir, "auth.json"));
otherProcessAuth.set("prime-inference", { type: "api_key", key: "test-key" });
@@ -1174,7 +1148,6 @@ describe("ModelRegistry", () => {
});
describe("API key resolution", () => {
- /** Create provider config with custom apiKey */
function providerWithApiKey(apiKey: string) {
return {
baseUrl: "https://example.com/v1",
@@ -1283,7 +1256,6 @@ describe("ModelRegistry", () => {
});
test("apiKey as literal value is used directly when not an env var", async () => {
- // Make sure this isn't an env var
delete process.env.literal_api_key_value;
writeRawModelsJson({
diff --git a/packages/coding-agent/test/model-resolver.test.ts b/packages/coding-agent/test/model-resolver.test.ts
index f62be8a262..bb56a730bd 100644
--- a/packages/coding-agent/test/model-resolver.test.ts
+++ b/packages/coding-agent/test/model-resolver.test.ts
@@ -8,7 +8,6 @@ import {
resolveModelScopeFromModels,
} from "../src/core/model-resolver.js";
-// Mock models for testing
const mockModels: Model<"anthropic-messages">[] = [
{
id: "claude-sonnet-4-5",
@@ -36,7 +35,6 @@ const mockModels: Model<"anthropic-messages">[] = [
},
];
-// Mock OpenRouter models with colons in IDs
const mockOpenRouterModels: Model<"anthropic-messages">[] = [
{
id: "qwen/qwen3-coder:exacto",
@@ -239,7 +237,6 @@ describe("parseModelPattern", () => {
describe("edge cases", () => {
test("empty pattern matches via partial matching", () => {
- // Empty string is included in all model IDs, so partial matching finds a match
const result = parseModelPattern("", allModels);
expect(result.model).not.toBeNull();
expect(result.thinkingLevel).toBeUndefined();
@@ -247,8 +244,6 @@ describe("parseModelPattern", () => {
test("pattern ending with colon treats empty suffix as invalid", () => {
const result = parseModelPattern("sonnet:", allModels);
- // Empty string after colon is not a valid thinking level
- // So it tries to match "sonnet:" which won't match, then tries "sonnet"
expect(result.model?.id).toBe("claude-sonnet-4-5");
expect(result.warning).toContain("Invalid thinking level");
});
@@ -365,8 +360,6 @@ describe("resolveCliModel", () => {
});
test("prefers provider/model split over gateway model with matching id", () => {
- // When a user writes "zai/glm-5", and both a zai provider model (id: "glm-5")
- // and a gateway model (id: "zai/glm-5") exist, prefer the zai provider model.
const zaiModel: Model<"anthropic-messages"> = {
id: "glm-5",
name: "GLM-5",
diff --git a/packages/coding-agent/test/no-silent-catch.test.ts b/packages/coding-agent/test/no-silent-catch.test.ts
index 8ce2bb43fa..5f3ae54212 100644
--- a/packages/coding-agent/test/no-silent-catch.test.ts
+++ b/packages/coding-agent/test/no-silent-catch.test.ts
@@ -2,12 +2,6 @@ import { readdirSync, readFileSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { describe, expect, test } from "vitest";
-/**
- * Guardrail for ENG-4422: errors must never be swallowed without a trace.
- * An empty `catch {}` is only acceptable with a comment explaining why the
- * swallow is intentional (which this scan permits), or better, a log call.
- */
-
const REPO_ROOT = resolve(__dirname, "..", "..", "..");
const EMPTY_CATCH = /catch(\s*\([^)]*\))?\s*\{\s*\}/g;
diff --git a/packages/coding-agent/test/oauth-selector.test.ts b/packages/coding-agent/test/oauth-selector.test.ts
index fbce958bdd..5921e3afb0 100644
--- a/packages/coding-agent/test/oauth-selector.test.ts
+++ b/packages/coding-agent/test/oauth-selector.test.ts
@@ -410,14 +410,12 @@ describe("OAuthSelectorComponent", () => {
() => {},
);
- // Providers tab active first: provider shown, service hidden.
let output = stripAnsi(selector.render(120).join("\n"));
expect(output).toContain("Providers");
expect(output).toContain("MCP Connections");
expect(output).toContain("Anthropic");
expect(output).not.toContain("Serper");
- // Right arrow switches to the MCP Connections tab.
selector.handleInput("\x1b[C");
output = stripAnsi(selector.render(120).join("\n"));
expect(output).toContain("Serper (web search)");
diff --git a/packages/coding-agent/test/package-manager.test.ts b/packages/coding-agent/test/package-manager.test.ts
index a767677fc3..e0455c9380 100644
--- a/packages/coding-agent/test/package-manager.test.ts
+++ b/packages/coding-agent/test/package-manager.test.ts
@@ -26,7 +26,6 @@ class MockSpawnedProcess extends EventEmitter {
}
}
-// Helper to check if a resource is enabled
const isEnabled = (r: ResolvedResource, pathMatch: string, matchFn: "endsWith" | "includes" = "endsWith") => {
const normalizedPath = normalizeForMatch(r.path);
const normalizedMatch = normalizeForMatch(pathMatch);
@@ -116,7 +115,6 @@ Content`,
settingsManager.setSkillPaths(["skills"]);
const result = await packageManager.resolve();
- // Skills with SKILL.md are returned as file paths
expect(result.skills.some((r) => r.path === skillFile && r.enabled)).toBe(true);
});
@@ -213,8 +211,6 @@ Content`,
themes: 1,
});
- // Project auto-discovered has higher precedence than user auto-discovered,
- // so the surviving entry should be scoped to project.
expect(result.extensions[0].metadata.scope).toBe("project");
expect(result.skills[0].metadata.scope).toBe("project");
expect(result.prompts[0].metadata.scope).toBe("project");
@@ -241,7 +237,6 @@ Content`,
});
it("should resolve directory with package.json pi.extensions in extensions setting", async () => {
- // Create a package with pi.extensions in package.json
const pkgDir = join(tempDir, "my-extensions-pkg");
mkdirSync(join(pkgDir, "extensions"), { recursive: true });
writeFileSync(
@@ -257,12 +252,10 @@ Content`,
writeFileSync(join(pkgDir, "extensions", "cost.ts"), "export default function() {}");
writeFileSync(join(pkgDir, "extensions", "helper.ts"), "export const x = 1;"); // Not in manifest, shouldn't be loaded
- // Add the directory to extensions setting (not packages setting)
settingsManager.setExtensionPaths([pkgDir]);
const result = await packageManager.resolve();
- // Should find the extensions declared in package.json pi.extensions
expect(result.extensions.some((r) => r.path === join(pkgDir, "extensions", "clip.ts") && r.enabled)).toBe(
true,
);
@@ -270,7 +263,6 @@ Content`,
true,
);
- // Should NOT find helper.ts (not declared in manifest)
expect(result.extensions.some((r) => pathEndsWith(r.path, "helper.ts"))).toBe(false);
});
});
@@ -482,7 +474,6 @@ Content`,
const result = await packageManager.resolveExtensionSources([pkgDir]);
expect(result.extensions.some((r) => r.path === join(pkgDir, "src", "index.ts") && r.enabled)).toBe(true);
- // Skills with SKILL.md are returned as file paths
expect(result.skills.some((r) => r.path === join(pkgDir, "skills", "my-skill", "SKILL.md") && r.enabled)).toBe(
true,
);
@@ -522,10 +513,8 @@ Content`,
const extPath = join(tempDir, "ext.ts");
writeFileSync(extPath, "export default function() {}");
- // Local paths don't trigger install progress, but we can verify the callback is set
await packageManager.resolveExtensionSources([extPath]);
- // For now just verify no errors - npm/git would trigger actual events
expect(events.length).toBe(0);
});
});
@@ -718,16 +707,11 @@ Content`,
const events: ProgressEvent[] = [];
packageManager.setProgressCallback((event) => events.push(event));
- // Use public install method which emits progress events
try {
await packageManager.install("npm:[email protected]");
- } catch {
- // Expected to fail - package doesn't exist
- }
+ } catch {}
- // Should have emitted start event before failure
expect(events.some((e) => e.type === "start" && e.action === "install")).toBe(true);
- // Should have emitted error event
expect(events.some((e) => e.type === "error")).toBe(true);
});
@@ -738,12 +722,9 @@ Content`,
process.env.GIT_TERMINAL_PROMPT = "0";
try {
- // This should be parsed as a git source, not throw "unsupported"
try {
await packageManager.install("https://github.com/nonexistent/repo");
- } catch {
- // Expected to fail - repo doesn't exist
- }
+ } catch {}
} finally {
if (previousGitTerminalPrompt === undefined) {
delete process.env.GIT_TERMINAL_PROMPT;
@@ -752,7 +733,6 @@ Content`,
}
}
- // Should have attempted clone, not thrown unsupported error
expect(events.some((e) => e.type === "start" && e.action === "install")).toBe(true);
});
@@ -893,7 +873,6 @@ Content`,
const identity3 = (packageManager as any).getPackageIdentity("git:github.com/user/repo");
const identity4 = (packageManager as any).getPackageIdentity("https://github.com/user/repo.git");
- // All should have the same identity (normalized)
expect(identity1).toBe("git:github.com/user/repo");
expect(identity2).toBe("git:github.com/user/repo");
expect(identity3).toBe("git:github.com/user/repo");
@@ -905,16 +884,12 @@ Content`,
mkdirSync(join(pkgDir, "extensions"), { recursive: true });
writeFileSync(join(pkgDir, "extensions", "test.ts"), "export default function() {}");
- // Mock the package as if it were cloned from different URL formats
- // In reality, these would all point to the same local dir after install
settingsManager.setPackages([
"https://github.com/user/repo",
"git:github.com/user/repo",
"https://github.com/user/repo.git",
]);
- // Since these URLs don't actually exist and we can't clone them,
- // we verify they produce the same identity
const id1 = (packageManager as any).getPackageIdentity("https://github.com/user/repo");
const id2 = (packageManager as any).getPackageIdentity("git:github.com/user/repo");
const id3 = (packageManager as any).getPackageIdentity("https://github.com/user/repo.git");
@@ -924,7 +899,6 @@ Content`,
});
it("should handle HTTPS URLs with refs in resolve", async () => {
- // This tests that the ref is properly extracted and stored
const parsed = (packageManager as any).parseSource("https://github.com/user/repo@main");
expect(parsed.ref).toBe("main");
expect(parsed.pinned).toBe(true);
@@ -1090,8 +1064,6 @@ Content`,
describe("pattern filtering in package filters", () => {
it("should apply user filters on top of manifest filters (not replace)", async () => {
- // Manifest excludes baz.ts, user excludes bar.ts
- // Result should exclude BOTH
const pkgDir = join(tempDir, "layered-pkg");
mkdirSync(join(pkgDir, "extensions"), { recursive: true });
writeFileSync(join(pkgDir, "extensions", "foo.ts"), "export default function() {}");
@@ -1107,7 +1079,6 @@ Content`,
}),
);
- // User filter adds exclusion for bar.ts
settingsManager.setPackages([
{
source: pkgDir,
@@ -1119,11 +1090,8 @@ Content`,
]);
const result = await packageManager.resolve();
- // foo.ts should be included (not excluded by anyone)
expect(result.extensions.some((r) => isEnabled(r, "foo.ts"))).toBe(true);
- // bar.ts should be excluded (by user)
expect(result.extensions.some((r) => isDisabled(r, "bar.ts"))).toBe(true);
- // baz.ts should be excluded (by manifest)
expect(result.extensions.some((r) => pathEndsWith(r.path, "baz.ts"))).toBe(false);
});
@@ -1224,7 +1192,6 @@ Content`,
writeFileSync(join(extDir, "excluded.ts"), "export default function() {}");
writeFileSync(join(extDir, "force-back.ts"), "export default function() {}");
- // Exclude all, then force-include one back
settingsManager.setExtensionPaths(["extensions", "!extensions/*.ts", "+extensions/force-back.ts"]);
const result = await packageManager.resolve();
@@ -1287,7 +1254,6 @@ Content`,
writeFileSync(join(extDir, "a.ts"), "export default function() {}");
writeFileSync(join(extDir, "b.ts"), "export default function() {}");
- // Specifically exclude b.ts, then force it back
settingsManager.setExtensionPaths(["extensions", "!extensions/b.ts", "+extensions/b.ts"]);
const result = await packageManager.resolve();
@@ -1390,18 +1356,15 @@ Content`,
mkdirSync(join(pkgDir, "extensions"), { recursive: true });
writeFileSync(join(pkgDir, "extensions", "shared.ts"), "export default function() {}");
- // Same package in both global and project
settingsManager.setPackages([pkgDir]); // global
settingsManager.setProjectPackages([pkgDir]); // project
- // Debug: verify settings are stored correctly
const globalSettings = settingsManager.getGlobalSettings();
const projectSettings = settingsManager.getProjectSettings();
expect(globalSettings.packages).toEqual([pkgDir]);
expect(projectSettings.packages).toEqual([pkgDir]);
const result = await packageManager.resolve();
- // Should only appear once (deduped), with project scope
const sharedPaths = result.extensions.filter((r) => r.path.includes("shared-pkg"));
expect(sharedPaths.length).toBe(1);
expect(sharedPaths[0].metadata.scope).toBe("project");
@@ -1424,14 +1387,12 @@ Content`,
});
it("should dedupe SSH and HTTPS URLs for same repo", async () => {
- // Same repository, different URL formats
const httpsUrl = "https://github.com/user/repo";
const sshUrl = "git:[email protected]:user/repo";
const httpsIdentity = (packageManager as any).getPackageIdentity(httpsUrl);
const sshIdentity = (packageManager as any).getPackageIdentity(sshUrl);
- // Both should resolve to the same identity
expect(httpsIdentity).toBe("git:github.com/user/repo");
expect(sshIdentity).toBe("git:github.com/user/repo");
expect(httpsIdentity).toBe(sshIdentity);
@@ -1444,7 +1405,6 @@ Content`,
const httpsIdentity = (packageManager as any).getPackageIdentity(httpsUrl);
const sshIdentity = (packageManager as any).getPackageIdentity(sshUrl);
- // Identity should ignore ref (version)
expect(httpsIdentity).toBe("git:github.com/user/repo");
expect(sshIdentity).toBe("git:github.com/user/repo");
expect(httpsIdentity).toBe(sshIdentity);
@@ -1457,7 +1417,6 @@ Content`,
const sshProtocolIdentity = (packageManager as any).getPackageIdentity(sshProtocol);
const gitAtIdentity = (packageManager as any).getPackageIdentity(gitAt);
- // Both SSH formats should resolve to same identity
expect(sshProtocolIdentity).toBe("git:github.com/user/repo");
expect(gitAtIdentity).toBe("git:github.com/user/repo");
expect(sshProtocolIdentity).toBe(gitAtIdentity);
@@ -1476,7 +1435,6 @@ Content`,
const identities = urls.map((url) => (packageManager as any).getPackageIdentity(url));
- // All should produce the same identity
const uniqueIdentities = [...new Set(identities)];
expect(uniqueIdentities.length).toBe(1);
expect(uniqueIdentities[0]).toBe("git:github.com/user/repo");
@@ -1489,7 +1447,6 @@ Content`,
const id1 = (packageManager as any).getPackageIdentity(repo1Https);
const id2 = (packageManager as any).getPackageIdentity(repo2Ssh);
- // Different repos should have different identities
expect(id1).toBe("git:github.com/user/repo1");
expect(id2).toBe("git:github.com/user/repo2");
expect(id1).not.toBe(id2);
@@ -1498,32 +1455,25 @@ Content`,
describe("multi-file extension discovery (issue #1102)", () => {
it("should only load index.ts from subdirectories, not helper modules", async () => {
- // Regression test: packages with multi-file extensions in subdirectories
- // should only load the index.ts entry point, not helper modules like agents.ts
const pkgDir = join(tempDir, "multifile-pkg");
mkdirSync(join(pkgDir, "extensions", "subagent"), { recursive: true });
- // Main entry point
writeFileSync(
join(pkgDir, "extensions", "subagent", "index.ts"),
`import { helper } from "./agents.js";
export default function(api) { api.registerTool({ name: "test", description: "test", execute: async () => helper() }); }`,
);
- // Helper module (should NOT be loaded as standalone extension)
writeFileSync(
join(pkgDir, "extensions", "subagent", "agents.ts"),
`export function helper() { return "helper"; }`,
);
- // Top-level extension file (should be loaded)
writeFileSync(join(pkgDir, "extensions", "standalone.ts"), "export default function(api) {}");
const result = await packageManager.resolveExtensionSources([pkgDir]);
- // Should find the index.ts and standalone.ts
expect(result.extensions.some((r) => pathEndsWith(r.path, "subagent/index.ts") && r.enabled)).toBe(true);
expect(result.extensions.some((r) => pathEndsWith(r.path, "standalone.ts") && r.enabled)).toBe(true);
- // Should NOT find agents.ts as a standalone extension
expect(result.extensions.some((r) => pathEndsWith(r.path, "agents.ts"))).toBe(false);
});
@@ -1531,7 +1481,6 @@ export default function(api) { api.registerTool({ name: "test", description: "te
const pkgDir = join(tempDir, "manifest-subdir-pkg");
mkdirSync(join(pkgDir, "extensions", "custom"), { recursive: true });
- // Subdirectory with its own manifest
writeFileSync(
join(pkgDir, "extensions", "custom", "package.json"),
JSON.stringify({
@@ -1545,10 +1494,8 @@ export default function(api) { api.registerTool({ name: "test", description: "te
const result = await packageManager.resolveExtensionSources([pkgDir]);
- // Should find main.ts declared in manifest
expect(result.extensions.some((r) => pathEndsWith(r.path, "custom/main.ts") && r.enabled)).toBe(true);
- // Should NOT find utils.ts (not declared in manifest)
expect(result.extensions.some((r) => pathEndsWith(r.path, "utils.ts"))).toBe(false);
});
@@ -1556,10 +1503,8 @@ export default function(api) { api.registerTool({ name: "test", description: "te
const pkgDir = join(tempDir, "mixed-pkg");
mkdirSync(join(pkgDir, "extensions", "complex"), { recursive: true });
- // Top-level extension
writeFileSync(join(pkgDir, "extensions", "simple.ts"), "export default function(api) {}");
- // Subdirectory with index.ts + helpers
writeFileSync(
join(pkgDir, "extensions", "complex", "index.ts"),
"import { a } from './a.js'; export default function(api) {}",
@@ -1569,15 +1514,12 @@ export default function(api) { api.registerTool({ name: "test", description: "te
const result = await packageManager.resolveExtensionSources([pkgDir]);
- // Should find simple.ts and complex/index.ts
expect(result.extensions.some((r) => pathEndsWith(r.path, "simple.ts") && r.enabled)).toBe(true);
expect(result.extensions.some((r) => pathEndsWith(r.path, "complex/index.ts") && r.enabled)).toBe(true);
- // Should NOT find helper modules
expect(result.extensions.some((r) => pathEndsWith(r.path, "complex/a.ts"))).toBe(false);
expect(result.extensions.some((r) => pathEndsWith(r.path, "complex/b.ts"))).toBe(false);
- // Total should be exactly 2
expect(result.extensions.filter((r) => r.enabled).length).toBe(2);
});
@@ -1585,16 +1527,13 @@ export default function(api) { api.registerTool({ name: "test", description: "te
const pkgDir = join(tempDir, "no-entry-pkg");
mkdirSync(join(pkgDir, "extensions", "broken"), { recursive: true });
- // Subdirectory with no index.ts and no manifest
writeFileSync(join(pkgDir, "extensions", "broken", "helper.ts"), "export const x = 1;");
writeFileSync(join(pkgDir, "extensions", "broken", "another.ts"), "export const y = 2;");
- // Valid top-level extension
writeFileSync(join(pkgDir, "extensions", "valid.ts"), "export default function(api) {}");
const result = await packageManager.resolveExtensionSources([pkgDir]);
- // Should only find the valid top-level extension
expect(result.extensions.some((r) => pathEndsWith(r.path, "valid.ts") && r.enabled)).toBe(true);
expect(result.extensions.filter((r) => r.enabled).length).toBe(1);
});
diff --git a/packages/coding-agent/test/paths.test.ts b/packages/coding-agent/test/paths.test.ts
index 208da3f91c..5120bd854c 100644
--- a/packages/coding-agent/test/paths.test.ts
+++ b/packages/coding-agent/test/paths.test.ts
@@ -54,9 +54,7 @@ describe("canonicalizePath", () => {
const dir = createTempDir();
const target = join(dir, "target.txt");
const link = join(dir, "link.txt");
- // Create a symlink whose target does not exist.
symlinkSync(target, link);
- // realpathSync would throw, so canonicalizePath returns the link path.
expect(canonicalizePath(link)).toBe(link);
});
});
diff --git a/packages/coding-agent/test/refinement.test.ts b/packages/coding-agent/test/refinement.test.ts
index 9efbdd0606..19a7313975 100644
--- a/packages/coding-agent/test/refinement.test.ts
+++ b/packages/coding-agent/test/refinement.test.ts
@@ -677,7 +677,6 @@ describe("harness refinement", () => {
expect(state.entries).toEqual({ prompt: {}, memory: {}, skill: {}, subagent: {} });
expect(state.refinements).toEqual([]);
- // Still usable: a refinement applies and persists cleanly over the bad file.
applyRefinementProposal(
state,
proposal("Recover", [
@@ -1290,7 +1289,6 @@ describe("global refinement history", () => {
const dir = makeTempDir();
const valid = sampleResult("refine_valid");
appendGlobalRefinement(dir, valid);
- // Corrupt append: a non-JSON line and a JSON object that is not a refinement result.
appendFileSync(getRefinementHistoryPath(dir), "not json\n", "utf8");
appendFileSync(getRefinementHistoryPath(dir), `${JSON.stringify({ id: "x" })}\n`, "utf8");
@@ -1410,7 +1408,6 @@ describe("global refinement history", () => {
expect(plan.rollbackOf).toBe("refine_rollback_target");
expect(plan.rollbackScope).toBe("local");
- // The entry still exists until the proposal is applied.
expect(state.entries.memory.rollback_me).toBeDefined();
applyRefinementProposal(state, plan.proposal, { id: plan.id, rollbackOf: plan.rollbackOf });
expect(state.entries.memory.rollback_me).toBeUndefined();
diff --git a/packages/coding-agent/test/resource-loader.test.ts b/packages/coding-agent/test/resource-loader.test.ts
index accdb4355f..fc444ff4fc 100644
--- a/packages/coding-agent/test/resource-loader.test.ts
+++ b/packages/coding-agent/test/resource-loader.test.ts
@@ -599,7 +599,6 @@ Explicit override.`,
describe("extension conflict detection", () => {
it("should detect tool conflicts between extensions", async () => {
- // Create two extensions that register the same tool
const ext1Dir = join(agentDir, "extensions", "ext1");
const ext2Dir = join(agentDir, "extensions", "ext2");
mkdirSync(ext1Dir, { recursive: true });
diff --git a/packages/coding-agent/test/restore-sandbox-env.test.ts b/packages/coding-agent/test/restore-sandbox-env.test.ts
index fa9036eb29..921cd824ac 100644
--- a/packages/coding-agent/test/restore-sandbox-env.test.ts
+++ b/packages/coding-agent/test/restore-sandbox-env.test.ts
@@ -49,7 +49,6 @@ describe("restoreSandboxEnv", () => {
value: { bun: "1.2.0", node: "20.0.0" },
});
- // Clear env to simulate the bun sandbox bug.
const envBackup = { ...process.env };
for (const key of Object.keys(process.env)) {
delete process.env[key];
@@ -63,7 +62,6 @@ describe("restoreSandboxEnv", () => {
expect(process.env.FOO).toBe("bar");
expect(process.env.BAZ).toBe("qux");
- // Restore.
for (const key of Object.keys(process.env)) {
delete process.env[key];
}
diff --git a/packages/coding-agent/test/rpc.test.ts b/packages/coding-agent/test/rpc.test.ts
index 9d4a97d495..d3d6f346b8 100644
--- a/packages/coding-agent/test/rpc.test.ts
+++ b/packages/coding-agent/test/rpc.test.ts
@@ -8,9 +8,6 @@ import { RpcClient } from "../src/modes/rpc/rpc-client.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
-/**
- * RPC mode tests.
- */
describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_TOKEN)("RPC mode", () => {
let client: RpcClient;
let sessionDir: string;
@@ -47,17 +44,14 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should save messages to session file", async () => {
await client.start();
- // Send prompt and wait for completion
const events = await client.promptAndWait("Reply with just the word 'hello'");
- // Should have message events
const messageEndEvents = events.filter((e) => e.type === "message_end");
- expect(messageEndEvents.length).toBeGreaterThanOrEqual(2); // user + assistant
+ expect(messageEndEvents.length).toBeGreaterThanOrEqual(2);
// Wait for file writes
await new Promise((resolve) => setTimeout(resolve, 200));
- // Verify session file
const sessionsPath = join(sessionDir, "sessions");
expect(existsSync(sessionsPath)).toBe(true);
@@ -74,10 +68,8 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
.split("\n")
.map((line) => JSON.parse(line));
- // First entry should be session header
expect(entries[0].type).toBe("session");
- // Should have user and assistant messages
const messages = entries.filter((e: { type: string }) => e.type === "message");
expect(messages.length).toBeGreaterThanOrEqual(2);
@@ -89,10 +81,8 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should handle manual compaction", async () => {
await client.start();
- // First send a prompt to have messages to compact
await client.promptAndWait("Say hello");
- // Compact
const result = await client.compact();
expect(result.summary).toBeDefined();
expect(result.tokensBefore).toBeGreaterThan(0);
@@ -100,7 +90,6 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
// Wait for file writes
await new Promise((resolve) => setTimeout(resolve, 200));
- // Verify compaction in session file
const sessionsPath = join(sessionDir, "sessions");
const sessionDirs = readdirSync(sessionsPath);
const cwdSessionDir = join(sessionsPath, sessionDirs[0]);
@@ -128,17 +117,14 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should add bash output to context", async () => {
await client.start();
- // First send a prompt to initialize session
await client.promptAndWait("Say hi");
- // Run bash command
const uniqueValue = `test-${Date.now()}`;
await client.bash(`echo ${uniqueValue}`);
// Wait for file writes
await new Promise((resolve) => setTimeout(resolve, 200));
- // Verify bash message in session
const sessionsPath = join(sessionDir, "sessions");
const sessionDirs = readdirSync(sessionsPath);
const cwdSessionDir = join(sessionsPath, sessionDirs[0]);
@@ -160,16 +146,13 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should include bash output in LLM context", async () => {
await client.start();
- // Run a bash command with a unique value
const uniqueValue = `unique-${Date.now()}`;
await client.bash(`echo ${uniqueValue}`);
- // Ask the LLM what the output was
const events = await client.promptAndWait(
"What was the exact output of the echo command I just ran? Reply with just the value, nothing else.",
);
- // Find assistant's response
const messageEndEvents = events.filter((e) => e.type === "message_end") as AgentEvent[];
const assistantMessage = messageEndEvents.find(
(e) => e.type === "message_end" && e.message?.role === "assistant",
@@ -184,10 +167,8 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should set and get thinking level", async () => {
await client.start();
- // Set thinking level
await client.setThinkingLevel("high");
- // Verify via state
const state = await client.getState();
expect(state.thinkingLevel).toBe("high");
}, 30000);
@@ -195,16 +176,13 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should cycle thinking level", async () => {
await client.start();
- // Get initial level
const initialState = await client.getState();
const initialLevel = initialState.thinkingLevel;
- // Cycle
const result = await client.cycleThinkingLevel();
expect(result).toBeDefined();
expect(result!.level).not.toBe(initialLevel);
- // Verify via state
const newState = await client.getState();
expect(newState.thinkingLevel).toBe(result!.level);
}, 30000);
@@ -215,7 +193,6 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
const models = await client.getAvailableModels();
expect(models.length).toBeGreaterThan(0);
- // All models should have required fields
for (const model of models) {
expect(model.provider).toBeDefined();
expect(model.id).toBeDefined();
@@ -227,7 +204,6 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should get session stats", async () => {
await client.start();
- // Send a prompt first
await client.promptAndWait("Hello");
const stats = await client.getSessionStats();
@@ -240,17 +216,13 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should create new session", async () => {
await client.start();
- // Send a prompt
await client.promptAndWait("Hello");
- // Verify messages exist
let state = await client.getState();
expect(state.messageCount).toBeGreaterThan(0);
- // New session
await client.newSession();
- // Verify messages cleared
state = await client.getState();
expect(state.messageCount).toBe(0);
}, 90000);
@@ -258,10 +230,8 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should export to HTML", async () => {
await client.start();
- // Send a prompt first
await client.promptAndWait("Hello");
- // Export
const result = await client.exportHtml();
expect(result.path).toBeDefined();
expect(result.path.endsWith(".html")).toBe(true);
@@ -271,14 +241,11 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should get last assistant text", async () => {
await client.start();
- // Initially null
let text = await client.getLastAssistantText();
expect(text).toBeUndefined();
- // Send prompt
await client.promptAndWait("Reply with just: test123");
- // Should have text now
text = await client.getLastAssistantText();
expect(text).toContain("test123");
}, 90000);
@@ -286,24 +253,20 @@ describe.skipIf(!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_OAUTH_T
test("should set and get session name", async () => {
await client.start();
- // Initially undefined
let state = await client.getState();
expect(state.sessionName).toBeUndefined();
// Send a prompt first - session files are only written after first assistant message
await client.promptAndWait("Reply with just 'ok'");
- // Set name
await client.setSessionName("my-test-session");
- // Verify via state
state = await client.getState();
expect(state.sessionName).toBe("my-test-session");
// Wait for file writes
await new Promise((resolve) => setTimeout(resolve, 200));
- // Verify session_info entry in session file
const sessionsPath = join(sessionDir, "sessions");
const sessionDirs = readdirSync(sessionsPath);
const cwdSessionDir = join(sessionsPath, sessionDirs[0]);
diff --git a/packages/coding-agent/test/sdk-skills.test.ts b/packages/coding-agent/test/sdk-skills.test.ts
index f54225151d..eb9b9ba6c2 100644
--- a/packages/coding-agent/test/sdk-skills.test.ts
+++ b/packages/coding-agent/test/sdk-skills.test.ts
@@ -17,7 +17,6 @@ describe("createAgentSession skills option", () => {
skillsDir = join(tempDir, "skills", "test-skill");
mkdirSync(skillsDir, { recursive: true });
- // Create a test skill in the pi skills directory
writeFileSync(
join(skillsDir, "SKILL.md"),
`---
@@ -45,7 +44,6 @@ This is a test skill.
sessionManager: SessionManager.inMemory(),
});
- // Skills should be discovered and exposed on the session
expect(session.resourceLoader.getSkills().skills.length).toBeGreaterThan(0);
expect(session.resourceLoader.getSkills().skills.some((s) => s.name === "test-skill")).toBe(true);
});
diff --git a/packages/coding-agent/test/session-info-modified-timestamp.test.ts b/packages/coding-agent/test/session-info-modified-timestamp.test.ts
index 1dd1cb4155..f29cdb6bfe 100644
--- a/packages/coding-agent/test/session-info-modified-timestamp.test.ts
+++ b/packages/coding-agent/test/session-info-modified-timestamp.test.ts
@@ -51,7 +51,6 @@ describe("SessionInfo.modified", () => {
createSessionFile(filePath);
const before = await stat(filePath);
- // Ensure the file mtime can differ from our message timestamp even on coarse filesystems.
await new Promise((r) => setTimeout(r, 10));
const mgr = SessionManager.open(filePath);
diff --git a/packages/coding-agent/test/session-manager-flush.test.ts b/packages/coding-agent/test/session-manager-flush.test.ts
index 418b52b2e4..50ddafd555 100644
--- a/packages/coding-agent/test/session-manager-flush.test.ts
+++ b/packages/coding-agent/test/session-manager-flush.test.ts
@@ -206,7 +206,6 @@ describe("SessionManager.flushNow", () => {
it("is a no-op for in-memory (non-persisted) sessions", () => {
const mgr = SessionManager.inMemory("/tmp");
mgr.appendCustomEntry("thread_goal_state", { active: true });
- // Should not throw
mgr.flushNow();
expect(mgr.getSessionFile()).toBeUndefined();
});
@@ -250,7 +249,6 @@ describe("SessionManager.flushNow", () => {
timestamp: Date.now(),
});
- // File should contain exactly: header, custom(goal), user, assistant
const content = readFileSync(file, "utf8");
const lines = content.trim().split("\n");
expect(lines.length).toBe(4);
@@ -270,8 +268,6 @@ describe("SessionManager.flushNow", () => {
expect(assistantMsg.type).toBe("message");
expect(assistantMsg.message.role).toBe("assistant");
- // Verify valid parent chain: custom(null) -> user(custom) -> assistant(user)
- // (session header is not part of the entry parent chain)
expect(custom.parentId).toBeNull();
expect(userMsg.parentId).toBe(custom.id);
expect(assistantMsg.parentId).toBe(userMsg.id);
@@ -403,7 +399,6 @@ describe("SessionManager.appendCustomMessageEntryWithRollback", () => {
const file = mgr.getSessionFile()!;
const before = readFileSync(file, "utf8");
- // Simulate a partial append: the fs write tears the file, then throws.
const internals = mgr as unknown as { _persist(entry: unknown): void };
const originalPersist = internals._persist.bind(mgr);
internals._persist = () => {
diff --git a/packages/coding-agent/test/session-manager-git-state.test.ts b/packages/coding-agent/test/session-manager-git-state.test.ts
index ac595e7a6e..742896ea0b 100644
--- a/packages/coding-agent/test/session-manager-git-state.test.ts
+++ b/packages/coding-agent/test/session-manager-git-state.test.ts
@@ -61,7 +61,6 @@ describe("SessionManager git state", () => {
const entry = sm.getEntries().find((e) => e.type === "git_state");
expect(entry).toMatchObject({ type: "git_state", git: { commit: secondSha } });
- // A second call with no further change is a no-op.
expect(sm.recordGitStateIfChanged()).toBeUndefined();
});
@@ -70,7 +69,6 @@ describe("SessionManager git state", () => {
const msgId = sm.appendMessage({ role: "user", content: [{ type: "text", text: "hi" }], timestamp: 1 });
commit(repoDir, "second");
- // On the main path this appends git_state(secondSha).
expect(sm.recordGitStateIfChanged()).toBeDefined();
// Navigate to before that entry: this branch's nearest git context is the header (firstSha),
@@ -130,7 +128,6 @@ describe("SessionManager git state", () => {
const forked = SessionManager.forkFrom(sourcePath, repoDir, sessionDir);
- // Header carries the target repo git, not the source's.
expect(forked.getHeader()?.git).toEqual({
branch: "main",
commit: firstSha,
diff --git a/packages/coding-agent/test/session-manager/build-context.test.ts b/packages/coding-agent/test/session-manager/build-context.test.ts
index 4a64a73457..afbdd1d8bf 100644
--- a/packages/coding-agent/test/session-manager/build-context.test.ts
+++ b/packages/coding-agent/test/session-manager/build-context.test.ts
@@ -130,7 +130,6 @@ describe("buildSessionContext", () => {
msg("3", "2", "assistant", "hi"),
];
const ctx = buildSessionContext(entries);
- // Assistant message overwrites model change
expect(ctx.model).toEqual({ provider: "anthropic", modelId: "claude-test" });
});
});
@@ -148,7 +147,6 @@ describe("buildSessionContext", () => {
];
const ctx = buildSessionContext(entries);
- // Should have: summary + kept (3,4) + after (6,7) = 5 messages
expect(ctx.messages).toHaveLength(5);
expect((ctx.messages[0] as any).summary).toContain("Summary of first two turns");
expect((ctx.messages[1] as any).content).toBe("second");
@@ -166,7 +164,6 @@ describe("buildSessionContext", () => {
];
const ctx = buildSessionContext(entries);
- // Summary + all messages (1,2,4)
expect(ctx.messages).toHaveLength(4);
expect((ctx.messages[0] as any).summary).toContain("Empty summary");
});
@@ -196,7 +193,6 @@ describe("buildSessionContext", () => {
];
const ctx = buildSessionContext(entries);
- // Should use second summary, keep from 4
expect(ctx.messages).toHaveLength(4);
expect((ctx.messages[0] as any).summary).toContain("Second summary");
});
@@ -204,9 +200,6 @@ describe("buildSessionContext", () => {
describe("with branches", () => {
it("follows path to specified leaf", () => {
- // Tree:
- // 1 -> 2 -> 3 (branch A)
- // \-> 4 (branch B)
const entries: SessionEntry[] = [
msg("1", null, "user", "start"),
msg("2", "1", "assistant", "response"),
@@ -239,10 +232,6 @@ describe("buildSessionContext", () => {
});
it("complex tree with multiple branches and compaction", () => {
- // Tree:
- // 1 -> 2 -> 3 -> 4 -> compaction(5) -> 6 -> 7 (main path)
- // \-> 8 -> 9 (abandoned branch)
- // \-> branchSummary(10) -> 11 (resumed from 3)
const entries: SessionEntry[] = [
msg("1", null, "user", "start"),
msg("2", "1", "assistant", "r1"),
@@ -251,15 +240,12 @@ describe("buildSessionContext", () => {
compaction("5", "4", "Compacted history", "3"),
msg("6", "5", "user", "q3"),
msg("7", "6", "assistant", "r3"),
- // Abandoned branch from 3
msg("8", "3", "user", "wrong path"),
msg("9", "8", "assistant", "wrong response"),
- // Branch summary resuming from 3
branchSummary("10", "3", "Tried wrong approach", "9"),
msg("11", "10", "user", "better approach"),
];
- // Main path to 7: summary + kept(3,4) + after(6,7)
const ctxMain = buildSessionContext(entries, "7");
expect(ctxMain.messages).toHaveLength(5);
expect((ctxMain.messages[0] as any).summary).toContain("Compacted history");
@@ -268,7 +254,6 @@ describe("buildSessionContext", () => {
expect((ctxMain.messages[3] as any).content).toBe("q3");
expect((ctxMain.messages[4] as any).content[0].text).toBe("r3");
- // Branch path to 11: 1,2,3 + branch_summary + 11
const ctxBranch = buildSessionContext(entries, "11");
expect(ctxBranch.messages).toHaveLength(5);
expect((ctxBranch.messages[0] as any).content).toBe("start");
@@ -292,7 +277,6 @@ describe("buildSessionContext", () => {
msg("2", "missing", "assistant", "orphan"), // parent doesn't exist
];
const ctx = buildSessionContext(entries, "2");
- // Should only get the orphan since parent chain is broken
expect(ctx.messages).toHaveLength(1);
});
});
diff --git a/packages/coding-agent/test/session-manager/file-operations.test.ts b/packages/coding-agent/test/session-manager/file-operations.test.ts
index 6125b4c3b9..cfd1217034 100644
--- a/packages/coding-agent/test/session-manager/file-operations.test.ts
+++ b/packages/coding-agent/test/session-manager/file-operations.test.ts
@@ -497,7 +497,6 @@ describe("findMostRecentSession", () => {
const file2 = join(tempDir, "newer.jsonl");
writeFileSync(file1, '{"type":"session","id":"old","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
- // Small delay to ensure different mtime
await new Promise((r) => setTimeout(r, 10));
writeFileSync(file2, '{"type":"session","id":"new","timestamp":"2025-01-01T00:00:00Z","cwd":"/tmp"}\n');
@@ -534,12 +533,10 @@ describe("SessionManager.setSessionFile with corrupted files", () => {
const sm = SessionManager.open(emptyFile, tempDir);
- // Should have created a new session with valid header
expect(sm.getSessionId()).toBeTruthy();
expect(sm.getHeader()).toBeTruthy();
expect(sm.getHeader()?.type).toBe("session");
- // File should now contain a valid header
const content = readFileSync(emptyFile, "utf-8");
const lines = content.trim().split("\n").filter(Boolean);
expect(lines.length).toBe(1);
@@ -550,7 +547,6 @@ describe("SessionManager.setSessionFile with corrupted files", () => {
it("truncates and rewrites file without valid header", () => {
const noHeaderFile = join(tempDir, "no-header.jsonl");
- // File with messages but no session header (corrupted state)
writeFileSync(
noHeaderFile,
'{"type":"message","id":"abc","parentId":"orphaned","timestamp":"2025-01-01T00:00:00Z","message":{"role":"assistant","content":"test"}}\n',
@@ -558,12 +554,10 @@ describe("SessionManager.setSessionFile with corrupted files", () => {
const sm = SessionManager.open(noHeaderFile, tempDir);
- // Should have created a new session with valid header
expect(sm.getSessionId()).toBeTruthy();
expect(sm.getHeader()).toBeTruthy();
expect(sm.getHeader()?.type).toBe("session");
- // File should now contain only a valid header (old content truncated)
const content = readFileSync(noHeaderFile, "utf-8");
const lines = content.trim().split("\n").filter(Boolean);
expect(lines.length).toBe(1);
@@ -578,7 +572,6 @@ describe("SessionManager.setSessionFile with corrupted files", () => {
const sm = SessionManager.open(explicitPath, tempDir);
- // The session file path should be preserved
expect(sm.getSessionFile()).toBe(explicitPath);
});
@@ -586,11 +579,9 @@ describe("SessionManager.setSessionFile with corrupted files", () => {
const corruptedFile = join(tempDir, "corrupted.jsonl");
writeFileSync(corruptedFile, "garbage content\n");
- // First open recovers the file
const sm1 = SessionManager.open(corruptedFile, tempDir);
const sessionId = sm1.getSessionId();
- // Second open should load the recovered file successfully
const sm2 = SessionManager.open(corruptedFile, tempDir);
expect(sm2.getSessionId()).toBe(sessionId);
expect(sm2.getHeader()?.type).toBe("session");
diff --git a/packages/coding-agent/test/session-manager/labels.test.ts b/packages/coding-agent/test/session-manager/labels.test.ts
index e703abf815..2aca80e344 100644
--- a/packages/coding-agent/test/session-manager/labels.test.ts
+++ b/packages/coding-agent/test/session-manager/labels.test.ts
@@ -7,14 +7,11 @@ describe("SessionManager labels", () => {
const msgId = session.appendMessage({ role: "user", content: "hello", timestamp: 1 });
- // No label initially
expect(session.getLabel(msgId)).toBeUndefined();
- // Set a label
const labelId = session.appendLabelChange(msgId, "checkpoint");
expect(session.getLabel(msgId)).toBe("checkpoint");
- // Label entry should be in entries
const entries = session.getEntries();
const labelEntry = entries.find((e) => e.type === "label") as LabelEntry;
expect(labelEntry).toBeDefined();
@@ -31,7 +28,6 @@ describe("SessionManager labels", () => {
session.appendLabelChange(msgId, "checkpoint");
expect(session.getLabel(msgId)).toBe("checkpoint");
- // Clear the label
session.appendLabelChange(msgId, undefined);
expect(session.getLabel(msgId)).toBeUndefined();
});
@@ -84,12 +80,10 @@ describe("SessionManager labels", () => {
const msg2LabelEntry = entries.find((e) => e.id === msg2LabelId) as LabelEntry;
const tree = session.getTree();
- // Find the message nodes (skip label entries)
const msg1Node = tree.find((n) => n.entry.id === msg1Id);
expect(msg1Node?.label).toBe("start");
expect(msg1Node?.labelTimestamp).toBe(msg1LabelEntry.timestamp);
- // msg2 is a child of msg1
const msg2Node = msg1Node?.children.find((n) => n.entry.id === msg2Id);
expect(msg2Node?.label).toBe("response");
expect(msg2Node?.labelTimestamp).toBe(msg2LabelEntry.timestamp);
@@ -123,14 +117,11 @@ describe("SessionManager labels", () => {
const msg1LabelEntry = originalEntries.find((e) => e.id === msg1LabelId) as LabelEntry;
const msg2LabelEntry = originalEntries.find((e) => e.id === msg2LabelId) as LabelEntry;
- // Branch from msg2 (in-memory mode returns null, but updates internal state)
session.createBranchedSession(msg2Id);
- // Labels should be preserved
expect(session.getLabel(msg1Id)).toBe("important");
expect(session.getLabel(msg2Id)).toBe("also-important");
- // New label entries should exist
const entries = session.getEntries();
const labelEntries = entries.filter((e) => e.type === "label") as LabelEntry[];
expect(labelEntries).toHaveLength(2);
@@ -165,15 +156,12 @@ describe("SessionManager labels", () => {
});
const msg3Id = session.appendMessage({ role: "user", content: "followup", timestamp: 3 });
- // Label all messages
session.appendLabelChange(msg1Id, "first");
session.appendLabelChange(msg2Id, "second");
session.appendLabelChange(msg3Id, "third");
- // Branch from msg2 (excludes msg3)
session.createBranchedSession(msg2Id);
- // Only labels for msg1 and msg2 should be preserved
expect(session.getLabel(msg1Id)).toBe("first");
expect(session.getLabel(msg2Id)).toBe("second");
expect(session.getLabel(msg3Id)).toBeUndefined();
diff --git a/packages/coding-agent/test/session-manager/save-entry.test.ts b/packages/coding-agent/test/session-manager/save-entry.test.ts
index a384a07427..2ba92204cd 100644
--- a/packages/coding-agent/test/session-manager/save-entry.test.ts
+++ b/packages/coding-agent/test/session-manager/save-entry.test.ts
@@ -5,13 +5,10 @@ describe("SessionManager.saveCustomEntry", () => {
it("saves custom entries and includes them in tree traversal", () => {
const session = SessionManager.inMemory();
- // Save a message
const msgId = session.appendMessage({ role: "user", content: "hello", timestamp: 1 });
- // Save a custom entry
const customId = session.appendCustomEntry("my_data", { foo: "bar" });
- // Save another message
const msg2Id = session.appendMessage({
role: "assistant",
content: [{ type: "text", text: "hi" }],
@@ -30,7 +27,6 @@ describe("SessionManager.saveCustomEntry", () => {
timestamp: 2,
});
- // Custom entry should be in entries
const entries = session.getEntries();
expect(entries).toHaveLength(3);
@@ -41,14 +37,12 @@ describe("SessionManager.saveCustomEntry", () => {
expect(customEntry.id).toBe(customId);
expect(customEntry.parentId).toBe(msgId);
- // Tree structure should be correct
const path = session.getBranch();
expect(path).toHaveLength(3);
expect(path[0].id).toBe(msgId);
expect(path[1].id).toBe(customId);
expect(path[2].id).toBe(msg2Id);
- // buildSessionContext should work (custom entries skipped in messages)
const ctx = session.buildSessionContext();
expect(ctx.messages).toHaveLength(2); // only message entries
});
diff --git a/packages/coding-agent/test/session-manager/tree-traversal.test.ts b/packages/coding-agent/test/session-manager/tree-traversal.test.ts
index fb855fc1bd..9b7206d452 100644
--- a/packages/coding-agent/test/session-manager/tree-traversal.test.ts
+++ b/packages/coding-agent/test/session-manager/tree-traversal.test.ts
@@ -207,12 +207,10 @@ describe("SessionManager append and tree traversal", () => {
it("returns tree with branches after branch", () => {
const session = SessionManager.inMemory();
- // Build: 1 -> 2 -> 3
const id1 = session.appendMessage(userMsg("1"));
const id2 = session.appendMessage(assistantMsg("2"));
const id3 = session.appendMessage(userMsg("3"));
- // Branch from id2, add new path: 2 -> 4
session.branch(id2);
const id4 = session.appendMessage(userMsg("4-branch"));
@@ -237,15 +235,12 @@ describe("SessionManager append and tree traversal", () => {
const _id1 = session.appendMessage(userMsg("root"));
const id2 = session.appendMessage(assistantMsg("response"));
- // Branch A
session.branch(id2);
const idA = session.appendMessage(userMsg("branch-A"));
- // Branch B
session.branch(id2);
const idB = session.appendMessage(userMsg("branch-B"));
- // Branch C
session.branch(id2);
const idC = session.appendMessage(userMsg("branch-C"));
@@ -267,7 +262,6 @@ describe("SessionManager append and tree traversal", () => {
const id3 = session.appendMessage(userMsg("3"));
const _id4 = session.appendMessage(assistantMsg("4"));
- // Branch from 2: 2 -> 5 -> 6
session.branch(id2);
const id5 = session.appendMessage(userMsg("5"));
const _id6 = session.appendMessage(assistantMsg("6"));
@@ -278,7 +272,6 @@ describe("SessionManager append and tree traversal", () => {
const tree = session.getTree();
- // Verify structure
const node2 = tree[0].children[0];
expect(node2.children).toHaveLength(2); // id3 and id5
@@ -409,7 +402,6 @@ describe("SessionManager append and tree traversal", () => {
const id2 = session.appendMessage(assistantMsg("msg2"));
session.appendMessage(userMsg("msg3"));
- // Branch from 2: 2 -> 4
session.branch(id2);
session.appendMessage(assistantMsg("msg4-branch"));
@@ -434,7 +426,6 @@ describe("createBranchedSession", () => {
it("creates new session with path to specified leaf (in-memory)", () => {
const session = SessionManager.inMemory();
- // Build: 1 -> 2 -> 3 -> 4
const id1 = session.appendMessage(userMsg("1"));
const id2 = session.appendMessage(assistantMsg("2"));
const id3 = session.appendMessage(userMsg("3"));
@@ -448,7 +439,6 @@ describe("createBranchedSession", () => {
const result = session.createBranchedSession(id2);
expect(result).toBeUndefined(); // in-memory returns null
- // Session should now only have entries 1 and 2
const entries = session.getEntries();
expect(entries).toHaveLength(2);
expect(entries[0].id).toBe(id1);
@@ -458,12 +448,10 @@ describe("createBranchedSession", () => {
it("extracts correct path from branched tree", () => {
const session = SessionManager.inMemory();
- // Build: 1 -> 2 -> 3
const id1 = session.appendMessage(userMsg("1"));
const id2 = session.appendMessage(assistantMsg("2"));
session.appendMessage(userMsg("3"));
- // Branch from 2: 2 -> 4 -> 5
session.branch(id2);
const id4 = session.appendMessage(userMsg("4"));
const id5 = session.appendMessage(assistantMsg("5"));
@@ -481,7 +469,6 @@ describe("createBranchedSession", () => {
mkdirSync(tempDir, { recursive: true });
try {
- // Create a persisted session with a couple of turns
const session = SessionManager.create(tempDir, tempDir);
const id1 = session.appendMessage(userMsg("first question"));
session.appendMessage(assistantMsg("first answer"));
@@ -502,7 +489,6 @@ describe("createBranchedSession", () => {
// Now the assistant responds
session.appendMessage(assistantMsg("new answer"));
- // File should now exist with exactly one header and no duplicate IDs
expect(existsSync(newFile!)).toBe(true);
const content = readFileSync(newFile!, "utf-8");
const lines = content.trim().split("\n").filter(Boolean);
@@ -535,7 +521,6 @@ describe("createBranchedSession", () => {
const newFile = session.createBranchedSession(id2);
expect(newFile).toBeDefined();
- // Path includes an assistant, so file should be written immediately
expect(existsSync(newFile!)).toBe(true);
const content = readFileSync(newFile!, "utf-8");
const lines = content.trim().split("\n").filter(Boolean);
diff --git a/packages/coding-agent/test/settings-manager-bug.test.ts b/packages/coding-agent/test/settings-manager-bug.test.ts
index dd35f30093..7fafa2458d 100644
--- a/packages/coding-agent/test/settings-manager-bug.test.ts
+++ b/packages/coding-agent/test/settings-manager-bug.test.ts
@@ -3,18 +3,6 @@ import { join } from "path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SettingsManager } from "../src/core/settings-manager.js";
-/**
- * Tests for the fix to a bug where external file changes to arrays were overwritten.
- *
- * The bug scenario was:
- * 1. Pi starts with settings.json containing packages: ["npm:some-pkg"]
- * 2. User externally edits file to packages: []
- * 3. User changes an unrelated setting (e.g., theme) via UI
- * 4. save() would overwrite packages back to ["npm:some-pkg"] from stale in-memory state
- *
- * The fix tracks which fields were explicitly modified during the session, and only
- * those fields override file values during save().
- */
describe("SettingsManager - External Edit Preservation", () => {
const testDir = join(process.cwd(), "test-settings-bug-tmp");
const agentDir = join(testDir, "agent");
@@ -37,7 +25,6 @@ describe("SettingsManager - External Edit Preservation", () => {
it("should preserve file changes to packages array when changing unrelated setting", async () => {
const settingsPath = join(agentDir, "settings.json");
- // Initial state: packages has one item
writeFileSync(
settingsPath,
JSON.stringify({
@@ -46,25 +33,19 @@ describe("SettingsManager - External Edit Preservation", () => {
}),
);
- // Pi starts up, loads settings into memory
const manager = SettingsManager.create(projectDir, agentDir);
- // At this point, globalSettings.packages = ["npm:pi-mcp-adapter"]
expect(manager.getPackages()).toEqual(["npm:pi-mcp-adapter"]);
- // User externally edits settings.json to remove the package
const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
- currentSettings.packages = []; // User wants to remove this!
+ currentSettings.packages = [];
writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));
- // Verify file was changed
expect(JSON.parse(readFileSync(settingsPath, "utf-8")).packages).toEqual([]);
- // User changes an UNRELATED setting via UI (this triggers save)
manager.setTheme("light");
await manager.flush();
- // With the fix, packages should be preserved as [] (not reverted to startup value)
const savedSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
expect(savedSettings.packages).toEqual([]);
@@ -84,18 +65,15 @@ describe("SettingsManager - External Edit Preservation", () => {
const manager = SettingsManager.create(projectDir, agentDir);
- // User externally updates extensions
const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
currentSettings.extensions = ["/new/extension.ts"];
writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));
- // Change unrelated setting
manager.setDefaultThinkingLevel("high");
await manager.flush();
const savedSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
- // With the fix, extensions should be preserved (not reverted to startup value)
expect(savedSettings.extensions).toEqual(["/new/extension.ts"]);
});
diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.ts
index 9a0955d867..7ea918da5b 100644
--- a/packages/coding-agent/test/settings-manager.test.ts
+++ b/packages/coding-agent/test/settings-manager.test.ts
@@ -10,7 +10,6 @@ describe("SettingsManager", () => {
const projectDir = join(testDir, "project");
beforeEach(() => {
- // Clean up and create fresh directories
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true });
}
@@ -26,7 +25,6 @@ describe("SettingsManager", () => {
describe("preserves externally added settings", () => {
it("should preserve enabledModels when changing thinking level", async () => {
- // Create initial settings file
const settingsPath = join(agentDir, "settings.json");
writeFileSync(
settingsPath,
@@ -36,19 +34,15 @@ describe("SettingsManager", () => {
}),
);
- // Create SettingsManager (simulates pi starting up)
const manager = SettingsManager.create(projectDir, agentDir);
- // Simulate user editing settings.json externally to add enabledModels
const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
currentSettings.enabledModels = ["claude-opus-4-5", "gpt-5.2-codex"];
writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));
- // User changes thinking level via Shift+Tab
manager.setDefaultThinkingLevel("high");
await manager.flush();
- // Verify enabledModels is preserved
const savedSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
expect(savedSettings.enabledModels).toEqual(["claude-opus-4-5", "gpt-5.2-codex"]);
expect(savedSettings.defaultThinkingLevel).toBe("high");
@@ -67,17 +61,14 @@ describe("SettingsManager", () => {
const manager = SettingsManager.create(projectDir, agentDir);
- // User adds custom settings externally
const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
currentSettings.shellPath = "/bin/zsh";
currentSettings.extensions = ["/path/to/extension.ts"];
writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));
- // User changes theme
manager.setTheme("light");
await manager.flush();
- // Verify all settings preserved
const savedSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
expect(savedSettings.shellPath).toBe("/bin/zsh");
expect(savedSettings.extensions).toEqual(["/path/to/extension.ts"]);
@@ -95,16 +86,13 @@ describe("SettingsManager", () => {
const manager = SettingsManager.create(projectDir, agentDir);
- // User externally sets thinking level to "low"
const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
currentSettings.defaultThinkingLevel = "low";
writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));
- // But then changes it via UI to "high"
manager.setDefaultThinkingLevel("high");
await manager.flush();
- // In-memory change should win
const savedSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));
expect(savedSettings.defaultThinkingLevel).toBe("high");
});
@@ -365,44 +353,33 @@ describe("SettingsManager", () => {
describe("project settings directory creation", () => {
it("should not create .pi folder when only reading project settings", () => {
- // Create agent dir with global settings, but NO .pi folder in project
const settingsPath = join(agentDir, "settings.json");
writeFileSync(settingsPath, JSON.stringify({ theme: "dark" }));
- // Delete the .pi folder that beforeEach created
rmSync(join(projectDir, ".prime", "agent"), { recursive: true });
- // Create SettingsManager (reads both global and project settings)
const manager = SettingsManager.create(projectDir, agentDir);
- // .pi folder should NOT have been created just from reading
expect(existsSync(join(projectDir, ".prime", "agent"))).toBe(false);
- // Settings should still be loaded from global
expect(manager.getTheme()).toBe("dark");
});
it("should create .pi folder when writing project settings", async () => {
- // Create agent dir with global settings, but NO .pi folder in project
const settingsPath = join(agentDir, "settings.json");
writeFileSync(settingsPath, JSON.stringify({ theme: "dark" }));
- // Delete the .pi folder that beforeEach created
rmSync(join(projectDir, ".prime", "agent"), { recursive: true });
const manager = SettingsManager.create(projectDir, agentDir);
- // .pi folder should NOT exist yet
expect(existsSync(join(projectDir, ".prime", "agent"))).toBe(false);
- // Write a project-specific setting
manager.setProjectPackages([{ source: "npm:test-pkg" }]);
await manager.flush();
- // Now .pi folder should exist
expect(existsSync(join(projectDir, ".prime", "agent"))).toBe(true);
- // And settings file should be created
expect(existsSync(join(projectDir, ".prime", "agent", "settings.json"))).toBe(true);
});
});
@@ -498,7 +475,6 @@ describe("SettingsManager", () => {
const manager = SettingsManager.create(projectDir, agentDir);
const servers = manager.getMcpServers();
expect(servers?.acme).toEqual({ type: "http", url: "https://global.acme/mcp", oauth: true });
- // Project override replaces the shared entry.
expect(servers?.shared).toEqual({ type: "http", url: "https://project.shared/mcp" });
});
});
diff --git a/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts b/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts
index 05107784eb..eb3b26c3fa 100644
--- a/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts
@@ -9,7 +9,7 @@ import { DefaultResourceLoader } from "../../../src/core/resource-loader.js";
import { createAgentSession } from "../../../src/core/sdk.js";
import { SessionManager } from "../../../src/core/session-manager.js";
import { SettingsManager } from "../../../src/core/settings-manager.js";
-import { allToolNames, createAllToolDefinitions } from "../../../src/core/tools/index.js";
+import { createAllToolDefinitions } from "../../../src/core/tools/index.js";
describe("regression #4428: remove legacy pi-mono built-in tools", () => {
let tempDir: string;
@@ -28,7 +28,6 @@ describe("regression #4428: remove legacy pi-mono built-in tools", () => {
});
it("registers only ipython as a built-in tool", () => {
- expect([...allToolNames]).toEqual(["ipython"]);
expect(Object.keys(createAllToolDefinitions(process.cwd()))).toEqual(["ipython"]);
});
diff --git a/packages/tui/src/autocomplete.ts b/packages/tui/src/autocomplete.ts
index bc11f530e4..4b50464df7 100644
--- a/packages/tui/src/autocomplete.ts
+++ b/packages/tui/src/autocomplete.ts
@@ -121,7 +121,6 @@ function buildCompletionValue(
return `${openQuote}${path}${closeQuote}`;
}
-// Use fd to walk directory tree (fast, respects .gitignore)
async function walkDirectoryWithFd(
baseDir: string,
fdPath: string,
@@ -235,8 +234,6 @@ export interface SlashCommand {
argumentHint?: string;
sourceTag?: string;
takesArgument?: boolean;
- // Function to get argument completions for this command
- // Returns null if no argument completion is available
getArgumentCompletions?(argumentPrefix: string): Awaitable<AutocompleteItem[] | null>;
}
@@ -247,8 +244,6 @@ export interface AutocompleteSuggestions {
}
export interface AutocompleteProvider {
- // Get autocomplete suggestions for current text/cursor position
- // Returns null if no suggestions available
getSuggestions(
lines: string[],
cursorLine: number,
@@ -256,8 +251,6 @@ export interface AutocompleteProvider {
options: { signal: AbortSignal; force?: boolean },
): Promise<AutocompleteSuggestions | null>;
- // Apply the selected item
- // Returns the new text and cursor position
applyCompletion(
lines: string[],
cursorLine: number,
@@ -270,11 +263,9 @@ export interface AutocompleteProvider {
cursorCol: number;
};
- // Check if file completion should trigger for explicit Tab completion
shouldTriggerFileCompletion?(lines: string[], cursorLine: number, cursorCol: number): boolean;
}
-// Combined provider that handles both slash commands and file paths
export class CombinedAutocompleteProvider implements AutocompleteProvider {
private commands: (SlashCommand | AutocompleteItem)[];
private basePath: string;
@@ -419,9 +410,7 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
};
}
- // Check if we're completing a file attachment (prefix starts with "@")
if (prefix.startsWith("@")) {
- // This is a file attachment completion
// Don't add space after directories so user can continue autocompleting
const isDirectory = item.label.endsWith("/");
const suffix = isDirectory ? "" : " ";
@@ -455,7 +444,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
};
}
- // For file paths, complete the path
const newLine = beforePrefix + item.value + adjustedAfterCursor;
const newLines = [...lines];
newLines[cursorLine] = newLine;
@@ -471,7 +459,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
};
}
- // Extract @ prefix for fuzzy file suggestions
private extractAtPrefix(text: string): string | null {
const quotedPrefix = extractQuotedPrefix(text);
if (quotedPrefix?.startsWith('@"')) {
@@ -488,7 +475,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
return null;
}
- // Extract a path-like prefix from the text before cursor
private extractPathPrefix(text: string, forceExtract: boolean = false): string | null {
const quotedPrefix = extractQuotedPrefix(text);
if (quotedPrefix) {
@@ -498,19 +484,15 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
const lastDelimiterIndex = findLastDelimiter(text);
const pathPrefix = lastDelimiterIndex === -1 ? text : text.slice(lastDelimiterIndex + 1);
- // For forced extraction (Tab key), always return something
if (forceExtract) {
return pathPrefix;
}
// For natural triggers, return if it looks like a path, ends with /, starts with ~/, .
- // Only return empty string if the text looks like it's starting a path context
if (pathPrefix.includes("/") || pathPrefix.startsWith(".") || pathPrefix.startsWith("~/")) {
return pathPrefix;
}
- // Return empty string only after a space (not for completely empty text)
- // Empty text should not trigger file suggestions - that's for forced Tab completion
if (pathPrefix === "" && text.endsWith(" ")) {
return pathPrefix;
}
@@ -518,11 +500,9 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
return null;
}
- // Expand home directory (~/) to actual home path
private expandHomePath(path: string): string {
if (path.startsWith("~/")) {
const expandedPath = join(homedir(), path.slice(2));
- // Preserve trailing slash if original path had one
return path.endsWith("/") && !expandedPath.endsWith("/") ? `${expandedPath}/` : expandedPath;
} else if (path === "~") {
return homedir();
@@ -568,7 +548,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
return `${toDisplayPath(displayBase)}${normalizedRelativePath}`;
}
- // Get file/directory suggestions for a given path prefix
private getFileSuggestions(prefix: string): AutocompleteItem[] {
try {
let searchDir: string;
@@ -576,7 +555,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
const { rawPrefix, isAtPrefix, isQuotedPrefix } = parsePathPrefix(prefix);
let expandedPrefix = rawPrefix;
- // Handle home directory expansion
if (expandedPrefix.startsWith("~")) {
expandedPrefix = this.expandHomePath(expandedPrefix);
}
@@ -591,7 +569,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
(isAtPrefix && rawPrefix === "");
if (isRootPrefix) {
- // Complete from specified position
if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
searchDir = expandedPrefix;
} else {
@@ -599,7 +576,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
}
searchPrefix = "";
} else if (rawPrefix.endsWith("/")) {
- // If prefix ends with /, show contents of that directory
if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
searchDir = expandedPrefix;
} else {
@@ -607,7 +583,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
}
searchPrefix = "";
} else {
- // Split into directory and file prefix
const dir = dirname(expandedPrefix);
const file = basename(expandedPrefix);
if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
@@ -626,14 +601,13 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
continue;
}
- // Check if entry is a directory (or a symlink pointing to a directory)
let isDirectory = entry.isDirectory();
if (!isDirectory && entry.isSymbolicLink()) {
try {
const fullPath = join(searchDir, entry.name);
isDirectory = statSync(fullPath).isDirectory();
} catch {
- // Broken symlink or permission error - treat as file
+ // Ignore broken or inaccessible symbolic links.
}
}
@@ -642,16 +616,13 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
const displayPrefix = rawPrefix;
if (displayPrefix.endsWith("/")) {
- // If prefix ends with /, append entry to the prefix
relativePath = displayPrefix + name;
} else if (displayPrefix.includes("/") || displayPrefix.includes("\\")) {
- // Preserve ~/ format for home directory paths
if (displayPrefix.startsWith("~/")) {
const homeRelativeDir = displayPrefix.slice(2); // Remove ~/
const dir = dirname(homeRelativeDir);
relativePath = `~/${dir === "." ? name : join(dir, name)}`;
} else if (displayPrefix.startsWith("/")) {
- // Absolute path - construct properly
const dir = dirname(displayPrefix);
if (dir === "/") {
relativePath = `/${name}`;
@@ -660,13 +631,11 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
}
} else {
relativePath = join(dirname(displayPrefix), name);
- // path.join normalizes away ./ prefix, preserve it
if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {
relativePath = `./${relativePath}`;
}
}
} else {
- // For standalone entries, preserve ~/ if original prefix was ~/
if (displayPrefix.startsWith("~")) {
relativePath = `~/${name}`;
} else {
@@ -688,7 +657,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
});
}
- // Sort directories first, then alphabetically
suggestions.sort((a, b) => {
const aIsDir = a.value.endsWith("/");
const bIsDir = b.value.endsWith("/");
@@ -699,13 +667,10 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
return suggestions;
} catch (_e) {
- // Directory doesn't exist or not accessible
return [];
}
}
- // Score an entry against the query (higher = better match)
- // isDirectory adds bonus to prioritize folders
private scoreEntry(filePath: string, query: string, isDirectory: boolean): number {
const fileName = basename(filePath);
const lowerFileName = fileName.toLowerCase();
@@ -713,22 +678,16 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
let score = 0;
- // Exact filename match (highest)
if (lowerFileName === lowerQuery) score = 100;
- // Filename starts with query
else if (lowerFileName.startsWith(lowerQuery)) score = 80;
- // Substring match in filename
else if (lowerFileName.includes(lowerQuery)) score = 50;
- // Substring match in full path
else if (filePath.toLowerCase().includes(lowerQuery)) score = 30;
- // Directories get a bonus to appear first
if (isDirectory && score > 0) score += 10;
return score;
}
- // Fuzzy file search using fd (fast, respects .gitignore)
private async getFuzzyFileSuggestions(
query: string,
options: { isQuotedPrefix: boolean; signal: AbortSignal },
@@ -783,7 +742,6 @@ export class CombinedAutocompleteProvider implements AutocompleteProvider {
}
}
- // Check if we should trigger file completion (called on Tab key)
shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
return getSlashCommandContext(lines, cursorLine, cursorCol)?.kind !== "name";
}
diff --git a/packages/tui/src/components/box.ts b/packages/tui/src/components/box.ts
index e1f265479a..7badbcd657 100644
--- a/packages/tui/src/components/box.ts
+++ b/packages/tui/src/components/box.ts
@@ -19,7 +19,6 @@ export class Box implements Component {
private paddingY: number;
private bgFn?: (text: string) => string;
- // Cache for rendered output
private cache?: RenderCache;
constructor(paddingX = 1, paddingY = 1, bgFn?: (text: string) => string) {
@@ -82,7 +81,6 @@ export class Box implements Component {
const contentWidth = Math.max(1, width - this.paddingX * 2);
const leftPad = " ".repeat(this.paddingX);
- // Render all children
const childLines: string[] = [];
const selectionRegions: TableCellSelectionRegion[] = [];
for (const child of this.children) {
@@ -109,34 +107,27 @@ export class Box implements Component {
return [];
}
- // Check if bgFn output changed by sampling
const bgSample = this.bgFn ? this.bgFn("test") : undefined;
- // Check cache validity
if (this.matchCache(width, childLines, bgSample)) {
this.cache!.selectionRegions = selectionRegions;
return this.cache!.lines;
}
- // Apply background and padding
const result: string[] = [];
- // Top padding
for (let i = 0; i < this.paddingY; i++) {
result.push(this.applyBg("", width));
}
- // Content
for (const line of childLines) {
result.push(this.applyBg(line, width));
}
- // Bottom padding
for (let i = 0; i < this.paddingY; i++) {
result.push(this.applyBg("", width));
}
- // Update cache
this.cache = { childLines, width, bgSample, lines: result, selectionRegions };
return result;
diff --git a/packages/tui/src/components/cancellable-loader.ts b/packages/tui/src/components/cancellable-loader.ts
index e8bd85b90e..99628b59d4 100644
--- a/packages/tui/src/components/cancellable-loader.ts
+++ b/packages/tui/src/components/cancellable-loader.ts
@@ -13,15 +13,15 @@ import { Loader } from "./loader.js";
export class CancellableLoader extends Loader {
private abortController = new AbortController();
- /** Called when user presses Escape */
+ /** Invoked after Escape aborts this loader. */
onAbort?: () => void;
- /** AbortSignal that is aborted when user presses Escape */
+ /** Abort signal triggered when Escape cancels this loader. */
get signal(): AbortSignal {
return this.abortController.signal;
}
- /** Whether the loader was aborted */
+ /** Whether Escape has already aborted this loader. */
get aborted(): boolean {
return this.abortController.signal.aborted;
}
diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.ts
index 9de16488c3..431b659186 100644
--- a/packages/tui/src/components/editor.ts
+++ b/packages/tui/src/components/editor.ts
@@ -45,12 +45,10 @@ function segmentWithMarkers(text: string, validPasteIds: Set<number>): Iterable<
const hasPaste = validPasteIds.size > 0 && text.includes("[paste #");
const hasImage = text.includes("[image #");
- // Fast path: nothing to merge.
if (!hasPaste && !hasImage) {
return baseSegmenter.segment(text);
}
- // Find all marker spans (paste markers gated by valid IDs, image markers always).
const markers: Array<{ start: number; end: number }> = [];
if (hasPaste) {
for (const m of text.matchAll(PASTE_MARKER_REGEX)) {
@@ -67,16 +65,13 @@ function segmentWithMarkers(text: string, validPasteIds: Set<number>): Iterable<
if (markers.length === 0) {
return baseSegmenter.segment(text);
}
- // The merge loop below assumes spans are sorted ascending by start.
markers.sort((a, b) => a.start - b.start);
- // Build merged segment list.
const baseSegments = baseSegmenter.segment(text);
const result: Intl.SegmentData[] = [];
let markerIdx = 0;
for (const seg of baseSegments) {
- // Skip past markers that are entirely before this segment.
while (markerIdx < markers.length && markers[markerIdx]!.end <= seg.index) {
markerIdx++;
}
@@ -84,8 +79,6 @@ function segmentWithMarkers(text: string, validPasteIds: Set<number>): Iterable<
const marker = markerIdx < markers.length ? markers[markerIdx]! : null;
if (marker && seg.index >= marker.start && seg.index < marker.end) {
- // This segment falls inside a marker.
- // If this is the first segment of the marker, emit a merged segment.
if (seg.index === marker.start) {
const markerText = text.slice(marker.start, marker.end);
result.push({
@@ -94,7 +87,6 @@ function segmentWithMarkers(text: string, validPasteIds: Set<number>): Iterable<
input: text,
});
}
- // Otherwise skip (already merged into the first segment).
} else {
result.push(seg);
}
@@ -204,7 +196,6 @@ export function wordWrapLine(line: string, maxWidth: number, preSegmented?: Intl
}
}
- // Push final chunk.
chunks.push({ text: line.slice(chunkStart), startIndex: chunkStart, endIndex: line.length });
return chunks;
@@ -260,7 +251,6 @@ export class Editor implements Component, Focusable {
cursorCol: 0,
};
- /** Focusable interface - set by TUI when focus changes */
focused: boolean = false;
protected tui: TUI;
@@ -268,19 +258,15 @@ export class Editor implements Component, Focusable {
private paddingX: number = 0;
private promptPrefix: string = "";
- // Store last render width for cursor navigation
private lastWidth: number = 80;
- // Vertical scrolling support
private scrollOffset: number = 0;
- // Border color (can be changed dynamically)
public borderColor: (str: string) => string;
public backgroundColor: ((str: string) => string) | undefined;
public autocompleteBackgroundColor: ((str: string) => string) | undefined;
public commandColor: ((str: string) => string) | undefined;
- // Autocomplete support
private autocompleteProvider?: AutocompleteProvider;
private autocompleteList?: SelectList;
private autocompleteState: "regular" | "force" | null = null;
@@ -299,26 +285,20 @@ export class Editor implements Component, Focusable {
invalidate: () => this.autocompleteList?.invalidate(),
};
- // Paste tracking for large pastes
private pastes: Map<number, string> = new Map();
private pasteCounter: number = 0;
- // Bracketed paste mode buffering
private pasteBuffer: string = "";
private isInPaste: boolean = false;
- // Prompt history for up/down navigation
private history: string[] = [];
private historyIndex: number = -1; // -1 = not browsing, 0 = most recent, 1 = older, etc.
- // Kill ring for Emacs-style kill/yank operations
private killRing = new KillRing();
private lastAction: "kill" | "yank" | "type-word" | null = null;
- // Character jump mode
private jumpMode: "forward" | "backward" | null = null;
- // Preferred visual column for vertical cursor movement (sticky column)
private preferredVisualCol: number | null = null;
// When the cursor is snapped to the start of an atomic segment, e.g. a
@@ -328,7 +308,6 @@ export class Editor implements Component, Focusable {
// to.
private snappedFromCursorCol: number | null = null;
- // Undo support
private undoStack = new UndoStack<EditorUndoSnapshot>((snapshot) => ({
lines: [...snapshot.lines],
cursorLine: snapshot.cursorLine,
@@ -430,10 +409,8 @@ export class Editor implements Component, Focusable {
addToHistory(text: string): void {
const trimmed = text.trim();
if (!trimmed) return;
- // Don't add consecutive duplicates
if (this.history.length > 0 && this.history[0] === trimmed) return;
this.history.unshift(trimmed);
- // Limit history size
if (this.history.length > 100) {
this.history.pop();
}
@@ -477,7 +454,6 @@ export class Editor implements Component, Focusable {
const newIndex = this.historyIndex - direction; // Up(-1) increases index, Down(1) decreases
if (newIndex < -1 || newIndex >= this.history.length) return;
- // Capture state when first entering history browsing mode
if (this.historyIndex === -1 && newIndex >= 0) {
this.pushUndoSnapshot();
}
@@ -485,7 +461,6 @@ export class Editor implements Component, Focusable {
this.historyIndex = newIndex;
if (this.historyIndex === -1) {
- // Returned to "current" state - clear editor
this.setTextInternal("");
} else {
this.setTextInternal(this.history[this.historyIndex] || "");
@@ -498,7 +473,6 @@ export class Editor implements Component, Focusable {
this.state.lines = lines.length === 0 ? [""] : lines;
this.state.cursorLine = this.state.lines.length - 1;
this.setCursorCol(this.state.lines[this.state.cursorLine]?.length || 0);
- // Reset scroll - render() will adjust to show cursor
this.scrollOffset = 0;
if (this.onChange) {
@@ -506,9 +480,7 @@ export class Editor implements Component, Focusable {
}
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
private getRenderMetrics(width: number): {
useBackgroundSurface: boolean;
@@ -550,34 +522,27 @@ export class Editor implements Component, Focusable {
// without padding we reserve 1 column for the cursor.
const layoutWidth = Math.max(1, inputWidth - (paddingX ? 0 : 1));
- // Store for cursor navigation (must match wrapping width)
this.lastWidth = layoutWidth;
const horizontal = this.borderColor("─");
- // Layout the text
const layoutLines = this.layoutText(layoutWidth);
- // Calculate max visible lines: 30% of terminal height, minimum 5 lines
const terminalRows = this.tui.terminal.rows;
const maxVisibleLines = Math.max(5, Math.floor(terminalRows * 0.3));
- // Find the cursor line index in layoutLines
let cursorLineIndex = layoutLines.findIndex((line) => line.hasCursor);
if (cursorLineIndex === -1) cursorLineIndex = 0;
- // Adjust scroll offset to keep cursor visible
if (cursorLineIndex < this.scrollOffset) {
this.scrollOffset = cursorLineIndex;
} else if (cursorLineIndex >= this.scrollOffset + maxVisibleLines) {
this.scrollOffset = cursorLineIndex - maxVisibleLines + 1;
}
- // Clamp scroll offset to valid range
const maxScrollOffset = Math.max(0, layoutLines.length - maxVisibleLines);
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScrollOffset));
- // Get visible lines slice
const visibleLines = layoutLines.slice(this.scrollOffset, this.scrollOffset + maxVisibleLines);
const result: string[] = [];
@@ -593,7 +558,6 @@ export class Editor implements Component, Focusable {
};
if (!useBackgroundSurface) {
- // Render top border (with scroll indicator if scrolled down)
if (this.scrollOffset > 0) {
const indicator = `─── ↑ ${this.scrollOffset} more `;
const remaining = width - visibleWidth(indicator);
@@ -609,7 +573,6 @@ export class Editor implements Component, Focusable {
const line = this.scrollOffset > 0 ? this.borderColor(` ↑ ${this.scrollOffset} more`) : "";
result.push(renderSurfaceLine(truncateToWidth(line, width)));
}
- // Render each visible layout line
// Emit hardware cursor marker only when focused and not showing autocomplete
const emitCursorMarker = this.focused && !this.autocompleteState;
@@ -621,7 +584,6 @@ export class Editor implements Component, Focusable {
let lineVisibleWidth = visibleWidth(layoutLine.text);
let cursorInPadding = false;
- // Add cursor if this line has it
if (layoutLine.hasCursor && layoutLine.cursorPos !== undefined) {
const before = displayText.slice(0, layoutLine.cursorPos);
const after = displayText.slice(layoutLine.cursorPos);
@@ -630,20 +592,15 @@ export class Editor implements Component, Focusable {
const marker = emitCursorMarker ? CURSOR_MARKER : "";
if (after.length > 0) {
- // Cursor is on a character (grapheme) - replace it with highlighted version
- // Get the first grapheme from 'after'
const afterGraphemes = [...this.segment(after)];
const firstGrapheme = afterGraphemes[0]?.segment || "";
const restAfter = after.slice(firstGrapheme.length);
const cursor = `\x1b[7m${firstGrapheme}${cursorReset}`;
displayText = before + marker + cursor + restAfter;
- // lineVisibleWidth stays the same - we're replacing, not adding
} else {
- // Cursor is at the end - add highlighted space
const cursor = `\x1b[7m ${cursorReset}`;
displayText = before + marker + cursor;
lineVisibleWidth = lineVisibleWidth + 1;
- // If cursor overflows content width into the padding, flag it
if (lineVisibleWidth > inputWidth && paddingX > 0) {
cursorInPadding = true;
}
@@ -657,11 +614,9 @@ export class Editor implements Component, Focusable {
layoutLine.hasCursor ? layoutLine.cursorPos : undefined,
);
- // Calculate padding based on actual visible width
const padding = " ".repeat(Math.max(0, inputWidth - lineVisibleWidth));
const lineRightPadding = cursorInPadding ? rightPadding.slice(1) : rightPadding;
- // Render the line (no side borders, just horizontal lines above and below)
const contentLine = `${promptLeadingPadding}${linePromptPrefix}${promptTrailingPadding}${displayText}${padding}${lineRightPadding}`;
const anchorMarker = layoutLine.hasCursor ? this.getAutocompleteAnchorMarker() : "";
result.push(anchorMarker + (useBackgroundSurface ? renderSurfaceLine(contentLine) : contentLine));
@@ -704,9 +659,7 @@ export class Editor implements Component, Focusable {
handleInput(data: string): void {
const kb = getKeybindings();
- // Handle character jump mode (awaiting next character to jump to)
if (this.jumpMode !== null) {
- // Cancel if the hotkey is pressed again
if (kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward")) {
this.jumpMode = null;
return;
@@ -714,18 +667,15 @@ export class Editor implements Component, Focusable {
const printable = decodePrintableKey(data) ?? (data.charCodeAt(0) >= 32 ? data : undefined);
if (printable !== undefined) {
- // Printable character - perform the jump
const direction = this.jumpMode;
this.jumpMode = null;
this.jumpToChar(printable, direction);
return;
}
- // Control character - cancel and fall through to normal handling
this.jumpMode = null;
}
- // Handle bracketed paste mode
if (data.includes("\x1b[200~")) {
this.isInPaste = true;
this.pasteBuffer = "";
@@ -751,18 +701,15 @@ export class Editor implements Component, Focusable {
return;
}
- // Ctrl+C - let parent handle (exit/clear)
if (kb.matches(data, "tui.input.copy")) {
return;
}
- // Undo
if (kb.matches(data, "tui.editor.undo")) {
this.undo();
return;
}
- // Handle autocomplete mode
if (this.autocompleteState && this.autocompleteList) {
if (kb.matches(data, "tui.select.cancel")) {
this.cancelAutocomplete();
@@ -825,7 +772,6 @@ export class Editor implements Component, Focusable {
if (this.onChange) this.onChange(this.getText());
return;
}
- // Fall through to submit
} else {
this.cancelAutocomplete();
if (this.onChange) this.onChange(this.getText());
@@ -835,13 +781,11 @@ export class Editor implements Component, Focusable {
}
}
- // Tab - trigger completion
if (kb.matches(data, "tui.input.tab") && !this.autocompleteState) {
this.handleTabCompletion();
return;
}
- // Deletion actions
if (kb.matches(data, "tui.editor.deleteToLineEnd")) {
this.deleteToEndOfLine();
return;
@@ -867,7 +811,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Kill ring actions
if (kb.matches(data, "tui.editor.yank")) {
this.yank();
return;
@@ -877,7 +820,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Cursor movement actions
if (kb.matches(data, "tui.editor.cursorLineStart")) {
this.moveToLineStart();
return;
@@ -895,7 +837,6 @@ export class Editor implements Component, Focusable {
return;
}
- // New line
if (
kb.matches(data, "tui.input.newLine") ||
(data.charCodeAt(0) === 10 && data.length > 1) ||
@@ -913,7 +854,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Submit (Enter)
if (kb.matches(data, "tui.input.submit")) {
if (this.disableSubmit) return;
@@ -930,14 +870,12 @@ export class Editor implements Component, Focusable {
return;
}
- // Arrow key navigation (with history support)
if (kb.matches(data, "tui.editor.cursorUp")) {
if (this.isEditorEmpty()) {
this.navigateHistory(-1);
} else if (this.historyIndex > -1 && this.isOnFirstVisualLine()) {
this.navigateHistory(-1);
} else if (this.isOnFirstVisualLine()) {
- // Already at top - jump to start of line
this.moveToLineStart();
} else {
this.moveCursor(-1, 0);
@@ -948,7 +886,6 @@ export class Editor implements Component, Focusable {
if (this.historyIndex > -1 && this.isOnLastVisualLine()) {
this.navigateHistory(1);
} else if (this.isOnLastVisualLine()) {
- // Already at bottom - jump to end of line
this.moveToLineEnd();
} else {
this.moveCursor(1, 0);
@@ -964,7 +901,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Page up/down - scroll by page and move cursor
if (kb.matches(data, "tui.editor.pageUp")) {
this.pageScroll(-1);
return;
@@ -974,7 +910,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Character jump mode triggers
if (kb.matches(data, "tui.editor.jumpForward")) {
this.jumpMode = "forward";
return;
@@ -984,7 +919,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Shift+Space - insert regular space
if (matchesKey(data, "shift+space")) {
this.insertCharacter(" ");
return;
@@ -996,7 +930,6 @@ export class Editor implements Component, Focusable {
return;
}
- // Regular characters
if (data.charCodeAt(0) >= 32) {
this.insertCharacter(data);
}
@@ -1006,7 +939,6 @@ export class Editor implements Component, Focusable {
const layoutLines: LayoutLine[] = [];
if (this.state.lines.length === 0 || (this.state.lines.length === 1 && this.state.lines[0] === "")) {
- // Empty editor
layoutLines.push({
text: "",
hasCursor: true,
@@ -1015,7 +947,6 @@ export class Editor implements Component, Focusable {
return layoutLines;
}
- // Process each logical line
for (let i = 0; i < this.state.lines.length; i++) {
const line = this.state.lines[i] || "";
const hiddenPrefixLength = this.getLineHiddenTextPrefixLength(i, line);
@@ -1033,7 +964,6 @@ export class Editor implements Component, Focusable {
}
if (lineVisibleWidth <= contentWidth) {
- // Line fits in one layout line
if (isCurrentLine) {
layoutLines.push({
text: displayLine,
@@ -1047,7 +977,6 @@ export class Editor implements Component, Focusable {
});
}
} else {
- // Line needs wrapping - use word-aware wrapping
const chunks = wordWrapLine(displayLine, contentWidth, [...this.segment(displayLine)]);
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
@@ -1057,7 +986,6 @@ export class Editor implements Component, Focusable {
const cursorPos = Math.max(0, this.state.cursorCol - hiddenPrefixLength);
const isLastChunk = chunkIndex === chunks.length - 1;
- // Determine if cursor is in this chunk
// For word-wrapped chunks, we need to handle the case where
// cursor might be in trimmed whitespace at end of chunk
let hasCursorInChunk = false;
@@ -1065,16 +993,12 @@ export class Editor implements Component, Focusable {
if (isCurrentLine) {
if (isLastChunk) {
- // Last chunk: cursor belongs here if >= startIndex
hasCursorInChunk = cursorPos >= chunk.startIndex;
adjustedCursorPos = cursorPos - chunk.startIndex;
} else {
- // Non-last chunk: cursor belongs here if in range [startIndex, endIndex)
- // But we need to handle the visual position in the trimmed text
hasCursorInChunk = cursorPos >= chunk.startIndex && cursorPos < chunk.endIndex;
if (hasCursorInChunk) {
adjustedCursorPos = cursorPos - chunk.startIndex;
- // Clamp to text length (in case cursor was in trimmed whitespace)
if (adjustedCursorPos > chunk.text.length) {
adjustedCursorPos = chunk.text.length;
}
@@ -1147,7 +1071,6 @@ export class Editor implements Component, Focusable {
this.lastAction = null;
this.historyIndex = -1; // Exit history browsing mode
const normalized = this.normalizeText(text);
- // Push undo snapshot if content differs (makes programmatic changes undoable)
if (this.getText() !== normalized) {
this.pushUndoSnapshot();
}
@@ -1185,7 +1108,6 @@ export class Editor implements Component, Focusable {
private insertTextAtCursorInternal(text: string): void {
if (!text) return;
- // Normalize line endings and tabs
const normalized = this.normalizeText(text);
const insertedLines = normalized.split("\n");
@@ -1194,25 +1116,18 @@ export class Editor implements Component, Focusable {
const afterCursor = currentLine.slice(this.state.cursorCol);
if (insertedLines.length === 1) {
- // Single line - insert at cursor position
this.state.lines[this.state.cursorLine] = beforeCursor + normalized + afterCursor;
this.setCursorCol(this.state.cursorCol + normalized.length);
} else {
- // Multi-line insertion
this.state.lines = [
- // All lines before current line
...this.state.lines.slice(0, this.state.cursorLine),
- // The first inserted line merged with text before cursor
beforeCursor + insertedLines[0],
- // All middle inserted lines
...insertedLines.slice(1, -1),
- // The last inserted line with text after cursor
insertedLines[insertedLines.length - 1] + afterCursor,
- // All lines after current line
...this.state.lines.slice(this.state.cursorLine + 1),
];
@@ -1225,7 +1140,6 @@ export class Editor implements Component, Focusable {
}
}
- // All the editor methods from before...
private insertCharacter(char: string, skipUndoCoalescing?: boolean): void {
this.historyIndex = -1; // Exit history browsing mode
@@ -1253,30 +1167,23 @@ export class Editor implements Component, Focusable {
this.onChange(this.getText());
}
- // Check if we should trigger or update autocomplete
if (!this.autocompleteState) {
const slashContext = this.getCurrentSlashCommandContext();
if (char === "/" && slashContext?.kind === "name") {
this.tryTriggerAutocomplete();
- }
- // Auto-trigger for symbol-based completion like @ or # at token boundaries
- else if (char === "@" || char === "#") {
+ } else if (char === "@" || char === "#") {
const currentLine = this.state.lines[this.state.cursorLine] || "";
const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
const charBeforeSymbol = textBeforeCursor[textBeforeCursor.length - 2];
if (textBeforeCursor.length === 1 || charBeforeSymbol === " " || charBeforeSymbol === "\t") {
this.tryTriggerAutocomplete();
}
- }
- // Also auto-trigger when typing letters in a slash command or symbol completion context
- else if (/[a-zA-Z0-9.\-_]/.test(char)) {
+ } else if (/[a-zA-Z0-9.\-_]/.test(char)) {
const currentLine = this.state.lines[this.state.cursorLine] || "";
const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
if (slashContext) {
this.tryTriggerAutocomplete();
- }
- // Check if we're in a symbol-based completion context like @ or #
- else if (textBeforeCursor.match(/(?:^|[\s])[@#][^\s]*$/)) {
+ } else if (textBeforeCursor.match(/(?:^|[\s])[@#][^\s]*$/)) {
this.tryTriggerAutocomplete();
}
}
@@ -1304,10 +1211,8 @@ export class Editor implements Component, Focusable {
return match;
});
- // Clean the pasted text: normalize line endings, expand tabs
const cleanText = this.normalizeText(decodedText);
- // Filter out non-printable characters except newlines
let filteredText = cleanText
.split("")
.filter((char) => char === "\n" || char.charCodeAt(0) >= 32)
@@ -1329,12 +1234,10 @@ export class Editor implements Component, Focusable {
// Check if this is a large paste (> 10 lines or > 1000 characters)
const totalChars = filteredText.length;
if (pastedLines.length > 10 || totalChars > 1000) {
- // Store the paste and insert a marker
this.pasteCounter++;
const pasteId = this.pasteCounter;
this.pastes.set(pasteId, filteredText);
- // Insert marker like "[paste #1 +123 lines]" or "[paste #1 1234 chars]"
const marker =
pastedLines.length > 10
? `[paste #${pasteId} +${pastedLines.length} lines]`
@@ -1344,7 +1247,6 @@ export class Editor implements Component, Focusable {
}
if (pastedLines.length === 1) {
- // Single line - insert atomically (do not trigger autocomplete during paste)
this.insertTextAtCursorInternal(filteredText);
return;
}
@@ -1365,11 +1267,9 @@ export class Editor implements Component, Focusable {
const before = currentLine.slice(0, this.state.cursorCol);
const after = currentLine.slice(this.state.cursorCol);
- // Split current line
this.state.lines[this.state.cursorLine] = before;
this.state.lines.splice(this.state.cursorLine + 1, 0, after);
- // Move cursor to start of new line
this.state.cursorLine++;
this.setCursorCol(0);
@@ -1415,10 +1315,8 @@ export class Editor implements Component, Focusable {
if (this.state.cursorCol > lineStartCol) {
this.pushUndoSnapshot();
- // Delete grapheme before cursor (handles emojis, combining characters, etc.)
const beforeCursor = line.slice(lineStartCol, this.state.cursorCol);
- // Find the last grapheme in the text before cursor
const graphemes = [...this.segment(beforeCursor)];
const lastGrapheme = graphemes[graphemes.length - 1];
const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
@@ -1436,7 +1334,6 @@ export class Editor implements Component, Focusable {
} else if (this.state.cursorLine > 0) {
this.pushUndoSnapshot();
- // Merge with previous line
const currentLine = this.state.lines[this.state.cursorLine] || "";
const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
@@ -1501,7 +1398,6 @@ export class Editor implements Component, Focusable {
const moveToVisualCol = this.computeVerticalMoveColumn(currentVisualCol, sourceMaxVisualCol, targetMaxVisualCol);
- // Set cursor position
this.state.cursorLine = targetVL.logicalLine;
const targetCol = targetVL.startCol + moveToVisualCol;
const logicalLine = this.state.lines[targetVL.logicalLine] || "";
@@ -1629,7 +1525,6 @@ export class Editor implements Component, Focusable {
this.killRing.push(deletedText, { prepend: true, accumulate: this.lastAction === "kill" });
this.lastAction = "kill";
- // Delete from start of line up to cursor
this.state.lines[this.state.cursorLine] =
currentLine.slice(0, lineStartCol) + currentLine.slice(this.state.cursorCol);
this.setCursorCol(lineStartCol);
@@ -1666,7 +1561,6 @@ export class Editor implements Component, Focusable {
this.killRing.push(deletedText, { prepend: false, accumulate: this.lastAction === "kill" });
this.lastAction = "kill";
- // Delete from cursor to end of line
this.state.lines[this.state.cursorLine] = currentLine.slice(0, this.state.cursorCol);
} else if (this.state.cursorLine < this.state.lines.length - 1) {
this.pushUndoSnapshot();
@@ -1787,7 +1681,6 @@ export class Editor implements Component, Focusable {
// Delete grapheme at cursor position (handles emojis, combining characters, etc.)
const afterCursor = currentLine.slice(this.state.cursorCol);
- // Find the first grapheme at cursor
const graphemes = [...this.segment(afterCursor)];
const firstGrapheme = graphemes[0];
const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
@@ -1827,12 +1720,10 @@ export class Editor implements Component, Focusable {
const displayLine = line.slice(hiddenPrefixLength);
const lineVisWidth = visibleWidth(displayLine);
if (displayLine.length === 0) {
- // Empty line still takes one visual line
visualLines.push({ logicalLine: i, startCol: hiddenPrefixLength, length: 0 });
} else if (lineVisWidth <= width) {
visualLines.push({ logicalLine: i, startCol: hiddenPrefixLength, length: displayLine.length });
} else {
- // Line needs wrapping - use word-aware wrapping
const chunks = wordWrapLine(displayLine, width, [...this.segment(displayLine)]);
for (const chunk of chunks) {
visualLines.push({
@@ -1907,11 +1798,9 @@ export class Editor implements Component, Focusable {
const firstGrapheme = graphemes[0];
this.setCursorCol(this.state.cursorCol + (firstGrapheme ? firstGrapheme.segment.length : 1));
} else if (this.state.cursorLine < this.state.lines.length - 1) {
- // Wrap to start of next logical line
this.state.cursorLine++;
this.setCursorCol(0);
} else {
- // At end of last line - can't move, but set preferredVisualCol for up/down navigation
const currentVL = visualLines[currentVisualLine];
if (currentVL) {
this.preferredVisualCol = this.state.cursorCol - currentVL.startCol;
@@ -1926,7 +1815,6 @@ export class Editor implements Component, Focusable {
const previousCol = this.state.cursorCol - (lastGrapheme ? lastGrapheme.segment.length : 1);
this.setCursorCol(Math.max(lineStartCol, previousCol));
} else if (this.state.cursorLine > 0) {
- // Wrap to end of previous logical line
this.state.cursorLine--;
const prevLine = this.state.lines[this.state.cursorLine] || "";
this.setCursorCol(prevLine.length);
@@ -1956,7 +1844,6 @@ export class Editor implements Component, Focusable {
const currentLine = this.state.lines[this.state.cursorLine] || "";
const lineStartCol = this.getLineHiddenTextPrefixLength(this.state.cursorLine, currentLine);
- // If at start of line, move to end of previous line
if (this.state.cursorCol <= lineStartCol) {
if (this.state.cursorLine > 0) {
this.state.cursorLine--;
@@ -1970,7 +1857,6 @@ export class Editor implements Component, Focusable {
const graphemes = [...this.segment(textBeforeCursor)];
let newCol = this.state.cursorCol;
- // Skip trailing whitespace
while (
graphemes.length > 0 &&
!isAtomicMarker(graphemes[graphemes.length - 1]?.segment || "") &&
@@ -1982,10 +1868,8 @@ export class Editor implements Component, Focusable {
if (graphemes.length > 0) {
const lastGrapheme = graphemes[graphemes.length - 1]?.segment || "";
if (isAtomicMarker(lastGrapheme)) {
- // Paste marker is a single atomic word
newCol -= graphemes.pop()?.segment.length || 0;
} else if (isPunctuationChar(lastGrapheme)) {
- // Skip punctuation run
while (
graphemes.length > 0 &&
isPunctuationChar(graphemes[graphemes.length - 1]?.segment || "") &&
@@ -1994,7 +1878,6 @@ export class Editor implements Component, Focusable {
newCol -= graphemes.pop()?.segment.length || 0;
}
} else {
- // Skip word run
while (
graphemes.length > 0 &&
!isWhitespaceChar(graphemes[graphemes.length - 1]?.segment || "") &&
@@ -2029,18 +1912,14 @@ export class Editor implements Component, Focusable {
* Replaces the last yanked text with the previous entry in the ring.
*/
private yankPop(): void {
- // Only works if we just yanked and have more than one entry
if (this.lastAction !== "yank" || this.killRing.length <= 1) return;
this.pushUndoSnapshot();
- // Delete the previously yanked text (still at end of ring before rotation)
this.deleteYankedText();
- // Rotate the ring: move end to front
this.killRing.rotate();
- // Insert the new most recent entry (now at end after rotation)
const text = this.killRing.peek()!;
this.insertYankedText(text);
@@ -2056,14 +1935,12 @@ export class Editor implements Component, Focusable {
const lines = text.split("\n");
if (lines.length === 1) {
- // Single line - insert at cursor
const currentLine = this.state.lines[this.state.cursorLine] || "";
const before = currentLine.slice(0, this.state.cursorCol);
const after = currentLine.slice(this.state.cursorCol);
this.state.lines[this.state.cursorLine] = before + text + after;
this.setCursorCol(this.state.cursorCol + text.length);
} else {
- // Multi-line insert
const currentLine = this.state.lines[this.state.cursorLine] || "";
const before = currentLine.slice(0, this.state.cursorCol);
const after = currentLine.slice(this.state.cursorCol);
@@ -2101,7 +1978,6 @@ export class Editor implements Component, Focusable {
const yankLines = yankedText.split("\n");
if (yankLines.length === 1) {
- // Single line - delete backward from cursor
const currentLine = this.state.lines[this.state.cursorLine] || "";
const deleteLen = yankedText.length;
const before = currentLine.slice(0, this.state.cursorCol - deleteLen);
@@ -2109,7 +1985,6 @@ export class Editor implements Component, Focusable {
this.state.lines[this.state.cursorLine] = before + after;
this.setCursorCol(this.state.cursorCol - deleteLen);
} else {
- // Multi-line delete - cursor is at end of last yanked line
const startLine = this.state.cursorLine - (yankLines.length - 1);
const startCol = (this.state.lines[startLine] || "").length - (yankLines[0] || "").length;
@@ -2177,7 +2052,6 @@ export class Editor implements Component, Focusable {
const line = lines[lineIdx] || "";
const isCurrentLine = lineIdx === this.state.cursorLine;
- // Current line: start after/before cursor; other lines: search full line
const searchFrom = isCurrentLine
? isForward
? this.state.cursorCol + 1
@@ -2192,14 +2066,12 @@ export class Editor implements Component, Focusable {
return;
}
}
- // No match found - cursor stays in place
}
private moveWordForwards(): void {
this.lastAction = null;
const currentLine = this.state.lines[this.state.cursorLine] || "";
- // If at end of line, move to start of next line
if (this.state.cursorCol >= currentLine.length) {
if (this.state.cursorLine < this.state.lines.length - 1) {
this.state.cursorLine++;
@@ -2214,7 +2086,6 @@ export class Editor implements Component, Focusable {
let next = iterator.next();
let newCol = this.state.cursorCol;
- // Skip leading whitespace
while (!next.done && !isAtomicMarker(next.value.segment) && isWhitespaceChar(next.value.segment)) {
newCol += next.value.segment.length;
next = iterator.next();
@@ -2223,16 +2094,13 @@ export class Editor implements Component, Focusable {
if (!next.done) {
const firstGrapheme = next.value.segment;
if (isAtomicMarker(firstGrapheme)) {
- // Paste marker is a single atomic word
newCol += firstGrapheme.length;
} else if (isPunctuationChar(firstGrapheme)) {
- // Skip punctuation run
while (!next.done && isPunctuationChar(next.value.segment) && !isAtomicMarker(next.value.segment)) {
newCol += next.value.segment.length;
next = iterator.next();
}
} else {
- // Skip word run
while (
!next.done &&
!isWhitespaceChar(next.value.segment) &&
@@ -2252,7 +2120,6 @@ export class Editor implements Component, Focusable {
return getSlashCommandContext(this.state.lines, this.state.cursorLine, this.state.cursorCol);
}
- // Autocomplete methods
/**
* Find the best autocomplete item index for the given prefix.
* Returns -1 if no match is found.
diff --git a/packages/tui/src/components/image.ts b/packages/tui/src/components/image.ts
index 8678cc211c..9b05309818 100644
--- a/packages/tui/src/components/image.ts
+++ b/packages/tui/src/components/image.ts
@@ -28,10 +28,11 @@ export interface ImageOptions {
maxWidthCells?: number;
maxHeightCells?: number;
filename?: string;
- /** Render metadata instead of terminal graphics. */
+ /** Renders textual image metadata instead of terminal graphics. */
fallbackOnly?: boolean;
+ /** Prefix prepended to textual fallback metadata. */
fallbackPrefix?: string;
- /** Kitty image ID. If provided, reuses this ID (for animations/updates). */
+ /** Kitty image ID to reuse across updates or animations. */
imageId?: number;
}
@@ -62,7 +63,7 @@ export class Image implements Component {
this.imageId = options.imageId;
}
- /** Get the Kitty image ID used by this image (if any). */
+ /** Returns the Kitty image ID allocated or supplied for this image. */
getImageId(): number | undefined {
return this.imageId;
}
@@ -99,7 +100,6 @@ export class Image implements Component {
});
if (result) {
- // Store the image ID for later cleanup
if (result.imageId) {
this.imageId = result.imageId;
}
diff --git a/packages/tui/src/components/input.ts b/packages/tui/src/components/input.ts
index 322b306be5..35e635fb21 100644
--- a/packages/tui/src/components/input.ts
+++ b/packages/tui/src/components/input.ts
@@ -21,18 +21,14 @@ export class Input implements Component, Focusable {
public onSubmit?: (value: string) => void;
public onEscape?: () => void;
- /** Focusable interface - set by TUI when focus changes */
focused: boolean = false;
- // Bracketed paste mode buffering
private pasteBuffer: string = "";
private isInPaste: boolean = false;
- // Kill ring for Emacs-style kill/yank operations
private killRing = new KillRing();
private lastAction: "kill" | "yank" | "type-word" | null = null;
- // Undo support
private undoStack = new UndoStack<InputState>();
getValue(): string {
@@ -49,34 +45,23 @@ export class Input implements Component, Focusable {
}
handleInput(data: string): void {
- // Handle bracketed paste mode
- // Start of paste: \x1b[200~
- // End of paste: \x1b[201~
-
- // Check if we're starting a bracketed paste
if (data.includes("\x1b[200~")) {
this.isInPaste = true;
this.pasteBuffer = "";
data = data.replace("\x1b[200~", "");
}
- // If we're in a paste, buffer the data
if (this.isInPaste) {
- // Check if this chunk contains the end marker
this.pasteBuffer += data;
const endIndex = this.pasteBuffer.indexOf("\x1b[201~");
if (endIndex !== -1) {
- // Extract the pasted content
const pasteContent = this.pasteBuffer.substring(0, endIndex);
- // Process the complete paste
this.handlePaste(pasteContent);
- // Reset paste state
this.isInPaste = false;
- // Handle any remaining input after the paste marker
const remaining = this.pasteBuffer.substring(endIndex + 6); // 6 = length of \x1b[201~
this.pasteBuffer = "";
if (remaining) {
@@ -88,25 +73,21 @@ export class Input implements Component, Focusable {
const kb = getKeybindings();
- // Escape/Cancel
if (kb.matches(data, "tui.select.cancel")) {
if (this.onEscape) this.onEscape();
return;
}
- // Undo
if (kb.matches(data, "tui.editor.undo")) {
this.undo();
return;
}
- // Submit
if (kb.matches(data, "tui.input.submit") || data === "\n") {
if (this.onSubmit) this.onSubmit(this.value);
return;
}
- // Deletion
if (kb.matches(data, "tui.editor.deleteCharBackward")) {
this.handleBackspace();
return;
@@ -137,7 +118,6 @@ export class Input implements Component, Focusable {
return;
}
- // Kill ring actions
if (kb.matches(data, "tui.editor.yank")) {
this.yank();
return;
@@ -147,7 +127,6 @@ export class Input implements Component, Focusable {
return;
}
- // Cursor movement
if (kb.matches(data, "tui.editor.cursorLeft")) {
this.lastAction = null;
if (this.cursor > 0) {
@@ -214,7 +193,6 @@ export class Input implements Component, Focusable {
}
private insertCharacter(char: string): void {
- // Undo coalescing: consecutive word chars coalesce into one undo unit
if (isWhitespaceChar(char) || this.lastAction !== "type-word") {
this.pushUndo();
}
@@ -325,12 +303,10 @@ export class Input implements Component, Focusable {
this.pushUndo();
- // Delete the previously yanked text (still at end of ring before rotation)
const prevText = this.killRing.peek() || "";
this.value = this.value.slice(0, this.cursor - prevText.length) + this.value.slice(this.cursor);
this.cursor -= prevText.length;
- // Rotate and insert new entry
this.killRing.rotate();
const text = this.killRing.peek() || "";
this.value = this.value.slice(0, this.cursor) + text + this.value.slice(this.cursor);
@@ -359,7 +335,6 @@ export class Input implements Component, Focusable {
const textBeforeCursor = this.value.slice(0, this.cursor);
const graphemes = [...segmenter.segment(textBeforeCursor)];
- // Skip trailing whitespace
while (graphemes.length > 0 && isWhitespaceChar(graphemes[graphemes.length - 1]?.segment || "")) {
this.cursor -= graphemes.pop()?.segment.length || 0;
}
@@ -367,12 +342,10 @@ export class Input implements Component, Focusable {
if (graphemes.length > 0) {
const lastGrapheme = graphemes[graphemes.length - 1]?.segment || "";
if (isPunctuationChar(lastGrapheme)) {
- // Skip punctuation run
while (graphemes.length > 0 && isPunctuationChar(graphemes[graphemes.length - 1]?.segment || "")) {
this.cursor -= graphemes.pop()?.segment.length || 0;
}
} else {
- // Skip word run
while (
graphemes.length > 0 &&
!isWhitespaceChar(graphemes[graphemes.length - 1]?.segment || "") &&
@@ -395,7 +368,6 @@ export class Input implements Component, Focusable {
const iterator = segments[Symbol.iterator]();
let next = iterator.next();
- // Skip leading whitespace
while (!next.done && isWhitespaceChar(next.value.segment)) {
this.cursor += next.value.segment.length;
next = iterator.next();
@@ -404,13 +376,11 @@ export class Input implements Component, Focusable {
if (!next.done) {
const firstGrapheme = next.value.segment;
if (isPunctuationChar(firstGrapheme)) {
- // Skip punctuation run
while (!next.done && isPunctuationChar(next.value.segment)) {
this.cursor += next.value.segment.length;
next = iterator.next();
}
} else {
- // Skip word run
while (!next.done && !isWhitespaceChar(next.value.segment) && !isPunctuationChar(next.value.segment)) {
this.cursor += next.value.segment.length;
next = iterator.next();
@@ -423,20 +393,15 @@ export class Input implements Component, Focusable {
this.lastAction = null;
this.pushUndo();
- // Clean the pasted text - remove newlines and carriage returns
const cleanText = pastedText.replace(/\r\n/g, "").replace(/\r/g, "").replace(/\n/g, "").replace(/\t/g, " ");
- // Insert at cursor position
this.value = this.value.slice(0, this.cursor) + cleanText + this.value.slice(this.cursor);
this.cursor += cleanText.length;
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(width: number): string[] {
- // Calculate visible window
const prompt = "> ";
const availableWidth = width - prompt.length;
@@ -449,11 +414,8 @@ export class Input implements Component, Focusable {
const totalWidth = visibleWidth(this.value);
if (totalWidth < availableWidth) {
- // Everything fits (leave room for cursor at end)
visibleText = this.value;
} else {
- // Need horizontal scrolling
- // Reserve one column for cursor if it's at the end
const scrollWidth = this.cursor === this.value.length ? availableWidth - 1 : availableWidth;
const cursorCol = visibleWidth(this.value.slice(0, this.cursor));
@@ -462,13 +424,10 @@ export class Input implements Component, Focusable {
let startCol = 0;
if (cursorCol < halfWidth) {
- // Cursor near start
startCol = 0;
} else if (cursorCol > totalWidth - halfWidth) {
- // Cursor near end
startCol = Math.max(0, totalWidth - scrollWidth);
} else {
- // Cursor in middle
startCol = Math.max(0, cursorCol - halfWidth);
}
@@ -481,8 +440,6 @@ export class Input implements Component, Focusable {
}
}
- // Build line with fake cursor
- // Insert cursor character at cursor position
const graphemes = [...segmenter.segment(visibleText.slice(cursorDisplay))];
const cursorGrapheme = graphemes[0];
@@ -493,11 +450,9 @@ export class Input implements Component, Focusable {
// Hardware cursor marker (zero-width, emitted before fake cursor for IME positioning)
const marker = this.focused ? CURSOR_MARKER : "";
- // Use inverse video to show cursor
const cursorChar = `\x1b[7m${atCursor}\x1b[27m`; // ESC[7m = reverse video, ESC[27m = normal
const textWithCursor = beforeCursor + marker + cursorChar + afterCursor;
- // Calculate visual width
const visualLength = visibleWidth(textWithCursor);
const padding = " ".repeat(Math.max(0, availableWidth - visualLength));
const line = prompt + textWithCursor + padding;
diff --git a/packages/tui/src/components/loader.ts b/packages/tui/src/components/loader.ts
index 6bac6ce818..7816d8366f 100644
--- a/packages/tui/src/components/loader.ts
+++ b/packages/tui/src/components/loader.ts
@@ -2,9 +2,7 @@ import type { TUI } from "../tui.js";
import { Text } from "./text.js";
export interface LoaderIndicatorOptions {
- /** Animation frames. Use an empty array to hide the indicator. */
frames?: string[];
- /** Frame interval in milliseconds for animated indicators. */
intervalMs?: number;
}
diff --git a/packages/tui/src/components/markdown.ts b/packages/tui/src/components/markdown.ts
index 16e7fe752a..87b035a1d4 100644
--- a/packages/tui/src/components/markdown.ts
+++ b/packages/tui/src/components/markdown.ts
@@ -132,17 +132,11 @@ function pickMarkdownParser(text: string): Marked {
* Applied to all text unless overridden by markdown formatting.
*/
export interface DefaultTextStyle {
- /** Foreground color function */
color?: (text: string) => string;
- /** Background color function */
bgColor?: (text: string) => string;
- /** Bold text */
bold?: boolean;
- /** Italic text */
italic?: boolean;
- /** Strikethrough text */
strikethrough?: boolean;
- /** Underline text */
underline?: boolean;
}
@@ -166,11 +160,8 @@ export interface MarkdownTheme {
strikethrough: (text: string) => string;
underline: (text: string) => string;
highlightCode?: (code: string, lang?: string) => string[];
- /** Prefix applied to each rendered code block line (default: " ") */
codeBlockIndent?: string;
- /** Inline math, e.g. $x_i$ (default: `code`) */
math?: (text: string) => string;
- /** Display math block lines, e.g. $$...$$ (default: `codeBlock`) */
mathBlock?: (text: string) => string;
}
@@ -187,7 +178,6 @@ export class Markdown implements Component {
private theme: MarkdownTheme;
private defaultStylePrefix?: string;
- // Cache for rendered output
private cachedText?: string;
private cachedWidth?: number;
private cachedLines?: string[];
@@ -233,26 +223,21 @@ export class Markdown implements Component {
}
render(width: number): string[] {
- // Check cache
if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
return this.cachedLines;
}
- // Calculate available width for content (subtract horizontal padding)
const contentWidth = Math.max(1, width - this.paddingX * 2);
- // Don't render anything if there's no actual text
if (!this.text || this.text.trim() === "") {
const result: string[] = [];
this.selectionRegions = [];
- // Update cache
this.cachedText = this.text;
this.cachedWidth = width;
this.cachedLines = result;
return result;
}
- // Replace tabs with 3 spaces for consistent rendering
const normalizedText = this.text.replace(/\t/g, " ");
// Parse markdown to HTML-like tokens
@@ -284,7 +269,6 @@ export class Markdown implements Component {
}
this.blockCache = nextCache;
- // Add top/bottom padding (empty lines)
const bgFn = this.defaultTextStyle?.bgColor;
const emptyLine = " ".repeat(width);
const emptyLines: string[] = [];
@@ -293,7 +277,6 @@ export class Markdown implements Component {
emptyLines.push(line);
}
- // Combine top padding, content, and bottom padding
const markedResult = [...emptyLines, ...contentLines, ...emptyLines];
const { lines: result, regions } = extractTableCellSelectionRegions(markedResult, (index) => {
this.tableIdentities[index] ??= {};
@@ -301,7 +284,6 @@ export class Markdown implements Component {
});
this.selectionRegions = regions;
- // Update cache
this.cachedText = this.text;
this.cachedWidth = width;
this.cachedLines = result;
@@ -332,7 +314,6 @@ export class Markdown implements Component {
if (bgFn) {
blockLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
} else {
- // No background - just pad to width
const visibleLen = visibleWidth(lineWithMargins);
const paddingNeeded = Math.max(0, width - visibleLen);
blockLines.push(lineWithMargins + " ".repeat(paddingNeeded));
@@ -356,12 +337,10 @@ export class Markdown implements Component {
let styled = text;
- // Apply foreground color (NOT background - that's applied at padding stage)
if (this.defaultTextStyle.color) {
styled = this.defaultTextStyle.color(styled);
}
- // Apply text decorations using this.theme
if (this.defaultTextStyle.bold) {
styled = this.theme.bold(styled);
}
@@ -466,7 +445,6 @@ export class Markdown implements Component {
case "paragraph": {
const paragraphText = this.renderInlineTokens(token.tokens || [], styleContext);
lines.push(paragraphText);
- // Don't add spacing if next token is space or list
if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
lines.push("");
}
@@ -492,8 +470,6 @@ export class Markdown implements Component {
case "list": {
const listLines = this.renderList(token as any, 0, styleContext);
lines.push(...listLines);
- // Don't add spacing after lists if a space token follows
- // (the space token will handle it)
break;
}
@@ -514,7 +490,6 @@ export class Markdown implements Component {
return quoteStyle(lineWithReappliedStyle);
};
- // Calculate available width for quote content (subtract border "│ " = 2 chars)
const quoteContentWidth = Math.max(1, width - 2);
// Blockquotes contain block-level tokens (paragraph, list, code, etc.), so render
@@ -534,7 +509,6 @@ export class Markdown implements Component {
);
}
- // Avoid rendering an extra empty quote line before the outer blockquote spacing.
while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") {
renderedQuoteLines.pop();
}
@@ -560,19 +534,16 @@ export class Markdown implements Component {
break;
case "html":
- // Render HTML as plain text (escaped for terminal)
if ("raw" in token && typeof token.raw === "string") {
lines.push(this.applyDefaultStyle(token.raw.trim()));
}
break;
case "space":
- // Space tokens represent blank lines in markdown
lines.push("");
break;
default:
- // Handle any other token types as plain text
if ("text" in token && typeof token.text === "string") {
lines.push(token.text);
}
@@ -593,7 +564,6 @@ export class Markdown implements Component {
for (const token of tokens) {
switch (token.type) {
case "text":
- // Text tokens in list items can have nested tokens for inline formatting
if (token.tokens && token.tokens.length > 0) {
result += this.renderInlineTokens(token.tokens, resolvedStyleContext);
} else {
@@ -602,7 +572,6 @@ export class Markdown implements Component {
break;
case "paragraph":
- // Paragraph tokens contain nested inline tokens
result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
break;
@@ -637,7 +606,6 @@ export class Markdown implements Component {
// so we always show only the link text regardless of whether it matches href.
result += hyperlink(styledLink, token.href) + stylePrefix;
} else {
- // Fallback: print URL in parentheses when text differs from href.
// Compare raw token.text (not styled) against href for the equality check.
// For mailto: links strip the prefix (autolinked emails use text="[email protected]"
// but href="mailto:[email protected]").
@@ -662,14 +630,12 @@ export class Markdown implements Component {
}
case "html":
- // Render inline HTML as plain text
if ("raw" in token && typeof token.raw === "string") {
result += applyTextWithNewlines(token.raw);
}
break;
default:
- // Handle any other inline token types as plain text
if ("text" in token && typeof token.text === "string") {
result += applyTextWithNewlines(token.text);
}
@@ -693,40 +659,32 @@ export class Markdown implements Component {
): string[] {
const lines: string[] = [];
const indent = " ".repeat(depth);
- // Use the list's start property (defaults to 1 for ordered lists)
const startNumber = token.start ?? 1;
for (let i = 0; i < token.items.length; i++) {
const item = token.items[i];
const bullet = token.ordered ? `${startNumber + i}. ` : "- ";
- // Process item tokens to handle nested lists
const itemLines = this.renderListItem(item.tokens || [], depth, styleContext);
if (itemLines.length > 0) {
- // First line - check if it's a nested list
// A nested list will start with indent (spaces) followed by cyan bullet
const firstLine = itemLines[0];
const isNestedList = /^\s+\x1b\[36m[-\d]/.test(firstLine); // starts with spaces + cyan + bullet char
if (isNestedList) {
- // This is a nested list, just add it as-is (already has full indent)
lines.push(firstLine);
} else {
- // Regular text content - add indent and bullet
lines.push(indent + this.theme.listBullet(bullet) + firstLine);
}
- // Rest of the lines
for (let j = 1; j < itemLines.length; j++) {
const line = itemLines[j];
const isNestedListLine = /^\s+\x1b\[36m[-\d]/.test(line); // starts with spaces + cyan + bullet char
if (isNestedListLine) {
- // Nested list line - already has full indent
lines.push(line);
} else {
- // Regular content - add parent indent + 2 spaces for continuation
lines.push(`${indent} ${line}`);
}
}
@@ -848,7 +806,6 @@ export class Markdown implements Component {
return lines;
}
- // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
// = 2 + (n-1) * 3 + 2 = 3n + 1
const borderOverhead = 3 * numCols + 1;
const availableForCells = availableWidth - borderOverhead;
@@ -863,7 +820,6 @@ export class Markdown implements Component {
const maxUnbrokenWordWidth = 30;
- // Calculate natural column widths (what each column needs without constraints)
const naturalWidths: number[] = [];
const minWordWidths: number[] = [];
for (let i = 0; i < numCols; i++) {
@@ -911,15 +867,12 @@ export class Markdown implements Component {
minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
}
- // Calculate column widths that fit within available width
const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
let columnWidths: number[];
if (totalNaturalWidth <= availableWidth) {
- // Everything fits naturally
columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
} else {
- // Need to shrink columns to fit
const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
return total + Math.max(0, width - minColumnWidths[index]);
}, 0);
@@ -952,11 +905,9 @@ export class Markdown implements Component {
}
}
- // Render top border
const topBorderCells = columnWidths.map((w) => "─".repeat(w));
lines.push(markTableStart(`┌─${topBorderCells.join("─┬─")}─┐`));
- // Render header with wrapping
const headerCells = token.header.map((cell, i) => {
const text = this.renderInlineTokens(cell.tokens || [], styleContext);
return { lines: this.wrapCellText(text, columnWidths[i]), content: stripAnsi(text) };
@@ -972,12 +923,10 @@ export class Markdown implements Component {
lines.push(`│ ${rowParts.join(" │ ")} │`);
}
- // Render separator
const separatorCells = columnWidths.map((w) => "─".repeat(w));
const separatorLine = `├─${separatorCells.join("─┼─")}─┤`;
lines.push(separatorLine);
- // Render rows with wrapping
for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
const row = token.rows[rowIndex];
const rowCells = row.map((cell, i) => {
@@ -1000,7 +949,6 @@ export class Markdown implements Component {
}
}
- // Render bottom border
const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
lines.push(markTableEnd(`└─${bottomBorderCells.join("─┴─")}─┘`));
diff --git a/packages/tui/src/components/select-list.ts b/packages/tui/src/components/select-list.ts
index f5b4abb354..3663b3a584 100644
--- a/packages/tui/src/components/select-list.ts
+++ b/packages/tui/src/components/select-list.ts
@@ -67,7 +67,6 @@ export class SelectList implements Component {
setFilter(filter: string): void {
this.filteredItems = this.items.filter((item) => item.value.toLowerCase().startsWith(filter.toLowerCase()));
- // Reset selection when filter changes
this.selectedIndex = 0;
}
@@ -75,14 +74,11 @@ export class SelectList implements Component {
this.selectedIndex = Math.max(0, Math.min(index, this.filteredItems.length - 1));
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(width: number): string[] {
const lines: string[] = [];
- // If no items match filter, show message
if (this.filteredItems.length === 0) {
lines.push(this.theme.noMatch(" No matching commands"));
return lines;
@@ -90,14 +86,12 @@ export class SelectList implements Component {
const primaryColumnWidth = this.getPrimaryColumnWidth();
- // Calculate visible range with scrolling
const startIndex = Math.max(
0,
Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible),
);
const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);
- // Render visible items
for (let i = startIndex; i < endIndex; i++) {
const item = this.filteredItems[i];
if (!item) continue;
@@ -123,25 +117,18 @@ export class SelectList implements Component {
handleInput(keyData: string): void {
const kb = getKeybindings();
- // Up arrow - wrap to bottom when at top
if (kb.matches(keyData, "tui.select.up")) {
this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;
this.notifySelectionChange();
- }
- // Down arrow - wrap to top when at bottom
- else if (kb.matches(keyData, "tui.select.down")) {
+ } else if (kb.matches(keyData, "tui.select.down")) {
this.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;
this.notifySelectionChange();
- }
- // Enter
- else if (kb.matches(keyData, "tui.select.confirm")) {
+ } else if (kb.matches(keyData, "tui.select.confirm")) {
const selectedItem = this.filteredItems[this.selectedIndex];
if (selectedItem && this.onSelect) {
this.onSelect(selectedItem);
}
- }
- // Escape or Ctrl+C
- else if (kb.matches(keyData, "tui.select.cancel")) {
+ } else if (kb.matches(keyData, "tui.select.cancel")) {
if (this.onCancel) {
this.onCancel();
}
diff --git a/packages/tui/src/components/settings-list.ts b/packages/tui/src/components/settings-list.ts
index 6a6235dd5b..6351f60ac3 100644
--- a/packages/tui/src/components/settings-list.ts
+++ b/packages/tui/src/components/settings-list.ts
@@ -42,7 +42,6 @@ export class SettingsList implements Component {
private searchInput?: Input;
private searchEnabled: boolean;
- // Submenu state
private submenuComponent: Component | null = null;
private submenuItemIndex: number | null = null;
@@ -66,7 +65,6 @@ export class SettingsList implements Component {
}
}
- /** Update an item's currentValue */
updateValue(id: string, newValue: string): void {
const item = this.items.find((i) => i.id === id);
if (item) {
@@ -79,7 +77,6 @@ export class SettingsList implements Component {
}
render(width: number): string[] {
- // If submenu is active, render it instead
if (this.submenuComponent) {
return this.submenuComponent.render(width);
}
@@ -110,17 +107,14 @@ export class SettingsList implements Component {
return lines;
}
- // Calculate visible range with scrolling
const startIndex = Math.max(
0,
Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), displayItems.length - this.maxVisible),
);
const endIndex = Math.min(startIndex + this.maxVisible, displayItems.length);
- // Calculate max label width for alignment
const maxLabelWidth = Math.min(30, Math.max(...this.items.map((item) => visibleWidth(item.label))));
- // Render visible items
for (let i = startIndex; i < endIndex; i++) {
const item = displayItems[i];
if (!item) continue;
@@ -129,11 +123,9 @@ export class SettingsList implements Component {
const prefix = isSelected ? this.theme.cursor : " ";
const prefixWidth = visibleWidth(prefix);
- // Pad label to align values
const labelPadded = item.label + " ".repeat(Math.max(0, maxLabelWidth - visibleWidth(item.label)));
const labelText = this.theme.label(labelPadded, isSelected);
- // Calculate space for value
const separator = " ";
const usedWidth = prefixWidth + maxLabelWidth + visibleWidth(separator);
const valueMaxWidth = width - usedWidth - 2;
@@ -143,13 +135,11 @@ export class SettingsList implements Component {
lines.push(truncateToWidth(prefix + labelText + separator + valueText, width));
}
- // Add scroll indicator if needed
if (startIndex > 0 || endIndex < displayItems.length) {
const scrollText = ` (${this.selectedIndex + 1}/${displayItems.length})`;
lines.push(this.theme.hint(truncateToWidth(scrollText, width - 2, "")));
}
- // Add description for selected item
const selectedItem = displayItems[this.selectedIndex];
if (selectedItem?.description) {
lines.push("");
@@ -159,7 +149,6 @@ export class SettingsList implements Component {
}
}
- // Add hint
this.addHintLine(lines, width);
return lines;
@@ -173,7 +162,6 @@ export class SettingsList implements Component {
return;
}
- // Main list input handling
const kb = getKeybindings();
const displayItems = this.searchEnabled ? this.filteredItems : this.items;
if (kb.matches(data, "tui.select.up")) {
@@ -201,7 +189,6 @@ export class SettingsList implements Component {
if (!item) return;
if (item.submenu) {
- // Open submenu, passing current value so it can pre-select correctly
this.submenuItemIndex = this.selectedIndex;
this.submenuComponent = item.submenu(item.currentValue, (selectedValue?: string) => {
if (selectedValue !== undefined) {
@@ -211,7 +198,6 @@ export class SettingsList implements Component {
this.closeSubmenu();
});
} else if (item.values && item.values.length > 0) {
- // Cycle through values
const currentIndex = item.values.indexOf(item.currentValue);
const nextIndex = (currentIndex + 1) % item.values.length;
const newValue = item.values[nextIndex];
@@ -222,7 +208,6 @@ export class SettingsList implements Component {
private closeSubmenu(): void {
this.submenuComponent = null;
- // Restore selection to the item that opened the submenu
if (this.submenuItemIndex !== null) {
this.selectedIndex = this.submenuItemIndex;
this.submenuItemIndex = null;
diff --git a/packages/tui/src/components/spacer.ts b/packages/tui/src/components/spacer.ts
index 8c63d3c2ec..5ffc33a66e 100644
--- a/packages/tui/src/components/spacer.ts
+++ b/packages/tui/src/components/spacer.ts
@@ -14,9 +14,7 @@ export class Spacer implements Component {
this.lines = lines;
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(_width: number): string[] {
const result: string[] = [];
diff --git a/packages/tui/src/components/text.ts b/packages/tui/src/components/text.ts
index efcf25b451..f6bcf943a9 100644
--- a/packages/tui/src/components/text.ts
+++ b/packages/tui/src/components/text.ts
@@ -10,7 +10,6 @@ export class Text implements Component {
private paddingY: number; // Top/bottom padding
private customBgFn?: (text: string) => string;
- // Cache for rendered output
private cachedText?: string;
private cachedWidth?: number;
private cachedLines?: string[];
@@ -43,12 +42,10 @@ export class Text implements Component {
}
render(width: number): string[] {
- // Check cache
if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
return this.cachedLines;
}
- // Don't render anything if there's no actual text
if (!this.text || this.text.trim() === "") {
const result: string[] = [];
this.cachedText = this.text;
@@ -57,36 +54,28 @@ export class Text implements Component {
return result;
}
- // Replace tabs with 3 spaces
const normalizedText = this.text.replace(/\t/g, " ");
- // Calculate content width (subtract left/right margins)
const contentWidth = Math.max(1, width - this.paddingX * 2);
- // Wrap text (this preserves ANSI codes but does NOT pad)
const wrappedLines = wrapTextWithAnsi(normalizedText, contentWidth);
- // Add margins and background to each line
const leftMargin = " ".repeat(this.paddingX);
const rightMargin = " ".repeat(this.paddingX);
const contentLines: string[] = [];
for (const line of wrappedLines) {
- // Add margins
const lineWithMargins = leftMargin + line + rightMargin;
- // Apply background if specified (this also pads to full width)
if (this.customBgFn) {
contentLines.push(applyBackgroundToLine(lineWithMargins, width, this.customBgFn));
} else {
- // No background - just pad to width with spaces
const visibleLen = visibleWidth(lineWithMargins);
const paddingNeeded = Math.max(0, width - visibleLen);
contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
}
}
- // Add top/bottom padding (empty lines)
const emptyLine = " ".repeat(width);
const emptyLines: string[] = [];
for (let i = 0; i < this.paddingY; i++) {
@@ -96,7 +85,6 @@ export class Text implements Component {
const result = [...emptyLines, ...contentLines, ...emptyLines];
- // Update cache
this.cachedText = this.text;
this.cachedWidth = width;
this.cachedLines = result;
diff --git a/packages/tui/src/components/truncated-text.ts b/packages/tui/src/components/truncated-text.ts
index d0efc64b9e..721a62f8ef 100644
--- a/packages/tui/src/components/truncated-text.ts
+++ b/packages/tui/src/components/truncated-text.ts
@@ -19,47 +19,37 @@ export class TruncatedText implements Component {
this.text = text;
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(width: number): string[] {
const result: string[] = [];
- // Empty line padded to width
const emptyLine = " ".repeat(width);
- // Add vertical padding above
for (let i = 0; i < this.paddingY; i++) {
result.push(emptyLine);
}
- // Calculate available width after horizontal padding
const availableWidth = Math.max(1, width - this.paddingX * 2);
- // Take only the first line (stop at newline)
let singleLineText = this.text;
const newlineIndex = this.text.indexOf("\n");
if (newlineIndex !== -1) {
singleLineText = this.text.substring(0, newlineIndex);
}
- // Truncate text if needed (accounting for ANSI codes)
const displayText = truncateToWidth(singleLineText, availableWidth);
- // Add horizontal padding
const leftPadding = " ".repeat(this.paddingX);
const rightPadding = " ".repeat(this.paddingX);
const lineWithPadding = leftPadding + displayText + rightPadding;
- // Pad line to exactly width characters
const lineVisibleWidth = visibleWidth(lineWithPadding);
const paddingNeeded = Math.max(0, width - lineVisibleWidth);
const finalLine = lineWithPadding + " ".repeat(paddingNeeded);
result.push(finalLine);
- // Add vertical padding below
for (let i = 0; i < this.paddingY; i++) {
result.push(emptyLine);
}
diff --git a/packages/tui/src/editor-component.ts b/packages/tui/src/editor-component.ts
index 1678fc85f4..6bb0ad3345 100644
--- a/packages/tui/src/editor-component.ts
+++ b/packages/tui/src/editor-component.ts
@@ -14,10 +14,6 @@ export interface EditorPasteSnapshot {
* compatibility with the core application.
*/
export interface EditorComponent extends Component {
- // =========================================================================
- // Core text access (required)
- // =========================================================================
-
/** Get the current text content */
getText(): string;
@@ -27,20 +23,12 @@ export interface EditorComponent extends Component {
/** Handle raw terminal input (key presses, paste sequences, etc.) */
handleInput(data: string): void;
- // =========================================================================
- // Callbacks (required)
- // =========================================================================
-
/** Called when user submits (e.g., Enter key) */
onSubmit?: (text: string) => void;
/** Called when text changes */
onChange?: (text: string) => void;
- // =========================================================================
- // History support (optional)
- // =========================================================================
-
/** Add text to history for up/down navigation */
addToHistory?(text: string): void;
@@ -50,10 +38,6 @@ export interface EditorComponent extends Component {
/** Clear prompt history (e.g. when switching to a different session). */
clearHistory?(): void;
- // =========================================================================
- // Advanced text manipulation (optional)
- // =========================================================================
-
/** Insert text at current cursor position */
insertTextAtCursor?(text: string): void;
@@ -67,17 +51,9 @@ export interface EditorComponent extends Component {
restorePasteSnapshot?(snapshot: EditorPasteSnapshot): void;
- // =========================================================================
- // Autocomplete support (optional)
- // =========================================================================
-
/** Set the autocomplete provider */
setAutocompleteProvider?(provider: AutocompleteProvider): void;
- // =========================================================================
- // Appearance (optional)
- // =========================================================================
-
/** Border color function */
borderColor?: (str: string) => string;
diff --git a/packages/tui/src/fullscreen.ts b/packages/tui/src/fullscreen.ts
index 7c21e55caa..45a7c3617f 100644
--- a/packages/tui/src/fullscreen.ts
+++ b/packages/tui/src/fullscreen.ts
@@ -105,7 +105,6 @@ export class FullscreenViewport {
let dockLines = dock;
const dockHeight = clippedFullscreenDockHeight(dockLines.length, height);
if (dockLines.length > dockHeight) {
- // bottom of the dock (editor + footer) wins over widgets above it
dockLines = dockLines.slice(dockLines.length - dockHeight);
}
const windowHeight = height - dockLines.length;
@@ -140,7 +139,6 @@ export class FullscreenViewport {
return flipped ? { start: b, end: a } : { start: a, end: b };
}
- // Per-line selected column span, or null when the line is outside the selection.
private selectionSpan(lineIndex: number, sel: { start: SelectionPoint; end: SelectionPoint }): ColumnSpan | null {
if (lineIndex < sel.start.line || lineIndex > sel.end.line) return null;
return {
@@ -646,7 +644,6 @@ export class FullscreenViewport {
height: number,
cursorPos: { row: number; col: number } | null,
): void {
- // over-tall frames (overlay overflow) show their bottom `height` lines
if (frame.length > height) {
frame = frame.slice(frame.length - height);
}
diff --git a/packages/tui/src/fuzzy.ts b/packages/tui/src/fuzzy.ts
index 4a3557862c..a483996542 100644
--- a/packages/tui/src/fuzzy.ts
+++ b/packages/tui/src/fuzzy.ts
@@ -31,24 +31,20 @@ export function fuzzyMatch(query: string, text: string): FuzzyMatch {
if (textLower[i] === normalizedQuery[queryIndex]) {
const isWordBoundary = i === 0 || /[\s\-_./:]/.test(textLower[i - 1]!);
- // Reward consecutive matches
if (lastMatchIndex === i - 1) {
consecutiveMatches++;
score -= consecutiveMatches * 5;
} else {
consecutiveMatches = 0;
- // Penalize gaps
if (lastMatchIndex >= 0) {
score += (i - lastMatchIndex - 1) * 2;
}
}
- // Reward word boundary matches
if (isWordBoundary) {
score -= 10;
}
- // Slight penalty for later matches
score += i * 0.1;
lastMatchIndex = i;
diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.ts
index 4accb4fe8b..865555dfba 100644
--- a/packages/tui/src/index.ts
+++ b/packages/tui/src/index.ts
@@ -1,6 +1,3 @@
-// Core TUI interfaces and classes
-
-// Autocomplete support
export {
type AutocompleteItem,
type AutocompleteProvider,
@@ -8,7 +5,6 @@ export {
CombinedAutocompleteProvider,
type SlashCommand,
} from "./autocomplete.js";
-// Components
export { Box } from "./components/box.js";
export { CancellableLoader } from "./components/cancellable-loader.js";
export { Editor, type EditorOptions, type EditorTheme } from "./components/editor.js";
@@ -27,18 +23,14 @@ export { type SettingItem, SettingsList, type SettingsListTheme } from "./compon
export { Spacer } from "./components/spacer.js";
export { Text } from "./components/text.js";
export { TruncatedText } from "./components/truncated-text.js";
-// Editor component interface (for custom editors)
export type { EditorComponent, EditorPasteSnapshot } from "./editor-component.js";
-// Fullscreen (alternate-screen) viewport
export {
clippedFullscreenDockHeight,
FULLSCREEN_MIN_TRANSCRIPT_ROWS,
FullscreenViewport,
type ScrollInfo,
} from "./fullscreen.js";
-// Fuzzy matching
export { type FuzzyMatch, fuzzyFilter, fuzzyFilterScored, fuzzyMatch, type ScoredItem } from "./fuzzy.js";
-// Keybindings
export {
getKeybindings,
type Keybinding,
@@ -51,7 +43,6 @@ export {
setKeybindings,
TUI_KEYBINDINGS,
} from "./keybindings.js";
-// Keyboard input handling
export {
decodeKittyPrintable,
isKeyRelease,
@@ -64,9 +55,7 @@ export {
parseKey,
setKittyProtocolActive,
} from "./keys.js";
-// LaTeX math to Unicode conversion
export { latexToUnicode } from "./latex.js";
-// SGR mouse event parsing
export {
isMouseSequence,
isWheelDown,
@@ -76,12 +65,9 @@ export {
type MouseEvent,
parseSgrMouseEvent,
} from "./mouse.js";
-// Render caching
export { VersionedRenderCache } from "./render-cache.js";
export type { TableCellSelectionRegion } from "./selection-metadata.js";
-// Input buffering for batch splitting
export { StdinBuffer, type StdinBufferEventMap, type StdinBufferOptions } from "./stdin-buffer.js";
-// Terminal interface and implementations
export { ProcessTerminal, type Terminal, type TerminalStopOptions } from "./terminal.js";
export {
bestAnsiColor,
@@ -105,7 +91,6 @@ export {
type TerminalBackgroundKind,
type TerminalColorMode,
} from "./terminal-colors.js";
-// Terminal image support
export {
allocateImageId,
type CellDimensions,
@@ -148,5 +133,4 @@ export {
TUI,
type TuiStopOptions,
} from "./tui.js";
-// Utilities
export { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "./utils.js";
diff --git a/packages/tui/src/keybindings.ts b/packages/tui/src/keybindings.ts
index 4308c35b97..f35de327e9 100644
--- a/packages/tui/src/keybindings.ts
+++ b/packages/tui/src/keybindings.ts
@@ -5,7 +5,6 @@ import { type KeyId, matchesKey } from "./keys.js";
* Downstream packages can add keybindings via declaration merging.
*/
export interface Keybindings {
- // Editor navigation and editing
"tui.editor.cursorUp": true;
"tui.editor.cursorDown": true;
"tui.editor.cursorLeft": true;
@@ -27,17 +26,14 @@ export interface Keybindings {
"tui.editor.yank": true;
"tui.editor.yankPop": true;
"tui.editor.undo": true;
- // Generic input actions
"tui.input.newLine": true;
"tui.input.submit": true;
"tui.input.tab": true;
"tui.input.copy": true;
- // Fullscreen transcript viewport
"tui.viewport.pageUp": true;
"tui.viewport.pageDown": true;
"tui.viewport.top": true;
"tui.viewport.follow": true;
- // Generic selection actions
"tui.select.up": true;
"tui.select.down": true;
"tui.select.pageUp": true;
diff --git a/packages/tui/src/keys.ts b/packages/tui/src/keys.ts
index c34801fafc..73b165d167 100644
--- a/packages/tui/src/keys.ts
+++ b/packages/tui/src/keys.ts
@@ -18,10 +18,6 @@
* - isKittyProtocolActive() - Query global Kitty protocol state
*/
-// =============================================================================
-// Global Kitty Protocol State
-// =============================================================================
-
let _kittyProtocolActive = false;
/**
@@ -39,10 +35,6 @@ export function isKittyProtocolActive(): boolean {
return _kittyProtocolActive;
}
-// =============================================================================
-// Type-Safe Key Identifiers
-// =============================================================================
-
type Letter =
| "a"
| "b"
@@ -161,7 +153,6 @@ export type KeyId = BaseKey | ModifiedKeyId<BaseKey>;
* - Key.ctrlShift("p"), Key.ctrlAlt("x"), Key.ctrlSuper("k") for combined modifiers
*/
export const Key = {
- // Special keys
escape: "escape" as const,
esc: "esc" as const,
enter: "enter" as const,
@@ -193,7 +184,6 @@ export const Key = {
f11: "f11" as const,
f12: "f12" as const,
- // Symbol keys
backtick: "`" as const,
hyphen: "-" as const,
equals: "=" as const,
@@ -226,13 +216,11 @@ export const Key = {
greaterthan: ">" as const,
question: "?" as const,
- // Single modifiers
ctrl: <K extends BaseKey>(key: K): `ctrl+${K}` => `ctrl+${key}`,
shift: <K extends BaseKey>(key: K): `shift+${K}` => `shift+${key}`,
alt: <K extends BaseKey>(key: K): `alt+${K}` => `alt+${key}`,
super: <K extends BaseKey>(key: K): `super+${K}` => `super+${key}`,
- // Combined modifiers
ctrlShift: <K extends BaseKey>(key: K): `ctrl+shift+${K}` => `ctrl+shift+${key}`,
shiftCtrl: <K extends BaseKey>(key: K): `shift+ctrl+${K}` => `shift+ctrl+${key}`,
ctrlAlt: <K extends BaseKey>(key: K): `ctrl+alt+${K}` => `ctrl+alt+${key}`,
@@ -246,15 +234,10 @@ export const Key = {
altSuper: <K extends BaseKey>(key: K): `alt+super+${K}` => `alt+super+${key}`,
superAlt: <K extends BaseKey>(key: K): `super+alt+${K}` => `super+alt+${key}`,
- // Triple modifiers
ctrlShiftAlt: <K extends BaseKey>(key: K): `ctrl+shift+alt+${K}` => `ctrl+shift+alt+${key}`,
ctrlShiftSuper: <K extends BaseKey>(key: K): `ctrl+shift+super+${K}` => `ctrl+shift+super+${key}`,
} as const;
-// =============================================================================
-// Constants
-// =============================================================================
-
const SYMBOL_KEYS = new Set([
"`",
"-",
@@ -494,10 +477,6 @@ const matchesLegacyModifierSequence = (data: string, key: LegacyModifierKey, mod
return false;
};
-// =============================================================================
-// Kitty Protocol Parsing
-// =============================================================================
-
/**
* Event types from Kitty keyboard protocol (flag 2)
* 1 = key press, 2 = key repeat, 3 = key release
@@ -517,7 +496,6 @@ interface ParsedModifyOtherKeysSequence {
modifier: number;
}
-// Store the last parsed event type for isKeyRelease() to query
let _lastEventType: KeyEventType = "press";
/**
@@ -533,8 +511,6 @@ export function isKeyRelease(data: string): boolean {
return false;
}
- // Quick check: release events with flag 2 contain ":3"
- // Format: \x1b[<codepoint>;<modifier>:3u
if (
data.includes(":3u") ||
data.includes(":3~") ||
@@ -606,7 +582,6 @@ function parseKittySequence(data: string): ParsedKittySequence | null {
return { codepoint, shiftedKey, baseLayoutKey, modifier: modValue - 1, eventType };
}
- // Arrow keys with modifier: \x1b[1;<mod>A/B/C/D or \x1b[1;<mod>:<event>A/B/C/D
const arrowMatch = data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);
if (arrowMatch) {
const modValue = parseInt(arrowMatch[1]!, 10);
@@ -656,7 +631,6 @@ function matchesKittySequence(data: string, expectedCodepoint: number, expectedM
const actualMod = parsed.modifier & ~LOCK_MASK;
const expectedMod = expectedModifier & ~LOCK_MASK;
- // Check if modifiers match
if (actualMod !== expectedMod) return false;
const normalizedCodepoint = normalizeShiftedLetterIdentityCodepoint(
@@ -668,7 +642,6 @@ function matchesKittySequence(data: string, expectedCodepoint: number, expectedM
expectedModifier,
);
- // Primary match: codepoint matches directly after normalizing functional keys
if (normalizedCodepoint === normalizedExpectedCodepoint) return true;
// Alternate match: use base layout key for non-Latin keyboard layouts.
@@ -733,10 +706,6 @@ function matchesRawBackspace(data: string, expectedModifier: number): boolean {
return isWindowsTerminalSession() ? expectedModifier === MODIFIERS.ctrl : expectedModifier === 0;
}
-// =============================================================================
-// Generic Key Matching
-// =============================================================================
-
/**
* Get the control character for a key.
* Uses the universal formula: code & 0x1f (mask to lower 5 bits)
@@ -752,7 +721,6 @@ function rawCtrlChar(key: string): string | null {
if ((code >= 97 && code <= 122) || char === "[" || char === "\\" || char === "]" || char === "_") {
return String.fromCharCode(code & 0x1f);
}
- // Handle - as _ (same physical key on US keyboards)
if (char === "-") {
return String.fromCharCode(31); // Same as Ctrl+_
}
@@ -1165,7 +1133,6 @@ export function matchesKey(data: string, keyId: KeyId): boolean {
}
}
- // Handle single letter/digit keys and symbols
if (key.length === 1 && ((key >= "a" && key <= "z") || isDigitKey(key) || SYMBOL_KEYS.has(key))) {
const codepoint = key.charCodeAt(0);
const rawCtrl = rawCtrlChar(key);
@@ -1216,7 +1183,6 @@ export function matchesKey(data: string, keyId: KeyId): boolean {
);
}
- // Check both raw char and Kitty sequence (needed for release events)
return data === key || matchesKittySequence(data, codepoint, 0);
}
@@ -1331,7 +1297,6 @@ export function parseKey(data: string): string | undefined {
if (data === "\x1b[5~") return "pageUp";
if (data === "\x1b[6~") return "pageDown";
- // Raw Ctrl+letter
if (data.length === 1) {
const code = data.charCodeAt(0);
if (code >= 1 && code <= 26) {
@@ -1345,10 +1310,6 @@ export function parseKey(data: string): string | undefined {
return undefined;
}
-// =============================================================================
-// Kitty CSI-u Printable Decoding
-// =============================================================================
-
const KITTY_CSI_U_REGEX = /^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/;
const KITTY_PRINTABLE_ALLOWED_MODIFIERS = MODIFIERS.shift | LOCK_MASK;
diff --git a/packages/tui/src/kill-ring.ts b/packages/tui/src/kill-ring.ts
index 2292f91aa3..81183b5862 100644
--- a/packages/tui/src/kill-ring.ts
+++ b/packages/tui/src/kill-ring.ts
@@ -27,12 +27,10 @@ export class KillRing {
}
}
- /** Get most recent entry without modifying the ring. */
peek(): string | undefined {
return this.ring.length > 0 ? this.ring[this.ring.length - 1] : undefined;
}
- /** Move last entry to front (for yank-pop cycling). */
rotate(): void {
if (this.ring.length > 1) {
const last = this.ring.pop()!;
diff --git a/packages/tui/src/latex.ts b/packages/tui/src/latex.ts
index 11762ff990..1200e518e0 100644
--- a/packages/tui/src/latex.ts
+++ b/packages/tui/src/latex.ts
@@ -11,7 +11,6 @@
*/
const SYMBOLS: Record<string, string> = {
- // Greek lowercase
alpha: "α",
beta: "β",
gamma: "γ",
@@ -41,7 +40,6 @@ const SYMBOLS: Record<string, string> = {
chi: "χ",
psi: "ψ",
omega: "ω",
- // Greek uppercase
Gamma: "Γ",
Delta: "Δ",
Theta: "Θ",
@@ -53,7 +51,6 @@ const SYMBOLS: Record<string, string> = {
Phi: "Φ",
Psi: "Ψ",
Omega: "Ω",
- // Big operators
sum: "∑",
prod: "∏",
coprod: "∐",
@@ -69,7 +66,6 @@ const SYMBOLS: Record<string, string> = {
bigvee: "⋁",
bigwedge: "⋀",
bigsqcup: "⨆",
- // Binary operators
pm: "±",
mp: "∓",
times: "×",
@@ -96,7 +92,6 @@ const SYMBOLS: Record<string, string> = {
uplus: "⊎",
dagger: "†",
ddagger: "‡",
- // Relations
leq: "≤",
le: "≤",
geq: "≥",
@@ -135,7 +130,6 @@ const SYMBOLS: Record<string, string> = {
triangleq: "≜",
coloneqq: "≔",
coloneq: "≔",
- // Arrows
to: "→",
rightarrow: "→",
leftarrow: "←",
@@ -169,7 +163,6 @@ const SYMBOLS: Record<string, string> = {
searrow: "↘",
nwarrow: "↖",
swarrow: "↙",
- // Misc
infty: "∞",
partial: "∂",
nabla: "∇",
@@ -203,7 +196,6 @@ const SYMBOLS: Record<string, string> = {
prime: "′",
therefore: "∴",
because: "∵",
- // Dots
dots: "…",
ldots: "…",
dotsc: "…",
@@ -212,7 +204,6 @@ const SYMBOLS: Record<string, string> = {
dotsb: "⋯",
vdots: "⋮",
ddots: "⋱",
- // Delimiters
langle: "⟨",
rangle: "⟩",
lceil: "⌈",
diff --git a/packages/tui/src/mouse.ts b/packages/tui/src/mouse.ts
index fdcad4684f..c08f03dae1 100644
--- a/packages/tui/src/mouse.ts
+++ b/packages/tui/src/mouse.ts
@@ -1,16 +1,15 @@
-/** SGR mouse event parsing (CSI < button ; x ; y M/m). */
-
export interface MouseEvent {
- /** Base button code with modifier/motion bits stripped (wheel: 64 up, 65 down). */
+ /** Base SGR button code with modifier and motion bits removed; wheel up/down are 64/65. */
button: number;
- /** 1-based column. */
+ /** One-based terminal column. */
x: number;
- /** 1-based row. */
+ /** One-based terminal row. */
y: number;
- /** True for press/wheel/drag ("M"), false for release ("m"). */
+ /** True for SGR `M` reports (press, wheel, or drag), false for release `m`. */
press: boolean;
- /** True for drag/motion reports (bit 32). */
+ /** Whether the SGR motion bit is set. */
motion: boolean;
+ /** Modifier bits carried by the SGR report. */
shift: boolean;
alt: boolean;
ctrl: boolean;
@@ -26,7 +25,6 @@ const MODIFIER_ALT = 8;
const MODIFIER_CTRL = 16;
const MOTION_BIT = 32;
-/** True for any mouse report (SGR or legacy), parseable or not. */
export function isMouseSequence(sequence: string): boolean {
return sequence.startsWith("\x1b[<") || sequence.startsWith("\x1b[M");
}
diff --git a/packages/tui/src/stdin-buffer.ts b/packages/tui/src/stdin-buffer.ts
index 4aaf462709..4b393c5113 100644
--- a/packages/tui/src/stdin-buffer.ts
+++ b/packages/tui/src/stdin-buffer.ts
@@ -37,43 +37,33 @@ function isCompleteSequence(data: string): "complete" | "incomplete" | "not-esca
const afterEsc = data.slice(1);
- // CSI sequences: ESC [
if (afterEsc.startsWith("[")) {
- // Check for old-style mouse sequence: ESC[M + 3 bytes
if (afterEsc.startsWith("[M")) {
- // Old-style mouse needs ESC[M + 3 bytes = 6 total
return data.length >= 6 ? "complete" : "incomplete";
}
return isCompleteCsiSequence(data);
}
- // OSC sequences: ESC ]
if (afterEsc.startsWith("]")) {
return isCompleteOscSequence(data);
}
- // DCS sequences: ESC P ... ESC \ (includes XTVersion responses)
if (afterEsc.startsWith("P")) {
return isCompleteDcsSequence(data);
}
- // APC sequences: ESC _ ... ESC \ (includes Kitty graphics responses)
if (afterEsc.startsWith("_")) {
return isCompleteApcSequence(data);
}
- // SS3 sequences: ESC O
if (afterEsc.startsWith("O")) {
- // ESC O followed by a single character
return afterEsc.length >= 2 ? "complete" : "incomplete";
}
- // Meta key sequences: ESC followed by a single character
if (afterEsc.length === 1) {
return "complete";
}
- // Unknown escape sequence - treat as complete
return "complete";
}
@@ -86,30 +76,22 @@ function isCompleteCsiSequence(data: string): "complete" | "incomplete" {
return "complete";
}
- // Need at least ESC [ and one more character
if (data.length < 3) {
return "incomplete";
}
const payload = data.slice(2);
- // CSI sequences end with a byte in the range 0x40-0x7E (@-~)
- // This includes all letters and several special characters
const lastChar = payload[payload.length - 1];
const lastCharCode = lastChar.charCodeAt(0);
if (lastCharCode >= 0x40 && lastCharCode <= 0x7e) {
- // Special handling for SGR mouse sequences
- // Format: ESC[<B;X;Ym or ESC[<B;X;YM
if (payload.startsWith("<")) {
- // Must have format: <digits;digits;digits[Mm]
const mouseMatch = /^<\d+;\d+;\d+[Mm]$/.test(payload);
if (mouseMatch) {
return "complete";
}
- // If it ends with M or m but doesn't match the pattern, still incomplete
if (lastChar === "M" || lastChar === "m") {
- // Check if we have the right structure
const parts = payload.slice(1, -1).split(";");
if (parts.length === 3 && parts.every((p) => /^\d+$/.test(p))) {
return "complete";
@@ -134,7 +116,6 @@ function isCompleteOscSequence(data: string): "complete" | "incomplete" {
return "complete";
}
- // OSC sequences end with ST (ESC \) or BEL (\x07)
if (data.endsWith(`${ESC}\\`) || data.endsWith("\x07")) {
return "complete";
}
@@ -152,7 +133,6 @@ function isCompleteDcsSequence(data: string): "complete" | "incomplete" {
return "complete";
}
- // DCS sequences end with ST (ESC \)
if (data.endsWith(`${ESC}\\`)) {
return "complete";
}
@@ -170,7 +150,6 @@ function isCompleteApcSequence(data: string): "complete" | "incomplete" {
return "complete";
}
- // APC sequences end with ST (ESC \)
if (data.endsWith(`${ESC}\\`)) {
return "complete";
}
@@ -196,9 +175,7 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
while (pos < buffer.length) {
const remaining = buffer.slice(pos);
- // Try to extract a sequence starting at this position
if (remaining.startsWith(ESC)) {
- // Find the end of this escape sequence
let seqEnd = 1;
while (seqEnd <= remaining.length) {
const candidate = remaining.slice(0, seqEnd);
@@ -211,7 +188,6 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
} else if (status === "incomplete") {
seqEnd++;
} else {
- // Should not happen when starting with ESC
sequences.push(candidate);
pos += seqEnd;
break;
@@ -222,7 +198,6 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
return { sequences, remainder: remaining };
}
} else {
- // Not an escape sequence - take a single character
sequences.push(remaining[0]!);
pos++;
}
@@ -262,7 +237,6 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
}
public process(data: string | Buffer): void {
- // Clear any pending timeout
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
diff --git a/packages/tui/src/undo-stack.ts b/packages/tui/src/undo-stack.ts
index db6bbfb113..dca99650a2 100644
--- a/packages/tui/src/undo-stack.ts
+++ b/packages/tui/src/undo-stack.ts
@@ -9,17 +9,14 @@ export class UndoStack<S> {
constructor(private readonly clone: (state: S) => S = structuredClone) {}
- /** Push a clone of the given state onto the stack. */
push(state: S): void {
this.stack.push(this.clone(state));
}
- /** Pop and return the most recent snapshot, or undefined if empty. */
pop(): S | undefined {
return this.stack.pop();
}
- /** Remove all snapshots. */
clear(): void {
this.stack.length = 0;
}
diff --git a/packages/tui/test/autocomplete.test.ts b/packages/tui/test/autocomplete.test.ts
index d85300a04d..5b2e8143cb 100644
--- a/packages/tui/test/autocomplete.test.ts
+++ b/packages/tui/test/autocomplete.test.ts
@@ -235,8 +235,6 @@ describe("CombinedAutocompleteProvider", () => {
const result = await getSuggestions(provider, lines, cursorLine, cursorCol, true);
console.log("Result:", result);
- // This might return null if /A doesn't match anything, which is fine
- // We're mainly testing that the prefix extraction works
if (result) {
assert.strictEqual(result.prefix, "/A", "Prefix should be '/A'");
}
diff --git a/packages/tui/test/bug-regression-isimageline-startswith-bug.test.ts b/packages/tui/test/bug-regression-isimageline-startswith-bug.test.ts
deleted file mode 100644
index ff15d18fba..0000000000
--- a/packages/tui/test/bug-regression-isimageline-startswith-bug.test.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-/**
- * Bug regression test for isImageLine() crash scenario
- *
- * Bug: When isImageLine() used startsWith() and terminal doesn't support images,
- * it would return false for lines containing image escape sequences, causing TUI to
- * crash with "Rendered line exceeds terminal width" error.
- *
- * Fix: Changed to use includes() to detect escape sequences anywhere in the line.
- *
- * This test demonstrates:
- * 1. The bug scenario with the old implementation
- * 2. That the fix works correctly
- */
-
-import assert from "node:assert";
-import { describe, it } from "node:test";
-
-describe("Bug regression: isImageLine() crash with image escape sequences", () => {
- describe("Bug scenario: Terminal without image support", () => {
- it("old implementation would return false, causing crash", () => {
- /**
- * OLD IMPLEMENTATION (buggy):
- * ```typescript
- * export function isImageLine(line: string): boolean {
- * const prefix = getImageEscapePrefix();
- * return prefix !== null && line.startsWith(prefix);
- * }
- * ```
- *
- * When terminal doesn't support images:
- * - getImageEscapePrefix() returns null
- * - isImageLine() returns false even for lines containing image sequences
- * - TUI performs width check on line containing 300KB+ of base64 data
- * - Crash: "Rendered line exceeds terminal width (304401 > 115)"
- */
-
- // Simulate old implementation behavior
- const oldIsImageLine = (line: string, imageEscapePrefix: string | null): boolean => {
- return imageEscapePrefix !== null && line.startsWith(imageEscapePrefix);
- };
-
- // When terminal doesn't support images, prefix is null
- const terminalWithoutImageSupport = null;
-
- // Line containing image escape sequence with text before it (common bug scenario)
- const lineWithImageSequence =
- "Read image file [image/jpeg]\x1b]1337;File=size=800,600;inline=1:base64data...\x07";
-
- // Old implementation would return false (BUG!)
- const oldResult = oldIsImageLine(lineWithImageSequence, terminalWithoutImageSupport);
- assert.strictEqual(
- oldResult,
- false,
- "Bug: old implementation returns false for line containing image sequence when terminal has no image support",
- );
- });
-
- it("new implementation returns true correctly", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- // Line containing image escape sequence with text before it
- const lineWithImageSequence =
- "Read image file [image/jpeg]\x1b]1337;File=size=800,600;inline=1:base64data...\x07";
-
- // New implementation should return true (FIX!)
- const newResult = isImageLine(lineWithImageSequence);
- assert.strictEqual(newResult, true, "Fix: new implementation returns true for line containing image sequence");
- });
-
- it("new implementation detects Kitty sequences in any position", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- const scenarios = [
- "At start: \x1b_Ga=T,f=100,data...\x1b\\",
- "Prefix \x1b_Ga=T,data...\x1b\\",
- "Suffix text \x1b_Ga=T,data...\x1b\\ suffix",
- "Middle \x1b_Ga=T,data...\x1b\\ more text",
- // Very long line (simulating 300KB+ crash scenario)
- `Text before \x1b_Ga=T,f=100${"A".repeat(300000)} text after`,
- ];
-
- for (const line of scenarios) {
- assert.strictEqual(isImageLine(line), true, `Should detect Kitty sequence in: ${line.slice(0, 50)}...`);
- }
- });
-
- it("new implementation detects iTerm2 sequences in any position", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- const scenarios = [
- "At start: \x1b]1337;File=size=100,100:base64...\x07",
- "Prefix \x1b]1337;File=inline=1:data==\x07",
- "Suffix text \x1b]1337;File=inline=1:data==\x07 suffix",
- "Middle \x1b]1337;File=inline=1:data==\x07 more text",
- // Very long line (simulating 304KB crash scenario)
- `Text before \x1b]1337;File=size=800,600;inline=1:${"B".repeat(300000)} text after`,
- ];
-
- for (const line of scenarios) {
- assert.strictEqual(isImageLine(line), true, `Should detect iTerm2 sequence in: ${line.slice(0, 50)}...`);
- }
- });
- });
-
- describe("Integration: Tool execution scenario", () => {
- /**
- * This simulates what happens when the `read` tool reads an image file.
- * The tool result contains both text and image content:
- *
- * ```typescript
- * {
- * content: [
- * { type: "text", text: "Read image file [image/jpeg]\n800x600" },
- * { type: "image", data: "base64...", mimeType: "image/jpeg" }
- * ]
- * }
- * ```
- *
- * When this is rendered, the image component creates escape sequences.
- * If isImageLine() doesn't detect them, TUI crashes.
- */
-
- it("detects image sequences in read tool output", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- // Simulate output when read tool processes an image
- // The line might have text from the read result plus the image escape sequence
- const toolOutputLine = "Read image file [image/jpeg]\x1b]1337;File=size=800,600;inline=1:base64image...\x07";
-
- assert.strictEqual(isImageLine(toolOutputLine), true, "Should detect image sequence in tool output line");
- });
-
- it("detects Kitty sequences from Image component", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- // Kitty image component creates multi-line output with escape sequences
- const kittyLine = "\x1b_Ga=T,f=100,t=f,d=base64data...\x1b\\\x1b_Gm=i=1;\x1b\\";
-
- assert.strictEqual(isImageLine(kittyLine), true, "Should detect Kitty image component output");
- });
-
- it("handles ANSI codes before image sequences", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- // Line might have styling (error, warning, etc.) before image data
- const lines = [
- "\x1b[31mError\x1b[0m: \x1b]1337;File=inline=1:base64==\x07",
- "\x1b[33mWarning\x1b[0m: \x1b_Ga=T,data...\x1b\\",
- "\x1b[1mBold\x1b[0m \x1b]1337;File=:base64==\x07\x1b[0m",
- ];
-
- for (const line of lines) {
- assert.strictEqual(
- isImageLine(line),
- true,
- `Should detect image sequence after ANSI codes: ${line.slice(0, 30)}...`,
- );
- }
- });
- });
-
- describe("Crash scenario simulation", () => {
- it("does NOT crash on very long lines with image sequences", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- /**
- * Simulate the exact crash scenario:
- * - Line is 304,401 characters (the crash log showed 58649 > 115)
- * - Contains image escape sequence somewhere in the middle
- * - Old implementation would return false, causing TUI to do width check
- * - New implementation returns true, skipping width check (preventing crash)
- */
-
- const base64Char = "A".repeat(100);
- const iterm2Sequence = "\x1b]1337;File=size=800,600;inline=1:";
-
- // Build a line that would cause the crash
- const crashLine =
- "Output: " +
- iterm2Sequence +
- base64Char.repeat(3040) + // ~304,000 chars
- " end of output";
-
- // Verify line is very long
- assert(crashLine.length > 300000, "Test line should be > 300KB");
-
- // New implementation should detect it (prevents crash)
- const detected = isImageLine(crashLine);
- assert.strictEqual(detected, true, "Should detect image sequence in very long line, preventing TUI crash");
- });
-
- it("handles lines exactly matching crash log dimensions", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- /**
- * Crash log showed: line 58649 chars wide, terminal width 115
- * Let's create a line with similar characteristics
- */
-
- const targetWidth = 58649;
- const prefix = "Text";
- const sequence = "\x1b_Ga=T,f=100";
- const suffix = "End";
- const padding = "A".repeat(targetWidth - prefix.length - sequence.length - suffix.length);
- const line = `${prefix}${sequence}${padding}${suffix}`;
-
- assert.strictEqual(line.length, 58649);
- assert.strictEqual(isImageLine(line), true, "Should detect image sequence in 58649-char line");
- });
- });
-
- describe("Negative cases: Don't false positive", () => {
- it("does not detect images in regular long text", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- // Very long line WITHOUT image sequences
- const longText = "A".repeat(100000);
-
- assert.strictEqual(isImageLine(longText), false, "Should not detect images in plain long text");
- });
-
- it("does not detect images in lines with file paths", async () => {
- const { isImageLine } = await import("../src/terminal-image.js");
-
- const filePaths = [
- "/path/to/1337/image.jpg",
- "/usr/local/bin/File_converter",
- "~/Documents/1337File_backup.png",
- "./_G_test_file.txt",
- ];
-
- for (const path of filePaths) {
- assert.strictEqual(isImageLine(path), false, `Should not falsely detect image sequence in path: ${path}`);
- }
- });
- });
-});
diff --git a/packages/tui/test/chat-simple.ts b/packages/tui/test/chat-simple.ts
index 836d1f53a5..cc1eb3e580 100644
--- a/packages/tui/test/chat-simple.ts
+++ b/packages/tui/test/chat-simple.ts
@@ -1,7 +1,3 @@
-/**
- * Simple chat interface demo using tui.ts
- */
-
import chalk from "chalk";
import { CombinedAutocompleteProvider } from "../src/autocomplete.js";
import { Editor } from "../src/components/editor.js";
@@ -12,21 +8,16 @@ import { ProcessTerminal } from "../src/terminal.js";
import { TUI } from "../src/tui.js";
import { defaultEditorTheme, defaultMarkdownTheme } from "./test-themes.js";
-// Create terminal
const terminal = new ProcessTerminal();
-// Create TUI
const tui = new TUI(terminal);
-// Create chat container with some initial messages
tui.addChild(
new Text("Welcome to Simple Chat!\n\nType your messages below. Type '/' for commands. Press Ctrl+C to exit."),
);
-// Create editor with autocomplete
const editor = new Editor(tui, defaultEditorTheme);
-// Set up autocomplete provider with slash commands and file completion
const autocompleteProvider = new CombinedAutocompleteProvider(
[
{ name: "delete", description: "Delete the last message" },
@@ -38,30 +29,20 @@ editor.setAutocompleteProvider(autocompleteProvider);
tui.addChild(editor);
-// Focus the editor
tui.setFocus(editor);
-// Track if we're waiting for bot response
let isResponding = false;
-// Handle message submission
editor.onSubmit = (value: string) => {
- // Prevent submission if already responding
if (isResponding) {
return;
}
const trimmed = value.trim();
- // Handle slash commands
if (trimmed === "/delete") {
const children = tui.children;
- // Remove component before editor (if there are any besides the initial text)
if (children.length > 3) {
- // children[0] = "Welcome to Simple Chat!"
- // children[1] = "Type your messages below..."
- // children[2...n-1] = messages
- // children[n] = editor
children.splice(children.length - 2, 1);
}
tui.requestRender();
@@ -70,7 +51,6 @@ editor.onSubmit = (value: string) => {
if (trimmed === "/clear") {
const children = tui.children;
- // Remove all messages but keep the welcome text and editor
children.splice(2, children.length - 3);
tui.requestRender();
return;
@@ -98,7 +78,6 @@ editor.onSubmit = (value: string) => {
setTimeout(() => {
tui.removeChild(loader);
- // Simulate a response
const responses = [
"That's interesting! Tell me more.",
"I see what you mean.",
@@ -111,19 +90,15 @@ editor.onSubmit = (value: string) => {
];
const randomResponse = responses[Math.floor(Math.random() * responses.length)];
- // Add assistant message with no background (transparent)
const botMessage = new Markdown(randomResponse, 1, 1, defaultMarkdownTheme);
children.splice(children.length - 1, 0, botMessage);
- // Re-enable submit
isResponding = false;
editor.disableSubmit = false;
- // Request render
tui.requestRender();
}, 1000);
}
};
-// Start the TUI
tui.start();
diff --git a/packages/tui/test/editor.test.ts b/packages/tui/test/editor.test.ts
index 2251eb89e8..14cad2c628 100644
--- a/packages/tui/test/editor.test.ts
+++ b/packages/tui/test/editor.test.ts
@@ -8,12 +8,10 @@ import { visibleWidth } from "../src/utils.js";
import { defaultEditorTheme } from "./test-themes.js";
import { VirtualTerminal } from "./virtual-terminal.js";
-/** Create a TUI with a virtual terminal for testing */
function createTestTUI(cols = 80, rows = 24): TUI {
return new TUI(new VirtualTerminal(cols, rows));
}
-/** Standard applyCompletion that replaces prefix with item.value */
function applyCompletion(
lines: string[],
cursorLine: number,
@@ -98,12 +96,10 @@ describe("Editor component", () => {
editor.addToHistory("second");
editor.addToHistory("third");
- // Go to oldest
editor.handleInput("\x1b[A"); // third
editor.handleInput("\x1b[A"); // second
editor.handleInput("\x1b[A"); // first
- // Navigate back
editor.handleInput("\x1b[B"); // second
assert.strictEqual(editor.getText(), "second");
@@ -134,7 +130,6 @@ describe("Editor component", () => {
editor.handleInput("\x1b[A"); // Up - shows "second"
editor.setText(""); // External clear
- // Up should start fresh from most recent
editor.handleInput("\x1b[A");
assert.strictEqual(editor.getText(), "second");
});
@@ -149,7 +144,6 @@ describe("Editor component", () => {
editor.handleInput("\x1b[A");
assert.strictEqual(editor.getText(), "valid");
- // Should not have more entries
editor.handleInput("\x1b[A");
assert.strictEqual(editor.getText(), "valid");
});
@@ -191,33 +185,26 @@ describe("Editor component", () => {
editor.addToHistory("history item");
editor.setText("line1\nline2");
- // Cursor is at end of line2, Up should move to line1
editor.handleInput("\x1b[A"); // Up - cursor movement
- // Insert character to verify cursor position
editor.handleInput("X");
- // X should be inserted in line1, not replace with history
assert.strictEqual(editor.getText(), "line1X\nline2");
});
it("limits history to 100 entries", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Add 105 entries
for (let i = 0; i < 105; i++) {
editor.addToHistory(`prompt ${i}`);
}
- // Navigate to oldest
for (let i = 0; i < 100; i++) {
editor.handleInput("\x1b[A");
}
- // Should be at entry 5 (oldest kept), not entry 0
assert.strictEqual(editor.getText(), "prompt 5");
- // One more Up should not change anything
editor.handleInput("\x1b[A");
assert.strictEqual(editor.getText(), "prompt 5");
});
@@ -227,11 +214,9 @@ describe("Editor component", () => {
editor.addToHistory("line1\nline2\nline3");
- // Browse to the multi-line entry
editor.handleInput("\x1b[A"); // Up - shows entry, cursor at end of line3
assert.strictEqual(editor.getText(), "line1\nline2\nline3");
- // Down should exit history since cursor is on last line
editor.handleInput("\x1b[B"); // Down
assert.strictEqual(editor.getText(), ""); // Exited to empty
});
@@ -242,17 +227,14 @@ describe("Editor component", () => {
editor.addToHistory("older entry");
editor.addToHistory("line1\nline2\nline3");
- // Browse to the multi-line entry
editor.handleInput("\x1b[A"); // Up - shows multi-line, cursor at end of line3
- // Up should move cursor within the entry (not on first line yet)
editor.handleInput("\x1b[A"); // Up - cursor moves to line2
assert.strictEqual(editor.getText(), "line1\nline2\nline3"); // Still same entry
editor.handleInput("\x1b[A"); // Up - cursor moves to line1 (now on first visual line)
assert.strictEqual(editor.getText(), "line1\nline2\nline3"); // Still same entry
- // Now Up should navigate to older history entry
editor.handleInput("\x1b[A"); // Up - navigate to older
assert.strictEqual(editor.getText(), "older entry");
});
@@ -262,19 +244,16 @@ describe("Editor component", () => {
editor.addToHistory("line1\nline2\nline3");
- // Browse to entry and move cursor up
editor.handleInput("\x1b[A"); // Up - shows entry, cursor at end
editor.handleInput("\x1b[A"); // Up - cursor to line2
editor.handleInput("\x1b[A"); // Up - cursor to line1
- // Now Down should move cursor down within the entry
editor.handleInput("\x1b[B"); // Down - cursor to line2
assert.strictEqual(editor.getText(), "line1\nline2\nline3");
editor.handleInput("\x1b[B"); // Down - cursor to line3
assert.strictEqual(editor.getText(), "line1\nline2\nline3");
- // Now on last line, Down should exit history
editor.handleInput("\x1b[B"); // Down - exit to empty
assert.strictEqual(editor.getText(), "");
});
@@ -314,7 +293,6 @@ describe("Editor component", () => {
editor.handleInput("\\");
- // Backslash should be visible immediately, not buffered
assert.strictEqual(editor.getText(), "\\");
});
@@ -348,7 +326,6 @@ describe("Editor component", () => {
editor.handleInput("x");
editor.handleInput("\r");
- // Should submit, not insert newline (backslash not at cursor)
assert.strictEqual(submitted, true);
});
@@ -361,7 +338,6 @@ describe("Editor component", () => {
assert.strictEqual(editor.getText(), "\\\\\\");
editor.handleInput("\r");
- // Only the last backslash is removed, newline inserted
assert.strictEqual(editor.getText(), "\\\\\n");
});
});
@@ -419,7 +395,6 @@ describe("Editor component", () => {
editor.handleInput("ö");
editor.handleInput("ü");
- // Delete the last character (ü)
editor.handleInput("\x7f"); // Backspace
const text = editor.getText();
@@ -432,7 +407,6 @@ describe("Editor component", () => {
editor.handleInput("😀");
editor.handleInput("👍");
- // Delete the last emoji (👍) - single backspace deletes whole grapheme cluster
editor.handleInput("\x7f"); // Backspace
const text = editor.getText();
@@ -446,11 +420,9 @@ describe("Editor component", () => {
editor.handleInput("ö");
editor.handleInput("ü");
- // Move cursor left twice
editor.handleInput("\x1b[D"); // Left arrow
editor.handleInput("\x1b[D"); // Left arrow
- // Insert 'x' in the middle
editor.handleInput("x");
const text = editor.getText();
@@ -464,13 +436,10 @@ describe("Editor component", () => {
editor.handleInput("👍");
editor.handleInput("🎉");
- // Move cursor left over last emoji (🎉) - single arrow moves over whole grapheme
editor.handleInput("\x1b[D"); // Left arrow
- // Move cursor left over second emoji (👍)
editor.handleInput("\x1b[D");
- // Insert 'x' between first and second emoji
editor.handleInput("x");
const text = editor.getText();
@@ -495,7 +464,6 @@ describe("Editor component", () => {
it("replaces the entire document with unicode text via setText (paste simulation)", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Simulate bracketed paste / programmatic replacement
editor.setText("Hällö Wörld! 😀 äöüÄÖÜß");
const text = editor.getText();
@@ -517,39 +485,32 @@ describe("Editor component", () => {
it("deletes words correctly with Ctrl+W and Alt+Backspace", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Basic word deletion
editor.setText("foo bar baz");
editor.handleInput("\x17"); // Ctrl+W
assert.strictEqual(editor.getText(), "foo bar ");
- // Trailing whitespace
editor.setText("foo bar ");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "foo ");
- // Punctuation run
editor.setText("foo bar...");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "foo bar");
- // Delete across multiple lines
editor.setText("line one\nline two");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "line one\nline ");
- // Delete empty line (merge)
editor.setText("line one\n");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "line one");
- // Grapheme safety (emoji as a word)
editor.setText("foo 😀😀 bar");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "foo 😀😀 ");
editor.handleInput("\x17");
assert.strictEqual(editor.getText(), "foo ");
- // Alt+Backspace
editor.setText("foo bar");
editor.handleInput("\x1b\x7f"); // Alt+Backspace (legacy)
assert.strictEqual(editor.getText(), "foo ");
@@ -559,33 +520,25 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("foo bar... baz");
- // Cursor at end
- // Move left over baz
editor.handleInput("\x1b[1;5D"); // Ctrl+Left
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 }); // after '...'
- // Move left over punctuation
editor.handleInput("\x1b[1;5D"); // Ctrl+Left
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // after 'bar'
- // Move left over bar
editor.handleInput("\x1b[1;5D"); // Ctrl+Left
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 }); // after 'foo '
- // Move right over bar
editor.handleInput("\x1b[1;5C"); // Ctrl+Right
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 }); // at end of 'bar'
- // Move right over punctuation run
editor.handleInput("\x1b[1;5C"); // Ctrl+Right
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 }); // after '...'
- // Move right skips space and lands after baz
editor.handleInput("\x1b[1;5C"); // Ctrl+Right
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 14 }); // end of line
- // Test forward from start with leading whitespace
editor.setText(" foo bar");
editor.handleInput("\x01"); // Ctrl+A to go to start
editor.handleInput("\x1b[1;5C"); // Ctrl+Right
@@ -598,11 +551,9 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
const width = 20;
- // ✅ is 2 columns wide, so "Hello ✅ World" is 14 columns
editor.setText("Hello ✅ World");
const lines = editor.render(width);
- // All content lines (between borders) should fit within width
for (let i = 1; i < lines.length - 1; i++) {
const lineWidth = visibleWidth(lines[i]!);
assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
@@ -613,13 +564,9 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
const width = 10;
- // Each ✅ is 2 columns. "✅✅✅✅✅" = 10 columns, fits exactly
- // "✅✅✅✅✅✅" = 12 columns, needs wrap
editor.setText("✅✅✅✅✅✅");
const lines = editor.render(width);
- // Should have 2 content lines (plus 2 border lines)
- // First line: 5 emojis (10 cols), second line: 1 emoji (2 cols) + padding
for (let i = 1; i < lines.length - 1; i++) {
const lineWidth = visibleWidth(lines[i]!);
assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
@@ -642,7 +589,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
const width = 10 + 1; // +1 col reserved for cursor
- // Each CJK char is 2 columns. "日本語テスト" = 6 chars = 12 columns
editor.setText("日本語テスト");
const lines = editor.render(width);
@@ -651,7 +597,6 @@ describe("Editor component", () => {
assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
}
- // Verify content split correctly
const contentLines = lines.slice(1, -1).map((l) => stripVTControlCharacters(l).trim());
assert.strictEqual(contentLines.length, 2);
assert.strictEqual(contentLines[0], "日本語テス"); // 5 chars = 10 columns
@@ -662,11 +607,9 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
const width = 15 + 1; // +1 col reserved for cursor
- // "Test ✅ OK 日本" = 4 + 1 + 2 + 1 + 2 + 1 + 4 = 15 columns (fits in width-1=15)
editor.setText("Test ✅ OK 日本");
const lines = editor.render(width);
- // Should fit in one content line
const contentLines = lines.slice(1, -1);
assert.strictEqual(contentLines.length, 1);
@@ -679,14 +622,11 @@ describe("Editor component", () => {
const width = 20;
editor.setText("A✅B");
- // Cursor should be at end (after B)
const lines = editor.render(width);
- // The cursor (reverse video space) should be visible
const contentLine = lines[1]!;
assert.ok(contentLine.includes("\x1b[7m"), "Should have reverse video cursor");
- // Line should still be correct width
assert.strictEqual(visibleWidth(contentLine), width);
});
@@ -694,8 +634,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
const width = 11;
- // "0123456789✅" = 10 ASCII + 2-wide emoji = 12 columns
- // Should wrap before the emoji since it would exceed width
editor.setText("0123456789✅");
const lines = editor.render(width);
@@ -710,14 +648,12 @@ describe("Editor component", () => {
for (const paddingX of [0, 1]) {
const editor = new Editor(createTestTUI(width + paddingX), defaultEditorTheme, { paddingX });
- // Type 9 chars → fills layoutWidth exactly, cursor at end on same line
for (const ch of "aaaaaaaaa") editor.handleInput(ch);
let lines = editor.render(width + paddingX);
let contentLines = lines.slice(1, -1);
assert.strictEqual(contentLines.length, 1, "Should be 1 content line before wrap");
assert.ok(contentLines[0]!.endsWith("\x1b[7m \x1b[0m"), "Cursor should be at end of line");
- // Type 1 more → text wraps to second line
editor.handleInput("a");
lines = editor.render(width + paddingX);
contentLines = lines.slice(1, -1);
@@ -766,16 +702,11 @@ describe("Editor component", () => {
editor.setText("Hello world this is a test of word wrapping functionality");
const lines = editor.render(width);
- // Get content lines (between borders)
const contentLines = lines.slice(1, -1).map((l) => stripVTControlCharacters(l).trim());
- // Should NOT break mid-word
- // Line 1 should end with a complete word
assert.ok(!contentLines[0]!.endsWith("-"), "Line should not end with hyphen (mid-word break)");
- // Each content line should be complete words
for (const line of contentLines) {
- // Words at end of line should be complete (no partial words)
const lastChar = line.trimEnd().slice(-1);
assert.ok(lastChar === "" || /[\w.,!?;:]/.test(lastChar), `Line ends unexpectedly with: "${lastChar}"`);
}
@@ -788,14 +719,11 @@ describe("Editor component", () => {
editor.setText("Word1 Word2 Word3 Word4 Word5 Word6");
const lines = editor.render(width);
- // Get content lines (between borders)
const contentLines = lines.slice(1, -1);
- // No line should start with whitespace (except for padding at the end)
for (let i = 0; i < contentLines.length; i++) {
const line = stripVTControlCharacters(contentLines[i]!);
const trimmedStart = line.trimStart();
- // The line should either be all padding or start with a word character
if (trimmedStart.length > 0) {
assert.ok(!/^\s+\S/.test(line.trimEnd()), `Line ${i} starts with unexpected whitespace before content`);
}
@@ -809,7 +737,6 @@ describe("Editor component", () => {
editor.setText("Check https://example.com/very/long/path/that/exceeds/width here");
const lines = editor.render(width);
- // All lines should fit within width
for (let i = 1; i < lines.length - 1; i++) {
const lineWidth = visibleWidth(lines[i]!);
assert.strictEqual(lineWidth, width, `Line ${i} has width ${lineWidth}, expected ${width}`);
@@ -824,7 +751,6 @@ describe("Editor component", () => {
const lines = editor.render(width);
const contentLine = stripVTControlCharacters(lines[1]!).trim();
- // Multiple spaces should be preserved
assert.ok(contentLine.includes("Word1 Word2"), "Multiple spaces should be preserved");
});
@@ -835,7 +761,6 @@ describe("Editor component", () => {
editor.setText("");
const lines = editor.render(width);
- // Should have border + empty content + border
assert.strictEqual(lines.length, 3);
});
@@ -846,15 +771,12 @@ describe("Editor component", () => {
editor.setText("1234567890");
const lines = editor.render(width);
- // Should have exactly 3 lines (top border, content, bottom border)
assert.strictEqual(lines.length, 3);
const contentLine = stripVTControlCharacters(lines[1]!);
assert.ok(contentLine.includes("1234567890"), "Content should contain the word");
});
it("wraps word to next line when it ends exactly at terminal width", () => {
- // "hello " (6) + "world" (5) = 11, but "world" is non-whitespace ending at width.
- // Thus, wrap it to next line. The trailing space stays with "hello" on line 1
const chunks = wordWrapLine("hello world test", 11);
assert.strictEqual(chunks.length, 2);
@@ -863,8 +785,6 @@ describe("Editor component", () => {
});
it("keeps whitespace at terminal width boundary on same line", () => {
- // "hello world " is exactly 12 chars (including trailing space)
- // The space at position 12 should stay on the first line
const chunks = wordWrapLine("hello world test", 12);
assert.strictEqual(chunks.length, 2);
@@ -941,9 +861,6 @@ describe("Editor component", () => {
});
it("force-breaks when wide char after word boundary wrap still overflows", () => {
- // " " (1) + "a"*186 (186) + "你" (2) = 189 visible width
- // maxWidth = 187: backtracking to the space would leave 186 + 2 = 188 > 187,
- // so the algorithm must force-break before the wide char instead.
const line = ` ${"a".repeat(186)}你`;
const chunks = wordWrapLine(line, 187);
@@ -953,13 +870,11 @@ describe("Editor component", () => {
`chunk "${chunk.text.slice(0, 20)}..." has visible width ${visibleWidth(chunk.text)}, expected <= 187`,
);
}
- // Verify no content is lost
const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
assert.strictEqual(reconstructed, line);
});
it("splits oversized atomic segment across multiple chunks", () => {
- // Simulate a paste marker wider than maxWidth by passing pre-segmented data
const marker = "[paste #1 +20 lines]"; // 21 chars
const line = `A${marker}B`;
const segments: Intl.SegmentData[] = [
@@ -970,7 +885,6 @@ describe("Editor component", () => {
const chunks = wordWrapLine(line, 10, segments);
- // Every chunk must fit within maxWidth
for (const chunk of chunks) {
assert.ok(
visibleWidth(chunk.text) <= 10,
@@ -978,7 +892,6 @@ describe("Editor component", () => {
);
}
- // Verify no content is lost
const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
assert.strictEqual(reconstructed, line);
});
@@ -996,7 +909,6 @@ describe("Editor component", () => {
for (const chunk of chunks) {
assert.ok(visibleWidth(chunk.text) <= 10);
}
- // "B" ends up on the last line (either alone or with the marker tail)
assert.strictEqual(chunks[chunks.length - 1]!.text.includes("B"), true);
const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
@@ -1065,7 +977,6 @@ describe("Editor component", () => {
const chunks = wordWrapLine(line, 10, segments);
- // All chunks must fit
for (const chunk of chunks) {
assert.ok(
visibleWidth(chunk.text) <= 10,
@@ -1073,7 +984,6 @@ describe("Editor component", () => {
);
}
- // Last chunk should contain "world" (normal wrapping resumes)
assert.strictEqual(chunks[chunks.length - 1]!.text, "world");
const reconstructed = chunks.map((c) => line.slice(c.startIndex, c.endIndex)).join("");
@@ -1089,7 +999,6 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // Ctrl+W - deletes "baz"
assert.strictEqual(editor.getText(), "foo bar ");
- // Move to beginning and yank
editor.handleInput("\x01"); // Ctrl+A
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "bazfoo bar ");
@@ -1099,7 +1008,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("hello world");
- // Move cursor to middle
editor.handleInput("\x01"); // Ctrl+A (start)
editor.handleInput("\x1b[C"); // Right 5 times
editor.handleInput("\x1b[C");
@@ -1139,7 +1047,6 @@ describe("Editor component", () => {
it("Alt+Y cycles through kill ring after Ctrl+Y", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Create kill ring with multiple entries
editor.setText("first");
editor.handleInput("\x17"); // Ctrl+W - deletes "first"
editor.setText("second");
@@ -1147,7 +1054,6 @@ describe("Editor component", () => {
editor.setText("third");
editor.handleInput("\x17"); // Ctrl+W - deletes "third"
- // Kill ring now has: [first, second, third]
assert.strictEqual(editor.getText(), "");
editor.handleInput("\x19"); // Ctrl+Y - yanks "third" (most recent)
@@ -1170,11 +1076,9 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // Ctrl+W - deletes "test"
editor.setText("other");
- // Type something to break the yank chain
editor.handleInput("x");
assert.strictEqual(editor.getText(), "otherx");
- // Alt+Y should do nothing
editor.handleInput("\x1by"); // Alt+Y
assert.strictEqual(editor.getText(), "otherx");
});
@@ -1202,7 +1106,6 @@ describe("Editor component", () => {
assert.strictEqual(editor.getText(), "");
- // Should be one combined entry
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "one two three");
});
@@ -1210,31 +1113,23 @@ describe("Editor component", () => {
it("Ctrl+U accumulates multiline deletes including newlines", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Start with multiline text, cursor at end
editor.setText("line1\nline2\nline3");
- // Cursor is at end of line3 (line 2, col 5)
- // Delete "line3"
editor.handleInput("\x15"); // Ctrl+U
assert.strictEqual(editor.getText(), "line1\nline2\n");
- // Delete newline (at start of empty line 2, merges with line1)
editor.handleInput("\x15"); // Ctrl+U
assert.strictEqual(editor.getText(), "line1\nline2");
- // Delete "line2"
editor.handleInput("\x15"); // Ctrl+U
assert.strictEqual(editor.getText(), "line1\n");
- // Delete newline
editor.handleInput("\x15"); // Ctrl+U
assert.strictEqual(editor.getText(), "line1");
- // Delete "line1"
editor.handleInput("\x15"); // Ctrl+U
assert.strictEqual(editor.getText(), "");
- // All deletions accumulated into one entry: "line1\nline2\nline3"
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "line1\nline2\nline3");
});
@@ -1243,7 +1138,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("prefix|suffix");
- // Position cursor at |
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6 times
@@ -1258,7 +1152,6 @@ describe("Editor component", () => {
it("non-delete actions break kill accumulation", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Delete "baz", then type "x" to break accumulation, then delete "x"
editor.setText("foo bar baz");
editor.handleInput("\x17"); // Ctrl+W - deletes "baz"
assert.strictEqual(editor.getText(), "foo bar ");
@@ -1269,11 +1162,9 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // Ctrl+W - deletes "x" (separate entry, not accumulated)
assert.strictEqual(editor.getText(), "foo bar ");
- // Yank most recent - should be "x", not "xbaz"
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "foo bar x");
- // Cycle to previous - should be "baz" (separate entry)
editor.handleInput("\x1by"); // Alt+Y
assert.strictEqual(editor.getText(), "foo bar baz");
});
@@ -1308,19 +1199,14 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // deletes "third"
editor.setText("");
- // Ring: [first, second, third]
-
editor.handleInput("\x19"); // Ctrl+Y - yanks "third"
editor.handleInput("\x1by"); // Alt+Y - cycles to "second", ring rotates
- // Now ring is: [third, first, second]
assert.strictEqual(editor.getText(), "second");
- // Do something else
editor.handleInput("x");
editor.setText("");
- // New yank should get "second" (now at end after rotation)
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "second");
});
@@ -1328,7 +1214,6 @@ describe("Editor component", () => {
it("consecutive deletions across lines coalesce into one entry", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // "1\n2\n3" with cursor at end, delete everything with Ctrl+W
editor.setText("1\n2\n3");
editor.handleInput("\x17"); // Ctrl+W - deletes "3"
assert.strictEqual(editor.getText(), "1\n2\n");
@@ -1345,7 +1230,6 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // Ctrl+W - deletes "1"
assert.strictEqual(editor.getText(), "");
- // All deletions should have accumulated into one entry
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "1\n2\n3");
});
@@ -1353,26 +1237,21 @@ describe("Editor component", () => {
it("Ctrl+K at line end deletes newline and coalesces", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // "ab" on line 1, "cd" on line 2, cursor at end of line 1
editor.setText("");
editor.handleInput("a");
editor.handleInput("b");
editor.handleInput("\n");
editor.handleInput("c");
editor.handleInput("d");
- // Move to end of first line
editor.handleInput("\x1b[A"); // Up arrow
editor.handleInput("\x05"); // Ctrl+E - end of line
- // Now at end of "ab", Ctrl+K should delete newline (merge with "cd")
editor.handleInput("\x0b"); // Ctrl+K - deletes newline
assert.strictEqual(editor.getText(), "abcd");
- // Continue deleting
editor.handleInput("\x0b"); // Ctrl+K - deletes "cd"
assert.strictEqual(editor.getText(), "ab");
- // Both deletions should accumulate
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "ab\ncd");
});
@@ -1384,7 +1263,6 @@ describe("Editor component", () => {
editor.handleInput("\x17"); // Ctrl+W - deletes "word"
editor.setText("hello world");
- // Move to middle (after "hello ")
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C");
@@ -1395,24 +1273,18 @@ describe("Editor component", () => {
it("handles yank-pop in middle of text", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Create two kill ring entries
editor.setText("FIRST");
editor.handleInput("\x17"); // Ctrl+W - deletes "FIRST"
editor.setText("SECOND");
editor.handleInput("\x17"); // Ctrl+W - deletes "SECOND"
- // Ring: ["FIRST", "SECOND"]
-
- // Set up "hello world" and position cursor after "hello "
editor.setText("hello world");
editor.handleInput("\x01"); // Ctrl+A - go to start of line
for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Move right 6
- // Yank "SECOND" in the middle
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "hello SECONDworld");
- // Yank-pop replaces "SECOND" with "FIRST"
editor.handleInput("\x1by"); // Alt+Y
assert.strictEqual(editor.getText(), "hello FIRSTworld");
});
@@ -1420,27 +1292,21 @@ describe("Editor component", () => {
it("multiline yank and yank-pop in middle of text", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Create single-line entry
editor.setText("SINGLE");
editor.handleInput("\x17"); // Ctrl+W - deletes "SINGLE"
- // Create multiline entry via consecutive Ctrl+U
editor.setText("A\nB");
editor.handleInput("\x15"); // Ctrl+U - deletes "B"
editor.handleInput("\x15"); // Ctrl+U - deletes newline
editor.handleInput("\x15"); // Ctrl+U - deletes "A"
- // Ring: ["SINGLE", "A\nB"]
- // Insert in middle of "hello world"
editor.setText("hello world");
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C");
- // Yank multiline "A\nB"
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "hello A\nBworld");
- // Yank-pop replaces with "SINGLE"
editor.handleInput("\x1by"); // Alt+Y
assert.strictEqual(editor.getText(), "hello SINGLEworld");
});
@@ -1457,7 +1323,6 @@ describe("Editor component", () => {
editor.handleInput("\x1bd"); // Alt+D - deletes " world" (skips whitespace, then word)
assert.strictEqual(editor.getText(), " test");
- // Yank should get accumulated text
editor.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(editor.getText(), "hello world test");
});
@@ -1466,7 +1331,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("line1\nline2");
- // Move to start of document, then to end of first line
editor.handleInput("\x1b[A"); // Up arrow - go to first line
editor.handleInput("\x05"); // Ctrl+E - end of line
@@ -1502,11 +1366,9 @@ describe("Editor component", () => {
editor.handleInput("d");
assert.strictEqual(editor.getText(), "hello world");
- // Undo removes " world" (space captured state before it, so we restore to "hello")
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello");
- // Undo removes "hello"
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "");
});
@@ -1689,11 +1551,9 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
- // Simulate bracketed paste of "beep boop"
editor.handleInput("\x1b[200~beep boop\x1b[201~");
assert.strictEqual(editor.getText(), "hellobeep boop world");
- // Single undo should restore entire pre-paste state
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello world");
@@ -1724,9 +1584,6 @@ describe("Editor component", () => {
it("decodes CSI-u Ctrl+letter sequences inside bracketed paste (tmux popup)", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // tmux popups with extended-keys-format=csi-u re-encode \n in pastes as
- // \x1b[106;5u (Ctrl+J). Without decoding, the per-char filter strips ESC
- // and leaks "[106;5u" between lines. See issue #3599.
editor.handleInput("\x1b[200~line1\x1b[106;5uline2\x1b[106;5uline3\x1b[201~");
assert.strictEqual(editor.getText(), "line1\nline2\nline3");
});
@@ -1738,11 +1595,9 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
- // Simulate bracketed paste of multi-line text
editor.handleInput("\x1b[200~line1\nline2\nline3\x1b[201~");
assert.strictEqual(editor.getText(), "helloline1\nline2\nline3 world");
- // Single undo should restore entire pre-paste state
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello world");
@@ -1757,11 +1612,9 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
- // Programmatic insertion (e.g., clipboard image path)
editor.insertTextAtCursor("/tmp/image.png");
assert.strictEqual(editor.getText(), "hello/tmp/image.png world");
- // Single undo should restore entire pre-insert state
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello world");
@@ -1776,16 +1629,13 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C"); // Move right 5 (after "hello", before space)
- // Insert multiline text
editor.insertTextAtCursor("line1\nline2\nline3");
assert.strictEqual(editor.getText(), "helloline1\nline2\nline3 world");
- // Cursor should be at end of inserted text (after "line3", before " world")
const cursor = editor.getCursor();
assert.strictEqual(cursor.line, 2);
assert.strictEqual(cursor.col, 5); // "line3".length
- // Single undo should restore entire pre-insert state
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello world");
});
@@ -1795,14 +1645,12 @@ describe("Editor component", () => {
editor.setText("");
- // Insert text with CRLF
editor.insertTextAtCursor("a\r\nb\r\nc");
assert.strictEqual(editor.getText(), "a\nb\nc");
editor.handleInput("\x1b[45;5u"); // Undo
assert.strictEqual(editor.getText(), "");
- // Insert text with CR only
editor.insertTextAtCursor("x\ry\rz");
assert.strictEqual(editor.getText(), "x\ny\nz");
});
@@ -1847,7 +1695,6 @@ describe("Editor component", () => {
assert.strictEqual(submitted, "hello");
assert.strictEqual(editor.getText(), "");
- // Undo should do nothing - stack was cleared
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "");
});
@@ -1855,11 +1702,9 @@ describe("Editor component", () => {
it("exits history browsing mode on undo", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Add "hello" to history
editor.addToHistory("hello");
assert.strictEqual(editor.getText(), "");
- // Type "world"
editor.handleInput("w");
editor.handleInput("o");
editor.handleInput("r");
@@ -1867,19 +1712,15 @@ describe("Editor component", () => {
editor.handleInput("d");
assert.strictEqual(editor.getText(), "world");
- // Ctrl+W - delete word
editor.handleInput("\x17"); // Ctrl+W
assert.strictEqual(editor.getText(), "");
- // Press Up - enter history browsing, shows "hello"
editor.handleInput("\x1b[A"); // Up arrow
assert.strictEqual(editor.getText(), "hello");
- // Undo should restore to "" (state before entering history browsing)
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "");
- // Undo again should restore to "world" (state before Ctrl+W)
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "world");
});
@@ -1887,12 +1728,10 @@ describe("Editor component", () => {
it("undo restores to pre-history state even after multiple history navigations", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Add history entries
editor.addToHistory("first");
editor.addToHistory("second");
editor.addToHistory("third");
- // Type something
editor.handleInput("c");
editor.handleInput("u");
editor.handleInput("r");
@@ -1902,11 +1741,9 @@ describe("Editor component", () => {
editor.handleInput("t");
assert.strictEqual(editor.getText(), "current");
- // Clear editor
editor.handleInput("\x17"); // Ctrl+W
assert.strictEqual(editor.getText(), "");
- // Navigate through history multiple times
editor.handleInput("\x1b[A"); // Up - "third"
assert.strictEqual(editor.getText(), "third");
editor.handleInput("\x1b[A"); // Up - "second"
@@ -1914,11 +1751,9 @@ describe("Editor component", () => {
editor.handleInput("\x1b[A"); // Up - "first"
assert.strictEqual(editor.getText(), "first");
- // Undo should go back to "" (state before we started browsing), not intermediate states
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "");
- // Another undo goes back to "current"
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "current");
});
@@ -1939,16 +1774,13 @@ describe("Editor component", () => {
editor.handleInput("d");
assert.strictEqual(editor.getText(), "hello world");
- // Move cursor left 5 (to after "hello ")
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[D");
- // Type "lol" in the middle
editor.handleInput("l");
editor.handleInput("o");
editor.handleInput("l");
assert.strictEqual(editor.getText(), "hello lolworld");
- // Undo should restore to "hello world" (before inserting "lol")
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello world");
@@ -1966,13 +1798,11 @@ describe("Editor component", () => {
editor.handleInput("o");
assert.strictEqual(editor.getText(), "hello");
- // Delete word on empty - multiple times (should be no-ops)
editor.handleInput("\x17"); // Ctrl+W - deletes "hello"
assert.strictEqual(editor.getText(), "");
editor.handleInput("\x17"); // Ctrl+W - no-op (nothing to delete)
editor.handleInput("\x17"); // Ctrl+W - no-op
- // Single undo should restore "hello"
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "hello");
});
@@ -1980,7 +1810,6 @@ describe("Editor component", () => {
it("undoes autocomplete", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Create a mock autocomplete provider
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
@@ -1998,18 +1827,15 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "di"
editor.handleInput("d");
editor.handleInput("i");
assert.strictEqual(editor.getText(), "di");
- // Press Tab to trigger autocomplete
editor.handleInput("\t");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "dist/");
assert.strictEqual(editor.isShowingAutocomplete(), false);
- // Undo should restore to "di"
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "di");
});
@@ -2108,20 +1934,17 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "Work"
editor.handleInput("W");
editor.handleInput("o");
editor.handleInput("r");
editor.handleInput("k");
assert.strictEqual(editor.getText(), "Work");
- // Press Tab - should auto-apply without showing menu
editor.handleInput("\t");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "Workspace/");
assert.strictEqual(editor.isShowingAutocomplete(), false);
- // Undo should restore to "Work"
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "Work");
});
@@ -2152,19 +1975,16 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "src"
editor.handleInput("s");
editor.handleInput("r");
editor.handleInput("c");
assert.strictEqual(editor.getText(), "src");
- // Press Tab - should show menu because there are multiple suggestions
editor.handleInput("\t");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "src");
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Tab again to accept first suggestion
editor.handleInput("\t");
assert.strictEqual(editor.getText(), "src/");
assert.strictEqual(editor.isShowingAutocomplete(), false);
@@ -2199,24 +2019,20 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Press Tab on empty prompt - should show all files (force mode)
editor.handleInput("\t");
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Type "r" - should narrow to "readme.md" (force mode keeps suggestions open)
editor.handleInput("r");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "r");
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Type "e" - should still show "readme.md"
editor.handleInput("e");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "re");
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Accept with Tab
editor.handleInput("\t");
assert.strictEqual(editor.getText(), "readme.md");
assert.strictEqual(editor.isShowingAutocomplete(), false);
@@ -2328,12 +2144,10 @@ describe("Editor component", () => {
it("hides autocomplete when backspacing slash command to empty", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider with slash commands
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
const prefix = text.slice(0, cursorCol);
- // Only return slash command suggestions when line starts with /
if (prefix.startsWith("/")) {
const commands = [
{ value: "/model", label: "model", description: "Change model" },
@@ -2352,13 +2166,11 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/" - should show slash command suggestions
editor.handleInput("/");
await flushAutocomplete();
assert.strictEqual(editor.getText(), "/");
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Backspace to delete "/" - should hide autocomplete completely
editor.handleInput("\x7f"); // Backspace
await flushAutocomplete();
assert.strictEqual(editor.getText(), "");
@@ -2442,13 +2254,11 @@ describe("Editor component", () => {
it("applies exact typed slash-argument value on Enter even when first item is highlighted", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider for /argtest command with argument completions
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
const beforeCursor = text.slice(0, cursorCol);
- // Check if we're in argument completion context: "/argtest <prefix>"
const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
if (argtestMatch) {
const argumentText = argtestMatch[1]!;
@@ -2457,7 +2267,6 @@ describe("Editor component", () => {
{ value: "two", label: "two" },
{ value: "three", label: "three" },
];
- // Return all arguments that start with the typed prefix
const filtered = allArguments.filter((arg) => arg.value.startsWith(argumentText));
if (filtered.length > 0) {
return { items: filtered, prefix: argumentText };
@@ -2470,7 +2279,6 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/argtest two"
editor.handleInput("/");
editor.handleInput("a");
editor.handleInput("r");
@@ -2488,23 +2296,19 @@ describe("Editor component", () => {
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Enter - should apply the exact typed value "two", not the first item
editor.handleInput("\r");
- // The exact typed value "two" should be retained
assert.strictEqual(editor.getText(), "/argtest two");
});
it("selects first prefix match on Enter when typed arg is not exact match", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider for /argtest command with argument completions
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
const beforeCursor = text.slice(0, cursorCol);
- // Check if we're in argument completion context
const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
if (argtestMatch) {
const argumentText = argtestMatch[1]!;
@@ -2513,7 +2317,6 @@ describe("Editor component", () => {
{ value: "three", label: "three" },
{ value: "twelve", label: "twelve" },
];
- // Return all items that start with the typed prefix
const filtered = allArguments.filter((arg) => arg.value.startsWith(argumentText));
if (filtered.length > 0) {
return { items: filtered, prefix: argumentText };
@@ -2526,7 +2329,6 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/argtest t" - filtered to [two, three, twelve], prefix "t" matches "two" first
editor.handleInput("/");
editor.handleInput("a");
editor.handleInput("r");
@@ -2541,7 +2343,6 @@ describe("Editor component", () => {
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Enter - "t" prefix matches "two" (first in list), so "two" is applied
editor.handleInput("\r");
assert.strictEqual(editor.getText(), "/argtest two");
});
@@ -2549,7 +2350,6 @@ describe("Editor component", () => {
it("highlights unique prefix match as user types (before full exact match)", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider that returns all items unfiltered (like real extensions do)
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
@@ -2558,7 +2358,6 @@ describe("Editor component", () => {
const argtestMatch = beforeCursor.match(/^\/argtest\s+(\S+)$/);
if (argtestMatch) {
const argumentText = argtestMatch[1]!;
- // Return all items - provider does not filter
const allArguments = [
{ value: "one", label: "one" },
{ value: "two", label: "two" },
@@ -2573,7 +2372,6 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/argtest tw" - "tw" is a prefix of only "two"
editor.handleInput("/");
editor.handleInput("a");
editor.handleInput("r");
@@ -2590,7 +2388,6 @@ describe("Editor component", () => {
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Enter - "tw" uniquely matches "two", so "two" should be applied
editor.handleInput("\r");
assert.strictEqual(editor.getText(), "/argtest two");
});
@@ -2598,7 +2395,6 @@ describe("Editor component", () => {
it("selects first prefix match when multiple items match", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider that returns all items unfiltered
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
@@ -2621,7 +2417,6 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/argtest t" - "t" is a prefix of both "two" and "three"
editor.handleInput("/");
editor.handleInput("a");
editor.handleInput("r");
@@ -2636,7 +2431,6 @@ describe("Editor component", () => {
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Enter - "t" matches "two" first, so "two" is selected
editor.handleInput("\r");
assert.strictEqual(editor.getText(), "/argtest two");
});
@@ -2644,14 +2438,11 @@ describe("Editor component", () => {
it("works for built-in-style command argument completion path (model-like)", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Mock provider for /model command with model completions
const mockProvider: AutocompleteProvider = {
getSuggestions: async (lines, _cursorLine, cursorCol) => {
const text = lines[0] || "";
const beforeCursor = text.slice(0, cursorCol);
- // Check if we're in /model argument completion context
- // Use [^ ]+ to match any non-space characters (including hyphens)
const modelMatch = beforeCursor.match(/^\/model\s+(\S+)$/);
if (modelMatch) {
const modelText = modelMatch[1]!;
@@ -2660,7 +2451,6 @@ describe("Editor component", () => {
{ value: "gpt-4o-mini", label: "gpt-4o-mini" },
{ value: "claude-sonnet", label: "claude-sonnet" },
];
- // Return all models that start with the typed prefix
const filtered = allModels.filter((m) => m.value.startsWith(modelText));
if (filtered.length > 0) {
return { items: filtered, prefix: modelText };
@@ -2673,7 +2463,6 @@ describe("Editor component", () => {
editor.setAutocompleteProvider(mockProvider);
- // Type "/model gpt-4o-mini" - exact match for second item in list
editor.handleInput("/");
editor.handleInput("m");
editor.handleInput("o");
@@ -2697,10 +2486,8 @@ describe("Editor component", () => {
await flushAutocomplete();
assert.strictEqual(editor.isShowingAutocomplete(), true);
- // Press Enter - should retain exact typed value, not apply first highlighted item
editor.handleInput("\r");
- // The exact typed value should be retained
assert.strictEqual(editor.getText(), "/model gpt-4o-mini");
});
@@ -2798,7 +2585,6 @@ describe("Editor component", () => {
editor.setText("hello world");
editor.handleInput("\x01"); // Ctrl+A - go to start
- // Move cursor to the 'o' in "hello" (col 4)
for (let i = 0; i < 4; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
@@ -2812,7 +2598,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("abc\ndef\nghi");
- // Cursor is at end (line 2, col 3). Move to line 0 via up arrows, then Ctrl+A
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x1b[A"); // Up - now on line 0
editor.handleInput("\x01"); // Ctrl+A - go to start of line
@@ -2828,7 +2613,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("hello world");
- // Cursor at end (col 11)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] (ESC followed by Ctrl+])
@@ -2841,7 +2625,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("abc\ndef\nghi");
- // Cursor at end of line 3
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 3 });
editor.handleInput("\x1b\x1d"); // Ctrl+Alt+]
@@ -2867,7 +2650,6 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("hello world");
- // Cursor at end
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
editor.handleInput("\x1b\x1d"); // Ctrl+Alt+]
@@ -2883,13 +2665,11 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
- // Search for lowercase 'h' - should not find it (only 'H' exists)
editor.handleInput("\x1d"); // Ctrl+]
editor.handleInput("h");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 }); // Cursor unchanged
- // Search for uppercase 'W' - should find it
editor.handleInput("\x1d"); // Ctrl+]
editor.handleInput("W");
@@ -2906,7 +2686,6 @@ describe("Editor component", () => {
editor.handleInput("\x1d"); // Ctrl+] - enter jump mode
editor.handleInput("\x1d"); // Ctrl+] again - cancel
- // Type 'o' normally - should insert, not jump
editor.handleInput("o");
assert.strictEqual(editor.getText(), "ohello world");
});
@@ -2921,10 +2700,8 @@ describe("Editor component", () => {
editor.handleInput("\x1d"); // Ctrl+] - enter jump mode
editor.handleInput("\x1b"); // Escape - cancel jump mode
- // Cursor should be unchanged (Escape itself doesn't move cursor in editor)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
- // Type 'o' normally - should insert, not jump
editor.handleInput("o");
assert.strictEqual(editor.getText(), "ohello world");
});
@@ -2933,13 +2710,11 @@ describe("Editor component", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
editor.setText("hello world");
- // Cursor at end
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] - enter backward jump mode
editor.handleInput("\x1b\x1d"); // Ctrl+Alt+] again - cancel
- // Type 'o' normally - should insert, not jump
editor.handleInput("o");
assert.strictEqual(editor.getText(), "hello worldo");
});
@@ -2951,13 +2726,11 @@ describe("Editor component", () => {
editor.handleInput("\x01"); // Ctrl+A - go to start
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
- // Jump to '('
editor.handleInput("\x1d"); // Ctrl+]
editor.handleInput("(");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
- // Jump to '='
editor.handleInput("\x1d"); // Ctrl+]
editor.handleInput("=");
@@ -2982,32 +2755,24 @@ describe("Editor component", () => {
editor.setText("hello world");
editor.handleInput("\x01"); // Ctrl+A - go to start
- // Type to set lastAction to "type-word"
editor.handleInput("x");
assert.strictEqual(editor.getText(), "xhello world");
- // Jump forward
editor.handleInput("\x1d"); // Ctrl+]
editor.handleInput("o");
- // Type more - should start a new undo unit (lastAction was reset)
editor.handleInput("Y");
assert.strictEqual(editor.getText(), "xhellYo world");
- // Undo should only undo "Y", not "x" as well
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "xhello world");
});
});
describe("Sticky column", () => {
- // Helper: position cursor at a specific line and column
function positionCursor(editor: Editor, line: number, col: number): void {
- // Go to line 0 first
for (let i = 0; i < 20; i++) editor.handleInput("\x1b[A");
- // Go to target line
for (let i = 0; i < line; i++) editor.handleInput("\x1b[B");
- // Go to target col
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < col; i++) editor.handleInput("\x1b[C");
}
@@ -3015,22 +2780,16 @@ describe("Editor component", () => {
it("preserves target column when moving up through a shorter line", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Line 0: "2222222222x222" (x at col 10)
- // Line 1: "" (empty)
- // Line 2: "1111111111_111111111111" (_ at col 10)
editor.setText("2222222222x222\n\n1111111111_111111111111");
- // Position cursor on _ (line 2, col 10)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 23 }); // At end
editor.handleInput("\x01"); // Ctrl+A - go to start of line
for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C"); // Move right to col 10
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
- // Press Up - should move to empty line (col clamped to 0)
editor.handleInput("\x1b[A"); // Up arrow
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
- // Press Up again - should move to line 0 at col 10 (on 'x')
editor.handleInput("\x1b[A"); // Up arrow
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
});
@@ -3040,18 +2799,15 @@ describe("Editor component", () => {
editor.setText("1111111111_111\n\n2222222222x222222222222");
- // Position cursor on _ (line 0, col 10)
editor.handleInput("\x1b[A"); // Up to line 1
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
- // Press Down - should move to empty line (col clamped to 0)
editor.handleInput("\x1b[B"); // Down arrow
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
- // Press Down again - should move to line 2 at col 10 (on 'x')
editor.handleInput("\x1b[B"); // Down arrow
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
});
@@ -3061,21 +2817,17 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Start at line 2, col 5
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
- // Move up through empty line
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 5 (sticky)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
- // Move left - resets sticky column
editor.handleInput("\x1b[D"); // Left
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 4 });
- // Move down twice
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 4 (new sticky from col 4)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 4 });
@@ -3086,23 +2838,19 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Start at line 0, col 5
editor.handleInput("\x1b[A"); // Up to line 1
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 5; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
- // Move down through empty line
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 5 (sticky)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
- // Move right - resets sticky column
editor.handleInput("\x1b[C"); // Right
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
- // Move up twice
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 6 (new sticky from col 6)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
@@ -3113,20 +2861,16 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Start at line 2, col 8
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
- // Move up through empty line
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x1b[A"); // Up - line 0, col 8
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
- // Type a character - resets sticky column
editor.handleInput("X");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 9 });
- // Move down twice
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 9 (new sticky from col 9)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 9 });
@@ -3137,20 +2881,16 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Start at line 2, col 8
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
- // Move up through empty line
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x1b[A"); // Up - line 0, col 8
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
- // Backspace - resets sticky column
editor.handleInput("\x7f"); // Backspace
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 });
- // Move down twice
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 7 (new sticky from col 7)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 7 });
@@ -3161,18 +2901,14 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Start at line 2, col 8
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
- // Move up - establishes sticky col 8
editor.handleInput("\x1b[A"); // Up - line 1, col 0
- // Ctrl+A - resets sticky column to 0
editor.handleInput("\x01"); // Ctrl+A
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
- // Move up
editor.handleInput("\x1b[A"); // Up - line 0, col 0 (new sticky from col 0)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
});
@@ -3182,20 +2918,16 @@ describe("Editor component", () => {
editor.setText("12345\n\n1234567890");
- // Start at line 2, col 3
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 3; i++) editor.handleInput("\x1b[C");
- // Move up through empty line - establishes sticky col 3
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 3
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
- // Ctrl+E - resets sticky column to end
editor.handleInput("\x05"); // Ctrl+E
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
- // Move down twice
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 5 (new sticky from col 5)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 });
@@ -3206,19 +2938,15 @@ describe("Editor component", () => {
editor.setText("hello world\n\nhello world");
- // Start at end of line 2 (col 11)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 11 });
- // Move up through empty line - establishes sticky col 11
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 11
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 11 });
- // Ctrl+Left - word movement resets sticky column
editor.handleInput("\x1b[1;5D"); // Ctrl+Left
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 }); // Before "world"
- // Move down twice
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 6 (new sticky from col 6)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
@@ -3229,22 +2957,18 @@ describe("Editor component", () => {
editor.setText("hello world\n\nhello world");
- // Start at line 0, col 0
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x01"); // Ctrl+A
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
- // Move down through empty line - establishes sticky col 0
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 0
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 0 });
- // Ctrl+Right - word movement resets sticky column
editor.handleInput("\x1b[1;5C"); // Ctrl+Right
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 5 }); // After "hello"
- // Move up twice
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 5 (new sticky from col 5)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
@@ -3255,34 +2979,28 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Go to line 0, col 8
editor.handleInput("\x1b[A"); // Up to line 1
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
- // Move down through empty line - establishes sticky col 8
editor.handleInput("\x1b[B"); // Down - line 1, col 0
editor.handleInput("\x1b[B"); // Down - line 2, col 8 (sticky)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 8 });
- // Type something to create undo state - this clears sticky and sets col to 9
editor.handleInput("X");
assert.strictEqual(editor.getText(), "1234567890\n\n12345678X90");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 9 });
- // Move up - establishes new sticky col 9
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 9
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 9 });
- // Undo - resets sticky column and restores cursor to line 2, col 8
editor.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(editor.getText(), "1234567890\n\n1234567890");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 8 });
- // Move up - should capture new sticky from restored col 8, not old col 9
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 8 (new sticky from restored position)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
@@ -3293,19 +3011,16 @@ describe("Editor component", () => {
editor.setText("1234567890\nab\ncd\nef\n1234567890");
- // Start at line 4, col 7
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 7; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 4, col: 7 });
- // Move up multiple times through short lines
editor.handleInput("\x1b[A"); // Up - line 3, col 2 (clamped)
editor.handleInput("\x1b[A"); // Up - line 2, col 2 (clamped)
editor.handleInput("\x1b[A"); // Up - line 1, col 2 (clamped)
editor.handleInput("\x1b[A"); // Up - line 0, col 7 (restored)
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 7 });
- // Move down multiple times - sticky should still be 7
editor.handleInput("\x1b[B"); // Down - line 1, col 2
editor.handleInput("\x1b[B"); // Down - line 2, col 2
editor.handleInput("\x1b[B"); // Down - line 3, col 2
@@ -3317,16 +3032,11 @@ describe("Editor component", () => {
const tui = createTestTUI(15, 24); // Narrow terminal
const editor = new Editor(tui, defaultEditorTheme);
- // Line 0: short
- // Line 1: 30 chars = wraps to 3 visual lines at width 10 (after padding)
editor.setText("short\n123456789012345678901234567890");
editor.render(15); // This gives 14 layout width
- // Position at end of line 1 (col 30)
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 30 });
- // Move up repeatedly - should traverse all visual lines of the wrapped text
- // and eventually reach line 0
editor.handleInput("\x1b[A"); // Up - to previous visual line within line 1
assert.strictEqual(editor.getCursor().line, 1);
@@ -3342,16 +3052,13 @@ describe("Editor component", () => {
editor.setText("1234567890\n\n1234567890");
- // Establish sticky column
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 8; i++) editor.handleInput("\x1b[C");
editor.handleInput("\x1b[A"); // Up
- // setText should reset sticky column
editor.setText("abcdefghij\n\nabcdefghij");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 }); // At end
- // Move up - should capture new sticky from current position (10)
editor.handleInput("\x1b[A"); // Up - line 1, col 0
editor.handleInput("\x1b[A"); // Up - line 0, col 10
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
@@ -3360,52 +3067,40 @@ describe("Editor component", () => {
it("sets preferredVisualCol when pressing right at end of prompt (last line)", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Line 0: 20 chars with 'x' at col 10
- // Line 1: empty
- // Line 2: 10 chars ending with '_'
editor.setText("111111111x1111111111\n\n333333333_");
- // Go to line 0, press Ctrl+E (end of line) - col 20
editor.handleInput("\x1b[A"); // Up to line 1
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x05"); // Ctrl+E - move to end of line
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 20 });
- // Move down to line 2 - cursor clamped to col 10 (end of line)
editor.handleInput("\x1b[B"); // Down to line 1, col 0
editor.handleInput("\x1b[B"); // Down to line 2, col 10 (clamped)
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 });
- // Press Right at end of prompt - nothing visible happens, but sets preferredVisualCol to 10
editor.handleInput("\x1b[C"); // Right - can't move, but sets preferredVisualCol
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 10 }); // Still at same position
- // Move up twice to line 0 - should use preferredVisualCol (10) to land on 'x'
editor.handleInput("\x1b[A"); // Up to line 1, col 0
editor.handleInput("\x1b[A"); // Up to line 0, col 10 (on 'x')
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
});
it("handles editor resizes when preferredVisualCol is on the same line", () => {
- // Create editor with wider terminal
const tui = createTestTUI(80, 24);
const editor = new Editor(tui, defaultEditorTheme);
editor.setText("12345678901234567890\n\n12345678901234567890");
- // Start at line 2, col 15
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 15; i++) editor.handleInput("\x1b[C");
- // Move up through empty line - establishes sticky col 15
editor.handleInput("\x1b[A"); // Up
editor.handleInput("\x1b[A"); // Up - line 0, col 15
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 15 });
- // Render with narrower width to simulate resize
editor.render(12); // Width 12
- // Move down - sticky should be clamped to new width
editor.handleInput("\x1b[B"); // Down - line 1
editor.handleInput("\x1b[B"); // Down - line 2, col should be clamped
assert.equal(editor.getCursor().col, 4);
@@ -3415,36 +3110,25 @@ describe("Editor component", () => {
const tui = createTestTUI(80, 24);
const editor = new Editor(tui, defaultEditorTheme);
- // Create a line that wraps into multiple visual lines at width 10
- // "12345678901234567890" = 20 chars, wraps to 2 visual lines at width 10
editor.setText("short\n12345678901234567890");
- // Go to line 1, col 15
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 15; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 15 });
- // Move up to establish sticky col 15
editor.handleInput("\x1b[A"); // Up to line 0
- // Line 0 has only 5 chars, so cursor at col 5
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 });
- // Narrow the editor
editor.render(10);
- // Move down - preferredVisualCol was 15, but width is 10
- // Should land on line 1, clamped to width (visual col 9, which is logical col 9)
editor.handleInput("\x1b[B"); // Down to line 1
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
- // Move up
editor.handleInput("\x1b[A"); // Up - should go to line 0
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 5 }); // Line 0 only has 5 chars
- // Restore the original width
editor.render(80);
- // Move down - preferredVisualCol was kept at 15
editor.handleInput("\x1b[B"); // Down to line 1
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 15 });
});
@@ -3457,20 +3141,15 @@ describe("Editor component", () => {
positionCursor(editor, 0, 18);
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 18 });
- // Narrow to width 10 (layoutWidth = 9).
- // Line 0 last segment has visual col max 9, line 1 first segment max 8
editor.render(10);
- // Move down: cursor clamps to 8
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
- // Widen back. Move up, the current visual col wins
editor.render(80);
editor.handleInput("\x1b[A");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 8 });
- // Preferred was cleared by the rewrapped branch
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
});
@@ -3483,31 +3162,24 @@ describe("Editor component", () => {
positionCursor(editor, 0, 18);
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 18 });
- // Narrow to width 10 (layoutWidth = 9). Moving down clamps to col 8
editor.render(10);
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
- // Widen the editor
editor.render(80);
- // Move down to short line "ab".
- // preferredVisualCol is replaced with current visual col (8), cursor clamps to 2
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 2 });
- // Moving up restores to preferred col 8
editor.handleInput("\x1b[A");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 8 });
});
});
describe("Paste marker atomic behavior", () => {
- /** Helper: simulate a large paste that creates a marker */
function pasteWithMarker(editor: Editor): string {
const bigContent = "line\n".repeat(20).trimEnd(); // 20 lines
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
- // The editor replaces large pastes with a marker like "[paste #1 +20 lines]"
return editor.getText();
}
@@ -3522,22 +3194,17 @@ describe("Editor component", () => {
editor.handleInput("A");
pasteWithMarker(editor);
editor.handleInput("B");
- // Text: "A[paste #1 +20 lines]B", cursor at end
- // Go to start
editor.handleInput("\x01"); // Ctrl+A
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
- // Right arrow: should move past "A"
editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
- // Right arrow: should skip the entire marker
editor.handleInput("\x1b[C");
const marker = editor.getText().match(/\[paste #\d+ \+\d+ lines\]/)![0];
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
- // Right arrow: should move past "B"
editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length + 1 });
});
@@ -3547,19 +3214,15 @@ describe("Editor component", () => {
editor.handleInput("A");
pasteWithMarker(editor);
editor.handleInput("B");
- // Cursor at end
- // Left arrow: past "B"
editor.handleInput("\x1b[D");
const text = editor.getText();
const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
- // Left arrow: skip the entire marker
editor.handleInput("\x1b[D");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
- // Left arrow: past "A"
editor.handleInput("\x1b[D");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 0 });
});
@@ -3573,14 +3236,11 @@ describe("Editor component", () => {
const text = editor.getText();
const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
- // Position cursor right after the marker (before "B")
editor.handleInput("\x01"); // Ctrl+A
- // Move past "A" and the marker
editor.handleInput("\x1b[C"); // past "A"
editor.handleInput("\x1b[C"); // past marker
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 + marker.length });
- // Backspace: should delete the entire marker at once
editor.handleInput("\x7f");
assert.strictEqual(editor.getText(), "AB");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
@@ -3592,11 +3252,9 @@ describe("Editor component", () => {
pasteWithMarker(editor);
editor.handleInput("B");
- // Position cursor on "A" (col 0) then move right once to be just before marker
editor.handleInput("\x01"); // Ctrl+A
editor.handleInput("\x1b[C"); // past "A", now at col 1 (start of marker)
- // Forward delete: should delete the entire marker at once
editor.handleInput("\x1b[3~"); // Delete key
assert.strictEqual(editor.getText(), "AB");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
@@ -3609,19 +3267,15 @@ describe("Editor component", () => {
pasteWithMarker(editor);
editor.handleInput(" ");
editor.handleInput("Y");
- // Text: "X [paste #1 +20 lines] Y"
const text = editor.getText();
const marker = text.match(/\[paste #\d+ \+\d+ lines\]/)![0];
- // Go to start
editor.handleInput("\x01"); // Ctrl+A
- // Ctrl+Right: skip "X"
editor.handleInput("\x1b[1;5C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 });
- // Ctrl+Right: skip whitespace + marker (marker treated as single non-ws, non-punct unit)
editor.handleInput("\x1b[1;5C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 2 + marker.length });
});
@@ -3634,16 +3288,13 @@ describe("Editor component", () => {
const textBefore = editor.getText();
- // Position after marker
editor.handleInput("\x01");
editor.handleInput("\x1b[C"); // past A
editor.handleInput("\x1b[C"); // past marker
- // Delete marker
editor.handleInput("\x7f");
assert.strictEqual(editor.getText(), "AB");
- // Undo
editor.handleInput("\x1b[45;5u");
assert.strictEqual(editor.getText(), textBefore);
});
@@ -3658,18 +3309,14 @@ describe("Editor component", () => {
const markers = [...text.matchAll(/\[paste #\d+ \+\d+ lines\]/g)];
assert.strictEqual(markers.length, 2);
- // Go to start
editor.handleInput("\x01");
- // Right arrow: should skip first marker atomically
editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markers[0]![0].length });
- // Right arrow: past space
editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markers[0]![0].length + 1 });
- // Right arrow: should skip second marker atomically
editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), {
line: 0,
@@ -3679,21 +3326,17 @@ describe("Editor component", () => {
it("does not treat manually typed marker-like text as atomic (no valid paste ID)", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Type text that matches the pattern but was typed manually (no paste entry)
const fakeMarker = "[paste #99 +5 lines]";
for (const ch of fakeMarker) editor.handleInput(ch);
assert.strictEqual(editor.getText(), fakeMarker);
- // No paste with ID 99 exists, so the marker is NOT treated atomically.
- // Right arrow should move one grapheme at a time.
editor.handleInput("\x01"); // Ctrl+A
editor.handleInput("\x1b[C"); // Right
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 1 }); // Just past "["
});
it("does not crash when paste marker is wider than terminal width", () => {
- // Reproduce: terminal width 8, paste marker "[paste #1 +47 lines]" (21 chars)
const tui = createTestTUI();
const editor = new Editor(tui, defaultEditorTheme);
const bigContent = "line\n".repeat(47).trimEnd();
@@ -3704,9 +3347,7 @@ describe("Editor component", () => {
assert.ok(marker, "paste marker should be created");
assert.ok(visibleWidth(marker[0]) > 8, "marker should be wider than render width");
- // Render at very narrow width - should not throw
const lines = editor.render(8);
- // Every rendered line must fit within the width (marker is split)
for (const line of lines) {
assert.ok(
visibleWidth(line) <= 8,
@@ -3716,30 +3357,22 @@ describe("Editor component", () => {
});
it("does not crash when text + paste marker exceeds terminal width with cursor on marker", () => {
- // Reproduce: terminal width 54, text "b".repeat(35) + "[paste #1 +27 lines]" + "bbbb"
- // Cursor lands on the paste marker after word-wrap, causing the rendered line
- // to be 55 visible chars (1 over the width).
const tui = createTestTUI();
const editor = new Editor(tui, defaultEditorTheme);
- // Type 35 'b' characters
for (let i = 0; i < 35; i++) editor.handleInput("b");
- // Paste 27 lines
const bigContent = "line\n".repeat(27).trimEnd();
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
- // Type a few more characters
for (let i = 0; i < 4; i++) editor.handleInput("b");
- // Move cursor left to land on the paste marker
editor.handleInput("\x1b[D"); // past last 'b'
editor.handleInput("\x1b[D"); // past last 'b'
editor.handleInput("\x1b[D"); // past last 'b'
editor.handleInput("\x1b[D"); // past last 'b'
editor.handleInput("\x1b[D"); // now on the paste marker
- // Render at width 54 - should not throw
const renderWidth = 54;
const lines = editor.render(renderWidth);
for (const line of lines) {
@@ -3751,24 +3384,17 @@ describe("Editor component", () => {
});
it("wordWrapLine re-checks overflow after backtracking to wrap opportunity", () => {
- // Reproduce crash #2: " " + "b".repeat(35) + atomic_marker(20 chars) + "bbbb"
- // layoutWidth=53. After wrapping at the space, the remaining 35 b's + marker = 55
- // must trigger a second force-break instead of silently overflowing.
const tui = createTestTUI();
const editor = new Editor(tui, defaultEditorTheme);
- // Type a space, then 35 b's
editor.handleInput(" ");
for (let i = 0; i < 35; i++) editor.handleInput("b");
- // Paste 27 lines to create marker
const bigContent = "line\n".repeat(27).trimEnd();
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
- // Type trailing chars
for (let i = 0; i < 4; i++) editor.handleInput("b");
- // Render at width 54 (contentWidth=54, layoutWidth=53 with paddingX=0)
const renderWidth = 54;
const lines = editor.render(renderWidth);
for (const line of lines) {
@@ -3883,34 +3509,24 @@ describe("Editor component", () => {
it("snaps to the paste marker start when navigating down into it", () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
- // Line 0: long enough text to establish a sticky column
editor.setText("12345678901234567890\n\nhello ");
- // Create a large paste to get a marker
const bigContent = "x".repeat(2000);
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
editor.render(80);
const text = editor.getText();
const _marker = text.match(/\[paste #\d+ \d+ chars\]/)![0];
- // Line 0: "12345678901234567890"
- // Line 1: "" (empty)
- // Line 2: "hello [paste #1 2000 chars]"
- // marker starts at col 6
- // Navigate to line 0, col 10
editor.handleInput("\x1b[A"); // Up to line 1
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A (start of line)
for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C"); // Right 10
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
- // Down to empty line
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
- // Down to paste marker line - sticky col 10 falls inside marker (starts at col 6).
- // Cursor should snap to start of marker (col 6), not end (col 6 + marker.length).
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 6 });
});
@@ -3919,12 +3535,6 @@ describe("Editor component", () => {
const tui = createTestTUI(30, 24);
const editor = new Editor(tui, defaultEditorTheme);
- // Build:
- // Line 0: "1234567890123456" (16 chars)
- // Line 1: "" (empty)
- // Line 2: "[paste #1 2000 chars]" (22 chars, paste marker)
- // Line 3: "" (empty)
- // Line 4: "abcdefghijklmnop" (16 chars)
for (const ch of "1234567890123456") editor.handleInput(ch);
editor.handleInput("\n");
editor.handleInput("\n");
@@ -3934,25 +3544,20 @@ describe("Editor component", () => {
for (const ch of "abcdefghijklmnop") editor.handleInput(ch);
editor.render(30);
- // Navigate to line 0, col 10
for (let i = 0; i < 4; i++) editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 10; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 10 });
- // Down to empty line - sticky col 10 established
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 0 });
- // Down to paste marker - cursor snapped to col 0 (start of marker)
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 2, col: 0 });
- // Down to empty line
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 3, col: 0 });
- // Down to last line - should restore sticky col 10
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 4, col: 10 });
});
@@ -3961,20 +3566,6 @@ describe("Editor component", () => {
const tui = createTestTUI(20, 24);
const editor = new Editor(tui, defaultEditorTheme);
- // Build:
- // Logical line 0: "abcdefgh" + marker(21 chars) + "ijklmnopqr"
- // Logical line 1: "123456789012345678"
- //
- // Marker "[paste #1 +100 lines]" (21 chars) is wider than the
- // terminal (20). Word-wrap splits at the space before "lines",
- // producing:
- // VL1: abcdefgh (startCol 0, len 8)
- // VL2: [paste #1 +100 (startCol 8, len 15) <- marker head
- // VL3: lines]ijklmnopqr (startCol 23, len 16) <- marker tail + content
- // VL4: 123456789012345678 (line 1)
- //
- // On VL3 the marker tail "lines]" occupies visual cols 0-5.
- // Content ("i") starts at visual col 6 = logical col 29.
for (const ch of "abcdefgh") editor.handleInput(ch);
const bigContent = "line\n".repeat(100).trimEnd();
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
@@ -3991,29 +3582,21 @@ describe("Editor component", () => {
const markerStart = 8;
const markerEnd = markerStart + markerLen; // 29
- // Navigate to line 0, col 6 (on "g"). Preferred col 6 is past the
- // marker tail on VL3, so the cursor should land on content ("i" at
- // col 29) without snapping back.
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A (start of line)
for (let i = 0; i < 6; i++) editor.handleInput("\x1b[C"); // Right to col 6
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
- // Down: cursor lands on paste marker start
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markerStart });
- // Down again: preferred col 6 lands at VL3 col 29 ("i"), which is
- // past the marker. Cursor stays on line 0.
editor.handleInput("\x1b[B");
assert.strictEqual(editor.getCursor().line, 0);
assert.strictEqual(editor.getCursor().col, markerEnd); // col 29 = "i"
- // Up: back to paste marker
editor.handleInput("\x1b[A");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: markerStart });
- // Up again: back to col 6 ("g")
editor.handleInput("\x1b[A");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 6 });
});
@@ -4022,14 +3605,6 @@ describe("Editor component", () => {
const tui = createTestTUI(20, 24);
const editor = new Editor(tui, defaultEditorTheme);
- // Same layout. Start at col 3 ("d"). Preferred col 3 maps to VL3
- // visual col 3 which is inside the "lines]" marker tail.
- // moveToVisualLine detects the continuation VL and skips to VL4
- // (line 1).
- // VL1: abcdefgh (startCol 0, len 8)
- // VL2: [paste #1 +100 (startCol 8, len 15) <- marker head
- // VL3: lines]ijklmnopqr (startCol 23, len 16) <- marker tail + content
- // VL4: 123456789012345678 (line 1)
for (const ch of "abcdefgh") editor.handleInput(ch);
const bigContent = "line\n".repeat(100).trimEnd();
editor.handleInput(`\x1b[200~${bigContent}\x1b[201~`);
@@ -4038,21 +3613,17 @@ describe("Editor component", () => {
for (const ch of "123456789012345678") editor.handleInput(ch);
editor.render(20);
- // Navigate to line 0, col 3 (on "d")
editor.handleInput("\x1b[A"); // Up to line 0
editor.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 3; i++) editor.handleInput("\x1b[C");
assert.deepStrictEqual(editor.getCursor(), { line: 0, col: 3 });
- // Down: marker
editor.handleInput("\x1b[B");
assert.strictEqual(editor.getCursor().col, 8);
- // Down: skips VL3 (col 3 in marker tail) and lands on line 1
editor.handleInput("\x1b[B");
assert.deepStrictEqual(editor.getCursor(), { line: 1, col: 3 });
- // Round-trip back
editor.handleInput("\x1b[A");
assert.strictEqual(editor.getCursor().col, 8); // marker
editor.handleInput("\x1b[A");
diff --git a/packages/tui/test/fullscreen.test.ts b/packages/tui/test/fullscreen.test.ts
index 5dd22d3491..3166b47003 100644
--- a/packages/tui/test/fullscreen.test.ts
+++ b/packages/tui/test/fullscreen.test.ts
@@ -82,8 +82,6 @@ function setup(transcriptLines: string[], cols = 40, rows = 10): Setup {
chat.lines = transcriptLines;
const dock = new TestComponent();
dock.lines = ["> prompt", "footer"];
- // Children drive inline rendering (before enter / after exit); the same
- // components are passed explicitly as fullscreen scroll/dock roots.
tui.addChild(chat);
tui.addChild(dock);
tui.start();
@@ -114,7 +112,6 @@ describe("TUI fullscreen mode", () => {
assert.strictEqual(terminal.getActiveBufferType(), "alternate");
assert.strictEqual(terminal.mouseTrackingActive, true, "probe succeeds → wheel tracking enabled");
- // rows=10, dock=2 → window shows the last 8 of 20 transcript lines
const viewport = terminal.getViewport();
assert.strictEqual(viewport[0], "Line 12");
assert.strictEqual(viewport[7], "Line 19");
@@ -302,7 +299,6 @@ describe("TUI fullscreen mode", () => {
terminal.sendInput(PAGE_UP);
await terminal.waitForRender();
- // window height 8 → page size 7; top was 22, now 15
assert.strictEqual(terminal.getViewport()[0], "Line 15");
terminal.sendInput(VIEWPORT_TOP);
@@ -723,7 +719,6 @@ describe("TUI fullscreen mode", () => {
tui.enterFullscreen({ scroll: [chat], dock });
await terminal.waitForRender();
- // window shows lines 12-19; press on row 1 col 1, drag to row 2 col 6
terminal.sendInput("\x1b[<0;1;1M");
terminal.sendInput("\x1b[<32;6;2M");
await terminal.waitForRender();
@@ -906,7 +901,6 @@ describe("TUI fullscreen mode", () => {
tui.enterFullscreen({ scroll: [chat], dock });
await terminal.waitForRender();
- // rows=10 and dock=2, so the user prompt is visible at screen row 9.
terminal.sendInput("\x1b[<0;3;9M");
terminal.sendInput("\x1b[<32;9;9M");
await terminal.waitForRender();
@@ -938,7 +932,6 @@ describe("TUI fullscreen mode", () => {
it("clicking an OSC 8 hyperlink opens it through the URL handler", async () => {
const transcript = lines(20);
- // window height is 8 (rows=10, dock=2), following shows lines 12..19
transcript[12] = "see \x1b]8;;https://example.com/docs\x1b\\\x1b[36mdocs\x1b[39m\x1b]8;;\x1b\\ here";
const { terminal, tui, chat, dock } = setup(transcript);
const opened: string[] = [];
@@ -946,13 +939,11 @@ describe("TUI fullscreen mode", () => {
tui.enterFullscreen({ scroll: [chat], dock });
await terminal.waitForRender();
- // "docs" occupies columns 5-8 on screen row 1
terminal.sendInput("\x1b[<0;6;1M");
terminal.sendInput("\x1b[<0;6;1m");
await terminal.waitForRender();
assert.deepStrictEqual(opened, ["https://example.com/docs"]);
- // clicking outside the link opens nothing
terminal.sendInput("\x1b[<0;2;1M");
terminal.sendInput("\x1b[<0;2;1m");
await terminal.waitForRender();
@@ -971,7 +962,6 @@ describe("TUI fullscreen mode", () => {
await terminal.waitForRender();
terminal.sendInput("\x1b[<0;6;1M");
- // The target can repaint between physical press and release while output streams.
transcript[12] = "updated without the URL";
tui.requestRender();
await terminal.waitForRender();
@@ -991,7 +981,6 @@ describe("TUI fullscreen mode", () => {
tui.enterFullscreen({ scroll: [chat], dock });
await terminal.waitForRender();
- // The tab is painted as three spaces, so the link starts at column 4.
terminal.sendInput("\x1b[<0;4;1M");
terminal.sendInput("\x1b[<0;4;1m");
await terminal.waitForRender();
@@ -1126,7 +1115,6 @@ describe("TUI fullscreen mode", () => {
tui.enterFullscreen({ scroll: [chat], dock });
await terminal.waitForRender();
- // rows=10, dock=2 → dock starts at screen row 9
terminal.sendInput("\x1b[<0;3;9M");
terminal.sendInput("\x1b[<0;3;9m");
await terminal.waitForRender();
diff --git a/packages/tui/test/fuzzy.test.ts b/packages/tui/test/fuzzy.test.ts
index 622a260aa1..d23abf855e 100644
--- a/packages/tui/test/fuzzy.test.ts
+++ b/packages/tui/test/fuzzy.test.ts
@@ -79,7 +79,6 @@ describe("fuzzyFilter", () => {
const items = ["a_p_p", "app", "application"];
const result = fuzzyFilter(items, "app", (x: string) => x);
- // "app" should be first (exact consecutive match at start)
assert.strictEqual(result[0], "app");
});
@@ -123,7 +122,6 @@ describe("fuzzyFilterScored", () => {
});
it("assigns equal scores to equally-good matches, enabling a stable tie-break", () => {
- // glm-5 / glm-5.1 / glm-5.2 all match "glm" identically; caller breaks the tie.
const items = ["glm-5", "glm-5.1", "glm-5.2"];
const result = fuzzyFilterScored(items, "glm", (x: string) => x);
assert.strictEqual(result.length, 3);
diff --git a/packages/tui/test/input.test.ts b/packages/tui/test/input.test.ts
index 3edd73ca1b..1dc71aa41b 100644
--- a/packages/tui/test/input.test.ts
+++ b/packages/tui/test/input.test.ts
@@ -12,7 +12,6 @@ describe("Input component", () => {
submitted = value;
};
- // Type hello, then backslash, then Enter
input.handleInput("h");
input.handleInput("e");
input.handleInput("l");
@@ -21,7 +20,6 @@ describe("Input component", () => {
input.handleInput("\\");
input.handleInput("\r");
- // Input is single-line, no backslash+Enter workaround
assert.strictEqual(submitted, "hello\\");
});
@@ -88,13 +86,11 @@ describe("Input component", () => {
const input = new Input();
input.setValue("foo bar baz");
- // Move cursor to end
input.handleInput("\x05"); // Ctrl+E
input.handleInput("\x17"); // Ctrl+W - deletes "baz"
assert.strictEqual(input.getValue(), "foo bar ");
- // Move to beginning and yank
input.handleInput("\x01"); // Ctrl+A
input.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(input.getValue(), "bazfoo bar ");
@@ -104,7 +100,6 @@ describe("Input component", () => {
const input = new Input();
input.setValue("hello world");
- // Move cursor to after "hello "
input.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) input.handleInput("\x1b[C");
@@ -140,7 +135,6 @@ describe("Input component", () => {
it("Alt+Y cycles through kill ring after Ctrl+Y", () => {
const input = new Input();
- // Create kill ring with multiple entries
input.setValue("first");
input.handleInput("\x05"); // Ctrl+E
input.handleInput("\x17"); // Ctrl+W - deletes "first"
@@ -175,7 +169,6 @@ describe("Input component", () => {
input.setValue("other");
input.handleInput("\x05"); // Ctrl+E
- // Type something to break the yank chain
input.handleInput("x");
assert.strictEqual(input.getValue(), "otherx");
@@ -272,11 +265,9 @@ describe("Input component", () => {
input.handleInput("\x1by"); // Alt+Y - cycles to "second"
assert.strictEqual(input.getValue(), "second");
- // Break chain and start fresh
input.handleInput("x");
input.setValue("");
- // New yank should get "second" (now at end after rotation)
input.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(input.getValue(), "second");
});
@@ -285,7 +276,6 @@ describe("Input component", () => {
const input = new Input();
input.setValue("prefix|suffix");
- // Position cursor at "|"
input.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) input.handleInput("\x1b[C"); // Move right 6
@@ -308,7 +298,6 @@ describe("Input component", () => {
input.handleInput("\x1bd"); // Alt+D - deletes " world"
assert.strictEqual(input.getValue(), " test");
- // Yank should get accumulated text
input.handleInput("\x19"); // Ctrl+Y
assert.strictEqual(input.getValue(), "hello world test");
});
@@ -320,7 +309,6 @@ describe("Input component", () => {
input.handleInput("\x05"); // Ctrl+E
input.handleInput("\x17"); // Ctrl+W - deletes "word"
input.setValue("hello world");
- // Move to middle (after "hello ")
input.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) input.handleInput("\x1b[C");
@@ -331,7 +319,6 @@ describe("Input component", () => {
it("handles yank-pop in middle of text", () => {
const input = new Input();
- // Create two kill ring entries
input.setValue("FIRST");
input.handleInput("\x05"); // Ctrl+E
input.handleInput("\x17"); // Ctrl+W - deletes "FIRST"
@@ -339,7 +326,6 @@ describe("Input component", () => {
input.handleInput("\x05"); // Ctrl+E
input.handleInput("\x17"); // Ctrl+W - deletes "SECOND"
- // Set up "hello world" and position cursor after "hello "
input.setValue("hello world");
input.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 6; i++) input.handleInput("\x1b[C");
@@ -376,11 +362,9 @@ describe("Input component", () => {
input.handleInput("d");
assert.strictEqual(input.getValue(), "hello world");
- // Undo removes " world"
input.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(input.getValue(), "hello");
- // Undo removes "hello"
input.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(input.getValue(), "");
});
@@ -534,11 +518,9 @@ describe("Input component", () => {
input.handleInput("\x01"); // Ctrl+A
for (let i = 0; i < 5; i++) input.handleInput("\x1b[C");
- // Simulate bracketed paste
input.handleInput("\x1b[200~beep boop\x1b[201~");
assert.strictEqual(input.getValue(), "hellobeep boop world");
- // Single undo should restore entire pre-paste state
input.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(input.getValue(), "hello world");
});
@@ -568,11 +550,9 @@ describe("Input component", () => {
input.handleInput("e");
assert.strictEqual(input.getValue(), "abcde");
- // Undo removes "de" (typed after movement)
input.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(input.getValue(), "abc");
- // Undo removes "abc"
input.handleInput("\x1b[45;5u"); // Ctrl+- (undo)
assert.strictEqual(input.getValue(), "");
});
diff --git a/packages/tui/test/key-tester.ts b/packages/tui/test/key-tester.ts
index 443ab3ac17..5103d54418 100755
--- a/packages/tui/test/key-tester.ts
+++ b/packages/tui/test/key-tester.ts
@@ -3,9 +3,6 @@ import { matchesKey } from "../src/keys.js";
import { ProcessTerminal } from "../src/terminal.js";
import { type Component, TUI } from "../src/tui.js";
-/**
- * Simple key code logger component
- */
class KeyLogger implements Component {
private log: string[] = [];
private maxLines = 20;
@@ -16,14 +13,12 @@ class KeyLogger implements Component {
}
handleInput(data: string): void {
- // Handle Ctrl+C (raw or Kitty protocol) for exit
if (matchesKey(data, "ctrl+c")) {
this.tui.stop();
console.log("\nExiting...");
process.exit(0);
}
- // Convert to various representations
const hex = Buffer.from(data).toString("hex");
const charCodes = Array.from(data)
.map((c) => c.charCodeAt(0))
@@ -39,40 +34,32 @@ class KeyLogger implements Component {
this.log.push(logLine);
- // Keep only last N lines
if (this.log.length > this.maxLines) {
this.log.shift();
}
- // Request re-render to show the new log entry
this.tui.requestRender();
}
- invalidate(): void {
- // No cached state to invalidate currently
- }
+ invalidate(): void {}
render(width: number): string[] {
const lines: string[] = [];
- // Title
lines.push("=".repeat(width));
lines.push("Key Code Tester - Press keys to see their codes (Ctrl+C to exit)".padEnd(width));
lines.push("=".repeat(width));
lines.push("");
- // Log entries
for (const entry of this.log) {
lines.push(entry.padEnd(width));
}
- // Fill remaining space
const remaining = Math.max(0, 25 - lines.length);
for (let i = 0; i < remaining; i++) {
lines.push("".padEnd(width));
}
- // Footer
lines.push("=".repeat(width));
lines.push("Test these:".padEnd(width));
lines.push(" - Shift + Enter (should show: \\x1b[13;2u with Kitty protocol)".padEnd(width));
@@ -86,7 +73,6 @@ class KeyLogger implements Component {
}
}
-// Set up TUI
const terminal = new ProcessTerminal();
const tui = new TUI(terminal);
const logger = new KeyLogger(tui);
@@ -94,12 +80,10 @@ const logger = new KeyLogger(tui);
tui.addChild(logger);
tui.setFocus(logger);
-// Handle Ctrl+C for clean exit (SIGINT still works for raw mode)
process.on("SIGINT", () => {
tui.stop();
console.log("\nExiting...");
process.exit(0);
});
-// Start the TUI
tui.start();
diff --git a/packages/tui/test/keys.test.ts b/packages/tui/test/keys.test.ts
index bf3c87e0d6..348d62a48c 100644
--- a/packages/tui/test/keys.test.ts
+++ b/packages/tui/test/keys.test.ts
@@ -1,7 +1,3 @@
-/**
- * Tests for keyboard input handling
- */
-
import assert from "node:assert";
import { describe, it } from "node:test";
import {
@@ -40,14 +36,10 @@ function withEnvVars(vars: Record<string, string | undefined>, fn: () => void):
describe("matchesKey", () => {
describe("Kitty protocol with alternate keys (non-Latin layouts)", () => {
- // Kitty protocol flag 4 (Report alternate keys) sends:
- // CSI codepoint:shifted:base ; modifier:event u
- // Where base is the key in standard PC-101 layout
-
it("should match Ctrl+c when pressing Ctrl+С (Cyrillic) with base layout key", () => {
setKittyProtocolActive(true);
- // Cyrillic 'с' = codepoint 1089, Latin 'c' = codepoint 99
- // Format: CSI 1089::99;5u (codepoint::base;modifier with ctrl=4, +1=5)
+ // Kitty alternate-key reports include the standard-layout base code point,
+ // allowing configured Latin bindings to work on non-Latin layouts.
const cyrillicCtrlC = "\x1b[1089::99;5u";
assert.strictEqual(matchesKey(cyrillicCtrlC, "ctrl+c"), true);
setKittyProtocolActive(false);
@@ -55,7 +47,6 @@ describe("matchesKey", () => {
it("should match Ctrl+d when pressing Ctrl+В (Cyrillic) with base layout key", () => {
setKittyProtocolActive(true);
- // Cyrillic 'в' = codepoint 1074, Latin 'd' = codepoint 100
const cyrillicCtrlD = "\x1b[1074::100;5u";
assert.strictEqual(matchesKey(cyrillicCtrlD, "ctrl+d"), true);
setKittyProtocolActive(false);
@@ -63,7 +54,6 @@ describe("matchesKey", () => {
it("should match Ctrl+z when pressing Ctrl+Я (Cyrillic) with base layout key", () => {
setKittyProtocolActive(true);
- // Cyrillic 'я' = codepoint 1103, Latin 'z' = codepoint 122
const cyrillicCtrlZ = "\x1b[1103::122;5u";
assert.strictEqual(matchesKey(cyrillicCtrlZ, "ctrl+z"), true);
setKittyProtocolActive(false);
@@ -71,8 +61,6 @@ describe("matchesKey", () => {
it("should match Ctrl+Shift+p with base layout key", () => {
setKittyProtocolActive(true);
- // Cyrillic 'з' = codepoint 1079, Latin 'p' = codepoint 112
- // ctrl=4, shift=1, +1 = 6
const cyrillicCtrlShiftP = "\x1b[1079::112;6u";
assert.strictEqual(matchesKey(cyrillicCtrlShiftP, "ctrl+shift+p"), true);
setKittyProtocolActive(false);
@@ -80,7 +68,6 @@ describe("matchesKey", () => {
it("should still match direct codepoint when no base layout key", () => {
setKittyProtocolActive(true);
- // Latin ctrl+c without base layout key (terminal doesn't support flag 4)
const latinCtrlC = "\x1b[99;5u";
assert.strictEqual(matchesKey(latinCtrlC, "ctrl+c"), true);
setKittyProtocolActive(false);
@@ -136,8 +123,6 @@ describe("matchesKey", () => {
it("should handle shifted key in format", () => {
setKittyProtocolActive(true);
- // Format with shifted key: CSI codepoint:shifted:base;modifier u
- // Latin 'c' with shifted 'C' (67) and base 'c' (99)
const shiftedKey = "\x1b[99:67:99;2u"; // shift modifier = 1, +1 = 2
assert.strictEqual(matchesKey(shiftedKey, "shift+c"), true);
setKittyProtocolActive(false);
@@ -145,8 +130,6 @@ describe("matchesKey", () => {
it("should handle event type in format", () => {
setKittyProtocolActive(true);
- // Format with event type: CSI codepoint::base;modifier:event u
- // Cyrillic ctrl+c release event (event type 3)
const releaseEvent = "\x1b[1089::99;5:3u";
assert.strictEqual(matchesKey(releaseEvent, "ctrl+c"), true);
setKittyProtocolActive(false);
@@ -154,10 +137,6 @@ describe("matchesKey", () => {
it("should handle full format with shifted key, base key, and event type", () => {
setKittyProtocolActive(true);
- // Full format: CSI codepoint:shifted:base;modifier:event u
- // Cyrillic 'С' (shifted) with base 'c', Ctrl+Shift pressed, repeat event
- // Cyrillic 'с' = 1089, Cyrillic 'С' = 1057, Latin 'c' = 99
- // ctrl=4, shift=1, +1 = 6, repeat event = 2
const fullFormat = "\x1b[1089:1057:99;6:2u";
assert.strictEqual(matchesKey(fullFormat, "ctrl+shift+c"), true);
setKittyProtocolActive(false);
@@ -165,7 +144,6 @@ describe("matchesKey", () => {
it("should prefer codepoint for Latin letters even when base layout differs", () => {
setKittyProtocolActive(true);
- // Dvorak Ctrl+K reports codepoint 'k' (107) and base layout 'v' (118)
const dvorakCtrlK = "\x1b[107::118;5u";
assert.strictEqual(matchesKey(dvorakCtrlK, "ctrl+k"), true);
assert.strictEqual(matchesKey(dvorakCtrlK, "ctrl+v"), false);
@@ -174,7 +152,6 @@ describe("matchesKey", () => {
it("should prefer codepoint for symbol keys even when base layout differs", () => {
setKittyProtocolActive(true);
- // Dvorak Ctrl+/ reports codepoint '/' (47) and base layout '[' (91)
const dvorakCtrlSlash = "\x1b[47::91;5u";
assert.strictEqual(matchesKey(dvorakCtrlSlash, "ctrl+/"), true);
assert.strictEqual(matchesKey(dvorakCtrlSlash, "ctrl+["), false);
@@ -183,7 +160,6 @@ describe("matchesKey", () => {
it("should not match wrong key even with base layout", () => {
setKittyProtocolActive(true);
- // Cyrillic ctrl+с with base 'c' should NOT match ctrl+d
const cyrillicCtrlC = "\x1b[1089::99;5u";
assert.strictEqual(matchesKey(cyrillicCtrlC, "ctrl+d"), false);
setKittyProtocolActive(false);
@@ -191,7 +167,6 @@ describe("matchesKey", () => {
it("should not match wrong modifiers even with base layout", () => {
setKittyProtocolActive(true);
- // Cyrillic ctrl+с should NOT match ctrl+shift+c
const cyrillicCtrlC = "\x1b[1089::99;5u";
assert.strictEqual(matchesKey(cyrillicCtrlC, "ctrl+shift+c"), false);
setKittyProtocolActive(false);
@@ -299,13 +274,11 @@ describe("matchesKey", () => {
describe("Legacy key matching", () => {
it("should match legacy Ctrl+c", () => {
setKittyProtocolActive(false);
- // Ctrl+c sends ASCII 3 (ETX)
assert.strictEqual(matchesKey("\x03", "ctrl+c"), true);
});
it("should match legacy Ctrl+d", () => {
setKittyProtocolActive(false);
- // Ctrl+d sends ASCII 4 (EOT)
assert.strictEqual(matchesKey("\x04", "ctrl+d"), true);
});
@@ -335,14 +308,10 @@ describe("matchesKey", () => {
it("should match legacy Ctrl+symbol", () => {
setKittyProtocolActive(false);
- // Ctrl+\ sends ASCII 28 (File Separator) in legacy terminals
assert.strictEqual(matchesKey("\x1c", "ctrl+\\"), true);
assert.strictEqual(parseKey("\x1c"), "ctrl+\\");
- // Ctrl+] sends ASCII 29 (Group Separator) in legacy terminals
assert.strictEqual(matchesKey("\x1d", "ctrl+]"), true);
assert.strictEqual(parseKey("\x1d"), "ctrl+]");
- // Ctrl+_ sends ASCII 31 (Unit Separator) in legacy terminals
- // Ctrl+- is on the same physical key on US keyboards
assert.strictEqual(matchesKey("\x1f", "ctrl+_"), true);
assert.strictEqual(matchesKey("\x1f", "ctrl+-"), true);
assert.strictEqual(parseKey("\x1f"), "ctrl+-");
@@ -350,17 +319,12 @@ describe("matchesKey", () => {
it("should match legacy Ctrl+Alt+symbol", () => {
setKittyProtocolActive(false);
- // Ctrl+Alt+[ sends ESC followed by ESC (Ctrl+[ = ESC)
assert.strictEqual(matchesKey("\x1b\x1b", "ctrl+alt+["), true);
assert.strictEqual(parseKey("\x1b\x1b"), "ctrl+alt+[");
- // Ctrl+Alt+\ sends ESC followed by ASCII 28
assert.strictEqual(matchesKey("\x1b\x1c", "ctrl+alt+\\"), true);
assert.strictEqual(parseKey("\x1b\x1c"), "ctrl+alt+\\");
- // Ctrl+Alt+] sends ESC followed by ASCII 29
assert.strictEqual(matchesKey("\x1b\x1d", "ctrl+alt+]"), true);
assert.strictEqual(parseKey("\x1b\x1d"), "ctrl+alt+]");
- // Ctrl+_ sends ASCII 31 (Unit Separator) in legacy terminals
- // Ctrl+- is on the same physical key on US keyboards
assert.strictEqual(matchesKey("\x1b\x1f", "ctrl+alt+_"), true);
assert.strictEqual(matchesKey("\x1b\x1f", "ctrl+alt+-"), true);
assert.strictEqual(parseKey("\x1b\x1f"), "ctrl+alt+-");
@@ -481,7 +445,6 @@ describe("matchesKey", () => {
it("should match alt+arrows", () => {
assert.strictEqual(matchesKey("\x1bp", "alt+up"), true);
assert.strictEqual(matchesKey("\x1bp", "up"), false);
- // Standard xterm CSI modified-arrow sequences (terminals without Kitty protocol)
assert.strictEqual(matchesKey("\x1b[1;3A", "alt+up"), true);
assert.strictEqual(matchesKey("\x1b[1;3B", "alt+down"), true);
});
@@ -525,7 +488,6 @@ describe("parseKey", () => {
describe("Kitty protocol with alternate keys", () => {
it("should return Latin key name when base layout key is present", () => {
setKittyProtocolActive(true);
- // Cyrillic ctrl+с with base layout 'c'
const cyrillicCtrlC = "\x1b[1089::99;5u";
assert.strictEqual(parseKey(cyrillicCtrlC), "ctrl+c");
setKittyProtocolActive(false);
@@ -533,7 +495,6 @@ describe("parseKey", () => {
it("should prefer codepoint for Latin letters when base layout differs", () => {
setKittyProtocolActive(true);
- // Dvorak Ctrl+K reports codepoint 'k' (107) and base layout 'v' (118)
const dvorakCtrlK = "\x1b[107::118;5u";
assert.strictEqual(parseKey(dvorakCtrlK), "ctrl+k");
setKittyProtocolActive(false);
@@ -541,7 +502,6 @@ describe("parseKey", () => {
it("should prefer codepoint for symbol keys when base layout differs", () => {
setKittyProtocolActive(true);
- // Dvorak Ctrl+/ reports codepoint '/' (47) and base layout '[' (91)
const dvorakCtrlSlash = "\x1b[47::91;5u";
assert.strictEqual(parseKey(dvorakCtrlSlash), "ctrl+/");
setKittyProtocolActive(false);
@@ -616,8 +576,6 @@ describe("parseKey", () => {
});
describe("combined modified arrows", () => {
- // xterm encodes modifiers as a 1-based parameter: 1 + shift(1) + alt(2) + ctrl(4).
- // Ctrl+Alt is therefore parameter 7, and parameter 8 is Shift+Ctrl+Alt.
it("matches xterm and Kitty Ctrl+Alt arrows", () => {
assert.equal(matchesKey("\x1b[1;7A", "ctrl+alt+up"), true);
assert.equal(matchesKey("\x1b[1;7B", "ctrl+alt+down"), true);
diff --git a/packages/tui/test/markdown-latex.test.ts b/packages/tui/test/markdown-latex.test.ts
index e613d73441..62ce399599 100644
--- a/packages/tui/test/markdown-latex.test.ts
+++ b/packages/tui/test/markdown-latex.test.ts
@@ -90,7 +90,6 @@ describe("latexToUnicode", () => {
it("keeps underscores literal inside text-mode commands", () => {
assert.strictEqual(latexToUnicode("\\text{x_i}"), "x_i");
assert.strictEqual(latexToUnicode("\\text{learning_rate} = 0.1"), "learning_rate = 0.1");
- // Math-mode font commands still apply scripts, as TeX does.
assert.strictEqual(latexToUnicode("\\mathrm{x_i}"), "xᵢ");
});
});
@@ -109,7 +108,6 @@ describe("Markdown math rendering", () => {
});
it("renders display math with CRLF line endings", () => {
- // marked normalizes \r\n before tokenizers run; pin that assumption.
const lines = renderPlain("\\[\r\nE = mc^2\r\n\\]\r\n");
assert.ok(lines.some((line) => line.includes("E = mc²")));
});
@@ -125,7 +123,6 @@ describe("Markdown math rendering", () => {
});
it("keeps underscores inside math out of emphasis", () => {
- // Without math support, marked would turn _k ... x_ into an em token.
const lines = renderPlain("\\[ a_k = b_k + x_k \\]");
assert.ok(lines.some((line) => line.includes("aₖ = bₖ + xₖ")));
});
@@ -165,8 +162,6 @@ describe("Markdown math rendering", () => {
});
it("renders display math indented four spaces instead of treating it as code", () => {
- // Models often indent display math; 4-space indents would otherwise lex
- // as an indented code block and show raw TeX verbatim.
const lines = renderPlain("Math:\n\n \\[\n E = mc^2\n \\]\n\n $$\n a^2 + b^2 = c^2\n $$");
assert.ok(lines.some((line) => line.includes("E = mc²")));
assert.ok(lines.some((line) => line.includes("a² + b² = c²")));
@@ -199,8 +194,6 @@ describe("Markdown math rendering", () => {
it("falls back to code/codeBlock theme styles", () => {
const markdown = new Markdown("$$x + y$$", 0, 0, defaultMarkdownTheme);
const lines = markdown.render(80);
- // defaultMarkdownTheme has no math entries; block math falls back to
- // codeBlock (green in the test theme).
const mathLine = lines.find((line) => stripAnsi(line).includes("x + y"));
assert.ok(mathLine);
assert.ok(mathLine.includes("\x1b[32m"));
diff --git a/packages/tui/test/markdown-streaming-bench.ts b/packages/tui/test/markdown-streaming-bench.ts
index dccb7f4c18..5032bc23f2 100644
--- a/packages/tui/test/markdown-streaming-bench.ts
+++ b/packages/tui/test/markdown-streaming-bench.ts
@@ -1,11 +1,3 @@
-/**
- * Benchmark: streaming-style Markdown rendering.
- *
- * Simulates an assistant message growing token by token (as during daemon
- * streaming) and measures per-update render cost. Run with:
- *
- * npx tsx test/markdown-streaming-bench.ts
- */
import { performance } from "node:perf_hooks";
import { Markdown } from "../src/components/markdown.js";
import { defaultMarkdownTheme } from "./test-themes.js";
diff --git a/packages/tui/test/markdown.test.ts b/packages/tui/test/markdown.test.ts
index 264b35caf9..c2e2b90d39 100644
--- a/packages/tui/test/markdown.test.ts
+++ b/packages/tui/test/markdown.test.ts
@@ -8,7 +8,6 @@ import { type Component, TUI } from "../src/tui.js";
import { defaultMarkdownTheme } from "./test-themes.js";
import { VirtualTerminal } from "./virtual-terminal.js";
-// Force full color in CI so ANSI assertions are deterministic
const chalk = new Chalk({ level: 3 });
function getCellItalic(terminal: VirtualTerminal, row: number, col: number): number {
@@ -46,13 +45,10 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
- // Check that we have content
assert.ok(lines.length > 0);
- // Strip ANSI codes for checking
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Check structure
assert.ok(plainLines.some((line) => line.includes("- Item 1")));
assert.ok(plainLines.some((line) => line.includes(" - Nested 1.1")));
assert.ok(plainLines.some((line) => line.includes(" - Nested 1.2")));
@@ -73,7 +69,6 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Check proper indentation
assert.ok(plainLines.some((line) => line.includes("- Level 1")));
assert.ok(plainLines.some((line) => line.includes(" - Level 2")));
assert.ok(plainLines.some((line) => line.includes(" - Level 3")));
@@ -121,8 +116,6 @@ describe("Markdown component", () => {
});
it("should maintain numbering when code blocks are not indented (LLM output)", () => {
- // When code blocks aren't indented, marked parses each item as a separate list.
- // We use token.start to preserve the original numbering.
const markdown = new Markdown(
`1. First item
@@ -145,13 +138,10 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trim());
- // Find all lines that start with a number and period
const numberedLines = plainLines.filter((line) => /^\d+\./.test(line));
- // Should have 3 numbered items
assert.strictEqual(numberedLines.length, 3, `Expected 3 numbered items, got: ${numberedLines.join(", ")}`);
- // Check the actual numbers
assert.ok(numberedLines[0].startsWith("1."), `First item should be "1.", got: ${numberedLines[0]}`);
assert.ok(numberedLines[1].startsWith("2."), `Second item should be "2.", got: ${numberedLines[1]}`);
assert.ok(numberedLines[2].startsWith("3."), `Third item should be "3.", got: ${numberedLines[2]}`);
@@ -173,12 +163,10 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Check table structure
assert.ok(plainLines.some((line) => line.includes("Name")));
assert.ok(plainLines.some((line) => line.includes("Age")));
assert.ok(plainLines.some((line) => line.includes("Alice")));
assert.ok(plainLines.some((line) => line.includes("Bob")));
- // Check for table borders
assert.ok(plainLines.some((line) => line.includes("│")));
assert.ok(plainLines.some((line) => line.includes("─")));
});
@@ -243,11 +231,9 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Check headers
assert.ok(plainLines.some((line) => line.includes("Left")));
assert.ok(plainLines.some((line) => line.includes("Center")));
assert.ok(plainLines.some((line) => line.includes("Right")));
- // Check content
assert.ok(plainLines.some((line) => line.includes("Long text")));
});
@@ -264,7 +250,6 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
- // Should render without errors
assert.ok(lines.length > 0);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
@@ -283,16 +268,13 @@ describe("Markdown component", () => {
defaultMarkdownTheme,
);
- // Render at narrow width that forces wrapping
const lines = markdown.render(50);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // All lines should fit within width
for (const line of plainLines) {
assert.ok(line.length <= 50, `Line exceeds width 50: "${line}" (length: ${line.length})`);
}
- // Content should still be present (possibly wrapped across lines)
const allText = plainLines.join(" ");
assert.ok(allText.includes("Command"), "Should contain 'Command'");
assert.ok(allText.includes("Description"), "Should contain 'Description'");
@@ -310,15 +292,12 @@ describe("Markdown component", () => {
defaultMarkdownTheme,
);
- // Render at width that forces the cell to wrap
const lines = markdown.render(25);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // Should have multiple data rows due to wrapping
const dataRows = plainLines.filter((line) => line.startsWith("│") && !line.includes("─"));
assert.ok(dataRows.length > 2, `Expected wrapped rows, got ${dataRows.length} rows`);
- // All content should be preserved (may be split across lines)
const allText = plainLines.join(" ");
assert.ok(allText.includes("very long"), "Should preserve 'very long'");
assert.ok(allText.includes("cell content"), "Should preserve 'cell content'");
@@ -326,7 +305,6 @@ describe("Markdown component", () => {
});
it("should wrap long unbroken tokens inside table cells (not only at line start)", () => {
- // Pin to no-hyperlinks so width checks work on plain text without OSC 8 sequences.
setCapabilities({ images: null, trueColor: false, hyperlinks: false });
const url = "https://example.com/this/is/a/very/long/url/that/should/wrap";
const markdown = new Markdown(
@@ -347,7 +325,6 @@ describe("Markdown component", () => {
assert.ok(line.length <= width, `Line exceeds width ${width}: "${line}" (length: ${line.length})`);
}
- // Borders should stay intact (exactly 2 vertical borders for a 1-col table)
const tableLines = plainLines.filter((line) => line.startsWith("│"));
assert.ok(tableLines.length > 0, "Expected table rows to render");
for (const line of tableLines) {
@@ -355,8 +332,6 @@ describe("Markdown component", () => {
assert.strictEqual(borderCount, 2, `Expected 2 borders, got ${borderCount}: "${line}"`);
}
- // Strip box drawing characters + whitespace so we can assert the URL is preserved
- // even if it was split across multiple wrapped lines.
const extracted = plainLines.join("").replace(/[│├┤─\s]/g, "");
assert.ok(extracted.includes("prefix"), "Should preserve 'prefix'");
assert.ok(extracted.includes(url), "Should preserve URL");
@@ -431,14 +406,11 @@ describe("Markdown component", () => {
defaultMarkdownTheme,
);
- // Very narrow width
const lines = markdown.render(15);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // Should not crash and should produce output
assert.ok(lines.length > 0, "Should produce output");
- // Lines should not exceed width
for (const line of plainLines) {
assert.ok(line.length <= 15, `Line exceeds width 15: "${line}" (length: ${line.length})`);
}
@@ -454,11 +426,9 @@ describe("Markdown component", () => {
defaultMarkdownTheme,
);
- // Wide width where table fits naturally
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // Should have proper table structure
const headerLine = plainLines.find((line) => line.includes("A") && line.includes("B"));
assert.ok(headerLine, "Should have header row");
assert.ok(headerLine?.includes("│"), "Header should have borders");
@@ -480,16 +450,13 @@ describe("Markdown component", () => {
defaultMarkdownTheme,
);
- // Width 40 with paddingX=2 means contentWidth=36
const lines = markdown.render(40);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // All lines should respect width
for (const line of plainLines) {
assert.ok(line.length <= 40, `Line exceeds width 40: "${line}" (length: ${line.length})`);
}
- // Table rows should have left padding
const tableRow = plainLines.find((line) => line.includes("│"));
assert.ok(tableRow?.startsWith(" "), "Table should have left padding");
});
@@ -535,12 +502,9 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Check heading
assert.ok(plainLines.some((line) => line.includes("Test Document")));
- // Check list
assert.ok(plainLines.some((line) => line.includes("- Item 1")));
assert.ok(plainLines.some((line) => line.includes(" - Nested item")));
- // Check table
assert.ok(plainLines.some((line) => line.includes("Col1")));
assert.ok(plainLines.some((line) => line.includes("│")));
});
@@ -548,7 +512,6 @@ describe("Markdown component", () => {
describe("Pre-styled text (thinking traces)", () => {
it("should preserve gray italic styling after inline code", () => {
- // This replicates how thinking content is rendered in assistant-message.ts
const markdown = new Markdown(
"This is thinking with `inline code` and more text after",
1,
@@ -563,14 +526,11 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const joinedOutput = lines.join("\n");
- // Should contain the inline code block
assert.ok(joinedOutput.includes("inline code"));
- // The output should have ANSI codes for gray (90) and italic (3)
assert.ok(joinedOutput.includes("\x1b[90m"), "Should have gray color code");
assert.ok(joinedOutput.includes("\x1b[3m"), "Should have italic code");
- // Verify that inline code is styled (theme uses yellow)
const hasCodeColor = joinedOutput.includes("\x1b[33m");
assert.ok(hasCodeColor, "Should style inline code");
});
@@ -590,14 +550,11 @@ describe("Markdown component", () => {
const lines = markdown.render(80);
const joinedOutput = lines.join("\n");
- // Should contain bold text
assert.ok(joinedOutput.includes("bold text"));
- // The output should have ANSI codes for gray (90) and italic (3)
assert.ok(joinedOutput.includes("\x1b[90m"), "Should have gray color code");
assert.ok(joinedOutput.includes("\x1b[3m"), "Should have italic code");
- // Should have bold codes (1 or 22 for bold on/off)
assert.ok(joinedOutput.includes("\x1b[1m"), "Should have bold code");
});
@@ -849,7 +806,6 @@ again, hello world`,
describe("Blockquotes with multiline content", () => {
it("should apply consistent styling to all lines in lazy continuation blockquote", () => {
- // Markdown "lazy continuation" - second line without > is still part of the quote
const markdown = new Markdown(
`>Foo
bar`,
@@ -863,22 +819,18 @@ bar`,
const lines = markdown.render(80);
- // Both lines should have the quote border
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const quotedLines = plainLines.filter((line) => line.startsWith("│ "));
assert.strictEqual(quotedLines.length, 2, `Expected 2 quoted lines, got: ${JSON.stringify(plainLines)}`);
- // Both lines should have italic (from theme.quote styling)
const fooLine = lines.find((line) => line.includes("Foo"));
const barLine = lines.find((line) => line.includes("bar"));
assert.ok(fooLine, "Should have Foo line");
assert.ok(barLine, "Should have bar line");
- // Check that both have italic (\x1b[3m) - blockquotes use theme styling, not default message color
assert.ok(fooLine?.includes("\x1b[3m"), `Foo line should have italic: ${fooLine}`);
assert.ok(barLine?.includes("\x1b[3m"), `bar line should have italic: ${barLine}`);
- // Blockquotes should NOT have the default message color (magenta)
assert.ok(!fooLine?.includes("\x1b[35m"), `Foo line should NOT have magenta color: ${fooLine}`);
assert.ok(!barLine?.includes("\x1b[35m"), `bar line should NOT have magenta color: ${barLine}`);
});
@@ -897,18 +849,15 @@ bar`,
const lines = markdown.render(80);
- // Both lines should have the quote border
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const quotedLines = plainLines.filter((line) => line.startsWith("│ "));
assert.strictEqual(quotedLines.length, 2, `Expected 2 quoted lines, got: ${JSON.stringify(plainLines)}`);
- // Both lines should have italic (from theme.quote styling)
const fooLine = lines.find((line) => line.includes("Foo"));
const barLine = lines.find((line) => line.includes("bar"));
assert.ok(fooLine?.includes("\x1b[3m"), `Foo line should have italic: ${fooLine}`);
assert.ok(barLine?.includes("\x1b[3m"), `bar line should have italic: ${barLine}`);
- // Blockquotes should NOT have the default message color (cyan)
assert.ok(!fooLine?.includes("\x1b[36m"), `Foo line should NOT have cyan color: ${fooLine}`);
assert.ok(!barLine?.includes("\x1b[36m"), `bar line should NOT have cyan color: ${barLine}`);
});
@@ -940,22 +889,17 @@ bar`,
const longText = "This is a very long blockquote line that should wrap to multiple lines when rendered";
const markdown = new Markdown(`> ${longText}`, 0, 0, defaultMarkdownTheme);
- // Render at narrow width to force wrapping
const lines = markdown.render(30);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // Filter to non-empty lines (exclude trailing blank line after blockquote)
const contentLines = plainLines.filter((line) => line.length > 0);
- // Should have multiple lines due to wrapping
assert.ok(contentLines.length > 1, `Expected multiple wrapped lines, got: ${JSON.stringify(contentLines)}`);
- // Every content line should start with the quote border
for (const line of contentLines) {
assert.ok(line.startsWith("│ "), `Wrapped line should have quote border: "${line}"`);
}
- // All content should be preserved
const allText = contentLines.join(" ");
assert.ok(allText.includes("very long"), "Should preserve 'very long'");
assert.ok(allText.includes("blockquote"), "Should preserve 'blockquote'");
@@ -977,19 +921,15 @@ bar`,
const lines = markdown.render(25);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
- // Filter to non-empty lines
const contentLines = plainLines.filter((line) => line.length > 0);
- // All lines should have the quote border
for (const line of contentLines) {
assert.ok(line.startsWith("│ "), `Line should have quote border: "${line}"`);
}
- // Check that italic is applied (from theme.quote)
const allOutput = lines.join("\n");
assert.ok(allOutput.includes("\x1b[3m"), "Should have italic");
- // Blockquotes should NOT have the default message color (yellow)
assert.ok(!allOutput.includes("\x1b[33m"), "Should NOT have yellow color from default style");
});
@@ -999,13 +939,11 @@ bar`,
const lines = markdown.render(80);
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
- // Should have the quote border
assert.ok(
plainLines.some((line) => line.startsWith("│ ")),
"Should have quote border",
);
- // Content should be preserved
const allPlain = plainLines.join(" ");
assert.ok(allPlain.includes("Quote with"), "Should preserve 'Quote with'");
assert.ok(allPlain.includes("bold"), "Should preserve 'bold'");
@@ -1013,13 +951,10 @@ bar`,
const allOutput = lines.join("\n");
- // Should have bold styling (\x1b[1m)
assert.ok(allOutput.includes("\x1b[1m"), "Should have bold styling");
- // Should have code styling (yellow = \x1b[33m from defaultMarkdownTheme)
assert.ok(allOutput.includes("\x1b[33m"), "Should have code styling (yellow)");
- // Should have italic from quote styling (\x1b[3m)
assert.ok(allOutput.includes("\x1b[3m"), "Should have italic from quote styling");
});
});
@@ -1031,18 +966,11 @@ bar`,
const lines = markdown.render(80);
const joinedOutput = lines.join("\n");
- // The heading theme is bold+cyan. After the yellow inline code, the heading
- // styling (bold+cyan) must be restored so subsequent text is styled correctly.
- // bold = \x1b[1m, cyan = \x1b[36m, yellow = \x1b[33m
assert.ok(joinedOutput.includes("\x1b[33m"), "Should have yellow for inline code");
- // Find the position of "should not be optional" in the raw output.
- // It must be preceded by heading style codes (bold+cyan), not appear unstyled.
const afterCodeIndex = joinedOutput.indexOf("should not be optional");
assert.ok(afterCodeIndex > 0, "Should contain text after inline code");
- // Look at the ANSI codes between the code span end and "should not be optional".
- // There should be bold (\x1b[1m) and cyan (\x1b[36m) re-applied.
const precedingChunk = joinedOutput.slice(Math.max(0, afterCodeIndex - 40), afterCodeIndex);
assert.ok(
precedingChunk.includes("\x1b[1m"),
@@ -1064,7 +992,6 @@ bar`,
assert.ok(afterCodeIndex > 0, "Should contain text after inline code");
const precedingChunk = joinedOutput.slice(Math.max(0, afterCodeIndex - 40), afterCodeIndex);
- // H1 uses heading + bold + underline
assert.ok(precedingChunk.includes("\x1b[1m"), `Should re-apply bold for h1: ${precedingChunk}`);
assert.ok(precedingChunk.includes("\x1b[36m"), `Should re-apply cyan for h1: ${precedingChunk}`);
assert.ok(precedingChunk.includes("\x1b[4m"), `Should re-apply underline for h1: ${precedingChunk}`);
@@ -1136,7 +1063,6 @@ bar`,
});
it("should not duplicate URL for autolinked emails", () => {
- // Hyperlinks capability does not affect the mailto: display check.
setCapabilities({ images: null, trueColor: false, hyperlinks: false });
const markdown = new Markdown("Contact [email protected] for help", 0, 0, defaultMarkdownTheme);
@@ -1144,7 +1070,6 @@ bar`,
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const joinedPlain = plainLines.join(" ");
- // Should contain the email once, not duplicated with mailto:
assert.ok(joinedPlain.includes("[email protected]"), "Should contain email");
assert.ok(!joinedPlain.includes("mailto:"), "Should not show mailto: prefix for autolinked emails");
});
@@ -1157,7 +1082,6 @@ bar`,
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const joinedPlain = plainLines.join(" ");
- // URL should appear only once
const urlCount = (joinedPlain.match(/https:\/\/example\.com/g) || []).length;
assert.strictEqual(urlCount, 1, "URL should appear exactly once");
});
@@ -1193,14 +1117,10 @@ bar`,
const lines = markdown.render(80);
const joined = lines.join("");
- // OSC 8 open: ESC ] 8 ; ; <url> ESC \
assert.ok(joined.includes("\x1b]8;;https://example.com\x1b\\"), "Should contain OSC 8 open sequence");
- // OSC 8 close: ESC ] 8 ; ; ESC \
assert.ok(joined.includes("\x1b]8;;\x1b\\"), "Should contain OSC 8 close sequence");
- // Visible text is present
const plainLines = lines.map((line) => line.replace(/\x1b[^a-zA-Z]*[a-zA-Z]|\x1b\].*?\x1b\\/g, ""));
assert.ok(plainLines.join("").includes("click here"), "Should contain link text");
- // URL is NOT printed inline as plain text
const rawPlain = lines.map((line) =>
line.replace(/\x1b\]8;;[^\x1b]*\x1b\\/g, "").replace(/\x1b\[[0-9;]*m/g, ""),
);
@@ -1229,7 +1149,6 @@ bar`,
const joined = lines.join("");
assert.ok(joined.includes("\x1b]8;;https://example.com\x1b\\"), "Should contain OSC 8 hyperlink");
- // URL should not also appear as raw parenthetical text
const rawPlain = lines.map((line) =>
line.replace(/\x1b\]8;;[^\x1b]*\x1b\\/g, "").replace(/\x1b\[[0-9;]*m/g, ""),
);
@@ -1239,8 +1158,6 @@ bar`,
describe("HTML-like tags in text", () => {
it("should render content with HTML-like tags as text", () => {
- // When the model emits something like <thinking>content</thinking> in regular text,
- // marked might treat it as HTML and hide the content
const markdown = new Markdown(
"This is text with <thinking>hidden content</thinking> that should be visible",
0,
@@ -1252,7 +1169,6 @@ bar`,
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const joinedPlain = plainLines.join(" ");
- // The content inside the tags should be visible
assert.ok(
joinedPlain.includes("hidden content") || joinedPlain.includes("<thinking>"),
"Should render HTML-like tags or their content as text, not hide them",
@@ -1266,7 +1182,6 @@ bar`,
const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
const joinedPlain = plainLines.join("\n");
- // HTML in code blocks should be visible
assert.ok(
joinedPlain.includes("<div>") && joinedPlain.includes("</div>"),
"Should render HTML in code blocks",
@@ -1275,9 +1190,6 @@ bar`,
});
describe("Streaming identity", () => {
- // Incremental setText (as during token streaming) must render byte-identical
- // to a fresh component constructed with the same final text. Guards the
- // per-block render cache against stale or mis-keyed entries.
const assertStreamingIdentity = (corpus: string, chunkSize: number, width: number) => {
const streaming = new Markdown("", 1, 1, defaultMarkdownTheme);
let text = "";
diff --git a/packages/tui/test/mouse.test.ts b/packages/tui/test/mouse.test.ts
index 73dfa5950f..29f3a344ca 100644
--- a/packages/tui/test/mouse.test.ts
+++ b/packages/tui/test/mouse.test.ts
@@ -25,7 +25,6 @@ describe("parseSgrMouseEvent", () => {
});
it("strips modifier bits into flags", () => {
- // 64 + shift(4) + ctrl(16) = 84
const event = parseSgrMouseEvent("\x1b[<84;3;7M");
assert.strictEqual(event!.button, 64);
assert.strictEqual(event!.shift, true);
diff --git a/packages/tui/test/overlay-navigation-bench.ts b/packages/tui/test/overlay-navigation-bench.ts
index c36053aa05..b65caac3b4 100644
--- a/packages/tui/test/overlay-navigation-bench.ts
+++ b/packages/tui/test/overlay-navigation-bench.ts
@@ -1,8 +1,3 @@
-/**
- * Benchmark focused full-pane overlay navigation. Run with:
- *
- * npx tsx test/overlay-navigation-bench.ts
- */
import { performance } from "node:perf_hooks";
import type { Terminal, TerminalStopOptions } from "../src/terminal.js";
import { type Component, type Focusable, TUI } from "../src/tui.js";
diff --git a/packages/tui/test/overlay-non-capturing.test.ts b/packages/tui/test/overlay-non-capturing.test.ts
index c388814cbc..29bf0bb193 100644
--- a/packages/tui/test/overlay-non-capturing.test.ts
+++ b/packages/tui/test/overlay-non-capturing.test.ts
@@ -225,8 +225,6 @@ describe("TUI overlay non-capturing", () => {
tui.setFocus(editor);
tui.start();
try {
- // Simulate showExtensionCustom: factory creates timer synchronously,
- // then .then() pushes controller as a microtask
let timerHandle: ReturnType<typeof tui.showOverlay>;
let doneFn: () => void;
@@ -236,24 +234,19 @@ describe("TUI overlay non-capturing", () => {
tui.hideOverlay();
resolve();
};
- // Factory runs synchronously: creates timer sub-overlay
timerHandle = tui.showOverlay(timer, { nonCapturing: true });
- // .then() runs as microtask — same as showExtensionCustom
Promise.resolve(controller).then((c) => {
tui.showOverlay(c);
});
});
- // Wait for .then() microtask and renders to settle
await new Promise<void>((r) => setTimeout(r, 50));
await renderAndFlush(tui, terminal);
assert.strictEqual(controller.focused, true);
assert.strictEqual(editor.focused, false);
- // Simulate Esc: cleanup + close (from inside handleInput)
doneFn!();
- // Now await the promise (simulating showExtensionCustom resolving)
await overlayPromise;
await renderAndFlush(tui, terminal);
diff --git a/packages/tui/test/overlay-options.test.ts b/packages/tui/test/overlay-options.test.ts
index 1199780f08..37e1c4c2fc 100644
--- a/packages/tui/test/overlay-options.test.ts
+++ b/packages/tui/test/overlay-options.test.ts
@@ -11,7 +11,6 @@ class StaticOverlay implements Component {
) {}
render(width: number): string[] {
- // Store the width we were asked to render at for verification
this.requestedWidth = width;
return this.lines;
}
@@ -37,7 +36,6 @@ describe("TUI overlay options", () => {
it("should truncate overlay lines that exceed declared width", async () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Overlay declares width 20 but renders lines much wider
const overlay = new StaticOverlay(["X".repeat(100)]);
tui.addChild(new EmptyContent());
@@ -45,11 +43,8 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash, and no line should exceed terminal width
const viewport = terminal.getViewport();
for (const line of viewport) {
- // visibleWidth not available here, but line length is a rough check
- // The important thing is it didn't crash
assert.ok(line !== undefined);
}
tui.stop();
@@ -58,7 +53,6 @@ describe("TUI overlay options", () => {
it("should handle overlay with complex ANSI sequences without crashing", async () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Simulate complex ANSI content like the crash log showed
const complexLine =
"\x1b[48;2;40;50;40m \x1b[38;2;128;128;128mSome styled content\x1b[39m\x1b[49m" +
"\x1b]8;;http://example.com\x07link\x1b]8;;\x07" +
@@ -70,7 +64,6 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash
const viewport = terminal.getViewport();
assert.ok(viewport.length > 0);
tui.stop();
@@ -80,7 +73,6 @@ describe("TUI overlay options", () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Base content with styling
class StyledContent implements Component {
render(width: number): string[] {
const styledLine = `\x1b[1m\x1b[38;2;255;0;0m${"X".repeat(width)}\x1b[0m`;
@@ -96,7 +88,6 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash and overlay should be visible
const viewport = terminal.getViewport();
const hasOverlay = viewport.some((line) => line?.includes("OVERLAY"));
assert.ok(hasOverlay, "Overlay should be visible");
@@ -106,7 +97,6 @@ describe("TUI overlay options", () => {
it("should handle wide characters at overlay boundary", async () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Wide chars (each takes 2 columns) at the edge of declared width
const wideCharLine = "中文日本語한글テスト漢字"; // Mix of CJK chars
const overlay = new StaticOverlay([wideCharLine]);
@@ -115,7 +105,6 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash
const viewport = terminal.getViewport();
assert.ok(viewport.length > 0);
tui.stop();
@@ -124,16 +113,13 @@ describe("TUI overlay options", () => {
it("should handle overlay positioned at terminal edge", async () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Overlay positioned at right edge with content that exceeds declared width
const overlay = new StaticOverlay(["X".repeat(50)]);
tui.addChild(new EmptyContent());
- // Position at col 60 with width 20 - should fit exactly at right edge
tui.showOverlay(overlay, { col: 60, width: 20 });
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash
const viewport = terminal.getViewport();
assert.ok(viewport.length > 0);
tui.stop();
@@ -143,7 +129,6 @@ describe("TUI overlay options", () => {
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Base content with OSC 8 hyperlinks (like file paths in agent output)
class HyperlinkContent implements Component {
render(width: number): string[] {
const link = `\x1b]8;;file:///path/to/file.ts\x07file.ts\x1b]8;;\x07`;
@@ -160,7 +145,6 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Should not crash - this was the original bug scenario
const viewport = terminal.getViewport();
assert.ok(viewport.length > 0);
tui.stop();
@@ -271,7 +255,6 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Should be on last row, ending at last column
const lastRow = viewport[23];
assert.ok(lastRow?.includes("BTM-RIGHT"), `Expected BTM-RIGHT on last row, got: ${lastRow}`);
assert.ok(lastRow?.trimEnd().endsWith("BTM-RIGHT"), `Expected BTM-RIGHT at end, got: ${lastRow}`);
@@ -289,10 +272,8 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Should be on first row, centered horizontally
const firstRow = viewport[0];
assert.ok(firstRow?.includes("CENTERED"), `Expected CENTERED on first row, got: ${firstRow}`);
- // Check it's roughly centered (col 35 for width 10 in 80 col terminal)
const colIndex = firstRow?.indexOf("CENTERED") ?? -1;
assert.ok(colIndex >= 30 && colIndex <= 40, `Expected centered, got col ${colIndex}`);
tui.stop();
@@ -306,7 +287,6 @@ describe("TUI overlay options", () => {
const overlay = new StaticOverlay(["NEG-MARGIN"]);
tui.addChild(new EmptyContent());
- // Negative margins should be treated as 0
tui.showOverlay(overlay, {
anchor: "top-left",
width: 12,
@@ -316,7 +296,6 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Should be at row 0, col 0 (negative margins clamped to 0)
assert.ok(viewport[0]?.startsWith("NEG-MARGIN"), `Expected NEG-MARGIN at start of row 0, got: ${viewport[0]}`);
tui.stop();
});
@@ -332,11 +311,9 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Should be on row 5 (not 0) due to margin
assert.ok(!viewport[0]?.includes("MARGIN"), "Should not be on row 0");
assert.ok(!viewport[4]?.includes("MARGIN"), "Should not be on row 4");
assert.ok(viewport[5]?.includes("MARGIN"), `Expected MARGIN on row 5, got: ${viewport[5]}`);
- // Should start at col 5 (not 0)
const colIndex = viewport[5]?.indexOf("MARGIN") ?? -1;
assert.strictEqual(colIndex, 5, `Expected col 5, got ${colIndex}`);
tui.stop();
@@ -390,13 +367,11 @@ describe("TUI overlay options", () => {
const overlay = new StaticOverlay(["PCT"]);
tui.addChild(new EmptyContent());
- // 50% should center both ways
tui.showOverlay(overlay, { width: 10, row: "50%", col: "50%" });
tui.start();
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Find the row with PCT
let foundRow = -1;
for (let i = 0; i < viewport.length; i++) {
if (viewport[i]?.includes("PCT")) {
@@ -404,7 +379,6 @@ describe("TUI overlay options", () => {
break;
}
}
- // Should be roughly centered vertically (row ~11-12 for 24 row terminal)
assert.ok(foundRow >= 10 && foundRow <= 13, `Expected centered row, got ${foundRow}`);
tui.stop();
});
@@ -464,7 +438,6 @@ describe("TUI overlay options", () => {
it("should truncate overlay to maxHeightPercent", async () => {
const terminal = new VirtualTerminal(80, 10);
const tui = new TUI(terminal);
- // 10 lines in a 10 row terminal with 50% maxHeight should show 5 lines
const overlay = new StaticOverlay(["L1", "L2", "L3", "L4", "L5", "L6", "L7", "L8", "L9", "L10"]);
tui.addChild(new EmptyContent());
@@ -488,7 +461,6 @@ describe("TUI overlay options", () => {
const overlay = new StaticOverlay(["ABSOLUTE"]);
tui.addChild(new EmptyContent());
- // Even with bottom-right anchor, row/col should win
tui.showOverlay(overlay, { anchor: "bottom-right", row: 3, col: 5, width: 10 });
tui.start();
await renderAndFlush(tui, terminal);
@@ -609,11 +581,9 @@ describe("TUI overlay options", () => {
tui.addChild(new EmptyContent());
- // First overlay at top-left
const overlay1 = new StaticOverlay(["FIRST-OVERLAY"]);
tui.showOverlay(overlay1, { anchor: "top-left", width: 20 });
- // Second overlay at top-left (should cover part of first)
const overlay2 = new StaticOverlay(["SECOND"]);
tui.showOverlay(overlay2, { anchor: "top-left", width: 10 });
@@ -621,10 +591,7 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Second overlay should be visible (on top)
assert.ok(viewport[0]?.includes("SECOND"), `Expected SECOND on row 0, got: ${viewport[0]}`);
- // Part of first overlay might still be visible after SECOND
- // FIRST-OVERLAY is 13 chars, SECOND is 6 chars, so "OVERLAY" part might show
tui.stop();
});
@@ -634,11 +601,9 @@ describe("TUI overlay options", () => {
tui.addChild(new EmptyContent());
- // Overlay at top-left
const overlay1 = new StaticOverlay(["TOP-LEFT"]);
tui.showOverlay(overlay1, { anchor: "top-left", width: 15 });
- // Overlay at bottom-right
const overlay2 = new StaticOverlay(["BTM-RIGHT"]);
tui.showOverlay(overlay2, { anchor: "bottom-right", width: 15 });
@@ -646,7 +611,6 @@ describe("TUI overlay options", () => {
await renderAndFlush(tui, terminal);
const viewport = terminal.getViewport();
- // Both should be visible
assert.ok(viewport[0]?.includes("TOP-LEFT"), `Expected TOP-LEFT on row 0, got: ${viewport[0]}`);
assert.ok(viewport[23]?.includes("BTM-RIGHT"), `Expected BTM-RIGHT on row 23, got: ${viewport[23]}`);
tui.stop();
@@ -658,7 +622,6 @@ describe("TUI overlay options", () => {
tui.addChild(new EmptyContent());
- // Show two overlays
const overlay1 = new StaticOverlay(["FIRST"]);
tui.showOverlay(overlay1, { anchor: "top-left", width: 10 });
@@ -668,15 +631,12 @@ describe("TUI overlay options", () => {
tui.start();
await renderAndFlush(tui, terminal);
- // Second should be visible
let viewport = terminal.getViewport();
assert.ok(viewport[0]?.includes("SECOND"), "SECOND should be visible initially");
- // Hide top overlay
tui.hideOverlay();
await renderAndFlush(tui, terminal);
- // First should now be visible
viewport = terminal.getViewport();
assert.ok(viewport[0]?.includes("FIRST"), "FIRST should be visible after hiding SECOND");
diff --git a/packages/tui/test/overlay-short-content.test.ts b/packages/tui/test/overlay-short-content.test.ts
index 98c370297b..f167b5249a 100644
--- a/packages/tui/test/overlay-short-content.test.ts
+++ b/packages/tui/test/overlay-short-content.test.ts
@@ -20,18 +20,14 @@ class SimpleOverlay implements Component {
describe("TUI overlay with short content", () => {
it("should render overlay when content is shorter than terminal height", async () => {
- // Terminal has 24 rows, but content only has 3 lines
const terminal = new VirtualTerminal(80, 24);
const tui = new TUI(terminal);
- // Only 3 lines of content
tui.addChild(new SimpleContent(["Line 1", "Line 2", "Line 3"]));
- // Show overlay centered - should be around row 10 in a 24-row terminal
const overlay = new SimpleOverlay();
tui.showOverlay(overlay);
- // Trigger render
tui.start();
await terminal.waitForRender();
diff --git a/packages/tui/test/regression-regional-indicator-width.test.ts b/packages/tui/test/regression-regional-indicator-width.test.ts
index 675ce97fa4..ec7f577805 100644
--- a/packages/tui/test/regression-regional-indicator-width.test.ts
+++ b/packages/tui/test/regression-regional-indicator-width.test.ts
@@ -4,10 +4,6 @@ import { visibleWidth, wrapTextWithAnsi } from "../src/utils.js";
describe("regional indicator width regression", () => {
it("treats partial flag grapheme as full-width to avoid streaming render drift", () => {
- // Repro context:
- // During streaming, "🇨🇳" often appears as an intermediate "🇨" first.
- // If "🇨" is measured as width 1 while terminal renders it as width 2,
- // differential rendering can drift and leave stale characters on screen.
const partialFlag = "🇨";
const listLine = " - 🇨";
@@ -16,8 +12,6 @@ describe("regional indicator width regression", () => {
});
it("wraps intermediate partial-flag list line before overflow", () => {
- // Width 9 cannot fit " - 🇨" if 🇨 is width 2 (8 + 2 = 10).
- // This must wrap to avoid terminal auto-wrap mismatch.
const wrapped = wrapTextWithAnsi(" - 🇨", 9);
assert.strictEqual(wrapped.length, 2);
diff --git a/packages/tui/test/stdin-buffer.test.ts b/packages/tui/test/stdin-buffer.test.ts
index 549b15f2ba..b502f51144 100644
--- a/packages/tui/test/stdin-buffer.test.ts
+++ b/packages/tui/test/stdin-buffer.test.ts
@@ -1,10 +1,3 @@
-/**
- * Tests for StdinBuffer
- *
- * Based on code from OpenTUI (https://github.com/anomalyco/opentui)
- * MIT License - Copyright (c) 2025 opentui
- */
-
import assert from "node:assert";
import { beforeEach, describe, it } from "node:test";
import { StdinBuffer } from "../src/stdin-buffer.js";
@@ -16,19 +9,16 @@ describe("StdinBuffer", () => {
beforeEach(() => {
buffer = new StdinBuffer({ timeout: 10 });
- // Collect emitted sequences
emittedSequences = [];
buffer.on("data", (sequence) => {
emittedSequences.push(sequence);
});
});
- // Helper to process data through the buffer
function processInput(data: string | Buffer): void {
buffer.process(data);
}
- // Helper to wait for async operations
async function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -128,7 +118,6 @@ describe("StdinBuffer", () => {
processInput("\x1b[<35");
assert.deepStrictEqual(emittedSequences, []);
- // Wait for timeout
await wait(15);
assert.deepStrictEqual(emittedSequences, ["\x1b[<35"]);
@@ -163,43 +152,36 @@ describe("StdinBuffer", () => {
describe("Kitty Keyboard Protocol", () => {
it("should handle Kitty CSI u press events", () => {
- // Press 'a' in Kitty protocol
processInput("\x1b[97u");
assert.deepStrictEqual(emittedSequences, ["\x1b[97u"]);
});
it("should handle Kitty CSI u release events", () => {
- // Release 'a' in Kitty protocol
processInput("\x1b[97;1:3u");
assert.deepStrictEqual(emittedSequences, ["\x1b[97;1:3u"]);
});
it("should handle batched Kitty press and release", () => {
- // Press 'a', release 'a' batched together (common over SSH)
processInput("\x1b[97u\x1b[97;1:3u");
assert.deepStrictEqual(emittedSequences, ["\x1b[97u", "\x1b[97;1:3u"]);
});
it("should handle multiple batched Kitty events", () => {
- // Press 'a', release 'a', press 'b', release 'b'
processInput("\x1b[97u\x1b[97;1:3u\x1b[98u\x1b[98;1:3u");
assert.deepStrictEqual(emittedSequences, ["\x1b[97u", "\x1b[97;1:3u", "\x1b[98u", "\x1b[98;1:3u"]);
});
it("should handle Kitty arrow keys with event type", () => {
- // Up arrow press with event type
processInput("\x1b[1;1:1A");
assert.deepStrictEqual(emittedSequences, ["\x1b[1;1:1A"]);
});
it("should handle Kitty functional keys with event type", () => {
- // Delete key release
processInput("\x1b[3;1:3~");
assert.deepStrictEqual(emittedSequences, ["\x1b[3;1:3~"]);
});
it("should handle plain characters mixed with Kitty sequences", () => {
- // Plain 'a' followed by Kitty release
processInput("a\x1b[97;1:3u");
assert.deepStrictEqual(emittedSequences, ["a", "\x1b[97;1:3u"]);
});
@@ -226,7 +208,6 @@ describe("StdinBuffer", () => {
});
it("should handle rapid typing simulation with Kitty protocol", () => {
- // Simulates typing "hi" quickly with releases interleaved
processInput("\x1b[104u\x1b[104;1:3u\x1b[105u\x1b[105;1:3u");
assert.deepStrictEqual(emittedSequences, ["\x1b[104u", "\x1b[104;1:3u", "\x1b[105u", "\x1b[105;1:3u"]);
});
@@ -281,7 +262,6 @@ describe("StdinBuffer", () => {
describe("Edge Cases", () => {
it("should handle empty input", () => {
processInput("");
- // Empty string emits an empty data event
assert.deepStrictEqual(emittedSequences, [""]);
});
@@ -289,7 +269,6 @@ describe("StdinBuffer", () => {
processInput("\x1b");
assert.deepStrictEqual(emittedSequences, []);
- // After timeout, should emit
await wait(15);
assert.deepStrictEqual(emittedSequences, ["\x1b"]);
});
@@ -331,7 +310,6 @@ describe("StdinBuffer", () => {
processInput("\x1b[<35");
assert.deepStrictEqual(emittedSequences, []);
- // Wait for timeout to flush
await wait(15);
assert.deepStrictEqual(emittedSequences, ["\x1b[<35"]);
@@ -355,13 +333,11 @@ describe("StdinBuffer", () => {
beforeEach(() => {
buffer = new StdinBuffer({ timeout: 10 });
- // Collect emitted sequences
emittedSequences = [];
buffer.on("data", (sequence) => {
emittedSequences.push(sequence);
});
- // Collect paste events
emittedPaste = [];
buffer.on("paste", (data) => {
emittedPaste.push(data);
@@ -428,10 +404,8 @@ describe("StdinBuffer", () => {
processInput("\x1b[<35");
buffer.destroy();
- // Wait longer than timeout
await wait(15);
- // Should not have emitted anything
assert.deepStrictEqual(emittedSequences, []);
});
});
diff --git a/packages/tui/test/terminal-image.test.ts b/packages/tui/test/terminal-image.test.ts
index 137deec33e..ca3703c177 100644
--- a/packages/tui/test/terminal-image.test.ts
+++ b/packages/tui/test/terminal-image.test.ts
@@ -1,7 +1,3 @@
-/**
- * Tests for terminal image detection and line handling
- */
-
import assert from "node:assert";
import { describe, it } from "node:test";
import { Image } from "../src/components/image.js";
@@ -53,19 +49,16 @@ function withEnv(overrides: Record<string, string | undefined>, fn: () => void):
describe("isImageLine", () => {
describe("iTerm2 image protocol", () => {
it("should detect iTerm2 image escape sequence at start of line", () => {
- // iTerm2 image escape sequence: ESC ]1337;File=...
const iterm2ImageLine = "\x1b]1337;File=size=100,100;inline=1:base64encodeddata==\x07";
assert.strictEqual(isImageLine(iterm2ImageLine), true);
});
it("should detect iTerm2 image escape sequence with text before it", () => {
- // Simulating a line that has text then image data (bug scenario)
const lineWithTextAndImage = "Some text \x1b]1337;File=size=100,100;inline=1:base64data==\x07 more text";
assert.strictEqual(isImageLine(lineWithTextAndImage), true);
});
it("should detect iTerm2 image escape sequence in middle of long line", () => {
- // Simulate a very long line with image data in the middle
const longLineWithImage =
"Text before image..." + "\x1b]1337;File=inline=1:verylongbase64data==" + "...text after";
assert.strictEqual(isImageLine(longLineWithImage), true);
@@ -84,19 +77,16 @@ describe("isImageLine", () => {
describe("Kitty image protocol", () => {
it("should detect Kitty image escape sequence at start of line", () => {
- // Kitty image escape sequence: ESC _G
const kittyImageLine = "\x1b_Ga=T,f=100,t=f,d=base64data...\x1b\\\x1b_Gm=i=1;\x1b\\";
assert.strictEqual(isImageLine(kittyImageLine), true);
});
it("should detect Kitty image escape sequence with text before it", () => {
- // Bug scenario: text + image data in same line
const lineWithTextAndKittyImage = "Output: \x1b_Ga=T,f=100;data...\x1b\\\x1b_Gm=i=1;\x1b\\";
assert.strictEqual(isImageLine(lineWithTextAndKittyImage), true);
});
it("should detect Kitty image escape sequence with padding", () => {
- // Kitty protocol adds padding to escape sequences
const kittyWithPadding = " \x1b_Ga=T,f=100...\x1b\\\x1b_Gm=i=1;\x1b\\ ";
assert.strictEqual(isImageLine(kittyWithPadding), true);
});
@@ -104,12 +94,9 @@ describe("isImageLine", () => {
describe("Bug regression tests", () => {
it("should detect image sequences in very long lines (304k+ chars)", () => {
- // This simulates the crash scenario: a line with 304,401 chars
- // containing image escape sequences somewhere
const base64Char = "A".repeat(100); // 100 chars of base64-like data
const imageSequence = "\x1b]1337;File=size=800,600;inline=1:";
- // Build a long line with image sequence
const longLine =
"Text prefix " +
imageSequence +
@@ -121,14 +108,11 @@ describe("isImageLine", () => {
});
it("should detect image sequences when terminal doesn't support images", () => {
- // The bug occurred when getImageEscapePrefix() returned null
- // isImageLine should still detect image sequences regardless
const lineWithImage = "Read image file [image/jpeg]\x1b]1337;File=inline=1:base64data==\x07";
assert.strictEqual(isImageLine(lineWithImage), true);
});
it("should detect image sequences with ANSI codes before them", () => {
- // Text might have ANSI styling before image data
const lineWithAnsiAndImage = "\x1b[31mError output \x1b]1337;File=inline=1:image==\x07";
assert.strictEqual(isImageLine(lineWithAnsiAndImage), true);
});
@@ -156,13 +140,11 @@ describe("isImageLine", () => {
});
it("should not detect images in lines with partial iTerm2 sequences", () => {
- // Similar prefix but missing the complete sequence
const partialSequence = "Some text with ]1337;File but missing ESC at start";
assert.strictEqual(isImageLine(partialSequence), false);
});
it("should not detect images in lines with partial Kitty sequences", () => {
- // Similar prefix but missing the complete sequence
const partialSequence = "Some text with _G but missing ESC at start";
assert.strictEqual(isImageLine(partialSequence), false);
});
@@ -189,7 +171,6 @@ describe("isImageLine", () => {
});
it("should not falsely detect image in line with file path containing keywords", () => {
- // File path might contain "1337" or "File" but without escape sequences
const filePathLine = "/path/to/File_1337_backup/image.jpg";
assert.strictEqual(isImageLine(filePathLine), false);
});
diff --git a/packages/tui/test/test-themes.ts b/packages/tui/test/test-themes.ts
index ff68b2bbe5..fd0748a8fb 100644
--- a/packages/tui/test/test-themes.ts
+++ b/packages/tui/test/test-themes.ts
@@ -1,7 +1,3 @@
-/**
- * Default themes for TUI tests using chalk
- */
-
import { Chalk } from "chalk";
import type { EditorTheme, MarkdownTheme, SelectListTheme } from "../src/index.js";
diff --git a/packages/tui/test/truncated-text.test.ts b/packages/tui/test/truncated-text.test.ts
index ac13917930..7cb409008d 100644
--- a/packages/tui/test/truncated-text.test.ts
+++ b/packages/tui/test/truncated-text.test.ts
@@ -4,7 +4,6 @@ import { Chalk } from "chalk";
import { TruncatedText } from "../src/components/truncated-text.js";
import { visibleWidth } from "../src/utils.js";
-// Force full color in CI so ANSI assertions are deterministic
const chalk = new Chalk({ level: 3 });
describe("TruncatedText component", () => {
@@ -12,10 +11,8 @@ describe("TruncatedText component", () => {
const text = new TruncatedText("Hello world", 1, 0);
const lines = text.render(50);
- // Should have exactly one content line (no vertical padding)
assert.strictEqual(lines.length, 1);
- // Line should be exactly 50 visible characters
const visibleLen = visibleWidth(lines[0]);
assert.strictEqual(visibleLen, 50);
});
@@ -24,10 +21,8 @@ describe("TruncatedText component", () => {
const text = new TruncatedText("Hello", 0, 2);
const lines = text.render(40);
- // Should have 2 padding lines + 1 content line + 2 padding lines = 5 total
assert.strictEqual(lines.length, 5);
- // All lines should be exactly 40 characters
for (const line of lines) {
assert.strictEqual(visibleWidth(line), 40);
}
@@ -40,10 +35,8 @@ describe("TruncatedText component", () => {
assert.strictEqual(lines.length, 1);
- // Should be exactly 30 characters
assert.strictEqual(visibleWidth(lines[0]), 30);
- // Should contain ellipsis
const stripped = lines[0].replace(/\x1b\[[0-9;]*m/g, "");
assert.ok(stripped.includes("..."));
});
@@ -55,10 +48,8 @@ describe("TruncatedText component", () => {
assert.strictEqual(lines.length, 1);
- // Should be exactly 40 visible characters (ANSI codes don't count)
assert.strictEqual(visibleWidth(lines[0]), 40);
- // Should preserve the color codes
assert.ok(lines[0].includes("\x1b["));
});
@@ -69,23 +60,18 @@ describe("TruncatedText component", () => {
assert.strictEqual(lines.length, 1);
- // Should be exactly 20 visible characters
assert.strictEqual(visibleWidth(lines[0]), 20);
- // Should contain reset code before ellipsis
assert.ok(lines[0].includes("\x1b[0m..."));
});
it("handles text that fits exactly", () => {
- // With paddingX=1, available width is 30-2=28
- // "Hello world" is 11 chars, fits comfortably
const text = new TruncatedText("Hello world", 1, 0);
const lines = text.render(30);
assert.strictEqual(lines.length, 1);
assert.strictEqual(visibleWidth(lines[0]), 30);
- // Should NOT contain ellipsis
const stripped = lines[0].replace(/\x1b\[[0-9;]*m/g, "");
assert.ok(!stripped.includes("..."));
});
@@ -106,7 +92,6 @@ describe("TruncatedText component", () => {
assert.strictEqual(lines.length, 1);
assert.strictEqual(visibleWidth(lines[0]), 40);
- // Should only contain "First line"
const stripped = lines[0].replace(/\x1b\[[0-9;]*m/g, "").trim();
assert.ok(stripped.includes("First line"));
assert.ok(!stripped.includes("Second line"));
@@ -121,7 +106,6 @@ describe("TruncatedText component", () => {
assert.strictEqual(lines.length, 1);
assert.strictEqual(visibleWidth(lines[0]), 25);
- // Should contain ellipsis and not second line
const stripped = lines[0].replace(/\x1b\[[0-9;]*m/g, "");
assert.ok(stripped.includes("..."));
assert.ok(!stripped.includes("Second line"));
diff --git a/packages/tui/test/tui-render.test.ts b/packages/tui/test/tui-render.test.ts
index 4c2a635d20..72b327762d 100644
--- a/packages/tui/test/tui-render.test.ts
+++ b/packages/tui/test/tui-render.test.ts
@@ -197,11 +197,9 @@ describe("TUI resize handling", () => {
const initialRedraws = tui.fullRedraws;
- // Resize height
terminal.resize(40, 15);
await terminal.waitForRender();
- // Should have triggered a full redraw
assert.ok(tui.fullRedraws > initialRedraws, "Height change should trigger full redraw");
const viewport = terminal.getViewport();
@@ -252,11 +250,9 @@ describe("TUI resize handling", () => {
const initialRedraws = tui.fullRedraws;
- // Resize width
terminal.resize(60, 10);
await terminal.waitForRender();
- // Should have triggered a full redraw
assert.ok(tui.fullRedraws > initialRedraws, "Width change should trigger full redraw");
tui.stop();
@@ -271,25 +267,21 @@ describe("TUI content shrinkage", () => {
const component = new TestComponent();
tui.addChild(component);
- // Start with many lines
component.lines = ["Line 0", "Line 1", "Line 2", "Line 3", "Line 4", "Line 5"];
tui.start();
await terminal.waitForRender();
const initialRedraws = tui.fullRedraws;
- // Shrink to fewer lines
component.lines = ["Line 0", "Line 1"];
tui.requestRender();
await terminal.waitForRender();
- // Should have triggered a full redraw to clear empty rows
assert.ok(tui.fullRedraws > initialRedraws, "Content shrinkage should trigger full redraw");
const viewport = terminal.getViewport();
assert.ok(viewport[0]?.includes("Line 0"), "First line preserved");
assert.ok(viewport[1]?.includes("Line 1"), "Second line preserved");
- // Lines below should be empty (cleared)
assert.strictEqual(viewport[2]?.trim(), "", "Line 2 should be cleared");
assert.strictEqual(viewport[3]?.trim(), "", "Line 3 should be cleared");
@@ -307,7 +299,6 @@ describe("TUI content shrinkage", () => {
tui.start();
await terminal.waitForRender();
- // Shrink to single line
component.lines = ["Only line"];
tui.requestRender();
await terminal.waitForRender();
@@ -330,13 +321,11 @@ describe("TUI content shrinkage", () => {
tui.start();
await terminal.waitForRender();
- // Shrink to empty
component.lines = [];
tui.requestRender();
await terminal.waitForRender();
const viewport = terminal.getViewport();
- // All lines should be empty
assert.strictEqual(viewport[0]?.trim(), "", "Line 0 should be cleared");
assert.strictEqual(viewport[1]?.trim(), "", "Line 1 should be cleared");
@@ -351,24 +340,19 @@ describe("TUI differential rendering", () => {
const component = new TestComponent();
tui.addChild(component);
- // Initial render: 5 identical lines
component.lines = ["Line 0", "Line 1", "Line 2", "Line 3", "Line 4"];
tui.start();
await terminal.waitForRender();
- // Shrink to 3 lines, all identical to before (no content changes in remaining lines)
component.lines = ["Line 0", "Line 1", "Line 2"];
tui.requestRender();
await terminal.waitForRender();
- // cursorRow should be 2 (last line of new content)
- // Verify by doing another render with a change on line 1
component.lines = ["Line 0", "CHANGED", "Line 2"];
tui.requestRender();
await terminal.waitForRender();
const viewport = terminal.getViewport();
- // Line 1 should show "CHANGED", proving cursor tracking was correct
assert.ok(viewport[1]?.includes("CHANGED"), `Expected "CHANGED" on line 1, got: ${viewport[1]}`);
tui.stop();
@@ -380,12 +364,10 @@ describe("TUI differential rendering", () => {
const component = new TestComponent();
tui.addChild(component);
- // Initial render
component.lines = ["Header", "Working...", "Footer"];
tui.start();
await terminal.waitForRender();
- // Simulate spinner animation - only middle line changes
const spinnerFrames = ["|", "/", "-", "\\"];
for (const frame of spinnerFrames) {
component.lines = ["Header", `Working ${frame}`, "Footer"];
@@ -444,7 +426,6 @@ describe("TUI differential rendering", () => {
tui.start();
await terminal.waitForRender();
- // Change only first line
component.lines = ["CHANGED", "Line 1", "Line 2", "Line 3"];
tui.requestRender();
await terminal.waitForRender();
@@ -468,7 +449,6 @@ describe("TUI differential rendering", () => {
tui.start();
await terminal.waitForRender();
- // Change only last line
component.lines = ["Line 0", "Line 1", "Line 2", "CHANGED"];
tui.requestRender();
await terminal.waitForRender();
@@ -492,7 +472,6 @@ describe("TUI differential rendering", () => {
tui.start();
await terminal.waitForRender();
- // Change lines 1 and 3, keep 0, 2, 4 the same
component.lines = ["Line 0", "CHANGED 1", "Line 2", "CHANGED 3", "Line 4"];
tui.requestRender();
await terminal.waitForRender();
@@ -513,7 +492,6 @@ describe("TUI differential rendering", () => {
const component = new TestComponent();
tui.addChild(component);
- // Start with content
component.lines = ["Line 0", "Line 1", "Line 2"];
tui.start();
await terminal.waitForRender();
@@ -521,12 +499,10 @@ describe("TUI differential rendering", () => {
let viewport = terminal.getViewport();
assert.ok(viewport[0]?.includes("Line 0"), "Initial content rendered");
- // Clear to empty
component.lines = [];
tui.requestRender();
await terminal.waitForRender();
- // Add content back - this should work correctly even after empty state
component.lines = ["New Line 0", "New Line 1"];
tui.requestRender();
await terminal.waitForRender();
@@ -648,17 +624,12 @@ describe("TUI differential rendering", () => {
});
describe("TUI viewport-preserving render", () => {
- // Regression: pressing Ctrl+O to expand all tool output changed lines above
- // the viewport, which forced a full redraw that cleared scrollback and
- // replayed the whole transcript from the top. requestRenderPreservingViewport
- // repaints only the visible viewport in place and leaves scrollback alone.
it("repaints in place without clearing scrollback when content above the viewport grows", async () => {
const terminal = new LoggingVirtualTerminal(40, 10);
const tui = new TUI(terminal);
const component = new TestComponent();
tui.addChild(component);
- // More lines than the viewport, so the top scrolls into scrollback.
component.lines = Array.from({ length: 30 }, (_, i) => `Line ${i}`);
tui.start();
await terminal.waitForRender();
@@ -666,8 +637,6 @@ describe("TUI viewport-preserving render", () => {
const initialRedraws = tui.fullRedraws;
- // "Expand" a block near the top: insert lines after Line 2 so the first
- // changed line is far above the viewport.
const expanded = [...component.lines];
expanded.splice(3, 0, "Expanded A", "Expanded B", "Expanded C");
component.lines = expanded;
@@ -679,12 +648,9 @@ describe("TUI viewport-preserving render", () => {
assert.ok(!writes.includes("\x1b[3J"), "Must not clear scrollback");
assert.ok(!writes.includes("\x1b[2J"), "Must not clear the screen");
- // The viewport stays anchored at the latest content (the bottom).
const viewport = terminal.getViewport();
assert.ok(viewport[viewport.length - 1]?.includes("Line 29"), "Latest line stays at the bottom");
- // Scrollback above the viewport is untouched — it still holds the
- // pre-toggle lines rather than being replayed.
const scrollback = terminal.getScrollBuffer();
assert.ok(
scrollback.some((l) => l.includes("Line 0")),
@@ -700,15 +666,11 @@ describe("TUI viewport-preserving render", () => {
const component = new TestComponent();
tui.addChild(component);
- // Tall transcript: viewport anchored at the bottom with history in scrollback.
component.lines = Array.from({ length: 30 }, (_, i) => `Line ${i}`);
tui.start();
await terminal.waitForRender();
terminal.clearWrites();
- // Collapse to a handful of lines that fit on screen (e.g. a rebuild after
- // compaction). Redraw the visible screen, but preserve terminal scrollback
- // so users can still read long prior output.
component.lines = ["Summary A", "Summary B", "Summary C"];
tui.requestRender();
await terminal.waitForRender();
@@ -735,7 +697,6 @@ describe("TUI viewport-preserving render", () => {
await terminal.waitForRender();
terminal.clearWrites();
- // Expand near the top so the repaint takes the viewport-preserving path.
const expanded = [...component.lines];
expanded.splice(6, 0, "Expanded A", "Expanded B", "Expanded C");
component.lines = expanded;
@@ -811,7 +772,6 @@ describe("TUI viewport-preserving render", () => {
tui.start();
await terminal.waitForRender();
- // Collapse (content shrinks) via the preserving path.
component.lines = Array.from({ length: 12 }, (_, i) => `Line ${i}`);
tui.requestRenderPreservingViewport();
await terminal.waitForRender();
@@ -819,8 +779,6 @@ describe("TUI viewport-preserving render", () => {
const redrawsAfterCollapse = tui.fullRedraws;
terminal.clearWrites();
- // A subsequent plain render with unchanged content must not re-trigger a
- // clearOnShrink full redraw.
tui.requestRender();
await terminal.waitForRender();
@@ -833,19 +791,11 @@ describe("TUI viewport-preserving render", () => {
describe("TUI above-viewport changes on a tall transcript", () => {
it("repaints in place instead of clearing scrollback when off-screen content changes", async () => {
- // Reproduces the attach-then-stream flicker: when a transcript is taller
- // than the viewport and content above the visible window changes (e.g. an
- // off-screen tool result resolving while the model streams), the renderer
- // used to replay the whole transcript on every change, flickering and
- // scrolling from the top. It should now repaint only the visible window
- // in place, leaving scrollback and history intact.
const terminal = new LoggingVirtualTerminal(40, 10);
const tui = new TUI(terminal);
const component = new TestComponent();
tui.addChild(component);
- // 30 lines into a 10-row terminal: viewport anchored at the bottom, with
- // lines 0-19 living in scrollback above the visible window.
component.lines = Array.from({ length: 30 }, (_, i) => `Line ${i}`);
tui.start();
await terminal.waitForRender();
@@ -853,8 +803,6 @@ describe("TUI above-viewport changes on a tall transcript", () => {
assert.ok(terminal.getViewport().join("\n").includes("Line 29"), "Latest line visible after initial paint");
terminal.clearWrites();
- // Mutate several lines above the viewport, as off-screen tool results would
- // while the model is streaming.
for (const i of [3, 7, 12]) {
component.lines[i] = `Line ${i} (updated)`;
tui.requestRender();
@@ -873,10 +821,6 @@ describe("TUI above-viewport changes on a tall transcript", () => {
});
it("preserves scrollback when a still-tall transcript shrinks (rebuild/compaction)", async () => {
- // A rebuild or compaction can replace the transcript with fewer lines that
- // still exceed the viewport. It still needs a full screen redraw, but must
- // not delete terminal scrollback because long prior output should remain
- // readable.
const terminal = new LoggingVirtualTerminal(40, 10);
const tui = new TUI(terminal);
const component = new TestComponent();
@@ -887,8 +831,6 @@ describe("TUI above-viewport changes on a tall transcript", () => {
await terminal.waitForRender();
terminal.clearWrites();
- // Replace with a shorter transcript that is still taller than the 10-row
- // viewport (15 lines), as a compaction would.
component.lines = Array.from({ length: 15 }, (_, i) => `Rebuilt ${i}`);
tui.requestRender();
await terminal.waitForRender();
diff --git a/packages/tui/test/viewport-overwrite-repro.ts b/packages/tui/test/viewport-overwrite-repro.ts
index 5a0ac4f9cc..cf84ca3498 100644
--- a/packages/tui/test/viewport-overwrite-repro.ts
+++ b/packages/tui/test/viewport-overwrite-repro.ts
@@ -1,22 +1,3 @@
-/**
- * TUI viewport overwrite repro
- *
- * Place this file at: packages/tui/test/viewport-overwrite-repro.ts
- * Run from repo root: npx tsx packages/tui/test/viewport-overwrite-repro.ts
- *
- * For reliable repro, run in a small terminal (8-12 rows) or a tmux session:
- * tmux new-session -d -s tui-bug -x 80 -y 12
- * tmux send-keys -t tui-bug "npx tsx packages/tui/test/viewport-overwrite-repro.ts" Enter
- * tmux attach -t tui-bug
- *
- * Expected behavior:
- * - PRE-TOOL lines remain visible above tool output.
- * - POST-TOOL lines append after tool output without overwriting earlier content.
- *
- * Actual behavior (bug):
- * - When content exceeds the viewport and new lines arrive after a tool-call pause,
- * some earlier PRE-TOOL lines near the bottom are overwritten by POST-TOOL lines.
- */
import { ProcessTerminal } from "../src/terminal.js";
import { type Component, TUI } from "../src/tui.js";
@@ -72,35 +53,28 @@ async function main(): Promise<void> {
ui.requestRender();
await sleep(300);
- // Phase 1: Stream pre-tool text until viewport is exceeded.
await streamLines(buffer, "PRE-TOOL LINE", preCount, 30, ui);
- // Phase 2: Simulate tool call pause and tool output.
buffer.append(["", "--- TOOL CALL START ---", "(pause...)", ""]);
ui.requestRender();
await sleep(700);
await streamLines(buffer, "TOOL OUT", toolCount, 20, ui);
- // Phase 3: Post-tool streaming. This is where overwrite often appears.
buffer.append(["", "=== POST-TOOL STREAM ==="]);
ui.requestRender();
await sleep(300);
await streamLines(buffer, "POST-TOOL LINE", postCount, 40, ui);
- // Leave the output visible briefly, then restore terminal state.
await sleep(1500);
ui.stop();
}
main().catch((error) => {
- // Ensure terminal is restored if something goes wrong.
try {
const ui = new TUI(new ProcessTerminal());
ui.stop();
- } catch {
- // Ignore restore errors.
- }
+ } catch {}
process.stderr.write(`${String(error)}\n`);
process.exitCode = 1;
});
diff --git a/packages/tui/test/virtual-terminal.ts b/packages/tui/test/virtual-terminal.ts
index 410b7a8e2f..1951511186 100644
--- a/packages/tui/test/virtual-terminal.ts
+++ b/packages/tui/test/virtual-terminal.ts
@@ -2,12 +2,8 @@ import type { Terminal as XtermTerminalType } from "@xterm/headless";
import xterm from "@xterm/headless";
import type { Terminal, TerminalStopOptions } from "../src/terminal.js";
-// Extract Terminal class from the module
const XtermTerminal = xterm.Terminal;
-/**
- * Virtual terminal for testing using xterm.js for accurate terminal emulation
- */
export class VirtualTerminal implements Terminal {
private xterm: XtermTerminalType;
private inputHandler?: (data: string) => void;
@@ -21,11 +17,9 @@ export class VirtualTerminal implements Terminal {
this._columns = columns;
this._rows = rows;
- // Create xterm instance with specified dimensions
this.xterm = new XtermTerminal({
cols: columns,
rows: rows,
- // Disable all interactive features for testing
disableStdin: true,
allowProposedApi: true,
});
@@ -34,16 +28,12 @@ export class VirtualTerminal implements Terminal {
start(onInput: (data: string) => void, onResize: () => void): void {
this.inputHandler = onInput;
this.resizeHandler = onResize;
- // Enable bracketed paste mode for consistency with ProcessTerminal
this.xterm.write("\x1b[?2004h");
}
- async drainInput(_maxMs?: number, _idleMs?: number): Promise<void> {
- // No-op for virtual terminal - no stdin to drain
- }
+ async drainInput(_maxMs?: number, _idleMs?: number): Promise<void> {}
stop(_options?: TerminalStopOptions): void {
- // Disable bracketed paste mode
this.xterm.write("\x1b[?2004l");
this.inputHandler = undefined;
this.resizeHandler = undefined;
@@ -62,19 +52,15 @@ export class VirtualTerminal implements Terminal {
}
get kittyProtocolActive(): boolean {
- // Virtual terminal always reports Kitty protocol as active for testing
return true;
}
moveBy(lines: number): void {
if (lines > 0) {
- // Move down
this.xterm.write(`\x1b[${lines}B`);
} else if (lines < 0) {
- // Move up
this.xterm.write(`\x1b[${-lines}A`);
}
- // lines === 0: no movement
}
hideCursor(): void {
@@ -120,26 +106,17 @@ export class VirtualTerminal implements Terminal {
}
setTitle(title: string): void {
- // OSC 0;title BEL - set terminal window title
this.xterm.write(`\x1b]0;${title}\x07`);
}
setProgress(_active: boolean): void {}
- // Test-specific methods not in Terminal interface
-
- /**
- * Simulate keyboard input
- */
sendInput(data: string): void {
if (this.inputHandler) {
this.inputHandler(data);
}
}
- /**
- * Resize the terminal
- */
resize(columns: number, rows: number): void {
this._columns = columns;
this._rows = rows;
@@ -149,33 +126,21 @@ export class VirtualTerminal implements Terminal {
}
}
- /**
- * Wait for all pending writes to complete. Viewport and scroll buffer will be updated.
- */
async flush(): Promise<void> {
- // Write an empty string to ensure all previous writes are flushed
return new Promise<void>((resolve) => {
this.xterm.write("", () => resolve());
});
}
- /**
- * Flush and get viewport - convenience method for tests
- */
async flushAndGetViewport(): Promise<string[]> {
await this.flush();
return this.getViewport();
}
- /**
- * Get the visible viewport (what's currently on screen)
- * Note: You should use getViewportAfterWrite() for testing after writing data
- */
getViewport(): string[] {
const lines: string[] = [];
const buffer = this.xterm.buffer.active;
- // Get only the visible lines (viewport)
for (let i = 0; i < this.xterm.rows; i++) {
const line = buffer.getLine(buffer.viewportY + i);
if (line) {
@@ -188,14 +153,10 @@ export class VirtualTerminal implements Terminal {
return lines;
}
- /**
- * Get the entire scroll buffer
- */
getScrollBuffer(): string[] {
const lines: string[] = [];
const buffer = this.xterm.buffer.active;
- // Get all lines in the buffer (including scrollback)
for (let i = 0; i < buffer.length; i++) {
const line = buffer.getLine(i);
if (line) {
@@ -208,23 +169,14 @@ export class VirtualTerminal implements Terminal {
return lines;
}
- /**
- * Clear the terminal viewport
- */
clear(): void {
this.xterm.clear();
}
- /**
- * Reset the terminal completely
- */
reset(): void {
this.xterm.reset();
}
- /**
- * Get cursor position
- */
getCursorPosition(): { x: number; y: number } {
const buffer = this.xterm.buffer.active;
return {
@@ -233,12 +185,10 @@ export class VirtualTerminal implements Terminal {
};
}
- /** Which xterm buffer is active: "normal" or "alternate". */
getActiveBufferType(): "normal" | "alternate" {
return this.xterm.buffer.active.type;
}
- /** Wait for TUI's throttled render pipeline to settle. */
async waitForRender(): Promise<void> {
await new Promise<void>((resolve) => process.nextTick(resolve));
await new Promise<void>((resolve) => setTimeout(resolve, 20));
diff --git a/packages/tui/test/wrap-ansi.test.ts b/packages/tui/test/wrap-ansi.test.ts
index 40d87cef62..fa1c1b46d0 100644
--- a/packages/tui/test/wrap-ansi.test.ts
+++ b/packages/tui/test/wrap-ansi.test.ts
@@ -13,10 +13,8 @@ describe("wrapTextWithAnsi", () => {
const wrapped = wrapTextWithAnsi(text, 40);
- // First line should NOT contain underline code - it's just "read this thread"
assert.strictEqual(wrapped[0], "read this thread");
- // Second line should start with underline, have URL content
assert.strictEqual(wrapped[1].startsWith(underlineOn), true);
assert.ok(wrapped[1].includes("https://"));
});
@@ -39,12 +37,9 @@ describe("wrapTextWithAnsi", () => {
const wrapped = wrapTextWithAnsi(text, 30);
- // Middle lines (with underlined content) should end with underline-off, not full reset
- // Line 1 and 2 contain underlined URL parts
for (let i = 1; i < wrapped.length - 1; i++) {
const line = wrapped[i];
if (line.includes(underlineOn)) {
- // Should end with underline off, NOT full reset
assert.strictEqual(line.endsWith(underlineOff), true);
assert.strictEqual(line.endsWith("\x1b[0m"), false);
}
@@ -60,12 +55,10 @@ describe("wrapTextWithAnsi", () => {
const wrapped = wrapTextWithAnsi(text, 15);
- // Each line should have background color
for (const line of wrapped) {
assert.ok(line.includes(bgBlue));
}
- // Middle lines should NOT end with full reset (kills background for padding)
for (let i = 0; i < wrapped.length - 1; i++) {
assert.strictEqual(wrapped[i].endsWith("\x1b[0m"), false);
}
@@ -80,16 +73,13 @@ describe("wrapTextWithAnsi", () => {
const wrapped = wrapTextWithAnsi(text, 20);
- // All lines should have background color 41 (either as \x1b[41m or combined like \x1b[4;41m)
for (const line of wrapped) {
const hasBgColor = line.includes("[41m") || line.includes(";41m") || line.includes("[41;");
assert.ok(hasBgColor);
}
- // Lines with underlined content should use underline-off at end, not full reset
for (let i = 0; i < wrapped.length - 1; i++) {
const line = wrapped[i];
- // If this line has underline on, it should end with underline off (not full reset)
if (
(line.includes("[4m") || line.includes("[4;") || line.includes(";4m")) &&
!line.includes(underlineOff)
@@ -139,12 +129,10 @@ describe("wrapTextWithAnsi", () => {
const wrapped = wrapTextWithAnsi(text, 10);
- // Each continuation line should start with red code
for (let i = 1; i < wrapped.length; i++) {
assert.strictEqual(wrapped[i].startsWith(red), true);
}
- // Middle lines should not end with full reset
for (let i = 0; i < wrapped.length - 1; i++) {
assert.strictEqual(wrapped[i].endsWith("\x1b[0m"), false);
}
@@ -154,17 +142,11 @@ describe("wrapTextWithAnsi", () => {
describe("wrapTextWithAnsi with OSC 8 hyperlinks", () => {
it("re-emits OSC 8 open at the start of continuation lines", () => {
- // A hyperlink whose text is long enough to wrap
const url = "https://example.com";
- // OSC 8 open + text that is 10 visible chars + OSC 8 close
const input = `\x1b]8;;${url}\x1b\\0123456789\x1b]8;;\x1b\\`;
const lines = wrapTextWithAnsi(input, 6);
- // Every line that contains visible text from inside the hyperlink
- // should start with the OSC 8 open sequence (or be preceded by it).
for (const line of lines) {
- // If the line has visible content it must begin with the OSC 8 re-open
- // OR it is the line where the close appeared with no following content.
const stripped = line.replace(/\x1b\]8;;[^\x1b\x07]*\x1b\\/g, "").replace(/\x1b\[[0-9;]*m/g, "");
if (stripped.trim().length > 0) {
assert.ok(
@@ -182,7 +164,6 @@ describe("wrapTextWithAnsi with OSC 8 hyperlinks", () => {
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i];
- // Every non-final line that is inside a hyperlink should end with the close
if (line.includes(`\x1b]8;;${url}\x1b\\`)) {
assert.ok(
line.endsWith("\x1b]8;;\x1b\\"),
@@ -212,8 +193,6 @@ describe("wrapTextWithAnsi with OSC 8 hyperlinks", () => {
const input = `before \x1b]8;;${url}\x1b\\link\x1b]8;;\x1b\\ after`;
const lines = wrapTextWithAnsi(input, 80);
- // With width 80 everything fits on one line; there should be exactly one
- // OSC 8 open and one OSC 8 close.
assert.strictEqual(lines.length, 1);
const openCount = (lines[0].match(/\x1b\]8;;https:[^\x1b]+\x1b\\/g) ?? []).length;
const closeCount = (lines[0].match(/\x1b\]8;;\x1b\\/g) ?? []).length;
diff --git a/scripts/boot-bench.mjs b/scripts/boot-bench.mjs
index 2479a87990..de456de786 100644
--- a/scripts/boot-bench.mjs
+++ b/scripts/boot-bench.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * Kernel boot fan-out benchmark for ENG-4387. Boots N IPython kernels concurrently
+ * Kernel boot fan-out benchmark. Boots N IPython kernels concurrently
* and reports boot success rate, per-kernel latency, peak RSS, and wall time.
*
* node scripts/boot-bench.mjs --mode forkserver --n 100
diff --git a/scripts/pack-prime-agent-release.mjs b/scripts/pack-prime-agent-release.mjs
index 9460443d16..d264025e11 100644
--- a/scripts/pack-prime-agent-release.mjs
+++ b/scripts/pack-prime-agent-release.mjs
@@ -1,8 +1,5 @@
#!/usr/bin/env node
-// TODO: Remove this R2 tarball packer once prime-agent and its internal workspace
-// dependencies are published through a real npm release flow.
-
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
diff --git a/scripts/release.mjs b/scripts/release.mjs
index 73ae06f9dc..a369dcced6 100755
--- a/scripts/release.mjs
+++ b/scripts/release.mjs
@@ -142,10 +142,8 @@ function addUnreleasedSection() {
}
}
-// Main flow
console.log("\n=== Release Script ===\n");
-// 1. Check for uncommitted changes
console.log("Checking for uncommitted changes...");
const status = run("git status --porcelain", { silent: true });
if (status && status.trim()) {
@@ -155,39 +153,32 @@ if (status && status.trim()) {
}
console.log(" Working directory clean\n");
-// 2. Bump or set version
const version = bumpOrSetVersion(RELEASE_TARGET);
console.log(` New version: ${version}\n`);
-// 3. Update changelogs
console.log("Updating CHANGELOG.md files...");
updateChangelogsForRelease(version);
console.log();
-// 4. Commit and tag
console.log("Committing and tagging...");
stageChangedFiles();
run(`git commit -m "Release v${version}"`);
run(`git tag v${version}`);
console.log();
-// 5. Publish
console.log("Publishing to npm...");
run("npm run publish");
console.log();
-// 6. Add new [Unreleased] sections
console.log("Adding [Unreleased] sections for next cycle...");
addUnreleasedSection();
console.log();
-// 7. Commit
console.log("Committing changelog updates...");
stageChangedFiles();
run(`git commit -m "Add [Unreleased] section for next cycle"`);
console.log();
-// 8. Push
console.log("Pushing to remote...");
run("git push origin main");
run(`git push origin v${version}`);
diff --git a/scripts/sync-versions.js b/scripts/sync-versions.js
index 136ed088ad..c850b4c75e 100644
--- a/scripts/sync-versions.js
+++ b/scripts/sync-versions.js
@@ -13,7 +13,6 @@ const packageDirs = readdirSync(packagesDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
-// Read all package.json files and build version map
const packages = {};
const versionMap = {};
@@ -33,7 +32,6 @@ for (const [name, version] of Object.entries(versionMap).sort()) {
console.log(` ${name}: ${version}`);
}
-// Verify all versions are the same (lockstep)
const versions = new Set(Object.values(versionMap));
if (versions.size > 1) {
console.error('\n❌ ERROR: Not all packages have the same version!');
@@ -46,12 +44,10 @@ if (versions.size > 1) {
console.log('\n✅ All packages at same version (lockstep)');
-// Update all inter-package dependencies
let totalUpdates = 0;
for (const [dir, pkg] of Object.entries(packages)) {
let updated = false;
- // Check dependencies
if (pkg.data.dependencies) {
for (const [depName, currentVersion] of Object.entries(pkg.data.dependencies)) {
if (versionMap[depName]) {
@@ -67,7 +63,6 @@ for (const [dir, pkg] of Object.entries(packages)) {
}
}
- // Check devDependencies
if (pkg.data.devDependencies) {
for (const [depName, currentVersion] of Object.entries(pkg.data.devDependencies)) {
if (versionMap[depName]) {
@@ -83,7 +78,6 @@ for (const [dir, pkg] of Object.entries(packages)) {
}
}
- // Write if updated
if (updated) {
writeFileSync(pkg.path, JSON.stringify(pkg.data, null, '\t') + '\n');
}