fix: recover failed task launches safely (#3437)

This commit is contained in:
Carlos Florêncio
2026-09-07 11:19:09 +01:00
committed by GitHub
parent 3c6af41063
commit 3fba828e2f
69 changed files with 2280 additions and 277 deletions
@@ -312,6 +312,8 @@ type ChatInputAreaProps = {
onRequestChangesTooltipDismiss?: () => void;
panelState: ChatPanelState;
isSending: boolean;
/** The task-owned launch card renders recovery for the failed start. */
launchErrorOwned?: boolean;
hideSessionsDropdown?: boolean;
minimalToolbar?: boolean;
/** Hide ACP/session-specific controls (model picker, mode, MCP, reset context,
@@ -428,6 +430,7 @@ export function ChatInputArea({
onScrollToStart,
statusTaskId = null,
showAgentStartHint = false,
launchErrorOwned = false,
}: ChatInputAreaProps) {
const { resolvedSessionId, taskId, isAgentBusy } = panelState;
const statusRowTaskId = resolveStatusRowTaskId(taskId, statusTaskId);
@@ -456,6 +459,7 @@ export function ChatInputArea({
minimalToolbar,
hideAgentControls,
hidePlanMode,
launchErrorOwned,
});
return (
<div
@@ -0,0 +1,112 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatInputContainer } from "./chat-input-container";
const { containerState } = vi.hoisted(() => ({
containerState: {
showNewSessionDialog: false,
setShowNewSessionDialog: vi.fn(),
contextPopoverOpen: false,
setContextPopoverOpen: vi.fn(),
height: "auto",
containerRef: { current: null },
resizeHandleProps: { onMouseDown: vi.fn(), onDoubleClick: vi.fn() },
value: "",
inputRef: { current: null },
addFiles: vi.fn().mockResolvedValue(undefined),
fileInputRef: { current: null },
handleChange: vi.fn(),
handleSubmitWithReset: vi.fn(),
allItems: [],
hasPendingAttachmentUploads: false,
isInputFocused: false,
setIsInputFocused: vi.fn(),
hasClarification: false,
hasPendingComments: false,
hasContextZone: false,
showFocusHint: false,
inputPlaceholder: "Ask to make changes",
isDisabled: false,
submitDisabled: false,
submitDisabledReason: undefined,
},
}));
vi.mock("./use-chat-input-container", () => ({
useChatInputContainer: () => containerState,
}));
vi.mock("./session-stopped-banner", () => ({
SessionStoppedBanner: () => <div data-testid="session-stopped-banner" />,
}));
vi.mock("./chat-input-body", () => ({
ChatInputBody: () => <div data-testid="chat-input-body" />,
}));
vi.mock("@/hooks/domains/session/use-session-recovery-actions", () => ({
useSessionRecoveryActions: () => ({}),
}));
vi.mock("@/hooks/use-is-utility-configured", () => ({
useIsUtilityConfigured: () => false,
}));
vi.mock("@/hooks/use-utility-agent-generator", () => ({
useUtilityAgentGenerator: () => ({
enhancePrompt: vi.fn(),
isEnhancingPrompt: false,
}),
}));
vi.mock("@/hooks/use-prompt-result-delivery", () => ({
usePromptResultDelivery: () => ({
pendingResult: null,
captureScope: vi.fn(),
deliver: vi.fn(),
applyPending: vi.fn(),
copyPending: vi.fn(),
}),
}));
vi.mock("@/lib/i18n", () => ({
t: (key: string) => key,
}));
const baseProps = {
onSubmit: vi.fn(),
sessionId: "session-1",
taskId: "task-1",
taskDescription: "",
planModeEnabled: false,
onPlanModeChange: vi.fn(),
isAgentBusy: false,
isStarting: false,
isSending: false,
onCancel: vi.fn(),
};
afterEach(() => cleanup());
describe("ChatInputContainer launch-error ownership", () => {
it("hides the editor when the task launch card owns a failed session", () => {
render(<ChatInputContainer {...baseProps} isFailed launchErrorOwned />);
expect(screen.queryByTestId("chat-input-body")).toBeNull();
expect(screen.queryByTestId("session-stopped-banner")).toBeNull();
});
it("renders the stopped banner when the failed session has no launch-card owner", () => {
render(<ChatInputContainer {...baseProps} isFailed />);
expect(screen.queryByTestId("chat-input-body")).toBeNull();
expect(screen.getByTestId("session-stopped-banner")).toBeTruthy();
});
it("keeps the editor visible when the owned launch error is not a failed session", () => {
render(<ChatInputContainer {...baseProps} launchErrorOwned />);
expect(screen.getByTestId("chat-input-body")).toBeTruthy();
expect(screen.queryByTestId("session-stopped-banner")).toBeNull();
});
});
@@ -21,6 +21,7 @@ import { useIsUtilityConfigured } from "@/hooks/use-is-utility-configured";
import { usePromptResultDelivery } from "@/hooks/use-prompt-result-delivery";
import { PromptResultRecovery } from "@/components/prompt-result-recovery";
import { t } from "@/lib/i18n";
import { shouldHideChatInputForLaunchError, shouldRenderStoppedSessionBanner } from "./types";
// Re-export ImageAttachment type for consumers
export type { ImageAttachment } from "./image-attachment-preview";
@@ -96,6 +97,8 @@ type ChatInputContainerProps = {
isCompleted?: boolean;
sessionErrorMessage?: string;
needsRecovery?: boolean;
/** The task-owned launch card renders the failed-start recovery. */
launchErrorOwned?: boolean;
executorUnavailable?: boolean;
executorUnavailableReason?: string;
contextItems?: ContextItem[];
@@ -287,6 +290,13 @@ function useChatPromptEnhancement({
return { handleEnhancePrompt, isEnhancingPrompt, isUtilityConfigured, promptDelivery };
}
function useChatInputRecoveryActions(taskId: string | null, sessionId: string | null) {
return useSessionRecoveryActions({
taskId: taskId ?? "",
sessionId: sessionId ?? "",
});
}
export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInputContainerProps>(
// eslint-disable-next-line complexity -- top-level component chooses the stopped or editor surface after shared hook setup.
function ChatInputContainer(props, ref) {
@@ -322,10 +332,7 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
onSubmit: props.onSubmit,
});
const recoveryActions = useSessionRecoveryActions({
taskId: taskId ?? "",
sessionId: sessionId ?? "",
});
const recoveryActions = useChatInputRecoveryActions(taskId, sessionId);
const promptEnhancement = useChatPromptEnhancement({
inputRef: s.inputRef,
@@ -335,7 +342,23 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
taskDescription,
});
if (p.isFailed || p.isCompleted || executorUnavailable) {
if (
shouldHideChatInputForLaunchError({
isFailed: p.isFailed,
launchErrorOwned: p.launchErrorOwned,
})
) {
return null;
}
if (
shouldRenderStoppedSessionBanner({
isFailed: p.isFailed,
isCompleted: p.isCompleted,
executorUnavailable,
launchErrorOwned: p.launchErrorOwned,
})
) {
return (
<SessionStoppedBanner
mode={p.isCompleted ? "completed" : "recoverable"}
@@ -15,7 +15,9 @@ vi.mock("@/components/task/chat/message-renderer", () => ({
import { MessageListFooter } from "./message-list-footer";
const AGENT_STATUS_TEST_ID = "agent-status";
const ACTION_MESSAGE_TEST_ID = "action-message";
const SESSION_ID = "session-1";
const FAILED_SESSION_STATE = "FAILED" as const;
afterEach(cleanup);
@@ -45,23 +47,30 @@ const laterFailure = {
},
} satisfies Message;
// eslint-disable-next-line max-lines-per-function -- footer ownership cases share one focused fixture.
describe("MessageListFooter", () => {
it("lets an actionable footer failure own the failure presentation", () => {
render(
<MessageListFooter
sessionState="FAILED"
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
footerActionMessages={[actionableFailure]}
/>,
);
expect(screen.getByTestId("action-message")).toBeTruthy();
expect(screen.getByTestId(ACTION_MESSAGE_TEST_ID)).toBeTruthy();
expect(screen.queryByTestId(AGENT_STATUS_TEST_ID)).toBeNull();
});
it("keeps the generic status for a failed session without an actionable footer", () => {
render(<MessageListFooter sessionState="FAILED" sessionId={SESSION_ID} messages={[]} />);
render(
<MessageListFooter
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
/>,
);
expect(screen.getByTestId(AGENT_STATUS_TEST_ID)).toBeTruthy();
});
@@ -81,13 +90,17 @@ describe("MessageListFooter", () => {
it("switches ownership when missing-branch recovery arrives after failure", () => {
const { rerender } = render(
<MessageListFooter sessionState="FAILED" sessionId={SESSION_ID} messages={[]} />,
<MessageListFooter
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
/>,
);
expect(screen.getByTestId(AGENT_STATUS_TEST_ID)).toBeTruthy();
rerender(
<MessageListFooter
sessionState="FAILED"
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
footerActionMessages={[actionableFailure]}
@@ -95,13 +108,13 @@ describe("MessageListFooter", () => {
);
expect(screen.queryByTestId(AGENT_STATUS_TEST_ID)).toBeNull();
expect(screen.getByTestId("action-message")).toBeTruthy();
expect(screen.getByTestId(ACTION_MESSAGE_TEST_ID)).toBeTruthy();
});
it("does not restore stale missing-branch recovery after a later failure", () => {
render(
<MessageListFooter
sessionState="FAILED"
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[actionableFailure, laterFailure]}
footerActionMessages={[actionableFailure]}
@@ -109,6 +122,56 @@ describe("MessageListFooter", () => {
);
expect(screen.getByTestId(AGENT_STATUS_TEST_ID)).toBeTruthy();
expect(screen.queryByTestId("action-message")).toBeNull();
expect(screen.queryByTestId(ACTION_MESSAGE_TEST_ID)).toBeNull();
});
it("hides launch failure footer surfaces when the task card owns the error", () => {
render(
<MessageListFooter
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
footerActionMessages={[actionableFailure]}
launchErrorOwned
/>,
);
expect(screen.queryByTestId(AGENT_STATUS_TEST_ID)).toBeNull();
expect(screen.queryByTestId(ACTION_MESSAGE_TEST_ID)).toBeNull();
});
it("keeps stale launch failure footer history when the current card owns the error", () => {
const staleFailure = {
...actionableFailure,
id: "failure-stale",
content: "Stale branch recovery",
metadata: {
...actionableFailure.metadata,
launch_error_stamp: "old-stamp",
},
} satisfies Message;
const currentFailure = {
...actionableFailure,
id: "failure-current",
content: "Current branch recovery",
metadata: {
...actionableFailure.metadata,
launch_error_stamp: "current-stamp",
},
} satisfies Message;
render(
<MessageListFooter
sessionState={FAILED_SESSION_STATE}
sessionId={SESSION_ID}
messages={[]}
footerActionMessages={[staleFailure, currentFailure]}
launchErrorOwned
launchErrorStamp="current-stamp"
/>,
);
expect(screen.getByText("Stale branch recovery")).toBeTruthy();
expect(screen.queryByText("Current branch recovery")).toBeNull();
});
});
@@ -3,6 +3,7 @@
import type { Message, TaskSessionState } from "@/lib/types/http";
import { AgentStatus } from "@/components/task/chat/messages/agent-status";
import { MessageRenderer } from "@/components/task/chat/message-renderer";
import { filterLaunchErrorMessages } from "./message-list-shared";
type MessageListFooterProps = {
sessionState?: TaskSessionState;
@@ -10,6 +11,12 @@ type MessageListFooterProps = {
messages: Message[];
isWorking?: boolean;
footerActionMessages?: Message[];
/** The task-owned launch card is rendering the current failure. */
launchErrorOwned?: boolean;
/** Stamp used to keep historical launch-only footer rows visible. */
launchErrorStamp?: string;
/** Timestamp used to identify unstamped synthetic rows from the active failure. */
launchErrorOccurredAt?: string;
};
function isMissingBranchFailure(message: Message): boolean {
@@ -45,18 +52,25 @@ export function MessageListFooter({
messages,
isWorking,
footerActionMessages = [],
launchErrorOwned = false,
launchErrorStamp,
launchErrorOccurredAt,
}: MessageListFooterProps) {
const currentActionableFailure = findCurrentActionableFailure(messages, footerActionMessages);
const recoveryOwnsFailure =
!launchErrorOwned &&
sessionState === "FAILED" &&
currentActionableFailure !== undefined &&
isMissingBranchFailure(currentActionableFailure);
const visibleFooterActionMessages = footerActionMessages.filter(
(message) => !isMissingBranchFailure(message) || message.id === currentActionableFailure?.id,
);
const visibleFooterActionMessages = launchErrorOwned
? filterLaunchErrorMessages(footerActionMessages, true, launchErrorStamp, launchErrorOccurredAt)
: footerActionMessages.filter(
(message) =>
!isMissingBranchFailure(message) || message.id === currentActionableFailure?.id,
);
return (
<>
{!recoveryOwnsFailure && (
{!recoveryOwnsFailure && !(launchErrorOwned && sessionState === "FAILED") && (
<AgentStatus
sessionState={sessionState}
sessionId={sessionId}
@@ -25,6 +25,8 @@ import {
getLastTurnGroupId,
getStreamingAgentMessageId,
canReassertDividerScroll,
filterLaunchErrorItems,
filterLaunchErrorMessages,
resolveLastPromptEdge,
isElementFullyVisible,
} from "./message-list-shared";
@@ -271,6 +273,9 @@ type NativeMessageListBodyProps = {
onScrollToMessage: (messageId: string, options?: { align?: "start" | "center" }) => void;
autoScrollEnabled: boolean;
dividerBeforeItemKey?: string | null;
launchErrorOwned: boolean;
launchErrorStamp?: string;
launchErrorOccurredAt?: string;
};
/**
@@ -474,6 +479,9 @@ function NativeMessageListBody({
onScrollToMessage,
autoScrollEnabled,
dividerBeforeItemKey,
launchErrorOwned,
launchErrorStamp,
launchErrorOccurredAt,
}: NativeMessageListBodyProps) {
return (
<div className="p-4">
@@ -515,6 +523,9 @@ function NativeMessageListBody({
messages={messages}
isWorking={isWorking}
footerActionMessages={footerActionMessages}
launchErrorOwned={launchErrorOwned}
launchErrorStamp={launchErrorStamp}
launchErrorOccurredAt={launchErrorOccurredAt}
/>
{/* Bottom anchor keeps the view pinned while auto-scroll is enabled.
@@ -558,14 +569,43 @@ export const NativeMessageList = memo(
dividerBeforeItemKey,
anchoredBarHeight,
isVisible = true,
launchErrorOwned = false,
launchErrorStamp,
launchErrorOccurredAt,
}: MessageListProps,
ref,
) {
const scrollRef = useRef<HTMLDivElement>(null);
const visibleItems = useMemo(
() =>
filterLaunchErrorItems(items, launchErrorOwned, launchErrorStamp, launchErrorOccurredAt),
[items, launchErrorOwned, launchErrorStamp, launchErrorOccurredAt],
);
const visibleMessages = useMemo(
() =>
filterLaunchErrorMessages(
messages,
launchErrorOwned,
launchErrorStamp,
launchErrorOccurredAt,
),
[messages, launchErrorOwned, launchErrorStamp, launchErrorOccurredAt],
);
const visibleFooterActionMessages = useMemo(
() =>
filterLaunchErrorMessages(
footerActionMessages ?? [],
launchErrorOwned,
launchErrorStamp,
launchErrorOccurredAt,
),
[footerActionMessages, launchErrorOwned, launchErrorStamp, launchErrorOccurredAt],
);
const { isInitialLoading, showLoadingState } = getConversationLoadingState({
messagesLoading,
messagesCount: messages.length,
messagesCount: visibleMessages.length,
isWorking,
sessionState,
});
@@ -574,15 +614,15 @@ export const NativeMessageList = memo(
});
const { activeTurnId } = useSessionTurn(sessionId);
const effectiveActiveTurnId = getEffectiveActiveTurnId(activeTurnId, isWorking);
const streamingMessageId = getStreamingAgentMessageId(messages);
const lastTurnGroupId = useMemo(() => getLastTurnGroupId(items), [items]);
const streamingMessageId = getStreamingAgentMessageId(visibleMessages);
const lastTurnGroupId = useMemo(() => getLastTurnGroupId(visibleItems), [visibleItems]);
const autoScrollEnabled = useTranscriptAutoScrollEnabled(sessionId);
const { handleScrollToMessage, sentinelRef, retryLoadMore, showRecovery } =
useNativeMessageListScroll({
scrollRef,
ref,
items,
messages,
items: visibleItems,
messages: visibleMessages,
isWorking,
sessionId,
enabled: autoScrollEnabled,
@@ -617,9 +657,9 @@ export const NativeMessageList = memo(
>
{stickyPromptBar}
<NativeMessageListBody
items={items}
messages={messages}
footerActionMessages={footerActionMessages}
items={visibleItems}
messages={visibleMessages}
footerActionMessages={visibleFooterActionMessages}
permissionsByToolCallId={permissionsByToolCallId}
childrenByParentToolCallId={childrenByParentToolCallId}
taskId={taskId}
@@ -642,6 +682,9 @@ export const NativeMessageList = memo(
onScrollToMessage={handleScrollToMessage}
autoScrollEnabled={autoScrollEnabled}
dividerBeforeItemKey={dividerBeforeItemKey}
launchErrorOwned={launchErrorOwned}
launchErrorStamp={launchErrorStamp}
launchErrorOccurredAt={launchErrorOccurredAt}
/>
</SessionPanelContent>
);
@@ -93,6 +93,8 @@ import {
getLastUserMessageId,
getFirstUserMessageId,
isElementFullyVisible,
filterLaunchErrorItems,
filterLaunchErrorMessages,
resolveLastPromptControls,
resolveLastPromptEdge,
shouldAutoScrollToBottom,
@@ -131,6 +133,106 @@ describe("getEffectiveActiveTurnId", () => {
});
});
describe("launch error-owned transcript filtering", () => {
it("removes launch-only messages only when the task card owns the error", () => {
const emptyTurn = {
id: "empty-turn-1",
metadata: { empty_turn: true },
} as unknown as Message;
const runtimeFailure = {
id: "runtime-failure-1",
metadata: { failure_kind: "provider_quota_limited" },
} as unknown as Message;
expect(filterLaunchErrorMessages([emptyTurn, runtimeFailure], false)).toEqual([
emptyTurn,
runtimeFailure,
]);
expect(filterLaunchErrorMessages([emptyTurn, runtimeFailure], true)).toEqual([runtimeFailure]);
});
it("removes preparation and previous-agent rows while retaining transcript messages", () => {
const runtimeMessage = { id: "message-1" } as unknown as Message;
const items: RenderItem[] = [
{ type: "prepare_progress", id: "prepare-1", sessionId: "s1" },
{
type: "agent_error_notice",
id: "agent-error-1",
sessionId: "s1",
error: { message: "matching error", stamp: "stamp-1" },
},
{
type: "agent_error_notice",
id: "agent-error-2",
sessionId: "s1",
error: { message: "unrelated error", stamp: "old-stamp" },
},
{
type: "message",
message: {
id: "empty-1",
created_at: "2026-06-14T12:00:01Z",
metadata: { empty_turn: true },
} as unknown as Message,
},
{ type: "message", message: runtimeMessage },
];
expect(filterLaunchErrorItems(items, true, "stamp-1", "2026-06-14T12:00:00Z")).toEqual([
{
type: "agent_error_notice",
id: "agent-error-2",
sessionId: "s1",
error: { message: "unrelated error", stamp: "old-stamp" },
},
{ type: "message", message: runtimeMessage },
]);
});
it("keeps stale launch-only history when the current failure has no carried stamp", () => {
const staleEmptyTurn = {
id: "empty-stale",
created_at: "2026-07-21T00:00:00Z",
metadata: { empty_turn: true },
} as unknown as Message;
const currentEmptyTurn = {
id: "empty-current",
created_at: "2026-07-22T00:00:00Z",
metadata: { empty_turn: true },
} as unknown as Message;
expect(filterLaunchErrorMessages([staleEmptyTurn, currentEmptyTurn], true)).toEqual([
staleEmptyTurn,
]);
expect(
filterLaunchErrorItems(
[
{ type: "message", message: staleEmptyTurn },
{ type: "message", message: currentEmptyTurn },
],
true,
"current-stamp",
"2026-07-22T00:00:00Z",
),
).toEqual([{ type: "message", message: staleEmptyTurn }]);
});
it("filters only launch-only rows carrying the active failure stamp", () => {
const staleMissingBranch = {
id: "missing-stale",
metadata: { failure_kind: "missing_pr_branch", launch_error_stamp: "old-stamp" },
} as unknown as Message;
const currentMissingBranch = {
id: "missing-current",
metadata: { failure_kind: "missing_pr_branch", launch_error_stamp: "current-stamp" },
} as unknown as Message;
expect(
filterLaunchErrorMessages([staleMissingBranch, currentMissingBranch], true, "current-stamp"),
).toEqual([staleMissingBranch]);
});
});
describe("canReassertDividerScroll", () => {
it("never applies without a divider target", () => {
expect(
@@ -17,6 +17,7 @@ import {
lastAgentErrorStamp,
readLastAgentError,
} from "@/lib/session-last-agent-error";
import { isLaunchErrorSurfaceMessage } from "./types";
import { useTranslation } from "react-i18next";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
@@ -67,6 +68,12 @@ export type MessageListProps = {
* remain mounted while inactive and use this transition to recover missed
* oldest-page sentinel observations. */
isVisible?: boolean;
/** The task-owned launch card renders the matching failure. */
launchErrorOwned?: boolean;
/** Stamp used to distinguish a matching last-agent-error notice. */
launchErrorStamp?: string;
/** Timestamp used to identify unstamped synthetic rows from the active failure. */
launchErrorOccurredAt?: string;
};
/** Imperative handle exposed by `MessageList`, letting the chat panel scroll
@@ -91,6 +98,86 @@ export function getItemKey(item: RenderItem): string {
return item.message.id;
}
const LAUNCH_ERROR_STAMP_KEYS = ["launch_error_stamp", "error_stamp"] as const;
function launchErrorSurfaceStamp(message: Message): string | undefined {
const metadata = message.metadata as Record<string, unknown> | undefined;
for (const key of LAUNCH_ERROR_STAMP_KEYS) {
const value = metadata?.[key];
if (typeof value === "string" && value.length > 0) return value;
}
return undefined;
}
function launchErrorSurfaceMessageIds(
messages: Message[],
launchErrorStamp?: string,
launchErrorOccurredAt?: string,
): Set<string> {
const launchMessages = messages.filter(isLaunchErrorSurfaceMessage);
if (launchMessages.length === 0) return new Set();
const unstampedMessages = launchMessages.filter(
(message) => launchErrorSurfaceStamp(message) === undefined,
);
const hiddenIds = new Set<string>();
if (launchErrorStamp) {
const stampedMatches = launchMessages.filter(
(message) => launchErrorSurfaceStamp(message) === launchErrorStamp,
);
stampedMatches.forEach((message) => hiddenIds.add(message.id));
}
const occurredAt = launchErrorOccurredAt ? Date.parse(launchErrorOccurredAt) : Number.NaN;
if (!Number.isNaN(occurredAt)) {
unstampedMessages.forEach((message) => {
const createdAt = Date.parse(message.created_at);
if (!Number.isNaN(createdAt) && createdAt >= occurredAt) hiddenIds.add(message.id);
});
}
if (hiddenIds.size > 0 || launchErrorStamp || launchErrorOccurredAt) return hiddenIds;
// Older synthetic rows do not carry the launch stamp. Keep historical rows
// intact and hide only the most recent row when no identity is available.
const fallbackMessage = launchMessages[launchMessages.length - 1];
return fallbackMessage ? new Set([fallbackMessage.id]) : new Set();
}
/** Remove the launch-only transcript decorations once the task card owns them. */
export function filterLaunchErrorMessages(
messages: Message[],
launchErrorOwned: boolean,
launchErrorStamp?: string,
launchErrorOccurredAt?: string,
): Message[] {
if (!launchErrorOwned) return messages;
const hiddenIds = launchErrorSurfaceMessageIds(messages, launchErrorStamp, launchErrorOccurredAt);
return messages.filter((message) => !hiddenIds.has(message.id));
}
/** Remove synthetic launch rows while preserving ordinary transcript activity. */
export function filterLaunchErrorItems(
items: RenderItem[],
launchErrorOwned: boolean,
launchErrorStamp?: string,
launchErrorOccurredAt?: string,
): RenderItem[] {
if (!launchErrorOwned) return items;
const hiddenMessageIds = launchErrorSurfaceMessageIds(
items.flatMap((item) => (item.type === "message" ? [item.message] : [])),
launchErrorStamp,
launchErrorOccurredAt,
);
return items.filter((item) => {
if (item.type === "prepare_progress") return false;
if (item.type === "agent_error_notice") {
return !launchErrorStamp || lastAgentErrorStamp(item.error) !== launchErrorStamp;
}
return item.type !== "message" || !hiddenMessageIds.has(item.message.id);
});
}
/** The active turn id, but only while the agent is working — turns no longer
* in progress aren't treated as active. */
export function getEffectiveActiveTurnId(
@@ -1,6 +1,7 @@
import { renderHook } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildStoppedBannerProps } from "./chat-input-container";
import { shouldHideChatInputForLaunchError, shouldRenderStoppedSessionBanner } from "./types";
import { useComposerProps } from "./use-composer-props";
function composerArgs(errorMessage: string) {
@@ -51,6 +52,20 @@ function composerArgs(errorMessage: string) {
}
describe("stopped-session error propagation", () => {
it("gives the task launch card ownership of a failed session", () => {
expect(
shouldRenderStoppedSessionBanner({
isFailed: true,
isCompleted: false,
executorUnavailable: false,
launchErrorOwned: true,
}),
).toBe(false);
expect(shouldHideChatInputForLaunchError({ isFailed: true, launchErrorOwned: true })).toBe(
true,
);
});
it("threads the sanitized session error from panel state into composer props", () => {
const errorMessage = "pods is forbidden: RBAC denied the request";
const { result } = renderHook(() => useComposerProps(composerArgs(errorMessage)));
+70 -1
View File
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vitest";
import { sessionId as toSessionId, taskId as toTaskId, type Message } from "@/lib/types/http";
import { isRichOutputMessage, kandevToolStemOf, type ToolCallMetadata } from "./types";
import {
isLaunchErrorSurfaceMessage,
isMatchingTaskLaunchError,
isTaskLaunchErrorOwnedBySession,
isRichOutputMessage,
kandevToolStemOf,
type ToolCallMetadata,
} from "./types";
function toolCall(rawName: string, field: "tool_name" | "title" | "content" = "title"): Message {
const metadata: Record<string, unknown> = {
@@ -65,3 +72,65 @@ describe("isRichOutputMessage", () => {
);
});
});
describe("task launch error presentation predicates", () => {
it("matches a summary error only by session and stamp", () => {
const activeError = { session_id: "session-1", stamp: "stamp-1" };
expect(
isMatchingTaskLaunchError(activeError, {
sessionId: "session-1",
errorStamp: "stamp-1",
}),
).toBe(true);
expect(
isMatchingTaskLaunchError(activeError, {
sessionId: "session-2",
errorStamp: "stamp-1",
}),
).toBe(false);
expect(
isMatchingTaskLaunchError(activeError, {
sessionId: "session-1",
errorStamp: "old-stamp",
}),
).toBe(false);
});
it("matches task-level errors only when the candidate has no session", () => {
const activeError = { stamp: "stamp-1" };
expect(isMatchingTaskLaunchError(activeError, { errorStamp: "stamp-1" })).toBe(true);
expect(
isMatchingTaskLaunchError(activeError, {
sessionId: "session-1",
errorStamp: "stamp-1",
}),
).toBe(false);
});
it("keeps a task-wide card visible without giving it ownership of a prior session", () => {
const activeError = { stamp: "stamp-1" };
expect(isTaskLaunchErrorOwnedBySession(activeError, null)).toBe(true);
expect(isTaskLaunchErrorOwnedBySession(activeError, undefined)).toBe(true);
expect(isTaskLaunchErrorOwnedBySession(activeError, "prior-session")).toBe(false);
});
it("gives a session-owned error ownership only of its exact session", () => {
const activeError = { session_id: "session-1", stamp: "stamp-1" };
expect(isTaskLaunchErrorOwnedBySession(activeError, "session-1")).toBe(true);
expect(isTaskLaunchErrorOwnedBySession(activeError, null)).toBe(false);
expect(isTaskLaunchErrorOwnedBySession(activeError, "session-2")).toBe(false);
});
it.each([
{ metadata: { empty_turn: true }, expected: true },
{ metadata: { failure_kind: "missing_pr_branch" }, expected: true },
{ metadata: { failure_kind: "provider_quota_limited" }, expected: false },
{ metadata: undefined, expected: false },
])("classifies launch-only message noise", ({ metadata, expected }) => {
expect(isLaunchErrorSurfaceMessage({ id: "message-1", metadata } as never)).toBe(expected);
});
});
+59
View File
@@ -1,6 +1,7 @@
"use client";
import type { Message } from "@/lib/types/http";
import type { TaskStatusSummaryActiveError } from "@/lib/types/task-status-summary";
import { extractKandevStem } from "./messages/kandev/parse";
export type SubagentTaskPayload = {
@@ -187,6 +188,64 @@ export function isSubagentMessage(message: Message): boolean {
return metadata?.normalized?.kind === "subagent_task";
}
export type TaskLaunchErrorIdentity = Pick<TaskStatusSummaryActiveError, "session_id" | "stamp">;
export function shouldRenderStoppedSessionBanner(input: {
isFailed: boolean;
isCompleted: boolean;
executorUnavailable: boolean;
launchErrorOwned?: boolean;
}): boolean {
return (
!input.launchErrorOwned && (input.isFailed || input.isCompleted || input.executorUnavailable)
);
}
export function shouldHideChatInputForLaunchError(input: {
isFailed: boolean;
launchErrorOwned?: boolean;
}): boolean {
return input.launchErrorOwned === true && input.isFailed;
}
/** Matches one rendered error surface to the task-owned launch error. */
export function isMatchingTaskLaunchError(
activeError: TaskLaunchErrorIdentity | null | undefined,
candidate: { sessionId?: string | null; errorStamp?: string | null },
): boolean {
if (!activeError?.stamp || !candidate.errorStamp) return false;
return (
(activeError.session_id ?? null) === (candidate.sessionId ?? null) &&
activeError.stamp === candidate.errorStamp
);
}
/** A task-wide launch error stays visible while any prior session is selected. */
export function isTaskLaunchErrorVisibleForSession(
activeError: TaskLaunchErrorIdentity | null | undefined,
sessionId: string | null | undefined,
): boolean {
if (!activeError?.stamp) return false;
if (sessionId === undefined || activeError.session_id == null) return true;
return activeError.session_id === sessionId;
}
/** Whether the active launch error owns the selected session's surfaces. */
export function isTaskLaunchErrorOwnedBySession(
activeError: TaskLaunchErrorIdentity | null | undefined,
sessionId: string | null | undefined,
): boolean {
if (!activeError?.stamp) return false;
if (activeError.session_id == null) return sessionId == null;
return sessionId != null && activeError.session_id === sessionId;
}
/** Messages that are only useful while a launch failure has no typed owner. */
export function isLaunchErrorSurfaceMessage(message: Message): boolean {
const metadata = message.metadata as Record<string, unknown> | undefined;
return metadata?.empty_turn === true || metadata?.failure_kind === "missing_pr_branch";
}
export type StatusMetadata = {
progress?: number;
status?: string;
@@ -16,6 +16,7 @@ type ComposerPropsArgs = {
handleSubmit: (payload: ChatSubmitPayload) => ChatSubmitResult;
handleCancelTurn: () => Promise<void>;
isSending: boolean;
launchErrorOwned?: boolean;
showRequestChangesTooltip: boolean;
onRequestChangesTooltipDismiss?: () => void;
onClarificationResolved: () => void;
@@ -41,6 +42,7 @@ export function useComposerProps(args: ComposerPropsArgs) {
handleSubmit,
handleCancelTurn,
isSending,
launchErrorOwned,
showRequestChangesTooltip,
onRequestChangesTooltipDismiss,
onClarificationResolved,
@@ -75,6 +77,7 @@ export function useComposerProps(args: ComposerPropsArgs) {
isPreparingEnvironment: panelState.isPreparingEnvironment,
isMoving,
isSending,
launchErrorOwned,
onCancel: handleCancelTurn,
placeholder,
pendingClarification: panelState.pendingClarification,