feat(web): add a Plan tab to the kanban preview panel (#3314)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { PanelLoadingState } from "@/components/panel-loading-state";
|
||||
import { getTaskPlan } from "@/lib/api/domains/plan-api";
|
||||
import { PlanReadOnlyMarkdown } from "@/components/editors/tiptap/tiptap-plan-readonly";
|
||||
import type { TaskPlan } from "@/lib/types/http-agents";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/**
|
||||
* Fetches and reads the task plan for the kanban preview panel without
|
||||
* marking it seen. Mirrors `LazyPlanPreview`'s lazy-load path rather than
|
||||
* `useTaskPlan`, whose initial fetch marks the plan seen by design — that
|
||||
* would clear the Plan tab's unseen indicator before the user ever looks.
|
||||
*
|
||||
* `failed` is local component state (not the shared store) so a rejected
|
||||
* fetch stops the effect instead of retrying every render. A reconnect or
|
||||
* explicit retry clears the error and lets the effect fetch again. Call this
|
||||
* once per preview panel —
|
||||
* `usePreviewPlanTab` owns it and passes the result down to
|
||||
* `PreviewPlanPanel` — a second mount would duplicate the fetch.
|
||||
*/
|
||||
export function usePreviewPlanSummary(taskId: string) {
|
||||
const plan = useAppStore((state) => state.taskPlans.byTaskId[taskId] ?? null);
|
||||
const loaded = useAppStore((state) => state.taskPlans.loadedByTaskId[taskId] ?? false);
|
||||
const loading = useAppStore((state) => state.taskPlans.loadingByTaskId[taskId] ?? false);
|
||||
const connectionStatus = useAppStore((state) => state.connection.status);
|
||||
const storeApi = useAppStoreApi();
|
||||
const [failedTaskId, setFailedTaskId] = useState<string | null>(null);
|
||||
const failed = failedTaskId === taskId;
|
||||
const retry = useCallback(() => {
|
||||
setFailedTaskId((current) => (current === taskId ? null : current));
|
||||
}, [taskId]);
|
||||
const previousConnectionStatus = useRef(connectionStatus);
|
||||
|
||||
useEffect(() => {
|
||||
const reconnected =
|
||||
previousConnectionStatus.current !== "connected" && connectionStatus === "connected";
|
||||
previousConnectionStatus.current = connectionStatus;
|
||||
if (reconnected) retry();
|
||||
}, [connectionStatus, retry]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loaded && failedTaskId === taskId) setFailedTaskId(null);
|
||||
}, [failedTaskId, loaded, taskId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (connectionStatus !== "connected" || failed) return;
|
||||
const currentPlanState = storeApi.getState().taskPlans;
|
||||
if (currentPlanState.loadedByTaskId[taskId] || currentPlanState.loadingByTaskId[taskId]) return;
|
||||
const { setTaskPlanLoading } = storeApi.getState();
|
||||
setTaskPlanLoading(taskId, true);
|
||||
getTaskPlan(taskId)
|
||||
.then((result) => {
|
||||
// Race guard: a WS `task.plan.created`/`task.plan.updated`/
|
||||
// `task.plan.deleted` push can land in the store while this WebSocket
|
||||
// request is in flight. `loadedByTaskId` (not `byTaskId` truthiness)
|
||||
// tells us whether the store already holds an authoritative entry —
|
||||
// a deleted plan is stored as `null` on purpose, and that tombstone
|
||||
// is a real entry, not "nothing arrived yet". Once an entry exists,
|
||||
// only ever move forward in time: never resurrect a tombstone, and
|
||||
// never replace a real plan with `null` or an older version.
|
||||
const state = storeApi.getState();
|
||||
const hasLiveEntry = state.taskPlans.loadedByTaskId[taskId] ?? false;
|
||||
const live = state.taskPlans.byTaskId[taskId] ?? null;
|
||||
if (hasLiveEntry) {
|
||||
if (live === null) return;
|
||||
if (result === null) return;
|
||||
if (Date.parse(result.updated_at) < Date.parse(live.updated_at)) return;
|
||||
}
|
||||
storeApi.getState().setTaskPlan(taskId, result);
|
||||
})
|
||||
.catch(() => {
|
||||
setFailedTaskId(taskId);
|
||||
})
|
||||
.finally(() => {
|
||||
storeApi.getState().setTaskPlanLoading(taskId, false);
|
||||
});
|
||||
}, [connectionStatus, failed, storeApi, taskId]);
|
||||
|
||||
return { plan, loaded, loading, failed: failed && !loaded, retry };
|
||||
}
|
||||
|
||||
type PreviewPlanPanelProps = {
|
||||
plan: TaskPlan | null;
|
||||
loaded: boolean;
|
||||
loading: boolean;
|
||||
failed: boolean;
|
||||
onRetry: () => void;
|
||||
};
|
||||
|
||||
/** Read-only plan render for the kanban preview panel's Plan tab. */
|
||||
export function PreviewPlanPanel({
|
||||
plan,
|
||||
loaded,
|
||||
loading,
|
||||
failed,
|
||||
onRetry,
|
||||
}: PreviewPlanPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (failed) {
|
||||
return (
|
||||
<div
|
||||
className="flex h-full flex-col items-center justify-center gap-3 text-sm text-muted-foreground"
|
||||
data-testid="preview-plan-error-state"
|
||||
>
|
||||
<span>{t("task:planLoadError")}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 min-w-11 cursor-pointer [@media(pointer:fine)]:min-h-0 [@media(pointer:fine)]:min-w-0"
|
||||
onClick={onRetry}
|
||||
data-testid="preview-plan-retry"
|
||||
>
|
||||
{t("task:retry")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading || !loaded) {
|
||||
return <PanelLoadingState testId="preview-plan-loading-state" label={t("task:loadingPlan")} />;
|
||||
}
|
||||
|
||||
if (!plan?.content) {
|
||||
return (
|
||||
<div
|
||||
className="flex h-full items-center justify-center text-sm text-muted-foreground"
|
||||
data-testid="preview-plan-empty-state"
|
||||
>
|
||||
{t("task:planIsEmpty")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full min-h-0 overflow-y-auto p-4" data-testid="preview-plan-panel">
|
||||
<PlanReadOnlyMarkdown content={plan.content} testId="preview-plan-content" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,29 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
renderHook,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { createStore } from "zustand/vanilla";
|
||||
import { useStore } from "zustand";
|
||||
import { sessionId as toSessionId, taskId as toTaskId, type TaskSession } from "@/lib/types/http";
|
||||
import type { TaskPlan } from "@/lib/types/http-agents";
|
||||
import type { ChatSubmitPayload } from "./chat/chat-input-container";
|
||||
import type { EntityReference } from "@/lib/types/entity-reference";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getWebSocketClient: vi.fn(),
|
||||
onSend: null as null | ((payload: ChatSubmitPayload) => Promise<void>),
|
||||
useTaskSessions: vi.fn(),
|
||||
useSessionResumption: vi.fn(),
|
||||
markTaskPlanSeen: vi.fn(),
|
||||
setTaskPlan: vi.fn(),
|
||||
setTaskPlanLoading: vi.fn(),
|
||||
getTaskPlan: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/ws/connection", () => ({
|
||||
@@ -18,15 +35,112 @@ vi.mock("./task-chat-panel", () => ({
|
||||
return <div data-testid="preview-chat" />;
|
||||
},
|
||||
}));
|
||||
vi.mock("@/hooks/use-task-sessions", () => ({
|
||||
useTaskSessions: mocks.useTaskSessions,
|
||||
}));
|
||||
vi.mock("@/hooks/domains/session/use-session-resumption", () => ({
|
||||
useSessionResumption: mocks.useSessionResumption,
|
||||
}));
|
||||
vi.mock("@/lib/api/domains/plan-api", () => ({
|
||||
getTaskPlan: mocks.getTaskPlan,
|
||||
}));
|
||||
vi.mock("@/components/editors/tiptap/tiptap-plan-readonly", () => ({
|
||||
PlanReadOnlyMarkdown: (props: { content: string; testId?: string }) => (
|
||||
<div data-testid={props.testId}>{props.content}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
import { PreviewSessionBody } from "./preview-session-tabs";
|
||||
type TaskPlansState = {
|
||||
byTaskId: Record<string, TaskPlan | null>;
|
||||
loadedByTaskId: Record<string, boolean>;
|
||||
loadingByTaskId: Record<string, boolean>;
|
||||
lastSeenUpdatedAtByTaskId: Record<string, string | undefined>;
|
||||
};
|
||||
|
||||
type FakeAppState = {
|
||||
agentProfiles: { items: never[] };
|
||||
connection: { status: "connected" | "disconnected" };
|
||||
taskPlans: TaskPlansState;
|
||||
markTaskPlanSeen: (taskId: string) => void;
|
||||
setTaskPlan: (taskId: string, plan: TaskPlan | null) => void;
|
||||
setTaskPlanLoading: (taskId: string, loading: boolean) => void;
|
||||
};
|
||||
|
||||
function emptyTaskPlans(): TaskPlansState {
|
||||
return { byTaskId: {}, loadedByTaskId: {}, loadingByTaskId: {}, lastSeenUpdatedAtByTaskId: {} };
|
||||
}
|
||||
|
||||
// A real (non-static) store double: production code drives loading/loaded
|
||||
// state through these actions, and components re-render on real state
|
||||
// changes, exactly like the app's actual Zustand store. This is required to
|
||||
// exercise effect-retrigger regressions (F1/F2) that a frozen mock object
|
||||
// cannot reproduce.
|
||||
const fakeStore = createStore<FakeAppState>()((set, get) => ({
|
||||
agentProfiles: { items: [] },
|
||||
connection: { status: "connected" },
|
||||
taskPlans: emptyTaskPlans(),
|
||||
markTaskPlanSeen: (taskId: string) => {
|
||||
mocks.markTaskPlanSeen(taskId);
|
||||
const plan = get().taskPlans.byTaskId[taskId];
|
||||
set((state) => ({
|
||||
taskPlans: {
|
||||
...state.taskPlans,
|
||||
lastSeenUpdatedAtByTaskId: {
|
||||
...state.taskPlans.lastSeenUpdatedAtByTaskId,
|
||||
[taskId]: plan?.updated_at ?? "",
|
||||
},
|
||||
},
|
||||
}));
|
||||
},
|
||||
setTaskPlan: (taskId: string, plan: TaskPlan | null) => {
|
||||
mocks.setTaskPlan(taskId, plan);
|
||||
set((state) => ({
|
||||
taskPlans: {
|
||||
...state.taskPlans,
|
||||
byTaskId: { ...state.taskPlans.byTaskId, [taskId]: plan },
|
||||
loadingByTaskId: { ...state.taskPlans.loadingByTaskId, [taskId]: false },
|
||||
loadedByTaskId: { ...state.taskPlans.loadedByTaskId, [taskId]: true },
|
||||
},
|
||||
}));
|
||||
},
|
||||
setTaskPlanLoading: (taskId: string, loading: boolean) => {
|
||||
mocks.setTaskPlanLoading(taskId, loading);
|
||||
set((state) => ({
|
||||
taskPlans: {
|
||||
...state.taskPlans,
|
||||
loadingByTaskId: { ...state.taskPlans.loadingByTaskId, [taskId]: loading },
|
||||
},
|
||||
}));
|
||||
},
|
||||
}));
|
||||
|
||||
function setTaskPlansState(patch: Partial<TaskPlansState>) {
|
||||
fakeStore.setState((state) => ({ taskPlans: { ...state.taskPlans, ...patch } }));
|
||||
}
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (state: FakeAppState) => unknown) => useStore(fakeStore, selector),
|
||||
useAppStoreApi: () => fakeStore,
|
||||
}));
|
||||
|
||||
import { PreviewSessionBody, PreviewSessionTabs } from "./preview-session-tabs";
|
||||
import { usePreviewPlanSummary } from "./preview-plan-panel";
|
||||
|
||||
const TASK_ID = "task-1";
|
||||
const TASK_ID_B = "task-2";
|
||||
const TIMESTAMP = "2026-07-21T00:00:00Z";
|
||||
const LATER_TIMESTAMP = "2026-07-22T00:00:00Z";
|
||||
const PLAN_INDICATOR_TESTID = "preview-plan-tab-indicator";
|
||||
const PLAN_TAB_TESTID = "preview-plan-tab";
|
||||
const PLAN_PANEL_TESTID = "preview-plan-panel";
|
||||
const PLAN_ERROR_TESTID = "preview-plan-error-state";
|
||||
|
||||
const session: TaskSession = {
|
||||
id: toSessionId("session-1"),
|
||||
task_id: toTaskId("task-1"),
|
||||
task_id: toTaskId(TASK_ID),
|
||||
state: "COMPLETED",
|
||||
started_at: "2026-07-21T00:00:00Z",
|
||||
updated_at: "2026-07-21T00:00:00Z",
|
||||
started_at: TIMESTAMP,
|
||||
updated_at: TIMESTAMP,
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
@@ -38,7 +152,7 @@ afterEach(() => {
|
||||
describe("PreviewSessionBody send failures", () => {
|
||||
it("rejects when the WebSocket client is unavailable", async () => {
|
||||
mocks.getWebSocketClient.mockReturnValue(null);
|
||||
render(<PreviewSessionBody session={session} taskId="task-1" />);
|
||||
render(<PreviewSessionBody session={session} taskId={TASK_ID} />);
|
||||
|
||||
await expect(mocks.onSend?.({ message: "hello" })).rejects.toMatchObject({
|
||||
name: "MessageSendError",
|
||||
@@ -50,7 +164,7 @@ describe("PreviewSessionBody send failures", () => {
|
||||
it("rethrows message.add failures to the chat input", async () => {
|
||||
const error = new Error("message.add failed");
|
||||
mocks.getWebSocketClient.mockReturnValue({ request: vi.fn().mockRejectedValue(error) });
|
||||
render(<PreviewSessionBody session={session} taskId="task-1" />);
|
||||
render(<PreviewSessionBody session={session} taskId={TASK_ID} />);
|
||||
|
||||
await expect(mocks.onSend?.({ message: "hello" })).rejects.toBe(error);
|
||||
});
|
||||
@@ -69,7 +183,7 @@ describe("PreviewSessionBody send failures", () => {
|
||||
url: "https://github.com/acme/repo/issues/42",
|
||||
scope: "acme/repo",
|
||||
};
|
||||
render(<PreviewSessionBody session={session} taskId="task-1" />);
|
||||
render(<PreviewSessionBody session={session} taskId={TASK_ID} />);
|
||||
|
||||
await mocks.onSend?.({
|
||||
message: "reference",
|
||||
@@ -80,7 +194,7 @@ describe("PreviewSessionBody send failures", () => {
|
||||
expect(request).toHaveBeenCalledWith(
|
||||
"message.add",
|
||||
{
|
||||
task_id: "task-1",
|
||||
task_id: TASK_ID,
|
||||
session_id: "session-1",
|
||||
client_message_id: expect.any(String),
|
||||
content: "reference",
|
||||
@@ -91,3 +205,498 @@ describe("PreviewSessionBody send failures", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function agentPlan(overrides: Partial<TaskPlan> = {}): TaskPlan {
|
||||
return {
|
||||
id: "plan-1",
|
||||
task_id: TASK_ID,
|
||||
title: "Plan",
|
||||
content: "## Plan content",
|
||||
created_by: "agent",
|
||||
created_at: TIMESTAMP,
|
||||
updated_at: TIMESTAMP,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("PreviewSessionTabs Plan tab", () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true });
|
||||
mocks.useSessionResumption.mockReturnValue({
|
||||
error: null,
|
||||
notice: null,
|
||||
resumeSession: vi.fn(),
|
||||
});
|
||||
mocks.getTaskPlan.mockResolvedValue(null);
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.useTaskSessions.mockReset();
|
||||
mocks.useSessionResumption.mockReset();
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
mocks.getTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("shows a Plan tab alongside session tabs", () => {
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.getByTestId(PLAN_TAB_TESTID)).toBeTruthy();
|
||||
expect(screen.getByTestId(`preview-session-tab-${session.id}`)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clicking the Plan tab swaps the chat body for the read-only plan and does not change the session", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
const onSessionChange = vi.fn();
|
||||
|
||||
render(
|
||||
<PreviewSessionTabs taskId={TASK_ID} sessionId={null} onSessionChange={onSessionChange} />,
|
||||
);
|
||||
expect(screen.getByTestId("preview-chat")).toBeTruthy();
|
||||
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
expect(screen.queryByTestId("preview-chat")).toBeNull();
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
expect(screen.getByText("## Plan content")).toBeTruthy();
|
||||
expect(onSessionChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the unseen indicator for an agent-authored plan the user hasn't seen", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.getByTestId(PLAN_INDICATOR_TESTID)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not show the indicator for a user-authored plan", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan({ created_by: "user" }) },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not show the indicator once the plan's updated_at has been seen", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
lastSeenUpdatedAtByTaskId: { [TASK_ID]: TIMESTAMP },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the Plan tab and renders the plan when the task has no sessions", () => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [], isLoaded: true });
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.getByTestId(PLAN_TAB_TESTID)).toBeTruthy();
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
expect(screen.queryByTestId("preview-empty-state")).toBeNull();
|
||||
expect(mocks.markTaskPlanSeen).toHaveBeenCalledWith(TASK_ID);
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("uses a touch-sized tab list for coarse-pointer previews", () => {
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
const list = screen
|
||||
.getByTestId("preview-session-tabs")
|
||||
.querySelector('[data-slot="tabs-list"]');
|
||||
expect(list).not.toBeNull();
|
||||
expect(list?.className).toContain("[@media(pointer:coarse)]:!h-11");
|
||||
});
|
||||
|
||||
it("clears the indicator (marks seen) when the Plan tab is clicked", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
expect(screen.getByTestId(PLAN_INDICATOR_TESTID)).toBeTruthy();
|
||||
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
expect(mocks.markTaskPlanSeen).toHaveBeenCalledWith(TASK_ID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewSessionTabs Plan tab session loading", () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [], isLoaded: false });
|
||||
mocks.useSessionResumption.mockReturnValue({
|
||||
error: null,
|
||||
notice: null,
|
||||
resumeSession: vi.fn(),
|
||||
});
|
||||
mocks.getTaskPlan.mockResolvedValue(null);
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.useTaskSessions.mockReset();
|
||||
mocks.useSessionResumption.mockReset();
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
mocks.getTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("does not mark a plan seen while the session list is still loading", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: agentPlan() },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
});
|
||||
|
||||
const { rerender } = render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(mocks.markTaskPlanSeen).not.toHaveBeenCalled();
|
||||
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true });
|
||||
rerender(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
|
||||
expect(screen.getByTestId(PLAN_INDICATOR_TESTID)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewSessionTabs Plan tab reliability", () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true });
|
||||
mocks.useSessionResumption.mockReturnValue({
|
||||
error: null,
|
||||
notice: null,
|
||||
resumeSession: vi.fn(),
|
||||
});
|
||||
mocks.getTaskPlan.mockResolvedValue(null);
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.useTaskSessions.mockReset();
|
||||
mocks.useSessionResumption.mockReset();
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
mocks.getTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("stops retrying the plan fetch after it rejects and shows an error state", async () => {
|
||||
mocks.getTaskPlan.mockRejectedValue(new Error("boom"));
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_ERROR_TESTID)).toBeTruthy();
|
||||
});
|
||||
expect(mocks.getTaskPlan).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A retry-loop regression would call getTaskPlan again on every one of
|
||||
// these render/microtask cycles.
|
||||
await act(async () => {
|
||||
for (let i = 0; i < 5; i += 1) await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(mocks.getTaskPlan).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retries the plan fetch for a task revisited after a failure", async () => {
|
||||
// `PreviewSessionTabs` is reused across tasks without remounting, so a
|
||||
// failure for TASK_ID must survive switching the preview to TASK_ID_B and
|
||||
// back. Only TASK_ID's fetch rejects (once); TASK_ID_B always resolves.
|
||||
mocks.getTaskPlan.mockImplementation((id: string) =>
|
||||
id === TASK_ID ? Promise.reject(new Error("boom")) : Promise.resolve(null),
|
||||
);
|
||||
|
||||
const { rerender } = render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_ERROR_TESTID)).toBeTruthy();
|
||||
});
|
||||
expect(mocks.getTaskPlan.mock.calls.filter(([id]) => id === TASK_ID)).toHaveLength(1);
|
||||
|
||||
// Switch away to another task, then back to the failed one.
|
||||
act(() => {
|
||||
rerender(<PreviewSessionTabs taskId={TASK_ID_B} sessionId={null} />);
|
||||
});
|
||||
mocks.getTaskPlan.mockImplementation((id: string) =>
|
||||
id === TASK_ID ? Promise.resolve(agentPlan()) : Promise.resolve(null),
|
||||
);
|
||||
act(() => {
|
||||
rerender(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
});
|
||||
|
||||
// Re-selecting the Plan tab is the retry signal.
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
});
|
||||
expect(mocks.getTaskPlan.mock.calls.filter(([id]) => id === TASK_ID)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewSessionTabs Plan tab recovery", () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true });
|
||||
mocks.useSessionResumption.mockReturnValue({
|
||||
error: null,
|
||||
notice: null,
|
||||
resumeSession: vi.fn(),
|
||||
});
|
||||
mocks.getTaskPlan.mockResolvedValue(null);
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.useTaskSessions.mockReset();
|
||||
mocks.useSessionResumption.mockReset();
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
mocks.getTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("retries a failed plan fetch after the WebSocket reconnects", async () => {
|
||||
mocks.getTaskPlan.mockRejectedValueOnce(new Error("boom")).mockResolvedValueOnce(agentPlan());
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_ERROR_TESTID)).toBeTruthy();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fakeStore.setState({ connection: { status: "disconnected" } });
|
||||
});
|
||||
act(() => {
|
||||
fakeStore.setState({ connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
});
|
||||
expect(mocks.getTaskPlan).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("shows an authoritative WebSocket plan after an earlier fetch failure", async () => {
|
||||
mocks.getTaskPlan.mockRejectedValue(new Error("boom"));
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_ERROR_TESTID)).toBeTruthy();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fakeStore.getState().setTaskPlan(TASK_ID, agentPlan({ updated_at: LATER_TIMESTAMP }));
|
||||
});
|
||||
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
expect(screen.queryByTestId(PLAN_ERROR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("retries a failed plan fetch from the error state", async () => {
|
||||
mocks.getTaskPlan.mockRejectedValueOnce(new Error("boom")).mockResolvedValueOnce(agentPlan());
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("preview-plan-retry")).toBeTruthy();
|
||||
});
|
||||
fireEvent.click(screen.getByTestId("preview-plan-retry"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
});
|
||||
expect(mocks.getTaskPlan).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewSessionTabs Plan tab indicator timing", () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true });
|
||||
mocks.useSessionResumption.mockReturnValue({
|
||||
error: null,
|
||||
notice: null,
|
||||
resumeSession: vi.fn(),
|
||||
});
|
||||
mocks.getTaskPlan.mockResolvedValue(null);
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mocks.useTaskSessions.mockReset();
|
||||
mocks.useSessionResumption.mockReset();
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
mocks.getTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("does not re-light the indicator when the plan finishes loading while the Plan tab is already open", async () => {
|
||||
mocks.getTaskPlan.mockResolvedValue(agentPlan());
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId(PLAN_PANEL_TESTID)).toBeTruthy();
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not re-light the indicator when the plan updates over WS while the Plan tab is open", () => {
|
||||
const initialPlan = agentPlan();
|
||||
setTaskPlansState({
|
||||
byTaskId: { [TASK_ID]: initialPlan },
|
||||
loadedByTaskId: { [TASK_ID]: true },
|
||||
lastSeenUpdatedAtByTaskId: { [TASK_ID]: initialPlan.updated_at },
|
||||
});
|
||||
|
||||
render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
|
||||
// Simulate a task.plan.updated WS event landing for this task while the
|
||||
// Plan tab is already the active view.
|
||||
const updatedPlan = agentPlan({ updated_at: LATER_TIMESTAMP });
|
||||
act(() => {
|
||||
setTaskPlansState({ byTaskId: { [TASK_ID]: updatedPlan } });
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mark the next task's plan seen when switching the previewed task while Plan is open", () => {
|
||||
setTaskPlansState({
|
||||
byTaskId: {
|
||||
[TASK_ID]: agentPlan(),
|
||||
[TASK_ID_B]: agentPlan({
|
||||
id: "plan-2",
|
||||
task_id: TASK_ID_B,
|
||||
updated_at: LATER_TIMESTAMP,
|
||||
}),
|
||||
},
|
||||
loadedByTaskId: { [TASK_ID]: true, [TASK_ID_B]: true },
|
||||
});
|
||||
|
||||
const { rerender } = render(<PreviewSessionTabs taskId={TASK_ID} sessionId={null} />);
|
||||
fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 });
|
||||
mocks.markTaskPlanSeen.mockReset();
|
||||
|
||||
act(() => {
|
||||
rerender(<PreviewSessionTabs taskId={TASK_ID_B} sessionId={null} />);
|
||||
});
|
||||
|
||||
expect(mocks.markTaskPlanSeen).not.toHaveBeenCalledWith(TASK_ID_B);
|
||||
expect(fakeStore.getState().taskPlans.lastSeenUpdatedAtByTaskId[TASK_ID_B]).toBeUndefined();
|
||||
expect(screen.queryByTestId(PLAN_INDICATOR_TESTID)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("usePreviewPlanSummary fetch race", () => {
|
||||
beforeEach(() => {
|
||||
fakeStore.setState({ taskPlans: emptyTaskPlans(), connection: { status: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mocks.getTaskPlan.mockReset();
|
||||
mocks.setTaskPlan.mockReset();
|
||||
});
|
||||
|
||||
it("does not overwrite a newer WS-pushed plan with a stale null fetch response", async () => {
|
||||
let resolveFetch: (value: TaskPlan | null) => void = () => {};
|
||||
mocks.getTaskPlan.mockReturnValue(
|
||||
new Promise<TaskPlan | null>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => usePreviewPlanSummary(TASK_ID));
|
||||
|
||||
const newerPlan = agentPlan({ updated_at: LATER_TIMESTAMP });
|
||||
act(() => {
|
||||
fakeStore.getState().setTaskPlan(TASK_ID, newerPlan);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
resolveFetch(null);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(fakeStore.getState().taskPlans.byTaskId[TASK_ID]).toEqual(newerPlan);
|
||||
expect(fakeStore.getState().taskPlans.loadingByTaskId[TASK_ID]).toBe(false);
|
||||
});
|
||||
|
||||
it("does not overwrite a newer WS-pushed plan with a stale, older fetch response", async () => {
|
||||
let resolveFetch: (value: TaskPlan | null) => void = () => {};
|
||||
mocks.getTaskPlan.mockReturnValue(
|
||||
new Promise<TaskPlan | null>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => usePreviewPlanSummary(TASK_ID));
|
||||
|
||||
const newerPlan = agentPlan({ updated_at: LATER_TIMESTAMP });
|
||||
act(() => {
|
||||
fakeStore.getState().setTaskPlan(TASK_ID, newerPlan);
|
||||
});
|
||||
|
||||
const staleFetchedPlan = agentPlan({ updated_at: TIMESTAMP });
|
||||
await act(async () => {
|
||||
resolveFetch(staleFetchedPlan);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(fakeStore.getState().taskPlans.byTaskId[TASK_ID]).toEqual(newerPlan);
|
||||
expect(fakeStore.getState().taskPlans.loadingByTaskId[TASK_ID]).toBe(false);
|
||||
});
|
||||
|
||||
it("does not resurrect a plan deleted over WS while the fetch was in flight", async () => {
|
||||
let resolveFetch: (value: TaskPlan | null) => void = () => {};
|
||||
mocks.getTaskPlan.mockReturnValue(
|
||||
new Promise<TaskPlan | null>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
renderHook(() => usePreviewPlanSummary(TASK_ID));
|
||||
|
||||
act(() => {
|
||||
fakeStore.getState().setTaskPlan(TASK_ID, null);
|
||||
fakeStore.getState().markTaskPlanSeen(TASK_ID);
|
||||
});
|
||||
|
||||
const staleFetchedPlan = agentPlan({ updated_at: TIMESTAMP });
|
||||
await act(async () => {
|
||||
resolveFetch(staleFetchedPlan);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(fakeStore.getState().taskPlans.byTaskId[TASK_ID]).toBeNull();
|
||||
expect(fakeStore.getState().taskPlans.loadingByTaskId[TASK_ID]).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useCallback, useLayoutEffect, useMemo, useState } from "react";
|
||||
import { AgentLogo } from "@/components/agent-logo";
|
||||
import { GridSpinner } from "@/components/grid-spinner";
|
||||
import { PanelLoadingState } from "@/components/panel-loading-state";
|
||||
@@ -15,6 +15,7 @@ import { sendMessageRequest } from "@/hooks/use-message-handler";
|
||||
import type { ChatSubmitPayload } from "./chat/chat-input-container";
|
||||
import { EnsureSessionErrorEmptyState, SessionRecoveryFeedback } from "./ensure-session-error";
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
import { PreviewPlanPanel, usePreviewPlanSummary } from "./preview-plan-panel";
|
||||
import { TaskChatPanel } from "./task-chat-panel";
|
||||
import {
|
||||
buildAgentLabelsById,
|
||||
@@ -26,6 +27,9 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const LABEL_SEPARATOR = " \u2022 ";
|
||||
const PLAN_TAB_ID = "plan";
|
||||
const PREVIEW_TAB_CLASS_NAME =
|
||||
"bg-muted/50 data-[state=active]:bg-muted [@media(pointer:coarse)]:!min-h-11";
|
||||
|
||||
type PreviewSessionTabsProps = {
|
||||
taskId: string;
|
||||
@@ -73,9 +77,16 @@ export function PreviewSessionTabs({
|
||||
// restart where the session row is persisted but agentctl isn't alive).
|
||||
const resumption = useSessionResumption(taskId, activeSessionId);
|
||||
|
||||
// Do not force the Plan view while the session list is still loading. The
|
||||
// first render can have zero sessions before the list arrives, and treating
|
||||
// that transient state as sessionless would mark an unseen plan as seen.
|
||||
const hasNoSessions = isLoaded && sortedSessions.length === 0;
|
||||
const planTabState = usePreviewPlanTab(taskId, hasNoSessions, onSessionChange);
|
||||
const { viewMode, planTab, hasPlan } = planTabState;
|
||||
|
||||
const tabs = useMemo<SessionTab[]>(
|
||||
() =>
|
||||
sortedSessions.map((session) => {
|
||||
() => [
|
||||
...sortedSessions.map((session) => {
|
||||
const profile = session.agent_profile_id ? profilesById[session.agent_profile_id] : null;
|
||||
return {
|
||||
id: session.id,
|
||||
@@ -86,40 +97,31 @@ export function PreviewSessionTabs({
|
||||
<SessionAgentLogo profile={profile} />
|
||||
),
|
||||
testId: `preview-session-tab-${session.id}`,
|
||||
className: "bg-muted/50 data-[state=active]:bg-muted",
|
||||
className: PREVIEW_TAB_CLASS_NAME,
|
||||
};
|
||||
}),
|
||||
[sortedSessions, agentLabelsById, profilesById],
|
||||
planTab,
|
||||
],
|
||||
[sortedSessions, agentLabelsById, profilesById, planTab],
|
||||
);
|
||||
|
||||
if (!isLoaded && sortedSessions.length === 0) {
|
||||
return <PreviewLoadingState label={t("task:loadingAgents")} />;
|
||||
}
|
||||
|
||||
if (sortedSessions.length === 0) {
|
||||
if (ensureSession?.status === "preparing") {
|
||||
return <PreviewLoadingState label={t("task:preparingWorkspace2")} />;
|
||||
}
|
||||
if (ensureSession?.status === "error") {
|
||||
return (
|
||||
<>
|
||||
<SessionRecoveryFeedback
|
||||
error={resumption.error}
|
||||
notice={resumption.notice}
|
||||
onRetry={() => void resumption.resumeSession()}
|
||||
workspaceId={workspaceId ?? null}
|
||||
/>
|
||||
<EnsureSessionErrorEmptyState
|
||||
error={ensureSession.error}
|
||||
onRetry={ensureSession.retry}
|
||||
workspaceId={workspaceId ?? null}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <PreviewEmptyState />;
|
||||
if (hasNoSessions && !hasPlan) {
|
||||
return (
|
||||
<PreviewNoSessionsState
|
||||
ensureSession={ensureSession}
|
||||
resumption={resumption}
|
||||
workspaceId={workspaceId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// A task can lose every session (deletion doesn't delete its plan) and
|
||||
// still have a plan worth showing — fall back to the Plan view rather than
|
||||
// an empty session body when there's nothing else to select.
|
||||
return (
|
||||
<div className="flex h-full flex-col min-h-0" data-testid="preview-session-tabs">
|
||||
<SessionRecoveryFeedback
|
||||
@@ -131,20 +133,118 @@ export function PreviewSessionTabs({
|
||||
<div className="border-b px-2 py-1">
|
||||
<SessionTabs
|
||||
tabs={tabs}
|
||||
activeTab={activeSessionId ?? ""}
|
||||
onTabChange={(id) => onSessionChange?.(id)}
|
||||
listClassName="bg-transparent p-0 !h-7 gap-1 overflow-x-auto overflow-y-hidden min-w-0 shrink [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]"
|
||||
activeTab={viewMode === "plan" ? PLAN_TAB_ID : (activeSessionId ?? "")}
|
||||
onTabChange={planTabState.handleTabChange}
|
||||
listClassName="bg-transparent p-0 !h-7 gap-1 overflow-x-auto overflow-y-hidden min-w-0 shrink [@media(pointer:coarse)]:!h-11 [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
{activeSession && (
|
||||
<PreviewSessionBody key={activeSession.id} session={activeSession} taskId={taskId} />
|
||||
)}
|
||||
<PreviewTabBody
|
||||
viewMode={viewMode}
|
||||
planState={planTabState.planState}
|
||||
activeSession={activeSession}
|
||||
taskId={taskId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders the Plan tab's content or the active session's chat, per `viewMode`. */
|
||||
function PreviewTabBody({
|
||||
viewMode,
|
||||
planState,
|
||||
activeSession,
|
||||
taskId,
|
||||
}: {
|
||||
viewMode: "session" | "plan";
|
||||
planState: ReturnType<typeof usePreviewPlanSummary>;
|
||||
activeSession: TaskSession | null;
|
||||
taskId: string;
|
||||
}) {
|
||||
if (viewMode === "plan") {
|
||||
return <PreviewPlanPanel {...planState} onRetry={planState.retry} />;
|
||||
}
|
||||
if (!activeSession) return null;
|
||||
return <PreviewSessionBody key={activeSession.id} session={activeSession} taskId={taskId} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the preview panel's Plan tab: local session-vs-plan view mode, the
|
||||
* unseen-plan indicator (mirrors `plan-tab.tsx`'s dot logic, scoped to this
|
||||
* task instead of the global active task), and clearing it on selection.
|
||||
*/
|
||||
function usePreviewPlanTab(
|
||||
taskId: string,
|
||||
hasNoSessions: boolean,
|
||||
onSessionChange?: (sessionId: string | null) => void,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const planState = usePreviewPlanSummary(taskId);
|
||||
const { plan, loaded, failed, retry } = planState;
|
||||
const hasPlan = loaded && plan !== null;
|
||||
const lastSeenPlanAt = useAppStore((state) => state.taskPlans.lastSeenUpdatedAtByTaskId[taskId]);
|
||||
const markTaskPlanSeen = useAppStore((state) => state.markTaskPlanSeen);
|
||||
const hasUnseenPlan = plan?.created_by === "agent" && lastSeenPlanAt !== plan.updated_at;
|
||||
|
||||
const [viewMode, setViewMode] = useState<"session" | "plan">("session");
|
||||
// A new preview task shouldn't inherit the previous task's Plan selection.
|
||||
// Reset during render (not a passive effect) because `PreviewSessionTabs`
|
||||
// is reused across tasks on card click without remounting: a passive
|
||||
// effect runs after the layout effect below, so it would still see
|
||||
// `viewMode === "plan"` on the taskId-change render and mark the new
|
||||
// task's plan seen before the reset took effect.
|
||||
const [prevTaskId, setPrevTaskId] = useState(taskId);
|
||||
if (prevTaskId !== taskId) {
|
||||
setPrevTaskId(taskId);
|
||||
setViewMode("session");
|
||||
}
|
||||
|
||||
const displayViewMode = hasNoSessions && hasPlan ? "plan" : viewMode;
|
||||
|
||||
// While the Plan tab is the active view, re-mark seen whenever the plan's
|
||||
// updated_at changes. Covers both clicking Plan before the fetch resolves
|
||||
// (nothing is marked seen until the plan actually arrives) and a WS plan
|
||||
// update landing while the tab is already open. useLayoutEffect so the
|
||||
// seen-mark commits before paint, matching plan-tab.tsx's dot logic.
|
||||
const planUpdatedAt = plan?.updated_at;
|
||||
useLayoutEffect(() => {
|
||||
if (displayViewMode === "plan" && planUpdatedAt !== undefined) {
|
||||
markTaskPlanSeen(taskId);
|
||||
}
|
||||
}, [displayViewMode, taskId, markTaskPlanSeen, planUpdatedAt]);
|
||||
|
||||
const handleTabChange = useCallback(
|
||||
(id: string) => {
|
||||
if (id === PLAN_TAB_ID) {
|
||||
setViewMode("plan");
|
||||
if (loaded) markTaskPlanSeen(taskId);
|
||||
// A prior fetch for this task failed; re-selecting the tab is the
|
||||
// user's explicit signal to try again, since the panel is reused
|
||||
// across tasks without remounting and would otherwise stay stuck.
|
||||
else if (failed) retry();
|
||||
} else {
|
||||
setViewMode("session");
|
||||
onSessionChange?.(id);
|
||||
}
|
||||
},
|
||||
[taskId, loaded, failed, retry, markTaskPlanSeen, onSessionChange],
|
||||
);
|
||||
|
||||
const planTab = useMemo<SessionTab>(
|
||||
() => ({
|
||||
id: PLAN_TAB_ID,
|
||||
label: t("task:plan"),
|
||||
icon: <PlanTabIcon hasUnseen={hasUnseenPlan} />,
|
||||
testId: "preview-plan-tab",
|
||||
className: PREVIEW_TAB_CLASS_NAME,
|
||||
}),
|
||||
[t, hasUnseenPlan],
|
||||
);
|
||||
|
||||
return { viewMode: displayViewMode, handleTabChange, planTab, planState, hasPlan };
|
||||
}
|
||||
|
||||
function resolveProfileSubLabel(
|
||||
session: TaskSession,
|
||||
profile: AgentProfileOption | null | undefined,
|
||||
@@ -165,6 +265,21 @@ function SessionAgentLogo({ profile }: { profile: AgentProfileOption | null | un
|
||||
return <AgentLogo agentName={profile.agent_name} size={12} className="shrink-0" />;
|
||||
}
|
||||
|
||||
/** Matches the full-page Plan tab's unseen dot (`plan-tab.tsx`), scoped to the previewed task. */
|
||||
function PlanTabIcon({ hasUnseen }: { hasUnseen: boolean }) {
|
||||
return (
|
||||
<span aria-hidden="true" className="relative inline-flex h-3 w-3 shrink-0 items-center">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/40" />
|
||||
{hasUnseen && (
|
||||
<span
|
||||
data-testid="preview-plan-tab-indicator"
|
||||
className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-primary"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function PreviewSessionBody({ session, taskId }: { session: TaskSession; taskId: string }) {
|
||||
const handleSendMessage = useCallback(
|
||||
async (payload: ChatSubmitPayload) => {
|
||||
@@ -222,3 +337,38 @@ function PreviewEmptyState() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Sessionless state: preparing/error/empty, per `ensureSession`. */
|
||||
function PreviewNoSessionsState({
|
||||
ensureSession,
|
||||
resumption,
|
||||
workspaceId,
|
||||
}: {
|
||||
ensureSession?: UseEnsureTaskSessionResult;
|
||||
resumption: ReturnType<typeof useSessionResumption>;
|
||||
workspaceId?: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (ensureSession?.status === "preparing") {
|
||||
return <PreviewLoadingState label={t("task:preparingWorkspace2")} />;
|
||||
}
|
||||
if (ensureSession?.status === "error") {
|
||||
return (
|
||||
<>
|
||||
<SessionRecoveryFeedback
|
||||
error={resumption.error}
|
||||
notice={resumption.notice}
|
||||
onRetry={() => void resumption.resumeSession()}
|
||||
workspaceId={workspaceId ?? null}
|
||||
/>
|
||||
<EnsureSessionErrorEmptyState
|
||||
error={ensureSession.error}
|
||||
onRetry={ensureSession.retry}
|
||||
workspaceId={workspaceId ?? null}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <PreviewEmptyState />;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,14 @@ import { waitForSessionDone } from "../../helpers/session";
|
||||
|
||||
const DONE_STATES = ["COMPLETED", "WAITING_FOR_INPUT"];
|
||||
|
||||
const CREATE_PLAN_SCRIPT = [
|
||||
'e2e:thinking("creating plan")',
|
||||
"e2e:delay(100)",
|
||||
'e2e:mcp:kandev:create_task_plan_kandev({"task_id":"{task_id}","content":"## Preview Plan\\n\\nStep one","title":"Plan v1"})',
|
||||
"e2e:delay(100)",
|
||||
'e2e:message("plan created")',
|
||||
].join("\n");
|
||||
|
||||
/**
|
||||
* Tests the session tabs on the kanban right-side preview panel:
|
||||
* - Every session of the task shows up as a tab
|
||||
@@ -293,3 +301,165 @@ test.describe("Preview auto-prepare", () => {
|
||||
.catch(() => undefined);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Tests the read-only Plan tab added to the preview panel's tab bar: it
|
||||
* carries the same unseen-plan indicator as the full-page Plan tab, and
|
||||
* selecting it swaps the chat body for the read-only plan render without
|
||||
* touching session selection.
|
||||
*/
|
||||
test.describe("Preview Plan tab", () => {
|
||||
test("shows the unseen indicator and swaps the chat body for the read-only plan", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
"Preview Plan Tab Task",
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: CREATE_PLAN_SCRIPT,
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const plan = await apiClient.getTaskPlan(task.id);
|
||||
return plan?.created_by === "agent" && plan.content.includes("Step one");
|
||||
},
|
||||
{ timeout: 30_000, message: "Waiting for agent-authored plan" },
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
await apiClient.saveUserSettings({ enable_preview_on_click: true });
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
|
||||
const previewCard = kanban.taskCardByTitle("Preview Plan Tab Task");
|
||||
await expect(previewCard).toBeVisible({ timeout: 10_000 });
|
||||
await previewCard.click();
|
||||
|
||||
const previewPanel = testPage.getByTestId("task-preview-panel");
|
||||
await expect(previewPanel).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// Chat is the default body, and the agent's plan-creation reply is visible.
|
||||
// Scoped to the agent's message (not any getByText match) because the raw
|
||||
// script description is itself echoed as a user message and contains the
|
||||
// literal substring `e2e:message("plan created")`.
|
||||
await expect(
|
||||
previewPanel.getByTestId("agent-message-highlight").getByText("plan created", {
|
||||
exact: false,
|
||||
}),
|
||||
).toBeVisible({
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
// Capture the active session tab and the URL's sessionId before opening
|
||||
// Plan, so the round-trip back to it can be verified below.
|
||||
const sessionTab = previewPanel.locator('[data-testid^="preview-session-tab-"]');
|
||||
const sessionIdBeforePlan = new URL(testPage.url()).searchParams.get("sessionId");
|
||||
expect(sessionIdBeforePlan).toBeTruthy();
|
||||
|
||||
// Plan tab is present with the unseen indicator (plan is agent-authored
|
||||
// and has never been marked seen in this browser).
|
||||
const planTab = previewPanel.getByTestId("preview-plan-tab");
|
||||
await expect(planTab).toBeVisible({ timeout: 15_000 });
|
||||
await expect(previewPanel.getByTestId("preview-plan-tab-indicator")).toBeVisible({
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
// Selecting the Plan tab swaps the chat body for the read-only plan.
|
||||
await planTab.click();
|
||||
await expect(planTab).toHaveAttribute("data-state", "active");
|
||||
await expect(
|
||||
previewPanel.getByTestId("agent-message-highlight").getByText("plan created", {
|
||||
exact: false,
|
||||
}),
|
||||
).not.toBeVisible();
|
||||
await expect(previewPanel.getByTestId("preview-plan-panel")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(previewPanel.getByText("Step one")).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// Selecting the tab cleared the unseen indicator, matching the full-page
|
||||
// Plan tab's behavior.
|
||||
await expect(previewPanel.getByTestId("preview-plan-tab-indicator")).toHaveCount(0);
|
||||
|
||||
// Switching back to the session tab restores its body and leaves the
|
||||
// URL's sessionId untouched — the Plan tab swap never mutated session
|
||||
// selection, it only changed which body is displayed.
|
||||
await sessionTab.click();
|
||||
await expect(
|
||||
previewPanel.getByTestId("agent-message-highlight").getByText("plan created", {
|
||||
exact: false,
|
||||
}),
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
expect(new URL(testPage.url()).searchParams.get("sessionId")).toBe(sessionIdBeforePlan);
|
||||
});
|
||||
|
||||
test("keeps the Plan tab touch-sized on a coarse-pointer tablet", async ({
|
||||
tabletTestPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
"Preview Plan Tablet Task",
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: CREATE_PLAN_SCRIPT,
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const plan = await apiClient.getTaskPlan(task.id);
|
||||
return plan?.content.includes("Step one") ?? false;
|
||||
},
|
||||
{ timeout: 30_000, message: "Waiting for tablet preview plan" },
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
await apiClient.saveUserSettings({ enable_preview_on_click: true });
|
||||
const kanban = new KanbanPage(tabletTestPage);
|
||||
await kanban.goto();
|
||||
|
||||
const card = kanban.taskCardByTitle("Preview Plan Tablet Task");
|
||||
await expect(card).toBeVisible({ timeout: 10_000 });
|
||||
await card.tap();
|
||||
|
||||
const previewPanel = tabletTestPage.getByTestId("task-preview-panel");
|
||||
await expect(previewPanel).toBeVisible({ timeout: 10_000 });
|
||||
const planTab = previewPanel.getByTestId("preview-plan-tab");
|
||||
await expect(planTab).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
const box = await planTab.boundingBox();
|
||||
const viewport = tabletTestPage.viewportSize();
|
||||
expect(box).not.toBeNull();
|
||||
expect(viewport).not.toBeNull();
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.x + box!.width).toBeLessThanOrEqual(viewport!.width);
|
||||
|
||||
const hitTarget = await tabletTestPage.evaluate(
|
||||
({ x, y }) =>
|
||||
document.elementFromPoint(x, y)?.closest<HTMLElement>('[data-testid="preview-plan-tab"]')
|
||||
?.dataset.testid ?? null,
|
||||
{ x: box!.x + box!.width / 2, y: box!.y + box!.height / 2 },
|
||||
);
|
||||
expect(hitTarget).toBe("preview-plan-tab");
|
||||
|
||||
await planTab.tap();
|
||||
await expect(previewPanel.getByText("Step one")).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1004,6 +1004,7 @@
|
||||
"planContentTooLarge": "Your plan is {{submitted}}, over the {{limit}} limit. Shorten the document and save again.",
|
||||
"planHistory": "Plan history",
|
||||
"planIsEmpty": "Plan is empty",
|
||||
"planLoadError": "Couldn't load the plan.",
|
||||
"planMode": "Plan mode",
|
||||
"planRestoredToV": "Plan restored to v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} char",
|
||||
|
||||
@@ -183,7 +183,7 @@
|
||||
"clarificationAnswerOverLimit_other": "{{count}} ćĥàŕàćţēŕś ōvēŕ ţĥē {{max}}-ćĥàŕàćţēŕ ĺĩḿĩţ.",
|
||||
"clarificationAnswerRuneCount": "{{current}} / {{max}}",
|
||||
"clarificationExpired": "Ţĥĩś qũēśţĩōń ĩś ńō ĺōńĝēŕ àćţĩvē, śō ŷōũŕ àńśŵēŕ ŵàś ńōţ ŕēćōŕďēď.",
|
||||
"clarificationResponseFailed": "Ćōũĺď ńōţ śēńď ŷōũŕ ŕēśpōńśē.",
|
||||
"clarificationResponseFailed": "Ćōũĺď ńōţ śēńď ŷōũŕ ŕēśƥōńśē.",
|
||||
"cleanup": "Ćĺēàńũƥ",
|
||||
"clearAllAnnotations": "Ćĺēàŕ àĺĺ àńńōţàţĩōńś",
|
||||
"clickAnywhereToStartWriting": "Ćĺĩćķ àńŷŵĥēŕē ţō śţàŕţ ŵŕĩţĩńĝ",
|
||||
@@ -1004,6 +1004,7 @@
|
||||
"planContentTooLarge": "Ŷōũŕ ƥĺàń ĩś {{submitted}}, ōvēŕ ţĥē {{limit}} ĺĩḿĩţ. Śĥōŕţēń ţĥē ďōćũḿēńţ àńď śàvē àĝàĩń.",
|
||||
"planHistory": "Ƥĺàń ĥĩśţōŕŷ",
|
||||
"planIsEmpty": "Ƥĺàń ĩś ēḿƥţŷ",
|
||||
"planLoadError": "Ćōũĺďń'ţ ĺōàď ţĥē ƥĺàń.",
|
||||
"planMode": "Ƥĺàń ḿōďē",
|
||||
"planRestoredToV": "Ƥĺàń ŕēśţōŕēď ţō v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} ćĥàŕ",
|
||||
|
||||
@@ -961,6 +961,7 @@
|
||||
"planContentTooLarge": "O seu plano tem {{submitted}}, acima do limite de {{limit}}. Reduza o documento e guarde novamente.",
|
||||
"planHistory": "Histórico do plano",
|
||||
"planIsEmpty": "O plano está vazio",
|
||||
"planLoadError": "Não foi possível carregar o plano.",
|
||||
"planMode": "Modo de plano",
|
||||
"planRestoredToV": "Plano restaurado para a v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} carácter",
|
||||
|
||||
@@ -960,6 +960,7 @@
|
||||
"planContentTooLarge": "您的计划为 {{submitted}},超过了 {{limit}} 的限制。请缩短文档后重新保存。",
|
||||
"planHistory": "计划历史",
|
||||
"planIsEmpty": "计划为空",
|
||||
"planLoadError": "无法加载计划。",
|
||||
"planMode": "计划模式",
|
||||
"planRestoredToV": "计划已恢复到 v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} 个字符",
|
||||
|
||||
@@ -960,6 +960,7 @@
|
||||
"planContentTooLarge": "您的計劃為 {{submitted}},超過了 {{limit}} 的限制。請縮短文件後重新儲存。",
|
||||
"planHistory": "計劃歷史",
|
||||
"planIsEmpty": "計劃為空",
|
||||
"planLoadError": "無法載入計劃。",
|
||||
"planMode": "計劃模式",
|
||||
"planRestoredToV": "計劃已恢復到 v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} 個字符",
|
||||
|
||||
@@ -960,6 +960,7 @@
|
||||
"planContentTooLarge": "您的計劃為 {{submitted}},超過了 {{limit}} 的限制。請縮短文件後重新儲存。",
|
||||
"planHistory": "計劃歷史",
|
||||
"planIsEmpty": "計劃為空",
|
||||
"planLoadError": "無法載入計劃。",
|
||||
"planMode": "計劃模式",
|
||||
"planRestoredToV": "計劃已恢復到 v{{revisionnumber}}",
|
||||
"planRevisionCharCount_one": "{{formatted}} 個字元",
|
||||
|
||||
Reference in New Issue
Block a user