feat: improve passthrough composer and session recovery (#1411)

This commit is contained in:
Carlos Florêncio
2026-06-17 19:01:42 +01:00
committed by GitHub
parent 1d61727df3
commit d8436dfd8f
36 changed files with 2139 additions and 449 deletions
@@ -41,7 +41,7 @@ import type { useChatPanelState } from "./use-chat-panel-state";
const PLAN_CONTEXT_PATH = "plan:context";
function buildSubmitMessage(
export function buildSubmitMessage(
message: string,
reviewComments: DiffComment[] | undefined,
pendingPRFeedback: import("@/lib/state/slices/comments").PRFeedbackComment[],
@@ -37,6 +37,7 @@ export type ChatInputEditorAreaProps = {
showRequestChangesTooltip: boolean;
hideSessionsDropdown?: boolean;
minimalToolbar?: boolean;
hideAgentControls?: boolean;
hidePlanMode?: boolean;
isAgentBusy: boolean;
onPlanModeChange: (enabled: boolean) => void;
@@ -126,7 +127,8 @@ export function ChatInputEditorArea(p: ChatInputEditorAreaProps) {
p;
const { isSending, onCancel, contextCount, contextPopoverOpen, setContextPopoverOpen } = p;
const { contextFiles, onImplementPlan, onEnhancePrompt, isEnhancingPrompt } = p;
const { isUtilityConfigured, hideSessionsDropdown, minimalToolbar, hidePlanMode } = p;
const { isUtilityConfigured, hideSessionsDropdown, minimalToolbar, hideAgentControls } = p;
const { hidePlanMode } = p;
const { onVoiceTranscript, onVoiceAutoSend } = p;
// Exclude auto-added plan context from the count — it's always present in plan mode
// and shouldn't by itself enable the send button.
@@ -195,6 +197,7 @@ export function ChatInputEditorArea(p: ChatInputEditorAreaProps) {
onVoiceAutoSend={onVoiceAutoSend}
hideSessionsDropdown={hideSessionsDropdown}
minimalToolbar={minimalToolbar}
hideAgentControls={hideAgentControls}
hidePlanMode={hidePlanMode}
/>
</div>
@@ -91,6 +91,7 @@ type ChatInputContainerProps = {
onImplementPlan?: (fresh: boolean) => void;
hideSessionsDropdown?: boolean;
minimalToolbar?: boolean;
hideAgentControls?: boolean;
/** Hide the plan mode toggle button (for ephemeral/quick chat sessions) */
hidePlanMode?: boolean;
};
@@ -304,6 +305,7 @@ function buildEditorAreaProps(
onVoiceAutoSend: extras.onVoiceAutoSend,
hideSessionsDropdown: p.hideSessionsDropdown,
minimalToolbar: p.minimalToolbar,
hideAgentControls: p.hideAgentControls,
hidePlanMode: p.hidePlanMode,
};
}
@@ -78,6 +78,8 @@ export type ChatInputToolbarProps = {
hideSessionsDropdown?: boolean;
/** When true, only render the submit/cancel button — no other controls */
minimalToolbar?: boolean;
/** Hide ACP/session-specific controls while keeping Plan, attachment, and context controls */
hideAgentControls?: boolean;
/** Hide the plan mode toggle button (for ephemeral/quick chat sessions) */
hidePlanMode?: boolean;
};
@@ -376,7 +378,9 @@ function buildCollapsibleItems(props: {
onEnhancePrompt?: () => void;
isEnhancingPrompt: boolean;
isUtilityConfigured: boolean;
hideAgentControls?: boolean;
}): ToolbarItemConfig[] {
if (props.hideAgentControls) return [];
return [
{
id: "mcp",
@@ -456,6 +460,7 @@ function AttachFilesButton({ onClick }: { onClick: () => void }) {
size="sm"
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40"
onClick={onClick}
data-testid="chat-attachments-button"
>
<IconPaperclip className="h-4 w-4" />
</Button>
@@ -513,6 +518,7 @@ const toolbarDefaults = {
contextFiles: [] as ContextFile[],
isEnhancingPrompt: false,
isUtilityConfigured: false,
hideAgentControls: false,
hidePlanMode: false,
};
@@ -571,6 +577,7 @@ export const ChatInputToolbar = memo(function ChatInputToolbar(rawProps: ChatInp
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40 relative"
data-testid="chat-context-button"
>
<IconAt className="h-4 w-4" />
{props.contextCount > 0 && !isCollapsed && (
@@ -551,6 +551,7 @@ function useEditorImperativeHandle(
const { kind, path, label } = node.attrs;
if (kind === "file") mentions.push({ path, name: label, pinned: false });
else if (kind === "prompt") mentions.push({ path, name: label, pinned: false });
else if (kind === "plan") mentions.push({ path, name: label, pinned: false });
}
});
return mentions;
@@ -109,8 +109,8 @@ describe("useSessionContextChange", () => {
});
it("summarizes sessions into prompt text", async () => {
const promptRef = { current: { value: "" } as unknown as HTMLTextAreaElement };
const summarize = vi.fn().mockResolvedValue("summary text");
const promptRef = { current: { value: "stale prompt" } as unknown as HTMLTextAreaElement };
const summarize = vi.fn().mockResolvedValue({ summary: "summary text" });
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const { result } = renderHook(() =>
@@ -136,7 +136,7 @@ describe("useSessionContextChange", () => {
it("handles summarize failures by clearing context and showing toast", async () => {
const promptRef = { current: { value: "" } as unknown as HTMLTextAreaElement };
const summarize = vi.fn().mockResolvedValue(null);
const summarize = vi.fn().mockResolvedValue({ summary: null, error: "connection refused" });
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const { result } = renderHook(() =>
@@ -157,16 +157,16 @@ describe("useSessionContextChange", () => {
expect(setContextValue).toHaveBeenCalledWith("blank");
expect(mockToast).toHaveBeenCalledWith({
title: "Summarize failed",
description:
"Could not generate a summary. Check that the summarize utility agent is configured and enabled in settings.",
description: "connection refused",
variant: "error",
});
expect(setHasPrompt).not.toHaveBeenCalled();
expect(promptRef.current.value).toBe("");
expect(setHasPrompt).toHaveBeenCalledWith(false);
});
it("does not toast when summarize succeeds after prompt ref unmounts", async () => {
const promptRef = { current: null as HTMLTextAreaElement | null };
const summarize = vi.fn().mockResolvedValue("summary text");
const summarize = vi.fn().mockResolvedValue({ summary: "summary text" });
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const { result } = renderHook(() =>
@@ -192,7 +192,7 @@ describe("useSessionContextChange", () => {
it("sanitizes unsafe characters from summarize result before setting prompt", async () => {
const promptRef = { current: { value: "" } as unknown as HTMLTextAreaElement };
const summarize = vi.fn().mockResolvedValue("line1\r\n<unsafe>\nline2");
const summarize = vi.fn().mockResolvedValue({ summary: "line1\r\n<unsafe>\nline2" });
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const { result } = renderHook(() =>
@@ -4,26 +4,18 @@ import { buildStartRequest } from "@/lib/services/session-launch-helpers";
import { toMessageAttachments } from "@/components/task-create-dialog-helpers";
import type { FileAttachment } from "./chat/file-attachment";
import type { AgentProfileOption } from "@/lib/state/slices";
type ToastFn = (opts: {
title: string;
description?: string;
variant?: "error" | "default";
}) => void;
import type { SummarizeSessionResult } from "@/hooks/use-summarize-session";
import { applySummarizeSessionResult, type SummaryToastFn } from "./session-context-summary";
type SessionContextChangeOpts = {
promptRef: RefObject<HTMLTextAreaElement | null>;
initialPrompt: string | null;
summarize: (sessionId: string) => Promise<string | null>;
toast: ToastFn;
summarize: (sessionId: string) => Promise<SummarizeSessionResult>;
toast: SummaryToastFn;
setContextValue: (v: string) => void;
setHasPrompt: (v: boolean) => void;
};
function sanitizePromptText(value: string): string {
return value.replace(/\r/g, "").replace(/[<>]/g, " ");
}
export function useSessionContextChange(opts: SessionContextChangeOpts) {
const { promptRef, initialPrompt, summarize, toast, setContextValue, setHasPrompt } = opts;
return useCallback(
@@ -39,18 +31,7 @@ export function useSessionContextChange(opts: SessionContextChangeOpts) {
} else if (value.startsWith("summarize:")) {
const sessionId = value.slice("summarize:".length);
const result = await summarize(sessionId);
if (result === null) {
setContextValue("blank");
toast({
title: "Summarize failed",
description:
"Could not generate a summary. Check that the summarize utility agent is configured and enabled in settings.",
variant: "error",
});
} else if (promptRef.current) {
promptRef.current.value = sanitizePromptText(result);
setHasPrompt(true);
}
applySummarizeSessionResult({ result, promptRef, setContextValue, setHasPrompt, toast });
}
},
[initialPrompt, promptRef, summarize, setContextValue, setHasPrompt, toast],
@@ -83,7 +64,7 @@ export function useSessionLaunchSubmit({
groupId?: string;
attachments: FileAttachment[];
onClose: () => void;
toast: ToastFn;
toast: SummaryToastFn;
setActiveSession: (taskId: string, sessionId: string) => void;
activateSession: (
sessionId: string,
@@ -17,7 +17,7 @@ import {
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
import { useIsUtilityConfigured } from "@/hooks/use-is-utility-configured";
import { useSummarizeSession } from "@/hooks/use-summarize-session";
import { useSummarizeSession, type SummarizeSessionResult } from "@/hooks/use-summarize-session";
import { useTaskSessions } from "@/hooks/use-task-sessions";
import { getLocalStorage } from "@/lib/local-storage";
import { STORAGE_KEYS } from "@/lib/settings/constants";
@@ -29,6 +29,7 @@ import {
useSubtaskFormState,
} from "./new-subtask-form-state";
import { PromptZone, SubtaskFormBody } from "./new-subtask-form-parts";
import { applySummarizeSessionResult, type SummaryToastFn } from "./session-context-summary";
import { useSubtaskPromptZone, useSubtaskSubmit } from "./use-subtask-submit";
type NewSubtaskDialogProps = {
@@ -166,9 +167,10 @@ function useContextChangeHandler(opts: {
setHasPrompt: (v: boolean) => void;
promptRef: React.RefObject<HTMLTextAreaElement | null>;
initialPrompt: string | null;
summarize: (sessionId: string) => Promise<string | null>;
summarize: (sessionId: string) => Promise<SummarizeSessionResult>;
toast: SummaryToastFn;
}) {
const { setContextValue, setHasPrompt, promptRef, initialPrompt, summarize } = opts;
const { setContextValue, setHasPrompt, promptRef, initialPrompt, summarize, toast } = opts;
return useCallback(
async (value: string) => {
if (!value) return;
@@ -187,13 +189,10 @@ function useContextChangeHandler(opts: {
}
if (value.startsWith("summarize:")) {
const result = await summarize(value.slice("summarize:".length));
if (result && promptRef.current) {
promptRef.current.value = result;
setHasPrompt(true);
}
applySummarizeSessionResult({ result, promptRef, setContextValue, setHasPrompt, toast });
}
},
[setContextValue, setHasPrompt, promptRef, initialPrompt, summarize],
[setContextValue, setHasPrompt, promptRef, initialPrompt, summarize, toast],
);
}
@@ -268,6 +267,7 @@ function NewSubtaskForm({
promptRef: promptZone.promptRef,
initialPrompt,
summarize,
toast,
});
const { handleSubmit } = useSubtaskSubmit({
fs,
@@ -0,0 +1,228 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { DiffComment } from "@/lib/diff/types";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import {
buildContextFilesMeta,
buildPassthroughFinalMessage,
buildPassthroughPlanContext,
clearPassthroughComposerContext,
formatPassthroughBaseMessage,
} from "./passthrough-chat-composer";
const mockGetTaskPlan = vi.hoisted(() => vi.fn());
vi.mock("@/lib/api/domains/plan-api", () => ({
getTaskPlan: mockGetTaskPlan,
}));
const SESSION_ID = "session-1";
const TASK_ID = "task-1";
const PLAN_CONTEXT_PATH = "plan:context";
function file(path: string, name = path): ContextFile {
return { path, name };
}
function comment(id = "comment-1"): DiffComment {
return {
id,
source: "diff",
sessionId: SESSION_ID,
filePath: "src/app.ts",
startLine: 10,
endLine: 11,
side: "additions",
codeContent: "const value = 1;",
text: "Please fix this",
status: "pending",
createdAt: "2026-06-17T00:00:00.000Z",
};
}
function panelState(overrides: Record<string, unknown> = {}) {
return {
resolvedSessionId: SESSION_ID,
taskId: TASK_ID,
contextFiles: [],
prompts: [],
pendingPRFeedback: [],
planComments: [],
planModeEnabled: false,
handleClearPRFeedback: vi.fn(),
clearSessionPlanComments: vi.fn(),
clearEphemeral: vi.fn(),
addContextFile: vi.fn(),
...overrides,
} as never;
}
beforeEach(() => {
mockGetTaskPlan.mockReset();
});
describe("passthrough chat composer metadata helpers", () => {
it("filters virtual prompt and plan context files from context_files metadata", () => {
expect(
buildContextFilesMeta([
file("src/app.ts", "app.ts"),
file("prompt:review", "Review prompt"),
file(PLAN_CONTEXT_PATH, "Plan"),
]),
).toEqual([{ path: "src/app.ts", name: "app.ts" }]);
expect(buildContextFilesMeta([file("prompt:review"), file(PLAN_CONTEXT_PATH)])).toBeUndefined();
});
it("prepends pending review comments when no structured comment payload is supplied", () => {
const result = formatPassthroughBaseMessage("Ship it", undefined, [comment()], panelState());
expect(result.commentsToSend).toHaveLength(1);
expect(result.formatted).toContain("### Review Comments");
expect(result.formatted).toContain("Please fix this");
expect(result.formatted).toContain("Ship it");
});
it("merges selected context files with inline file, prompt, and task mentions", async () => {
const inlineTask: TaskMentionData = {
taskId: "task-2",
title: "Follow-up task",
workflowId: "workflow-1",
workflowStepId: "step-1",
state: "in_progress",
};
const result = await buildPassthroughFinalMessage({
taskId: TASK_ID,
content: "Please check this",
pendingComments: [],
panelState: panelState({
contextFiles: [file("src/existing.ts", "existing.ts")],
prompts: [{ id: "prompt-1", name: "Review", content: "Look carefully." }],
}),
inlineMentions: [file("src/inline.ts", "inline.ts"), file("prompt:prompt-1", "Review")],
inlineTaskMentions: [inlineTask],
getState: () =>
({
kanban: { steps: [{ id: "step-1", title: "Review" }] },
kanbanMulti: { snapshots: {} },
taskPlans: { byTaskId: {} },
}) as never,
});
expect(result.contextFilesMeta).toEqual([
{ path: "src/existing.ts", name: "existing.ts" },
{ path: "src/inline.ts", name: "inline.ts" },
]);
expect(result.content).toContain("CONTEXT FILES");
expect(result.content).toContain("- src/existing.ts");
expect(result.content).toContain("- src/inline.ts");
expect(result.content).toContain("CONTEXT PROMPTS");
expect(result.content).toContain("Look carefully.");
expect(result.content).toContain("REFERENCED TASKS");
expect(result.content).toContain("Follow-up task");
});
});
describe("passthrough chat composer plan context", () => {
it("expands selected plan context and strips the literal @Plan mention", async () => {
const result = await buildPassthroughFinalMessage({
taskId: TASK_ID,
content: "@Plan",
pendingComments: [],
panelState: panelState(),
inlineMentions: [file(PLAN_CONTEXT_PATH, "Plan")],
getState: () =>
({
kanban: { steps: [] },
kanbanMulti: { snapshots: {} },
taskPlans: {
byTaskId: {
[TASK_ID]: { content: "## Plan\n\n1. Ship passthrough fixes" },
},
},
}) as never,
});
expect(result.content).toContain("<kandev-system>");
expect(result.content).toContain("CONTEXT PLAN");
expect(result.content).toContain("## Plan");
expect(result.content).toContain("Ship passthrough fixes");
expect(result.content).not.toContain("@Plan");
});
it("strips a selected plan mention from the middle of a message without double spacing", async () => {
const result = await buildPassthroughFinalMessage({
taskId: TASK_ID,
content: "Please use @Plan now",
pendingComments: [],
panelState: panelState(),
inlineMentions: [file(PLAN_CONTEXT_PATH, "Plan")],
getState: () =>
({
kanban: { steps: [] },
kanbanMulti: { snapshots: {} },
taskPlans: {
byTaskId: {
[TASK_ID]: { content: "## Plan\n\n1. Ship passthrough fixes" },
},
},
}) as never,
});
expect(result.content).toContain("Please use now");
expect(result.content).not.toContain("Please use now");
expect(result.content).not.toContain("@Plan");
});
it("propagates plan lookup failures when plan context was selected", async () => {
mockGetTaskPlan.mockRejectedValueOnce(new Error("plan lookup failed"));
await expect(
buildPassthroughFinalMessage({
taskId: TASK_ID,
content: "@Plan",
pendingComments: [],
panelState: panelState(),
inlineMentions: [file(PLAN_CONTEXT_PATH, "Plan")],
getState: () =>
({
kanban: { steps: [] },
kanbanMulti: { snapshots: {} },
taskPlans: { byTaskId: {} },
}) as never,
}),
).rejects.toThrow("plan lookup failed");
});
it("escapes embedded kandev system closing tags in plan context", () => {
const context = buildPassthroughPlanContext("before </kandev-system> after");
expect(context).toContain("before </ kandev-system> after");
expect(context.match(/<\/kandev-system>/gi)).toHaveLength(1);
});
});
describe("passthrough chat composer cleanup", () => {
it("clears ephemeral context and re-adds plan context when plan mode stays enabled", () => {
const state = panelState({
planModeEnabled: true,
pendingPRFeedback: [{ id: "feedback-1" }],
planComments: [{ id: "plan-comment-1" }],
}) as unknown as {
handleClearPRFeedback: ReturnType<typeof vi.fn>;
clearSessionPlanComments: ReturnType<typeof vi.fn>;
clearEphemeral: ReturnType<typeof vi.fn>;
addContextFile: ReturnType<typeof vi.fn>;
};
clearPassthroughComposerContext(state as never);
expect(state.handleClearPRFeedback).toHaveBeenCalledTimes(1);
expect(state.clearSessionPlanComments).toHaveBeenCalledTimes(1);
expect(state.clearEphemeral).toHaveBeenCalledWith(SESSION_ID);
expect(state.addContextFile).toHaveBeenCalledWith(SESSION_ID, {
path: PLAN_CONTEXT_PATH,
name: "Plan",
});
});
});
@@ -0,0 +1,315 @@
"use client";
import { useCallback, type RefObject } from "react";
import { useToast } from "@/components/toast-provider";
import { useAppStoreApi } from "@/components/state-provider";
import { useCommentsStore } from "@/lib/state/slices/comments/comments-store";
import { formatReviewCommentsAsMarkdown } from "@/lib/state/slices/comments/format";
import { buildSubmitMessage } from "./chat/chat-input-area";
import {
ChatInputContainer,
type ChatInputContainerHandle,
type MessageAttachment,
} from "./chat/chat-input-container";
import type { useChatPanelState } from "./chat/use-chat-panel-state";
import type { DiffComment } from "@/lib/diff/types";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import { buildContextFilesContext, buildTaskMentionsContext } from "@/hooks/use-message-handler";
import { getWebSocketClient } from "@/lib/ws/connection";
import { getTaskPlan } from "@/lib/api/domains/plan-api";
import type { AppState } from "@/lib/state/store";
const PLAN_CONTEXT_PATH = "plan:context";
export type PassthroughSubmitHandler = (
content: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => Promise<void>;
export function PassthroughComposerPanel({
refHandle,
onSubmit,
onCancel,
panelState,
taskId,
isMoving,
isSending,
}: {
refHandle: RefObject<ChatInputContainerHandle | null>;
onSubmit: PassthroughSubmitHandler;
onCancel: () => void;
panelState: ReturnType<typeof useChatPanelState>;
taskId: string | null;
isMoving: boolean;
isSending: boolean;
}) {
const hasContextComments =
panelState.planComments.length > 0 || panelState.pendingPRFeedback.length > 0;
return (
<div
data-testid="passthrough-composer"
onKeyDownCapture={(event) => {
if (event.key === "Escape") onCancel();
}}
>
<ChatInputContainer
ref={refHandle}
onSubmit={onSubmit}
sessionId={panelState.resolvedSessionId}
taskId={taskId}
taskTitle={panelState.task?.title}
taskDescription={panelState.taskDescription ?? ""}
planModeEnabled={panelState.planModeEnabled}
planModeAvailable={panelState.planModeAvailable}
mcpServers={panelState.mcpServers}
onPlanModeChange={panelState.handlePlanModeChange}
isAgentBusy={false}
isStarting={panelState.isStarting}
isPreparingEnvironment={panelState.isPreparingEnvironment}
isMoving={isMoving}
isSending={isSending}
onCancel={onCancel}
placeholder="Type a message, @mention files or prompts, Shift+Enter for newline"
pendingCommentsByFile={panelState.pendingCommentsByFile}
hasContextComments={hasContextComments}
submitKey={panelState.chatSubmitKey}
hasAgentCommands={false}
contextItems={panelState.contextItems}
planContextEnabled={panelState.planContextEnabled}
contextFiles={panelState.contextFiles}
onToggleContextFile={panelState.handleToggleContextFile}
onAddContextFile={panelState.handleAddContextFile}
hideSessionsDropdown
hideAgentControls
/>
</div>
);
}
type PassthroughFinalMessage = {
content: string;
commentsToSend: DiffComment[];
contextFilesMeta?: Array<{ path: string; name: string }>;
};
export function formatPassthroughBaseMessage(
content: string,
reviewComments: DiffComment[] | undefined,
pendingComments: DiffComment[],
panelState: ReturnType<typeof useChatPanelState>,
) {
const commentsToSend = reviewComments ?? pendingComments;
const hasStructuredComments =
!!reviewComments ||
panelState.pendingPRFeedback.length > 0 ||
panelState.planComments.length > 0;
if (hasStructuredComments) {
return {
formatted: buildSubmitMessage(
content,
commentsToSend.length > 0 ? commentsToSend : undefined,
panelState.pendingPRFeedback,
panelState.planComments,
),
commentsToSend,
};
}
if (pendingComments.length > 0) {
return {
formatted: formatReviewCommentsAsMarkdown(pendingComments) + content,
commentsToSend,
};
}
return { formatted: content, commentsToSend };
}
function hasPlanContext(files: ContextFile[]) {
return files.some((file) => file.path === PLAN_CONTEXT_PATH);
}
function stripSelectedPlanMentions(content: string, files: ContextFile[]) {
if (!hasPlanContext(files)) return content;
return content.replace(/\s*@Plan(?=\s|$)/g, "").trim();
}
function sanitizeSystemBlockContent(content: string) {
return content.replace(/<\/kandev-system>/gi, "</ kandev-system>");
}
export function buildPassthroughPlanContext(planContent: string | undefined | null) {
const trimmed = planContent?.trim();
if (!trimmed) return "";
return (
`\n\n<kandev-system>\n` +
`CONTEXT PLAN: The user has attached the current task plan as context. ` +
`Use this plan content to understand what they mean by the plan:\n` +
`${sanitizeSystemBlockContent(trimmed)}\n` +
`</kandev-system>`
);
}
function cachedTaskPlanContent(taskId: string, state: AppState) {
return state.taskPlans.byTaskId[taskId]?.content;
}
async function loadTaskPlanContent(taskId: string | null, getState: () => AppState) {
if (!taskId) return "";
const cached = cachedTaskPlanContent(taskId, getState());
if (cached !== undefined) return cached;
const plan = await getTaskPlan(taskId);
return plan?.content ?? "";
}
export async function buildPassthroughFinalMessage({
taskId,
content,
reviewComments,
pendingComments,
panelState,
inlineMentions,
inlineTaskMentions,
getState,
}: {
taskId: string | null;
content: string;
reviewComments?: DiffComment[];
pendingComments: DiffComment[];
panelState: ReturnType<typeof useChatPanelState>;
inlineMentions?: ContextFile[];
inlineTaskMentions?: TaskMentionData[];
getState: ReturnType<typeof useAppStoreApi>["getState"];
}): Promise<PassthroughFinalMessage> {
const { formatted, commentsToSend } = formatPassthroughBaseMessage(
content,
reviewComments,
pendingComments,
panelState,
);
const allContextFiles = [...panelState.contextFiles, ...(inlineMentions ?? [])];
const visibleContent = stripSelectedPlanMentions(formatted, allContextFiles);
const contextFilesContext = buildContextFilesContext(allContextFiles, panelState.prompts);
const planContext = hasPlanContext(allContextFiles)
? buildPassthroughPlanContext(await loadTaskPlanContent(taskId, getState))
: "";
const taskMentionsContext =
inlineTaskMentions && inlineTaskMentions.length > 0
? buildTaskMentionsContext(inlineTaskMentions, getState())
: "";
return {
content: visibleContent + contextFilesContext + planContext + taskMentionsContext,
commentsToSend,
contextFilesMeta: buildContextFilesMeta(allContextFiles),
};
}
export function buildContextFilesMeta(files: ContextFile[]) {
const realContextFiles = files.filter(
(f) => !f.path.startsWith("prompt:") && f.path !== PLAN_CONTEXT_PATH,
);
if (realContextFiles.length === 0) return undefined;
return realContextFiles.map((f) => ({ path: f.path, name: f.name }));
}
async function requestPassthroughMessage({
taskId,
sessionId,
message,
attachments,
}: {
taskId: string;
sessionId: string;
message: PassthroughFinalMessage;
attachments?: MessageAttachment[];
}) {
const client = getWebSocketClient();
if (!client) throw new Error("WebSocket client not available");
const hasAttachments = !!(attachments && attachments.length > 0);
await client.request(
"message.add",
{
task_id: taskId,
session_id: sessionId,
content: message.content,
...(hasAttachments && { attachments }),
...(message.contextFilesMeta && { context_files: message.contextFilesMeta }),
},
hasAttachments ? 30_000 : 10_000,
);
}
export function clearPassthroughComposerContext(panelState: ReturnType<typeof useChatPanelState>) {
if (panelState.pendingPRFeedback.length > 0) {
panelState.handleClearPRFeedback();
}
if (panelState.planComments.length > 0) {
panelState.clearSessionPlanComments();
}
if (!panelState.resolvedSessionId) return;
panelState.clearEphemeral(panelState.resolvedSessionId);
if (panelState.planModeEnabled) {
panelState.addContextFile(panelState.resolvedSessionId, {
path: "plan:context",
name: "Plan",
});
}
}
export function useSendPassthroughMessage({
taskId,
sessionId,
pendingComments,
panelState,
onSent,
}: {
taskId: string | null;
sessionId: string | null | undefined;
pendingComments: DiffComment[];
panelState: ReturnType<typeof useChatPanelState>;
onSent: () => void;
}) {
const { toast } = useToast();
const markCommentsSent = useCommentsStore((s) => s.markCommentsSent);
const storeApi = useAppStoreApi();
return useCallback(
async (
content: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => {
if (!taskId || !sessionId) {
toast({ title: "Session not ready", variant: "error" });
throw new Error("Session not ready");
}
try {
const message = await buildPassthroughFinalMessage({
taskId,
content,
reviewComments,
pendingComments,
panelState,
inlineMentions,
inlineTaskMentions,
getState: storeApi.getState,
});
await requestPassthroughMessage({ taskId, sessionId, message, attachments });
if (message.commentsToSend.length > 0) {
markCommentsSent(message.commentsToSend.map((c) => c.id));
}
clearPassthroughComposerContext(panelState);
onSent();
} catch (error) {
console.error("Failed to send passthrough message:", error);
toast({ title: "Failed to send message", variant: "error" });
throw error;
}
},
[taskId, sessionId, toast, pendingComments, panelState, storeApi, markCommentsSent, onSent],
);
}
@@ -1,124 +0,0 @@
"use client";
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type KeyboardEvent,
} from "react";
import { IconSend } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Textarea } from "@kandev/ui/textarea";
// Cap matches the `max-h-32` Tailwind class on the textarea below — 128 px.
const COMPOSER_MAX_HEIGHT_PX = 128;
/**
* PassthroughComposer is the kandev-controlled compose box rendered alongside
* the PTY in passthrough mode. Submitting forwards the typed text via the
* onSubmit prop (which posts `message.add` over WS); the backend's
* `Executor.Prompt` routes passthrough sessions to PTY stdin so the CLI agent
* actually receives it. Enter submits; Shift+Enter inserts a newline.
*/
export function PassthroughComposer({
onSubmit,
onCancel,
autoFocus = false,
placeholder = "Message the CLI agent (Enter to send, Shift+Enter for newline)",
header,
}: {
onSubmit: (content: string) => Promise<void>;
onCancel?: () => void;
autoFocus?: boolean;
placeholder?: string;
/** Optional content rendered above the textarea — e.g. a pending-comments preview. */
header?: React.ReactNode;
}) {
const [value, setValue] = useState("");
const [isSending, setIsSending] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const trimmed = value.trim();
const canSubmit = trimmed.length > 0 && !isSending;
// Auto-grow the textarea with content (Shift+Enter newlines, long pastes)
// up to the max-h-32 cap. Done in JS so it works in browsers without
// CSS field-sizing support.
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "auto";
el.style.height = `${Math.min(el.scrollHeight, COMPOSER_MAX_HEIGHT_PX)}px`;
}, [value]);
useEffect(() => {
if (autoFocus) {
textareaRef.current?.focus();
}
}, [autoFocus]);
const submit = useCallback(async () => {
if (!canSubmit) return;
setIsSending(true);
try {
await onSubmit(trimmed);
setValue(""); // only clear on success — preserve text so user can retry on send failure
} catch {
// onSubmit already surfaced the error via toast; the user's typed value
// stays in the textarea intentionally so they can retry without retyping.
} finally {
setIsSending(false);
}
}, [canSubmit, onSubmit, trimmed]);
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
if (e.nativeEvent.isComposing) return;
e.preventDefault();
void submit();
return;
}
if (e.key === "Escape" && onCancel) {
e.preventDefault();
onCancel();
}
},
[submit, onCancel],
);
return (
<div
className="flex flex-col flex-shrink-0 border-t bg-card"
data-testid="passthrough-composer"
>
{header}
<div className="flex items-end gap-2 px-2 py-2">
<Textarea
ref={textareaRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={placeholder}
rows={1}
disabled={isSending}
className="min-h-9 max-h-32 flex-1 resize-none overflow-y-auto"
data-testid="passthrough-composer-textarea"
/>
<Button
type="button"
size="sm"
variant="default"
onClick={() => void submit()}
disabled={!canSubmit}
className="cursor-pointer h-9 shrink-0"
data-testid="passthrough-composer-submit"
aria-label="Send message to CLI agent"
>
<IconSend className="h-4 w-4" />
</Button>
</div>
</div>
);
}
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// --- Constants declared before vi.mock so factories can reference them ---
const TASK_ID = "task-1";
const SESSION_ID = "session-1";
const SRC_FILE = "src/foo.ts";
// data-testid constants to avoid sonarjs/no-duplicate-string warnings
const TID_TOOLBAR = "passthrough-toolbar";
@@ -19,9 +20,14 @@ const TID_COMMENT_REMOVE = "passthrough-comment-remove";
const TID_COMMENT_FILE_REF = "passthrough-comment-file-ref";
const TID_PENDING_COUNT = "passthrough-pending-count";
const TID_PENDING_BANNER = "passthrough-pending-comments-banner";
const TID_PLAN_TOGGLE = "plan-mode-toggle-button";
const TID_ATTACHMENTS = "chat-attachments-button";
const TID_CONTEXT = "chat-context-button";
// --- Mutable state for per-test overrides ---
let mockSessionState: string | null = null;
let mockKeyboardShortcuts: Record<string, { key: string; modifiers?: Record<string, boolean> }> =
{};
let mockPendingByFile: Record<string, import("@/lib/state/slices/comments").DiffComment[]> = {};
let mockNextStep: {
proceedStepName: string | null;
@@ -35,6 +41,11 @@ const mockUpdateComment = vi.fn();
const mockRemoveComment = vi.fn();
const mockOpenFile = vi.fn();
let mockWsRequestFn = vi.fn();
const chatInputMock = vi.hoisted(() => ({
renderProps: vi.fn(),
focusInput: vi.fn(),
getTextareaElement: vi.fn(() => null as HTMLElement | null),
}));
// --- Module mocks (hoisted by Vitest) ---
@@ -46,7 +57,14 @@ vi.mock("@/components/state-provider", () => ({
? { [SESSION_ID]: { id: SESSION_ID, state: mockSessionState } }
: {},
},
userSettings: { keyboardShortcuts: mockKeyboardShortcuts, chatSubmitKey: "enter" },
}),
useAppStoreApi: () => ({
getState: () => ({
kanban: { steps: [] },
kanbanMulti: { snapshots: {} },
}),
}),
}));
vi.mock("@/components/toast-provider", () => ({
@@ -109,6 +127,87 @@ vi.mock("@kandev/ui/tooltip", () => ({
TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("./chat/use-chat-panel-state", () => ({
useChatPanelState: () => ({
resolvedSessionId: SESSION_ID,
taskId: TASK_ID,
task: { id: TASK_ID, title: "Task title" },
taskDescription: "Task description",
planModeEnabled: false,
planModeAvailable: true,
mcpServers: ["kandev"],
handlePlanModeChange: vi.fn(),
isStarting: false,
isPreparingEnvironment: false,
contextItems: [{ id: "file:src/foo.ts", kind: "file", label: "foo.ts", filePath: SRC_FILE }],
contextFiles: [{ path: SRC_FILE, name: "foo.ts" }],
handleToggleContextFile: vi.fn(),
handleAddContextFile: vi.fn(),
addContextFile: vi.fn(),
clearEphemeral: vi.fn(),
planContextEnabled: false,
chatSubmitKey: "enter",
prompts: [{ id: "prompt-1", name: "Prompt", content: "Prompt content" }],
planComments: [],
pendingPRFeedback: [],
pendingCommentsByFile: mockPendingByFile,
}),
}));
vi.mock("./chat/chat-input-container", async () => {
const React = await vi.importActual<typeof import("react")>("react");
const ChatInputContainer = React.forwardRef<Record<string, unknown>, Record<string, unknown>>(
function MockChatInputContainer(props, ref) {
const [value, setValue] = React.useState("");
chatInputMock.renderProps(props);
React.useImperativeHandle(ref, () => ({
focusInput: chatInputMock.focusInput,
getTextareaElement: chatInputMock.getTextareaElement,
getValue: () => value,
getSelectionStart: () => value.length,
insertText: vi.fn(),
clear: vi.fn(),
getAttachments: () => [],
}));
return (
<div data-testid="mock-chat-input-container">
{props.hasContextComments ? <div data-testid={TID_PENDING_BANNER} /> : null}
<button type="button" data-testid={TID_PLAN_TOGGLE}>
Plan
</button>
<button type="button" data-testid={TID_ATTACHMENTS}>
Attach
</button>
<button type="button" data-testid={TID_CONTEXT}>
Context
</button>
<textarea
data-testid={TID_TEXTAREA}
value={value}
onChange={(event) => setValue(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
(props.onCancel as () => void)?.();
return;
}
if (event.key === "Enter") {
event.preventDefault();
const result = (props.onSubmit as (message: string) => Promise<void> | void)?.(
value,
);
if (result && typeof result.then === "function") {
void result.catch(() => undefined);
}
}
}}
/>
</div>
);
},
);
return { ChatInputContainer };
});
// Import after mocks
import { PassthroughToolbar } from "./passthrough-toolbar";
@@ -118,7 +217,7 @@ function makeDiffComment(id: string): import("@/lib/state/slices/comments").Diff
id,
source: "diff",
sessionId: SESSION_ID,
filePath: "src/foo.ts",
filePath: SRC_FILE,
startLine: 1,
endLine: 1,
side: "additions",
@@ -140,12 +239,19 @@ async function openComposer() {
function resetMocks() {
mockSessionState = null;
mockKeyboardShortcuts = {};
mockPendingByFile = {};
mockNextStep = { proceedStepName: null, proceed: vi.fn(), isMoving: false };
mockWsRequestFn = vi.fn().mockResolvedValue(undefined);
chatInputMock.renderProps.mockClear();
vi.clearAllMocks();
}
function latestChatInputProps(): Record<string, unknown> {
const calls = chatInputMock.renderProps.mock.calls;
return (calls[calls.length - 1]?.[0] ?? {}) as Record<string, unknown>;
}
// ---------------------------------------------------------------------------
// Default / idle state
// ---------------------------------------------------------------------------
@@ -179,7 +285,7 @@ describe("PassthroughToolbar – composer toggle", () => {
beforeEach(resetMocks);
afterEach(cleanup);
it("clicking Chat toggle opens the composer and sets aria-pressed=true", async () => {
it("clicking Chat toggle opens and closes the composer", async () => {
renderToolbar();
const toggle = screen.getByTestId(TID_TOGGLE);
expect(toggle.getAttribute("aria-pressed")).toBe("false");
@@ -188,6 +294,11 @@ describe("PassthroughToolbar – composer toggle", () => {
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
expect(toggle.getAttribute("aria-pressed")).toBe("true");
fireEvent.click(toggle);
await waitFor(() => expect(screen.queryByTestId(TID_COMPOSER)).toBeNull());
expect(toggle.getAttribute("aria-pressed")).toBe("false");
});
it("pressing Escape inside the composer closes it", async () => {
@@ -198,6 +309,102 @@ describe("PassthroughToolbar – composer toggle", () => {
await waitFor(() => expect(screen.queryByTestId(TID_COMPOSER)).toBeNull());
});
it("wires passthrough composer controls and disables ACP-only controls", async () => {
renderToolbar();
await openComposer();
expect(screen.getByTestId(TID_PLAN_TOGGLE)).toBeTruthy();
expect(screen.getByTestId(TID_ATTACHMENTS)).toBeTruthy();
expect(screen.getByTestId(TID_CONTEXT)).toBeTruthy();
const props = latestChatInputProps();
expect(props.hasAgentCommands).toBe(false);
expect(props.hideAgentControls).toBe(true);
expect(props.contextItems).toEqual(
expect.arrayContaining([expect.objectContaining({ kind: "file", label: "foo.ts" })]),
);
expect(props.contextFiles).toEqual([{ path: SRC_FILE, name: "foo.ts" }]);
});
it("uses the passthrough-specific focus shortcut instead of the global slash shortcut", async () => {
mockKeyboardShortcuts = {
FOCUS_PASSTHROUGH_INPUT: { key: "y", modifiers: { ctrlOrCmd: true, shift: true } },
};
renderToolbar();
fireEvent.keyDown(window, { key: "/", code: "Slash" });
expect(screen.queryByTestId(TID_COMPOSER)).toBeNull();
fireEvent.keyDown(window, { key: "y", code: "KeyY", ctrlKey: true, shiftKey: true });
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
expect(chatInputMock.focusInput).toHaveBeenCalled();
});
it("shows the passthrough chat shortcut in the Chat tooltip", () => {
mockKeyboardShortcuts = {
FOCUS_PASSTHROUGH_INPUT: { key: "y", modifiers: { ctrlOrCmd: true, shift: true } },
};
renderToolbar();
expect(screen.getByText(/Ctrl\+Shift\+Y|Cmd\+Shift\+Y/)).toBeTruthy();
});
it("focus shortcut closes the composer when the composer textarea has focus", async () => {
mockKeyboardShortcuts = {
FOCUS_PASSTHROUGH_INPUT: { key: "y", modifiers: { ctrlOrCmd: true, shift: true } },
};
renderToolbar();
fireEvent.keyDown(window, { key: "y", code: "KeyY", ctrlKey: true, shiftKey: true });
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
const textarea = screen.getByTestId(TID_TEXTAREA);
textarea.focus();
fireEvent.keyDown(window, { key: "y", code: "KeyY", ctrlKey: true, shiftKey: true });
await waitFor(() => expect(screen.queryByTestId(TID_COMPOSER)).toBeNull());
});
it("does not steal focus from another editable field with the focus shortcut", () => {
mockKeyboardShortcuts = {
FOCUS_PASSTHROUGH_INPUT: { key: "y", modifiers: { ctrlOrCmd: true, shift: true } },
};
renderToolbar();
const input = document.createElement("input");
document.body.appendChild(input);
try {
input.focus();
fireEvent.keyDown(window, { key: "y", code: "KeyY", ctrlKey: true, shiftKey: true });
expect(screen.queryByTestId(TID_COMPOSER)).toBeNull();
expect(chatInputMock.focusInput).not.toHaveBeenCalled();
} finally {
input.remove();
}
});
it("focus shortcut works when xterm helper textarea owns focus", async () => {
mockKeyboardShortcuts = {
FOCUS_PASSTHROUGH_INPUT: { key: "y", modifiers: { ctrlOrCmd: true, shift: true } },
};
renderToolbar();
const xterm = document.createElement("div");
xterm.className = "xterm";
const textarea = document.createElement("textarea");
xterm.appendChild(textarea);
document.body.appendChild(xterm);
try {
textarea.focus();
fireEvent.keyDown(window, { key: "y", code: "KeyY", ctrlKey: true, shiftKey: true });
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
expect(chatInputMock.focusInput).toHaveBeenCalled();
} finally {
xterm.remove();
}
});
});
// ---------------------------------------------------------------------------
@@ -218,7 +425,12 @@ describe("PassthroughToolbar – send message", () => {
await waitFor(() =>
expect(mockWsRequestFn).toHaveBeenCalledWith(
"message.add",
{ task_id: TASK_ID, session_id: SESSION_ID, content: "hello" },
expect.objectContaining({
task_id: TASK_ID,
session_id: SESSION_ID,
content: expect.stringContaining("hello"),
context_files: [{ path: SRC_FILE, name: "foo.ts" }],
}),
10_000,
),
);
@@ -227,7 +439,7 @@ describe("PassthroughToolbar – send message", () => {
});
it("send with pending comments prepends review markdown and calls markCommentsSent", async () => {
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
mockPendingByFile = { [SRC_FILE]: [makeDiffComment("c1")] };
renderToolbar();
await openComposer();
@@ -238,7 +450,8 @@ describe("PassthroughToolbar – send message", () => {
const content = mockWsRequestFn.mock.calls[0][1].content as string;
expect(content).toMatch(/^### Review Comments\n/);
expect(content).toMatch(/ship it$/);
expect(content).toContain("ship it");
expect(content).toContain("CONTEXT FILES");
await waitFor(() => expect(mockMarkCommentsSent).toHaveBeenCalledWith(["c1"]));
});
@@ -273,7 +486,7 @@ describe("PassthroughToolbar – pending comment indicators", () => {
it("shows a numeric chip when the composer is collapsed and comments are pending", () => {
mockPendingByFile = {
"src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2"), makeDiffComment("c3")],
[SRC_FILE]: [makeDiffComment("c1"), makeDiffComment("c2"), makeDiffComment("c3")],
};
renderToolbar();
@@ -282,12 +495,11 @@ describe("PassthroughToolbar – pending comment indicators", () => {
});
it("renders the pending-comments banner inside the open composer when comments are pending", async () => {
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2")] };
mockPendingByFile = { [SRC_FILE]: [makeDiffComment("c1"), makeDiffComment("c2")] };
renderToolbar();
await openComposer();
const banner = screen.getByTestId(TID_PENDING_BANNER);
expect(banner.textContent).toMatch(/2/);
expect(latestChatInputProps().pendingCommentsByFile).toEqual(mockPendingByFile);
});
});
@@ -301,7 +513,7 @@ describe("PassthroughToolbar – Comments panel", () => {
it("clicking Comments opens a panel with one card per pending comment", async () => {
mockPendingByFile = {
"src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2")],
[SRC_FILE]: [makeDiffComment("c1"), makeDiffComment("c2")],
};
renderToolbar();
@@ -312,7 +524,7 @@ describe("PassthroughToolbar – Comments panel", () => {
});
it("editing a comment textarea calls updateComment with the new text", async () => {
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
mockPendingByFile = { [SRC_FILE]: [makeDiffComment("c1")] };
renderToolbar();
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
@@ -326,7 +538,7 @@ describe("PassthroughToolbar – Comments panel", () => {
});
it("clicking the file reference opens the file in an editor", async () => {
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
mockPendingByFile = { [SRC_FILE]: [makeDiffComment("c1")] };
renderToolbar();
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
@@ -334,11 +546,11 @@ describe("PassthroughToolbar – Comments panel", () => {
fireEvent.click(screen.getByTestId(TID_COMMENT_FILE_REF));
expect(mockOpenFile).toHaveBeenCalledWith("src/foo.ts");
expect(mockOpenFile).toHaveBeenCalledWith(SRC_FILE);
});
it("clicking the remove button on a comment calls removeComment", async () => {
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
mockPendingByFile = { [SRC_FILE]: [makeDiffComment("c1")] };
renderToolbar();
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
+106 -82
View File
@@ -1,6 +1,14 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type Dispatch,
type SetStateAction,
} from "react";
import {
IconArrowRight,
IconMessageCircle,
@@ -12,20 +20,54 @@ import {
import { Button } from "@kandev/ui/button";
import { Textarea } from "@kandev/ui/textarea";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { PRStatusChip } from "@/components/github/pr-status-chip";
import { PassthroughComposer } from "./passthrough-composer";
import { PRMergedBanner } from "./chat/chat-input-area";
import { type ChatInputContainerHandle } from "./chat/chat-input-container";
import { useChatPanelState } from "./chat/use-chat-panel-state";
import { useAppStore } from "@/components/state-provider";
import { useNextWorkflowStep } from "@/hooks/domains/kanban/use-plan-actions";
import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut";
import { usePendingDiffCommentsByFile } from "@/hooks/domains/comments/use-diff-comments";
import { useCommentsStore } from "@/lib/state/slices/comments/comments-store";
import { useFileEditors } from "@/hooks/use-file-editors";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { formatReviewCommentsAsMarkdown } from "@/lib/state/slices/comments/format";
import { getShortcut, isUnboundShortcut } from "@/lib/keyboard/shortcut-overrides";
import { formatShortcut } from "@/lib/keyboard/utils";
import type { KeyboardShortcut } from "@/lib/keyboard/constants";
import type { DiffComment } from "@/lib/diff/types";
import { getWebSocketClient } from "@/lib/ws/connection";
import { PassthroughTerminal } from "./passthrough-terminal";
import { PassthroughComposerPanel, useSendPassthroughMessage } from "./passthrough-chat-composer";
function isEditableElement(element: Element | null) {
if (element instanceof HTMLElement && element.closest(".xterm")) return false;
return (
element instanceof HTMLInputElement ||
element instanceof HTMLTextAreaElement ||
element instanceof HTMLSelectElement ||
(element instanceof HTMLElement && element.isContentEditable)
);
}
function usePassthroughComposerShortcut({
focusShortcut,
setComposerOpen,
}: {
focusShortcut: KeyboardShortcut;
setComposerOpen: Dispatch<SetStateAction<boolean>>;
}) {
useKeyboardShortcut(
focusShortcut,
useCallback(() => {
const activeElement = document.activeElement;
setComposerOpen((open) => {
if (open) return false;
if (isEditableElement(activeElement)) return open;
return true;
});
}, [setComposerOpen]),
{ capture: true, enabled: !isUnboundShortcut(focusShortcut) },
);
}
/**
* PassthroughToolbar wraps the PTY terminal with the kandev surface that the
@@ -49,10 +91,14 @@ export function PassthroughToolbar({
}) {
const [composerOpen, setComposerOpen] = useState(false);
const [commentsOpenState, setCommentsOpen] = useState(false);
const [isSending, setIsSending] = useState(false);
const chatInputRef = useRef<ChatInputContainerHandle | null>(null);
const sessionState = useAppStore((state) =>
sessionId ? (state.taskSessions.items[sessionId]?.state ?? null) : null,
);
const keyboardShortcuts = useAppStore((state) => state.userSettings?.keyboardShortcuts);
const focusShortcut = getShortcut("FOCUS_PASSTHROUGH_INPUT", keyboardShortcuts);
const isAgentBusy = sessionState === "RUNNING" || sessionState === "STARTING";
const nextStep = useNextWorkflowStep(taskId);
@@ -61,19 +107,40 @@ export function PassthroughToolbar({
const { pendingComments, pendingCount } = usePendingPassthroughComments(sessionId);
const { isMobile } = useResponsiveBreakpoint();
const { openFile } = useFileEditors();
const panelState = useChatPanelState({ sessionId: sessionId ?? null, onOpenFile: openFile });
// Derive open state: auto-close when pending comments are cleared
const commentsOpen = commentsOpenState && pendingCount > 0;
const handleSendMessage = useSendPassthroughMessage({
const sendPassthroughMessage = useSendPassthroughMessage({
taskId,
sessionId,
pendingComments,
panelState,
onSent: () => {
setComposerOpen(false);
setCommentsOpen(false);
},
});
const handleSendMessage = useCallback(
async (...args: Parameters<typeof sendPassthroughMessage>) => {
if (isSending) return;
setIsSending(true);
try {
await sendPassthroughMessage(...args);
} finally {
setIsSending(false);
}
},
[isSending, sendPassthroughMessage],
);
useEffect(() => {
if (!composerOpen) return;
requestAnimationFrame(() => chatInputRef.current?.focusInput());
}, [composerOpen]);
usePassthroughComposerShortcut({ focusShortcut, setComposerOpen });
return (
<div className="flex h-full flex-col bg-card" data-testid="passthrough-toolbar">
@@ -90,12 +157,14 @@ export function PassthroughToolbar({
)}
{composerOpen && (
<PassthroughComposer
<PassthroughComposerPanel
refHandle={chatInputRef}
onSubmit={handleSendMessage}
onCancel={() => setComposerOpen(false)}
autoFocus
placeholder="Type a message, Shift+Enter for newline, Esc to close"
header={pendingCount > 0 ? <PendingCommentsHint count={pendingCount} /> : null}
panelState={panelState}
taskId={taskId}
isMoving={nextStep.isMoving}
isSending={isSending}
/>
)}
@@ -106,6 +175,7 @@ export function PassthroughToolbar({
isMoving={nextStep.isMoving}
showProceed={showProceed}
composerOpen={composerOpen}
focusShortcut={focusShortcut}
onToggleComposer={() => setComposerOpen((open) => !open)}
commentsOpen={commentsOpen}
onToggleComments={() => setCommentsOpen((open) => !open)}
@@ -130,64 +200,13 @@ function usePendingPassthroughComments(sessionId: string | null | undefined) {
return { pendingComments, pendingCount: pendingComments.length };
}
function useSendPassthroughMessage({
taskId,
sessionId,
pendingComments,
onSent,
}: {
taskId: string | null;
sessionId: string | null | undefined;
pendingComments: DiffComment[];
onSent: () => void;
}) {
const { toast } = useToast();
const markCommentsSent = useCommentsStore((s) => s.markCommentsSent);
return useCallback(
async (content: string) => {
if (!taskId || !sessionId) {
toast({ title: "Session not ready", variant: "error" });
throw new Error("Session not ready");
}
const client = getWebSocketClient();
if (!client) {
toast({ title: "Not connected — please reload to retry", variant: "error" });
throw new Error("WebSocket client not available");
}
// Format pending review comments as markdown and prepend so they reach
// the agent's stdin alongside the user's typed prompt. Mark them sent
// only after the WS request resolves so a failed send doesn't drop the
// user's queued comments.
const formatted =
pendingComments.length > 0
? formatReviewCommentsAsMarkdown(pendingComments) + content
: content;
try {
await client.request(
"message.add",
{ task_id: taskId, session_id: sessionId, content: formatted },
10_000,
);
if (pendingComments.length > 0) {
markCommentsSent(pendingComments.map((c) => c.id));
}
onSent();
} catch (error) {
console.error("Failed to send passthrough message:", error);
toast({ title: "Failed to send message", variant: "error" });
throw error;
}
},
[taskId, sessionId, toast, pendingComments, markCommentsSent, onSent],
);
}
function ChatToggleButton({
composerOpen,
focusShortcut,
onToggle,
}: {
composerOpen: boolean;
focusShortcut: KeyboardShortcut;
onToggle: () => void;
}) {
return (
@@ -212,16 +231,20 @@ function ChatToggleButton({
</TooltipTrigger>
<TooltipContent className="max-w-xs">
{composerOpen ? (
<p>
Close the compose box (or press <kbd>Esc</kbd> inside it). The CLI agent terminal keeps
focus.
</p>
<div className="space-y-1">
<p>
Close the compose box (or press <kbd>Esc</kbd> inside it). The CLI agent terminal
keeps focus.
</p>
<PassthroughChatShortcutHint shortcut={focusShortcut} />
</div>
) : (
<div className="space-y-1">
<p>
Open a kandev-controlled compose box above the terminal to type a follow-up message.
Press <kbd>Enter</kbd> to send, <kbd>Shift+Enter</kbd> for a newline.
</p>
<PassthroughChatShortcutHint shortcut={focusShortcut} />
<p className="text-muted-foreground">
The text is delivered straight to the CLI agent&apos;s stdin — pending review comments
(if any) are prepended automatically.
@@ -233,6 +256,15 @@ function ChatToggleButton({
);
}
function PassthroughChatShortcutHint({ shortcut }: { shortcut: KeyboardShortcut }) {
if (isUnboundShortcut(shortcut)) return null;
return (
<p className="text-muted-foreground">
Shortcut: <kbd>{formatShortcut(shortcut)}</kbd> toggles this chat input.
</p>
);
}
function commentsToggleClassName(count: number, commentsOpen: boolean): string {
// Vivid amber when there are pending comments so the user sees "something
// to do" — washes back to plain outline once they're cleared / sent.
@@ -321,20 +353,6 @@ function CommentsTooltipBody({ commentsOpen, count }: { commentsOpen: boolean; c
);
}
function PendingCommentsHint({ count }: { count: number }) {
return (
<div
data-testid="passthrough-pending-comments-banner"
className="flex items-center gap-1.5 border-b bg-amber-500/10 px-2 py-1 text-xs text-amber-700 dark:text-amber-300"
>
<IconMessageDots className="h-3.5 w-3.5" />
<span>
{count} pending review comment{count === 1 ? "" : "s"} will be attached to this message.
</span>
</div>
);
}
function CommentsPanel({
comments,
openFile,
@@ -471,6 +489,7 @@ type StatusRowProps = {
isMoving: boolean;
showProceed: boolean;
composerOpen: boolean;
focusShortcut: KeyboardShortcut;
onToggleComposer: () => void;
commentsOpen: boolean;
onToggleComments: () => void;
@@ -484,6 +503,7 @@ function PassthroughStatusRow({
isMoving,
showProceed,
composerOpen,
focusShortcut,
onToggleComposer,
commentsOpen,
onToggleComments,
@@ -494,7 +514,11 @@ function PassthroughStatusRow({
data-testid="passthrough-status-row"
className="flex flex-shrink-0 items-center gap-1.5 border-t bg-card px-2 py-1 text-xs text-muted-foreground"
>
<ChatToggleButton composerOpen={composerOpen} onToggle={onToggleComposer} />
<ChatToggleButton
composerOpen={composerOpen}
focusShortcut={focusShortcut}
onToggle={onToggleComposer}
/>
<CommentsToggleButton
commentsOpen={commentsOpen}
onToggle={onToggleComments}
@@ -1,101 +0,0 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { render, fireEvent, screen, cleanup, waitFor } from "@testing-library/react";
import { PassthroughComposer } from "./passthrough-composer";
const TEXTAREA_TID = "passthrough-composer-textarea";
const SUBMIT_TID = "passthrough-composer-submit";
describe("PassthroughComposer", () => {
afterEach(() => {
cleanup();
});
it("submits trimmed text on Enter and clears the textarea", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<PassthroughComposer onSubmit={onSubmit} />);
const textarea = screen.getByTestId(TEXTAREA_TID) as HTMLTextAreaElement;
fireEvent.change(textarea, { target: { value: " hello agent " } });
fireEvent.keyDown(textarea, { key: "Enter" });
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
expect(onSubmit).toHaveBeenCalledWith("hello agent");
await waitFor(() => expect(textarea.value).toBe(""));
});
it("submits when the send button is clicked", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<PassthroughComposer onSubmit={onSubmit} />);
fireEvent.change(screen.getByTestId(TEXTAREA_TID), {
target: { value: "ping" },
});
fireEvent.click(screen.getByTestId(SUBMIT_TID));
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("ping"));
});
it("Shift+Enter inserts a newline and does not submit", () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<PassthroughComposer onSubmit={onSubmit} />);
const textarea = screen.getByTestId(TEXTAREA_TID);
fireEvent.change(textarea, { target: { value: "line1" } });
fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });
expect(onSubmit).not.toHaveBeenCalled();
});
it("does not submit empty or whitespace-only input", () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<PassthroughComposer onSubmit={onSubmit} />);
const textarea = screen.getByTestId(TEXTAREA_TID);
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSubmit).not.toHaveBeenCalled();
fireEvent.change(textarea, { target: { value: " \n " } });
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSubmit).not.toHaveBeenCalled();
const submitBtn = screen.getByTestId(SUBMIT_TID) as HTMLButtonElement;
expect(submitBtn.disabled).toBe(true);
});
it("preserves the typed text when onSubmit rejects so the user can retry", async () => {
const onSubmit = vi.fn().mockRejectedValue(new Error("network down"));
render(<PassthroughComposer onSubmit={onSubmit} />);
const textarea = screen.getByTestId(TEXTAREA_TID) as HTMLTextAreaElement;
fireEvent.change(textarea, { target: { value: "important request" } });
fireEvent.keyDown(textarea, { key: "Enter" });
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
// Composer must NOT clear on failure — losing typed text on a flaky WS
// disconnect was a real UX regression (issue #989 review feedback).
expect(textarea.value).toBe("important request");
// Composer must re-enable so the user can resubmit.
await waitFor(() => expect(textarea.disabled).toBe(false));
});
it("disables the composer while a submission is in flight", async () => {
let resolveSubmit!: () => void;
const submitPromise = new Promise<void>((resolve) => {
resolveSubmit = resolve;
});
const onSubmit = vi.fn().mockReturnValue(submitPromise);
render(<PassthroughComposer onSubmit={onSubmit} />);
const textarea = screen.getByTestId(TEXTAREA_TID) as HTMLTextAreaElement;
const submitBtn = screen.getByTestId(SUBMIT_TID) as HTMLButtonElement;
fireEvent.change(textarea, { target: { value: "hi" } });
fireEvent.keyDown(textarea, { key: "Enter" });
await waitFor(() => expect(textarea.disabled).toBe(true));
expect(submitBtn.disabled).toBe(true);
resolveSubmit();
await waitFor(() => expect(textarea.disabled).toBe(false));
expect(textarea.value).toBe("");
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from "vitest";
import { applySummarizeSessionResult } from "./session-context-summary";
describe("applySummarizeSessionResult", () => {
it("sanitizes unsafe characters before writing the prompt", () => {
const promptRef = { current: { value: "" } as HTMLTextAreaElement };
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const toast = vi.fn();
applySummarizeSessionResult({
result: { summary: "line1\r\n<unsafe>\nline2" },
promptRef,
setContextValue,
setHasPrompt,
toast,
});
expect(promptRef.current.value).toBe("line1\n unsafe \nline2");
expect(setHasPrompt).toHaveBeenCalledWith(true);
expect(toast).not.toHaveBeenCalled();
});
it("treats an empty summary string as a successful summary", () => {
const promptRef = { current: { value: "existing" } as HTMLTextAreaElement };
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const toast = vi.fn();
applySummarizeSessionResult({
result: { summary: "" },
promptRef,
setContextValue,
setHasPrompt,
toast,
});
expect(promptRef.current.value).toBe("");
expect(setHasPrompt).toHaveBeenCalledWith(true);
expect(toast).not.toHaveBeenCalled();
});
it("resets context and prompt state when summary is null", () => {
const promptRef = { current: { value: "stale prompt" } as HTMLTextAreaElement };
const setContextValue = vi.fn();
const setHasPrompt = vi.fn();
const toast = vi.fn();
applySummarizeSessionResult({
result: { summary: null, error: "connection refused" },
promptRef,
setContextValue,
setHasPrompt,
toast,
});
expect(setContextValue).toHaveBeenCalledWith("blank");
expect(promptRef.current.value).toBe("");
expect(setHasPrompt).toHaveBeenCalledWith(false);
expect(toast).toHaveBeenCalledWith({
title: "Summarize failed",
description: "connection refused",
variant: "error",
});
});
});
@@ -0,0 +1,47 @@
import type { RefObject } from "react";
import type { SummarizeSessionResult } from "@/hooks/use-summarize-session";
export type SummaryToastFn = (opts: {
title: string;
description?: string;
variant?: "error" | "default";
}) => void;
export function sanitizePromptText(value: string): string {
return value.replace(/\r/g, "").replace(/[<>]/g, " ");
}
export function applySummarizeSessionResult({
result,
promptRef,
setContextValue,
setHasPrompt,
toast,
}: {
result: SummarizeSessionResult;
promptRef: RefObject<HTMLTextAreaElement | null>;
setContextValue: (v: string) => void;
setHasPrompt: (v: boolean) => void;
toast: SummaryToastFn;
}) {
if (result.summary === null) {
setContextValue("blank");
if (promptRef.current) {
promptRef.current.value = "";
}
setHasPrompt(false);
toast({
title: "Summarize failed",
description:
result.error ??
"Could not generate a summary. Check that the summarize utility agent is configured and enabled in settings.",
variant: "error",
});
return;
}
if (promptRef.current) {
promptRef.current.value = sanitizePromptText(result.summary);
setHasPrompt(true);
}
}