From decd317988fd060863d6e9769ac041990b5e08a2 Mon Sep 17 00:00:00 2001 From: Henry Date: Thu, 3 Sep 2026 19:44:12 +0000 Subject: [PATCH] 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 Co-authored-by: Carlos Florencio --- .../components/task/preview-plan-panel.tsx | 144 ++++ .../task/preview-session-tabs.test.tsx | 629 +++++++++++++++++- .../components/task/preview-session-tabs.tsx | 216 +++++- .../tests/kanban/preview-session-tabs.spec.ts | 170 +++++ apps/web/src/locales/en/task.json | 1 + apps/web/src/locales/pseudo/task.json | 3 +- apps/web/src/locales/pt-pt/task.json | 1 + apps/web/src/locales/zh-cn/task.json | 1 + apps/web/src/locales/zh-hk/task.json | 1 + apps/web/src/locales/zh-tw/task.json | 1 + 10 files changed, 1123 insertions(+), 44 deletions(-) create mode 100644 apps/web/components/task/preview-plan-panel.tsx diff --git a/apps/web/components/task/preview-plan-panel.tsx b/apps/web/components/task/preview-plan-panel.tsx new file mode 100644 index 0000000000..fe645757da --- /dev/null +++ b/apps/web/components/task/preview-plan-panel.tsx @@ -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(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 ( +
+ {t("task:planLoadError")} + +
+ ); + } + + if (loading || !loaded) { + return ; + } + + if (!plan?.content) { + return ( +
+ {t("task:planIsEmpty")} +
+ ); + } + + return ( +
+ +
+ ); +} diff --git a/apps/web/components/task/preview-session-tabs.test.tsx b/apps/web/components/task/preview-session-tabs.test.tsx index 037938751e..df466dcce8 100644 --- a/apps/web/components/task/preview-session-tabs.test.tsx +++ b/apps/web/components/task/preview-session-tabs.test.tsx @@ -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), + 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
; }, })); +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 }) => ( +
{props.content}
+ ), +})); -import { PreviewSessionBody } from "./preview-session-tabs"; +type TaskPlansState = { + byTaskId: Record; + loadedByTaskId: Record; + loadingByTaskId: Record; + lastSeenUpdatedAtByTaskId: Record; +}; + +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()((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) { + 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(); + render(); 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(); + render(); 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(); + render(); 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 { + 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(); + + 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( + , + ); + 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(); + + 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(); + + 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(); + + 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(); + + 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(); + + 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(); + 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(); + + expect(mocks.markTaskPlanSeen).not.toHaveBeenCalled(); + + mocks.useTaskSessions.mockReturnValue({ sessions: [session], isLoaded: true }); + rerender(); + + 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(); + 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(); + 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(); + }); + mocks.getTaskPlan.mockImplementation((id: string) => + id === TASK_ID ? Promise.resolve(agentPlan()) : Promise.resolve(null), + ); + act(() => { + rerender(); + }); + + // 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + fireEvent.mouseDown(screen.getByTestId(PLAN_TAB_TESTID), { button: 0 }); + mocks.markTaskPlanSeen.mockReset(); + + act(() => { + rerender(); + }); + + 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((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((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((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); + }); +}); diff --git a/apps/web/components/task/preview-session-tabs.tsx b/apps/web/components/task/preview-session-tabs.tsx index 4d78917fe2..6aa299b386 100644 --- a/apps/web/components/task/preview-session-tabs.tsx +++ b/apps/web/components/task/preview-session-tabs.tsx @@ -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( - () => - 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({ ), 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 ; } - if (sortedSessions.length === 0) { - if (ensureSession?.status === "preparing") { - return ; - } - if (ensureSession?.status === "error") { - return ( - <> - void resumption.resumeSession()} - workspaceId={workspaceId ?? null} - /> - - - ); - } - return ; + if (hasNoSessions && !hasPlan) { + return ( + + ); } + // 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 (
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]" />
- {activeSession && ( - - )} +
); } +/** 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; + activeSession: TaskSession | null; + taskId: string; +}) { + if (viewMode === "plan") { + return ; + } + if (!activeSession) return null; + return ; +} + +/** + * 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( + () => ({ + id: PLAN_TAB_ID, + label: t("task:plan"), + icon: , + 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 ; } +/** Matches the full-page Plan tab's unseen dot (`plan-tab.tsx`), scoped to the previewed task. */ +function PlanTabIcon({ hasUnseen }: { hasUnseen: boolean }) { + return ( +