fix(web): replace completed session composer (#2734) (#2747)

This commit is contained in:
Carlos Florêncio
2026-08-17 21:22:02 +00:00
committed by GitHub
parent 1d42d0d95a
commit c38cec3044
19 changed files with 585 additions and 153 deletions
@@ -1,19 +1,14 @@
"use client";
import { forwardRef, useCallback, useState } from "react";
import { IconAlertTriangle, IconPlayerPlay, IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { NewSessionDialog } from "@/components/task/new-session-dialog";
import { useAppStore } from "@/components/state-provider";
import { forwardRef, useCallback } from "react";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { ClarificationRequestMetadata, Message } from "@/lib/types/http";
import type { DiffComment } from "@/lib/diff/types";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import type { MCPAttachmentHistory } from "@/lib/state/slices/session-runtime/types";
import type { EntityReference } from "@/lib/types/entity-reference";
import { getWebSocketClient } from "@/lib/ws/connection";
import { useChatInputContainer } from "./use-chat-input-container";
import { SessionStoppedBanner } from "./session-stopped-banner";
import {
ChatInputBody,
type ChatInputContextAreaProps,
@@ -24,7 +19,6 @@ import { useUtilityAgentGenerator } from "@/hooks/use-utility-agent-generator";
import { useIsUtilityConfigured } from "@/hooks/use-is-utility-configured";
import { usePromptResultDelivery } from "@/hooks/use-prompt-result-delivery";
import { PromptResultRecovery } from "@/components/prompt-result-recovery";
import { useTranslation } from "react-i18next";
import { t } from "@/lib/i18n";
// Re-export ImageAttachment type for consumers
@@ -98,6 +92,7 @@ type ChatInputContainerProps = {
submitKey?: "enter" | "cmd_enter";
hasAgentCommands?: boolean;
isFailed?: boolean;
isCompleted?: boolean;
needsRecovery?: boolean;
executorUnavailable?: boolean;
executorUnavailableReason?: string;
@@ -114,148 +109,10 @@ type ChatInputContainerProps = {
hidePlanMode?: boolean;
};
async function requestSessionRecover(
taskId: string,
sessionId: string,
action: "resume" | "fresh_start",
): Promise<boolean> {
const client = getWebSocketClient();
if (!client) return false;
try {
await client.request(
"session.recover",
{ task_id: taskId, session_id: sessionId, action },
30000,
);
return true;
} catch {
return false;
}
}
// The recovery banner keeps resume/fresh-start controls together for desktop
// and mobile layouts; its line count is intentionally bounded by that UI.
// eslint-disable-next-line max-lines-per-function
function FailedSessionBanner({
showDialog,
onShowDialog,
taskId,
sessionId,
workspaceId,
message,
detail,
resumeLabel,
resumingLabel,
}: {
showDialog: boolean;
onShowDialog: (open: boolean) => void;
taskId: string | null;
sessionId: string | null;
workspaceId?: string | null;
message?: string;
detail?: string;
resumeLabel?: string;
resumingLabel?: string;
}) {
const { t } = useTranslation();
// Resolved in the body, not as parameter defaults: those are evaluated before
// the component body, where `t` does not yet exist (docs/i18n.md).
const bannerMessage = message ?? t("task:agentHasStopped");
const resumeText = resumeLabel ?? t("task:resume");
const resumingText = resumingLabel ?? t("task:resuming");
const [isResuming, setIsResuming] = useState(false);
const [isStartingFresh, setIsStartingFresh] = useState(false);
const agentProfileId = useAppStore((s) =>
sessionId ? (s.taskSessions.items[sessionId]?.agent_profile_id ?? "") : "",
);
const profileExists = useAppStore(
(s) =>
agentProfileId !== "" &&
s.agentProfiles.items.some((p: { id: string }) => p.id === agentProfileId),
);
const handleRecover = useCallback(
async (action: "resume" | "fresh_start") => {
if (!sessionId || !taskId) return;
const setBusy = action === "resume" ? setIsResuming : setIsStartingFresh;
setBusy(true);
const ok = await requestSessionRecover(taskId, sessionId, action);
if (!ok) setBusy(false);
},
[sessionId, taskId],
);
const handleResume = useCallback(() => handleRecover("resume"), [handleRecover]);
const handleFreshStart = useCallback(() => {
if (!profileExists) {
onShowDialog(true);
return;
}
void handleRecover("fresh_start");
}, [profileExists, onShowDialog, handleRecover]);
return (
<>
<div className="rounded border border-border overflow-hidden">
<div className="flex items-center justify-between gap-3 px-4 py-3">
<div className="flex min-w-0 items-center gap-2 text-sm text-muted-foreground">
<IconAlertTriangle className="h-4 w-4 text-orange-500 shrink-0" />
<span className="truncate">{bannerMessage}</span>
{detail && <span className="shrink-0 text-xs text-muted-foreground">({detail})</span>}
</div>
<div className="flex items-center gap-2">
{sessionId && taskId && (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex" data-testid="failed-session-resume-wrapper">
<Button
variant="default"
size="sm"
data-testid="recovery-resume-button"
className="shrink-0 gap-1.5 cursor-pointer"
onClick={handleResume}
disabled={isResuming || !profileExists}
>
<IconPlayerPlay className="h-3.5 w-3.5" />
{isResuming ? resumingText : resumeText}
</Button>
</span>
</TooltipTrigger>
{!profileExists && (
<TooltipContent>{t("task:agentProfileNoLongerExists")}</TooltipContent>
)}
</Tooltip>
)}
<Button
variant="outline"
size="sm"
className="shrink-0 gap-1.5 cursor-pointer"
onClick={handleFreshStart}
disabled={isStartingFresh}
data-testid="recovery-fresh-button"
>
<IconRefresh className="h-3.5 w-3.5" />
{isStartingFresh ? t("task:starting") : t("task:startFreshSession")}
</Button>
</div>
</div>
</div>
{taskId && (
<NewSessionDialog
open={showDialog}
onOpenChange={onShowDialog}
taskId={taskId}
workspaceId={workspaceId}
/>
)}
</>
);
}
type ContainerState = ReturnType<typeof useChatInputContainer>;
type NormalizedChatInputProps = ChatInputContainerProps & {
isFailed: boolean;
isCompleted: boolean;
hasAgentCommands: boolean;
submitKey: "enter" | "cmd_enter";
planContextEnabled: boolean;
@@ -269,6 +126,7 @@ function normalizeChatInputProps(p: ChatInputContainerProps): NormalizedChatInpu
return {
...p,
isFailed: p.isFailed ?? false,
isCompleted: p.isCompleted ?? false,
hasAgentCommands: p.hasAgentCommands ?? false,
submitKey: p.submitKey ?? "cmd_enter",
planContextEnabled: p.planContextEnabled ?? false,
@@ -462,9 +320,10 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
taskDescription,
});
if (p.isFailed || executorUnavailable) {
if (p.isFailed || p.isCompleted || executorUnavailable) {
return (
<FailedSessionBanner
<SessionStoppedBanner
mode={p.isCompleted ? "completed" : "recoverable"}
showDialog={s.showNewSessionDialog}
onShowDialog={s.setShowNewSessionDialog}
taskId={taskId}
@@ -11,7 +11,7 @@ import { useTranslation } from "react-i18next";
* The extra gates mirror the composer's own send-availability signals: a
* session in recovery (needsRecovery — WAITING_FOR_INPUT with an error
* message) disables the editor, an unavailable executor environment
* replaces it with the FailedSessionBanner, and a pending clarification
* replaces it with the stopped-session banner, and a pending clarification
* routes every submission to the message queue (which only persists —
* it does not resume the stopped agent). In all three cases no message can
* be delivered to the agent, so promising that sending will start it would
@@ -0,0 +1,175 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useState } from "react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import type { SessionStoppedBannerProps } from "./session-stopped-banner";
const mocks = vi.hoisted(() => ({
request: vi.fn(),
agentProfiles: [{ id: "profile-1" }],
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
agentProfiles: { items: mocks.agentProfiles },
taskSessions: {
items: {
"session-1": { agent_profile_id: "profile-1" },
},
},
}),
}));
vi.mock("@/lib/ws/connection", () => ({
getWebSocketClient: () => ({ request: mocks.request }),
}));
vi.mock("@/components/task/new-session-dialog", () => ({
NewSessionDialog: ({
open,
taskId,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
taskId: string;
}) => (open ? <div data-testid="new-session-dialog">New agent dialog for {taskId}</div> : null),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) =>
({
"task:sessionCompleted": "This session is complete.",
"task:newAgent": "New Agent",
"task:agentHasStopped": "This agent has stopped.",
"task:resume": "Resume",
"task:resuming": "Resuming...",
"task:starting": "Starting...",
"task:startFreshSession": "Start fresh session",
"task:agentProfileNoLongerExists": "The agent profile no longer exists.",
})[key] ?? key,
}),
}));
import { SessionStoppedBanner } from "./session-stopped-banner";
const baseProps: Omit<SessionStoppedBannerProps, "mode" | "onShowDialog" | "showDialog"> = {
taskId: "task-1",
sessionId: "session-1",
workspaceId: "workspace-1",
};
function BannerHarness({
mode,
...overrides
}: Partial<SessionStoppedBannerProps> & { mode: "completed" | "recoverable" }) {
const [showDialog, setShowDialog] = useState(false);
return (
<TooltipProvider>
<SessionStoppedBanner
{...baseProps}
{...overrides}
mode={mode}
showDialog={showDialog}
onShowDialog={setShowDialog}
/>
</TooltipProvider>
);
}
beforeEach(() => {
mocks.request.mockReset().mockResolvedValue(undefined);
mocks.agentProfiles.splice(0, mocks.agentProfiles.length, { id: "profile-1" });
});
afterEach(cleanup);
describe("SessionStoppedBanner", () => {
it("offers only New Agent for a completed session and opens the new-session dialog", async () => {
render(<BannerHarness mode="completed" />);
expect(screen.getByTestId("completed-session-banner")).toBeTruthy();
expect(screen.getByText("This session is complete.")).toBeTruthy();
expect(screen.getByRole("button", { name: "New Agent" })).toBeTruthy();
expect(screen.queryByTestId("recovery-resume-button")).toBeNull();
expect(screen.queryByTestId("recovery-fresh-button")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "New Agent" }));
expect(await screen.findByTestId("new-session-dialog")).toBeTruthy();
expect(mocks.request).not.toHaveBeenCalled();
});
it("disables New Agent when no task is available", () => {
const onShowDialog = vi.fn();
render(
<TooltipProvider>
<SessionStoppedBanner
mode="completed"
showDialog={false}
onShowDialog={onShowDialog}
taskId={null}
sessionId={null}
/>
</TooltipProvider>,
);
const button = screen.getByRole("button", { name: "New Agent" }) as HTMLButtonElement;
expect(button.disabled).toBe(true);
fireEvent.click(button);
expect(onShowDialog).not.toHaveBeenCalled();
});
it("keeps resume and fresh-start recovery actions for a recoverable session", async () => {
render(<BannerHarness mode="recoverable" />);
fireEvent.click(screen.getByTestId("recovery-resume-button"));
await waitFor(() =>
expect(mocks.request).toHaveBeenCalledWith(
"session.recover",
{ task_id: "task-1", session_id: "session-1", action: "resume" },
30000,
),
);
fireEvent.click(screen.getByTestId("recovery-fresh-button"));
await waitFor(() =>
expect(mocks.request).toHaveBeenCalledWith(
"session.recover",
{ task_id: "task-1", session_id: "session-1", action: "fresh_start" },
30000,
),
);
});
it("opens the new-session dialog instead of recovering when the profile is missing", async () => {
mocks.agentProfiles.splice(0, mocks.agentProfiles.length);
render(<BannerHarness mode="recoverable" />);
expect(screen.getByTestId("recovery-resume-button").getAttribute("disabled")).not.toBeNull();
fireEvent.click(screen.getByTestId("recovery-fresh-button"));
expect(await screen.findByTestId("new-session-dialog")).toBeTruthy();
expect(mocks.request).not.toHaveBeenCalled();
});
it("preserves executor-unavailable recovery copy and controls", () => {
render(
<BannerHarness
mode="recoverable"
message="Executor environment is unavailable"
detail="Docker is offline"
resumeLabel="Restart"
resumingLabel="Restarting..."
/>,
);
expect(screen.getByText("Executor environment is unavailable")).toBeTruthy();
expect(screen.getByText("(Docker is offline)")).toBeTruthy();
expect(screen.getByRole("button", { name: "Restart" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Start fresh session" })).toBeTruthy();
});
});
@@ -0,0 +1,211 @@
"use client";
import { useCallback, useState } from "react";
import {
IconAlertTriangle,
IconCircleCheck,
IconPlayerPlay,
IconPlus,
IconRefresh,
} from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useTranslation } from "react-i18next";
import { NewSessionDialog } from "@/components/task/new-session-dialog";
import { useAppStore } from "@/components/state-provider";
import { getWebSocketClient } from "@/lib/ws/connection";
export type SessionStoppedBannerMode = "recoverable" | "completed";
export type SessionStoppedBannerProps = {
mode: SessionStoppedBannerMode;
showDialog: boolean;
onShowDialog: (open: boolean) => void;
taskId: string | null;
sessionId: string | null;
workspaceId?: string | null;
message?: string;
detail?: string;
resumeLabel?: string;
resumingLabel?: string;
};
async function requestSessionRecover(
taskId: string,
sessionId: string,
action: "resume" | "fresh_start",
): Promise<boolean> {
const client = getWebSocketClient();
if (!client) return false;
try {
await client.request(
"session.recover",
{ task_id: taskId, session_id: sessionId, action },
30000,
);
return true;
} catch {
return false;
}
}
function RecoverableSessionActions({
onShowDialog,
taskId,
sessionId,
resumeLabel,
resumingLabel,
}: Pick<
SessionStoppedBannerProps,
"onShowDialog" | "taskId" | "sessionId" | "resumeLabel" | "resumingLabel"
>) {
const { t } = useTranslation();
const resumeText = resumeLabel ?? t("task:resume");
const resumingText = resumingLabel ?? t("task:resuming");
const [isResuming, setIsResuming] = useState(false);
const [isStartingFresh, setIsStartingFresh] = useState(false);
const profileExists = useAppStore((s) => {
if (!sessionId) return false;
const agentProfileId = s.taskSessions.items[sessionId]?.agent_profile_id;
return (
!!agentProfileId && s.agentProfiles.items.some((p: { id: string }) => p.id === agentProfileId)
);
});
const handleRecover = useCallback(
async (action: "resume" | "fresh_start") => {
if (!sessionId || !taskId) return;
const setBusy = action === "resume" ? setIsResuming : setIsStartingFresh;
setBusy(true);
const ok = await requestSessionRecover(taskId, sessionId, action);
if (!ok) setBusy(false);
},
[sessionId, taskId],
);
const handleResume = useCallback(() => handleRecover("resume"), [handleRecover]);
const handleFreshStart = useCallback(() => {
if (!profileExists) {
onShowDialog(true);
return;
}
void handleRecover("fresh_start");
}, [profileExists, onShowDialog, handleRecover]);
return (
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
{sessionId && taskId && (
<Tooltip>
<TooltipTrigger asChild>
<span
className="inline-flex w-full sm:w-auto"
data-testid="failed-session-resume-wrapper"
>
<Button
variant="default"
size="sm"
data-testid="recovery-resume-button"
className="min-h-11 w-full shrink-0 gap-1.5 cursor-pointer sm:w-auto"
onClick={handleResume}
disabled={isResuming || !profileExists}
>
<IconPlayerPlay className="h-3.5 w-3.5" />
{isResuming ? resumingText : resumeText}
</Button>
</span>
</TooltipTrigger>
{!profileExists && (
<TooltipContent>{t("task:agentProfileNoLongerExists")}</TooltipContent>
)}
</Tooltip>
)}
<Button
variant="outline"
size="sm"
className="min-h-11 w-full shrink-0 gap-1.5 cursor-pointer sm:w-auto"
onClick={handleFreshStart}
disabled={isStartingFresh}
data-testid="recovery-fresh-button"
>
<IconRefresh className="h-3.5 w-3.5" />
{isStartingFresh ? t("task:starting") : t("task:startFreshSession")}
</Button>
</div>
);
}
export function SessionStoppedBanner({
mode,
showDialog,
onShowDialog,
taskId,
sessionId,
workspaceId,
message,
detail,
resumeLabel,
resumingLabel,
}: SessionStoppedBannerProps) {
const { t } = useTranslation();
const isCompleted = mode === "completed";
const bannerMessage = isCompleted
? t("task:sessionCompleted")
: (message ?? t("task:agentHasStopped"));
return (
<>
<div
data-testid={isCompleted ? "completed-session-banner" : "failed-session-banner"}
data-session-stopped-mode={mode}
className="overflow-hidden rounded border border-border"
>
<div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-1 items-start gap-2 text-sm text-muted-foreground">
{isCompleted ? (
<IconCircleCheck className="mt-0.5 h-4 w-4 shrink-0 text-green-500" />
) : (
<IconAlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-orange-500" />
)}
<span className="min-w-0 break-words">{bannerMessage}</span>
{detail && (
<span className="min-w-0 break-words text-xs text-muted-foreground">({detail})</span>
)}
</div>
{isCompleted ? (
<Button
variant="default"
size="sm"
data-testid="completed-session-new-agent-button"
className="min-h-11 w-full shrink-0 gap-1.5 cursor-pointer sm:w-auto"
onClick={() => {
if (taskId) onShowDialog(true);
}}
disabled={!taskId}
>
<IconPlus className="h-3.5 w-3.5" />
{t("task:newAgent")}
</Button>
) : (
<RecoverableSessionActions
onShowDialog={onShowDialog}
taskId={taskId}
sessionId={sessionId}
resumeLabel={resumeLabel}
resumingLabel={resumingLabel}
/>
)}
</div>
</div>
{taskId && (
<NewSessionDialog
open={showDialog}
onOpenChange={onShowDialog}
taskId={taskId}
workspaceId={workspaceId}
/>
)}
</>
);
}
@@ -86,6 +86,7 @@ export function useComposerProps(args: ComposerPropsArgs) {
submitKey: panelState.chatSubmitKey,
hasAgentCommands: !!(panelState.agentCommands && panelState.agentCommands.length > 0),
isFailed: panelState.isFailed,
isCompleted: panelState.isCompleted,
needsRecovery,
executorUnavailable: executor.unavailable,
executorUnavailableReason: executor.reason,
@@ -88,6 +88,7 @@ export function PassthroughComposerPanel({
mcpAttachmentHistory={panelState.mcpAttachmentHistory}
onPlanModeChange={panelState.handlePlanModeChange}
isAgentBusy={false}
isCompleted={panelState.isCompleted}
isStarting={panelState.isStarting}
isPreparingEnvironment={panelState.isPreparingEnvironment}
isMoving={isMoving}
@@ -166,6 +166,7 @@ vi.mock("./chat/use-chat-panel-state", () => ({
taskId: TASK_ID,
task: { id: TASK_ID, title: "Task title" },
taskDescription: "Task description",
isCompleted: mockSessionState === "COMPLETED",
planModeEnabled: mockPlanModeEnabled,
planModeAvailable: true,
mcpServers: ["kandev"],
@@ -461,6 +462,23 @@ describe("PassthroughToolbar – composer toggle", () => {
});
});
// ---------------------------------------------------------------------------
// Completed session state
// ---------------------------------------------------------------------------
describe("PassthroughToolbar – completed session", () => {
beforeEach(resetMocks);
afterEach(cleanup);
it("passes completed session state to the passthrough composer", async () => {
mockSessionState = "COMPLETED";
renderToolbar();
await openComposer();
expect(latestChatInputProps().isCompleted).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Implement plan handler
// ---------------------------------------------------------------------------
+10
View File
@@ -628,6 +628,16 @@ export class SessionPage {
return this.page.getByTestId("recovery-fresh-button");
}
/** Terminal-state banner shown when the active session has completed. */
completedSessionBanner(): Locator {
return this.activeChat().getByTestId("completed-session-banner");
}
/** "New Agent" action shown for a completed session. */
completedSessionNewAgentButton(): Locator {
return this.completedSessionBanner().getByTestId("completed-session-new-agent-button");
}
/** "Cancel" button shown on the yellow transient-retry (529 Overloaded) card. */
recoveryCancelRetryButton(): Locator {
return this.page.getByTestId("recovery-cancel-retry-button");
@@ -1,4 +1,5 @@
import { test, expect } from "../../fixtures/test-base";
import { waitForSessionDone } from "../../helpers/session";
import { SessionPage } from "../../pages/session-page";
const DONE_STATES = ["COMPLETED", "WAITING_FOR_INPUT"];
@@ -15,6 +16,87 @@ test.describe("New session dialog on mobile", () => {
}
});
test("opens New Agent from a completed session without horizontal overflow", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Mobile Completed Session New Agent Task",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
await waitForSessionDone(apiClient, task.id, task.session_id, "Waiting for first session");
await apiClient.seedTaskSession(task.id, {
state: "COMPLETED",
sessionId: task.session_id,
agentProfileId: seedData.agentProfileId,
completedAt: new Date().toISOString(),
});
await expect
.poll(async () => {
const { sessions } = await apiClient.listTaskSessions(task.id);
return sessions.find((session) => session.id === task.session_id)?.state;
})
.toBe("COMPLETED");
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
const banner = session.completedSessionBanner();
const newAgent = session.completedSessionNewAgentButton();
await expect(banner).toBeVisible({ timeout: 15_000 });
await expect(session.activeChat().locator(".tiptap.ProseMirror")).not.toBeVisible();
const [bannerBox, buttonBox] = await Promise.all([
banner.boundingBox(),
newAgent.boundingBox(),
]);
const viewport = testPage.viewportSize();
expect(bannerBox).not.toBeNull();
expect(buttonBox).not.toBeNull();
expect(viewport).not.toBeNull();
expect(buttonBox!.height).toBeGreaterThanOrEqual(44);
expect(buttonBox!.x).toBeGreaterThanOrEqual(bannerBox!.x);
expect(buttonBox!.x + buttonBox!.width).toBeLessThanOrEqual(bannerBox!.x + bannerBox!.width);
expect(buttonBox!.x + buttonBox!.width).toBeLessThanOrEqual(viewport!.width);
expect(
await testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
).toBe(true);
await newAgent.tap();
await expect(session.newSessionDialog()).toBeVisible({ timeout: 5_000 });
const dialogBox = await session.sessionLaunchDialog().boundingBox();
expect(dialogBox).not.toBeNull();
expect(dialogBox!.x).toBeGreaterThanOrEqual(0);
expect(dialogBox!.y).toBeGreaterThanOrEqual(0);
expect(dialogBox!.x + dialogBox!.width).toBeLessThanOrEqual(viewport!.width);
expect(dialogBox!.y + dialogBox!.height).toBeLessThanOrEqual(viewport!.height);
await session.newSessionPromptInput().fill("/e2e:simple-message");
await session.newSessionStartButton().tap();
await expect(session.newSessionDialog()).not.toBeVisible({ timeout: 10_000 });
await expect
.poll(async () => (await apiClient.listTaskSessions(task.id)).sessions.length, {
timeout: 30_000,
})
.toBe(2);
});
test("selects a saved prompt and launches from the mobile session controls", async ({
testPage,
apiClient,
@@ -4,7 +4,7 @@ import { openTaskSession } from "../../helpers/session";
/**
* Stop the running session via the tab context menu (session.stop → CANCELLED state),
* then wait for the FailedSessionBanner to appear.
* then wait for the recoverable session banner to appear.
*
* Note: clicking the cancel-agent-button sends `agent.cancel` which only cancels
* the current turn and transitions to WAITING_FOR_INPUT (not CANCELLED/FAILED).
@@ -19,7 +19,7 @@ async function stopRunningSession(session: SessionPage) {
await session.rightClickFirstSessionTab();
await session.contextMenuItem("Stop").click();
// Wait for the FailedSessionBanner's resume button to appear (isFailed = FAILED | CANCELLED)
// Wait for the recoverable banner's resume button to appear (isFailed = FAILED | CANCELLED)
await expect(session.recoveryResumeButton()).toBeVisible({ timeout: 30_000 });
}
@@ -113,7 +113,7 @@ test.describe("New session with deleted agent profile", () => {
// 5. Wait for the resume button to become disabled (confirms store updated)
await expect(session.recoveryResumeButton()).toBeDisabled({ timeout: 10_000 });
// 6. Click "Start fresh session" in the FailedSessionBanner — when the
// 6. Click "Start fresh session" in the recoverable banner. When the
// profile is missing this opens the new session dialog instead of
// triggering an immediate fresh_start recover.
await session.recoveryFreshButton().click();
@@ -1,4 +1,5 @@
import { test, expect } from "../../fixtures/test-base";
import { waitForSessionDone } from "../../helpers/session";
import { KanbanPage } from "../../pages/kanban-page";
import { SessionPage } from "../../pages/session-page";
@@ -21,6 +22,65 @@ test.describe("New session dialog", () => {
}
});
test("completed sessions replace the composer with a New Agent action", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Completed Session New Agent Task",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
await waitForSessionDone(apiClient, task.id, task.session_id, "Waiting for first session");
await apiClient.seedTaskSession(task.id, {
state: "COMPLETED",
sessionId: task.session_id,
agentProfileId: seedData.agentProfileId,
completedAt: new Date().toISOString(),
});
await expect
.poll(async () => {
const { sessions } = await apiClient.listTaskSessions(task.id);
return sessions.find((session) => session.id === task.session_id)?.state;
})
.toBe("COMPLETED");
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await expect(session.completedSessionBanner()).toBeVisible({ timeout: 15_000 });
await expect(session.completedSessionNewAgentButton()).toHaveText("New Agent");
await expect(session.activeChat().locator(".tiptap.ProseMirror")).not.toBeVisible();
await expect(session.submitButton()).not.toBeVisible();
await expect(session.recoveryResumeButton()).not.toBeVisible();
await expect(session.recoveryFreshButton()).not.toBeVisible();
await session.completedSessionNewAgentButton().click();
await expect(session.newSessionDialog()).toBeVisible({ timeout: 5_000 });
await session.newSessionPromptInput().fill("/e2e:simple-message");
await session.newSessionStartButton().click();
await expect(session.newSessionDialog()).not.toBeVisible({ timeout: 10_000 });
await expect
.poll(async () => (await apiClient.listTaskSessions(task.id)).sessions.length, {
timeout: 30_000,
})
.toBe(2);
await expect(session.sessionTabByText("2")).toBeVisible({ timeout: 15_000 });
});
test("opens dialog from + menu and shows environment info", async ({
testPage,
apiClient,
@@ -293,4 +293,11 @@ describe("deriveSessionFlags — supportsSteering", () => {
it("is false for RUNNING + background without the capability", () => {
expect(deriveSessionFlags(running("background", false)).supportsSteering).toBe(false);
});
it("marks completed sessions as terminal without treating them as failed", () => {
const flags = deriveSessionFlags(createMockSession("session-1", "task-1", "COMPLETED"));
expect(flags.isCompleted).toBe(true);
expect(flags.isFailed).toBe(false);
});
});
@@ -29,6 +29,7 @@ export function deriveSessionFlags(session: TaskSession | null | undefined) {
// background-idle) plus STARTING — it must stay up through (b).
const isWorking = isStarting || isRunning || hasBackgroundWork;
const isFailed = state === "FAILED" || state === "CANCELLED";
const isCompleted = state === "COMPLETED";
const needsRecovery = state === "WAITING_FOR_INPUT" && !!errorMessage;
return {
inputMode,
@@ -37,6 +38,7 @@ export function deriveSessionFlags(session: TaskSession | null | undefined) {
isAgentBusy,
supportsSteering,
isFailed,
isCompleted,
needsRecovery,
};
}
+1
View File
@@ -1600,6 +1600,7 @@
"sessionActionSetPrimary": "Set primary",
"sessionActionStop": "Stopping session",
"sessionActionSuccessful": "{{action}} successful",
"sessionCompleted": "This session is complete.",
"composerPlaceholderRecovery": "Choose a recovery option above to continue...",
"composerPlaceholderClarification": "Queue instructions while the question is pending...",
"composerPlaceholderBusy": "Queue instructions to the agent...",
+1
View File
@@ -1600,6 +1600,7 @@
"sessionActionSetPrimary": "Śēţ ƥŕĩḿàŕŷ",
"sessionActionStop": "Śţōƥƥĩńĝ śēśśĩōń",
"sessionActionSuccessful": "{{action}} śũććēśśƒũĺ",
"sessionCompleted": "Ţĥĩś śēśśĩōń ĩś ćōḿƥĺēţē.",
"composerPlaceholderRecovery": "Ćĥōōśē à ŕēćōvēŕŷ ōƥţĩōń àƀōvē ţō ćōńţĩńũē...",
"composerPlaceholderClarification": "Qũēũē ĩńśţŕũćţĩōńś ŵĥĩĺē ţĥē qũēśţĩōń ĩś ƥēńďĩńĝ...",
"composerPlaceholderBusy": "Qũēũē ĩńśţŕũćţĩōńś ţō ţĥē àĝēńţ...",
+1
View File
@@ -1563,6 +1563,7 @@
"sessionActionSetPrimary": "Definir como principal",
"sessionActionStop": "A parar sessão",
"sessionActionSuccessful": "{{action}} concluído",
"sessionCompleted": "Esta sessão está concluída.",
"advancedSettings": "Definições avançadas",
"agentHasStopped": "Este agente parou.",
"agentResponseChangedSelectAgain": "A resposta do agente mudou. Selecione o texto novamente.",
+1
View File
@@ -1563,6 +1563,7 @@
"sessionActionSetPrimary": "设为主要会话",
"sessionActionStop": "停止会话中",
"sessionActionSuccessful": "{{action}}成功",
"sessionCompleted": "此会话已完成。",
"advancedSettings": "高级设置",
"agentHasStopped": "该智能体已停止。",
"agentResponseChangedSelectAgain": "智能体的回复已变化。请重新选择文本。",
+1
View File
@@ -1563,6 +1563,7 @@
"sessionActionSetPrimary": "設為主要工作階段",
"sessionActionStop": "停止工作階段中",
"sessionActionSuccessful": "{{action}}成功",
"sessionCompleted": "此工作階段已完成。",
"advancedSettings": "高級設定",
"agentHasStopped": "該代理程式已停止。",
"agentResponseChangedSelectAgain": "代理程式的回覆已變化。請重新選擇文字。",
+1
View File
@@ -1563,6 +1563,7 @@
"sessionActionSetPrimary": "設為主要工作階段",
"sessionActionStop": "停止工作階段中",
"sessionActionSuccessful": "{{action}}成功",
"sessionCompleted": "此工作階段已完成。",
"advancedSettings": "進階設定",
"agentHasStopped": "該代理程式已停止。",
"agentResponseChangedSelectAgain": "代理程式的回覆已變化。請重新選擇文字。",