From e930061fe4e472be0e9885d6ed3e86d5c711089d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Tue, 16 Jun 2026 20:29:35 +0100 Subject: [PATCH] fix(web): chat badge, dockview preview routing, and agent-error icon cleanup (#1395) --- .../task/chat/message-list-shared.test.tsx | 2 + .../task/chat/message-list-shared.tsx | 26 +-- .../chat/messages/tool-subagent-message.tsx | 5 +- .../components/task/dockview-layout-setup.ts | 34 ++- .../task/dockview-session-tabs.test.ts | 94 +++++++++ .../components/task/dockview-session-tabs.ts | 39 +++- .../session-task-switcher-sheet-hooks.ts | 6 +- .../components/task/task-session-sidebar.tsx | 14 +- .../tests/layout/pane-resize-right.spec.ts | 71 +++++++ .../tests/layout/plan-panel-indicator.spec.ts | 7 +- .../layout/preview-tab-session-switch.spec.ts | 47 +++++ .../session/agent-error-indicator.spec.ts | 14 +- .../session/session-resume-dedup.spec.ts | 20 +- .../terminal/terminal-dockview-ui.spec.ts | 6 +- apps/web/lib/session-last-agent-error.test.ts | 52 ++++- apps/web/lib/session-last-agent-error.ts | 35 +++- .../state/dockview-env-switch-pinned.test.ts | 7 +- .../web/lib/state/dockview-env-switch.test.ts | 66 +++++- apps/web/lib/state/dockview-env-switch.ts | 44 +++- .../dockview-layout-builders-fixups.test.ts | 25 +++ .../web/lib/state/dockview-layout-builders.ts | 39 +++- .../lib/state/dockview-panel-actions.test.ts | 37 +++- apps/web/lib/state/dockview-panel-actions.ts | 22 +- apps/web/lib/state/dockview-store.ts | 15 +- apps/web/lib/state/dockview-widths-debug.ts | 14 ++ .../lib/state/layout-manager/merger.test.ts | 34 +++ apps/web/lib/state/layout-manager/merger.ts | 20 +- .../ui/dismissed-agent-errors-actions.ts | 24 +++ apps/web/lib/state/slices/ui/types.ts | 8 + apps/web/lib/state/slices/ui/ui-slice.ts | 3 + apps/web/lib/state/store.ts | 2 + apps/web/lib/task-agent-error.test.ts | 193 ++++++++++++++++-- apps/web/lib/task-agent-error.ts | 46 ++++- 33 files changed, 972 insertions(+), 99 deletions(-) create mode 100644 apps/web/lib/state/slices/ui/dismissed-agent-errors-actions.ts diff --git a/apps/web/components/task/chat/message-list-shared.test.tsx b/apps/web/components/task/chat/message-list-shared.test.tsx index a91e3161b8..11810eed57 100644 --- a/apps/web/components/task/chat/message-list-shared.test.tsx +++ b/apps/web/components/task/chat/message-list-shared.test.tsx @@ -19,6 +19,8 @@ const mockStoreState = vi.hoisted(() => ({ }, }, }, + dismissedAgentErrors: {} as Record, + dismissAgentError: () => {}, })); vi.mock("@/components/task/chat/message-renderer", () => ({ diff --git a/apps/web/components/task/chat/message-list-shared.tsx b/apps/web/components/task/chat/message-list-shared.tsx index e184aed4e1..02ae5bf110 100644 --- a/apps/web/components/task/chat/message-list-shared.tsx +++ b/apps/web/components/task/chat/message-list-shared.tsx @@ -1,6 +1,6 @@ "use client"; -import { memo, useCallback, useState } from "react"; +import { memo, useCallback } from "react"; import { Button } from "@kandev/ui/button"; import { IconAlertCircle, IconX } from "@tabler/icons-react"; import { GridSpinner } from "@/components/grid-spinner"; @@ -10,7 +10,7 @@ import { MessageRenderer } from "@/components/task/chat/message-renderer"; import { TurnGroupMessage } from "@/components/task/chat/messages/turn-group-message"; import { PrepareProgress } from "@/components/session/prepare-progress"; import { useAppStore } from "@/components/state-provider"; -import { lastAgentErrorDismissKey, readLastAgentError } from "@/lib/session-last-agent-error"; +import { lastAgentErrorStamp, readLastAgentError } from "@/lib/session-last-agent-error"; export type MessageListProps = { items: RenderItem[]; @@ -45,25 +45,27 @@ export function getLastTurnGroupId(items: RenderItem[]) { return null; } +// The chat banner stays visible until the user explicitly dismisses it, even +// after the agent resumes — so the user can read the full error message at +// their own pace. The sidebar icon, by contrast, also auto-hides once the +// agent posts a new message (see agentErrorMessageForTask). export function LastAgentErrorNotice({ sessionId }: { sessionId: string | null }) { const metadata = useAppStore((state) => sessionId ? state.taskSessions.items[sessionId]?.metadata : null, ); const error = readLastAgentError(metadata); - const dismissKey = sessionId && error ? lastAgentErrorDismissKey(sessionId, error) : ""; - const [dismissedKey, setDismissedKey] = useState(() => - dismissKey && globalThis.localStorage?.getItem(dismissKey) === "true" ? dismissKey : null, + const stamp = error ? lastAgentErrorStamp(error) : ""; + const dismissedStamp = useAppStore((state) => + sessionId ? state.dismissedAgentErrors[sessionId] : undefined, ); - const isDismissed = - dismissedKey === dismissKey || globalThis.localStorage?.getItem(dismissKey) === "true"; + const dismissAgentError = useAppStore((state) => state.dismissAgentError); const dismiss = useCallback(() => { - if (!dismissKey) return; - globalThis.localStorage?.setItem(dismissKey, "true"); - setDismissedKey(dismissKey); - }, [dismissKey]); + if (!sessionId || !stamp) return; + dismissAgentError(sessionId, stamp); + }, [dismissAgentError, sessionId, stamp]); - if (!error || isDismissed) return null; + if (!error || dismissedStamp === stamp) return null; return (
{subagentType} {description} {isActive && } diff --git a/apps/web/components/task/dockview-layout-setup.ts b/apps/web/components/task/dockview-layout-setup.ts index 7bfc4731e7..f52af13d15 100644 --- a/apps/web/components/task/dockview-layout-setup.ts +++ b/apps/web/components/task/dockview-layout-setup.ts @@ -15,6 +15,14 @@ import { setEnvLayout } from "@/lib/local-storage"; import { panelPortalManager } from "@/lib/layout/panel-portal-manager"; import { stopVscode } from "@/lib/api/domains/vscode-api"; import { parkUserShell, stopUserShell } from "@/lib/api/domains/user-shell-api"; +import { createDebugLogger, isDebug } from "@/lib/debug/log"; +import { + snapshotColumnWidths, + formatWidthsSnapshot, + formatJsonRootSizes, +} from "@/lib/state/dockview-widths-debug"; + +const debugWidths = createDebugLogger("dockview:widths"); // v3: bumped alongside DOCKVIEW_ENV_LAYOUT_PREFIX so the no-env fallback // also discards layouts captured with the now-removed dockview sidebar column. @@ -118,7 +126,12 @@ export function setupSashDragCapToggle(api: DockviewReadyEvent["api"]): () => vo // start a drag must not leave `sashDragging` permanently set (cubic P2). if (e.button !== 0) return; const t = e.target as HTMLElement | null; - if (t?.closest(".dv-sash")) sashDragging = true; + if (t?.closest(".dv-sash")) { + sashDragging = true; + if (isDebug()) { + debugWidths(`sash-drag-start ${formatWidthsSnapshot(snapshotColumnWidths(api))}`); + } + } }; const onMouseUp = (e: MouseEvent): void => { if (e.button !== 0 || !sashDragging) return; @@ -128,7 +141,18 @@ export function setupSashDragCapToggle(api: DockviewReadyEvent["api"]): () => vo const sv = getRootSplitview(api); if (!sv) return; const store = useDockviewStore.getState(); - if (store.rightPanelsVisible) setPinnedTarget("right", sv.getViewSize(sv.length - 1)); + if (store.rightPanelsVisible) { + const newRight = sv.getViewSize(sv.length - 1); + setPinnedTarget("right", newRight); + if (isDebug()) { + debugWidths( + `sash-drag-end captured=right:${Math.round(newRight)} ` + + `${formatWidthsSnapshot(snapshotColumnWidths(api))}`, + ); + } + } else if (isDebug()) { + debugWidths(`sash-drag-end ${formatWidthsSnapshot(snapshotColumnWidths(api))}`); + } }); }; document.addEventListener("mousedown", onMouseDown, true); @@ -228,6 +252,12 @@ export function setupLayoutPersistence( if (envId) { setEnvLayout(envId, json); } + if (isDebug()) { + debugWidths( + `persist env=${envId ?? "-"} ${formatWidthsSnapshot(snapshotColumnWidths(api))} ` + + `jsonSizes=${formatJsonRootSizes(json)}`, + ); + } } catch { // Ignore serialization errors } diff --git a/apps/web/components/task/dockview-session-tabs.test.ts b/apps/web/components/task/dockview-session-tabs.test.ts index dce1f87c62..6c3985e869 100644 --- a/apps/web/components/task/dockview-session-tabs.test.ts +++ b/apps/web/components/task/dockview-session-tabs.test.ts @@ -7,6 +7,7 @@ import { reconcileRemovedSessionPanels, resolveInitialPosition, resolveSessionTabSyncTarget, + shouldActivateSessionPanel, shouldRebuildDefaultForPendingSession, } from "./dockview-session-tabs"; import { CENTER_GROUP, RIGHT_TOP_GROUP } from "@/lib/state/layout-manager"; @@ -507,3 +508,96 @@ describe("resolveSessionTabSyncTarget", () => { expect(target).toBeNull(); }); }); + +describe("shouldActivateSessionPanel", () => { + const SID = "s-current"; + const SESSION_PANEL_ID = `session:${SID}`; + const baseArgs = { + prevTaskId: null, + prevSessionId: null, + currentTaskId: "task-A", + currentSessionId: SID, + currentActivePanelId: null, + }; + + it("activates when the session panel did not exist before (fresh creation)", () => { + expect(shouldActivateSessionPanel({ ...baseArgs, sessionPanelExistedBefore: false })).toBe( + true, + ); + }); + + it("activates on first mount when no panel is currently active", () => { + expect( + shouldActivateSessionPanel({ + ...baseArgs, + sessionPanelExistedBefore: true, + currentActivePanelId: null, + }), + ).toBe(true); + }); + + it("activates on first mount when the restored active panel is already the session", () => { + expect( + shouldActivateSessionPanel({ + ...baseArgs, + sessionPanelExistedBefore: true, + currentActivePanelId: SESSION_PANEL_ID, + }), + ).toBe(true); + }); + + /** + * Regression: on page refresh, dockview's fromJSON restores the active + * panel from the saved layout (e.g. a file diff the user had focused). + * We must not force-activate the session panel on top of it. + */ + it("does NOT override a restored non-session active panel on first mount", () => { + expect( + shouldActivateSessionPanel({ + ...baseArgs, + sessionPanelExistedBefore: true, + currentActivePanelId: "preview:commit-detail", + }), + ).toBe(false); + expect( + shouldActivateSessionPanel({ + ...baseArgs, + sessionPanelExistedBefore: true, + currentActivePanelId: "preview:file-editor", + }), + ).toBe(false); + expect( + shouldActivateSessionPanel({ + ...baseArgs, + sessionPanelExistedBefore: true, + currentActivePanelId: "plan", + }), + ).toBe(false); + }); + + it("activates on intra-task session switch (same task, different session)", () => { + expect( + shouldActivateSessionPanel({ + sessionPanelExistedBefore: true, + prevTaskId: "task-A", + prevSessionId: "s-old", + currentTaskId: "task-A", + currentSessionId: SID, + currentActivePanelId: "preview:commit-detail", + }), + ).toBe(true); + }); + + it("does NOT activate on task switch (preserves saved active panel for new task)", () => { + expect( + shouldActivateSessionPanel({ + sessionPanelExistedBefore: true, + prevTaskId: "task-A", + prevSessionId: "s-old", + currentTaskId: "task-B", + currentSessionId: SID, + currentActivePanelId: "preview:commit-detail", + }), + ).toBe(false); + }); +}); diff --git a/apps/web/components/task/dockview-session-tabs.ts b/apps/web/components/task/dockview-session-tabs.ts index 13a499b870..dc510b86d8 100644 --- a/apps/web/components/task/dockview-session-tabs.ts +++ b/apps/web/components/task/dockview-session-tabs.ts @@ -478,30 +478,44 @@ export function ensureSessionTabPrecedesNonSessionTabs(api: DockviewApi, session * * - It was just created by `ensureSessionPanel` (no prior dockview state * to honor), or - * - The hook is mounting for the first time (initial page load) — preserve - * the long-standing behavior of focusing the agent tab so the chat is - * visible immediately, even when a saved layout had a different center - * tab active, or + * - The hook is mounting for the first time (initial page load) AND + * dockview did not restore a different active panel from the saved + * layout — fall back to focusing the agent tab so chat is visible, or * - The user switched sessions within the same task (intra-task switch * where dockview hasn't re-activated the new session for us). * * After an env (task) switch the prev refs are populated and the task - * changed — `restoreSavedActiveViews` has already applied the saved active - * panel for the incoming task, so calling setActive here would override it - * and force the agent tab on top of whatever the user had focused. + * changed — the saved layout's active panel has already been restored for + * the incoming task, so calling setActive here would override it and force + * the agent tab on top of whatever the user had focused. + * + * On first mount when the session panel was already in the restored layout, + * respect dockview's restored active panel (e.g. a file diff the user had + * focused before refresh) instead of forcing the agent tab on top. */ -function shouldActivateSessionPanel(args: { +export function shouldActivateSessionPanel(args: { sessionPanelExistedBefore: boolean; prevTaskId: string | null; prevSessionId: string | null; currentTaskId: string | null; currentSessionId: string; + currentActivePanelId: string | null; }): boolean { - const { sessionPanelExistedBefore, prevTaskId, prevSessionId, currentTaskId, currentSessionId } = - args; + const { + sessionPanelExistedBefore, + prevTaskId, + prevSessionId, + currentTaskId, + currentSessionId, + currentActivePanelId, + } = args; if (!sessionPanelExistedBefore) return true; const isFirstMount = prevTaskId === null && prevSessionId === null; - if (isFirstMount) return true; + if (isFirstMount) { + const sessionPanelId = `session:${currentSessionId}`; + if (!currentActivePanelId || currentActivePanelId === sessionPanelId) return true; + return false; + } const taskChanged = prevTaskId !== currentTaskId; const sessionChanged = prevSessionId !== currentSessionId; return sessionChanged && !taskChanged; @@ -527,12 +541,14 @@ function activateSessionPanel( const activePanel = api.getPanel(`session:${effectiveSessionId}`); if (!activePanel) return activePanel; + const currentActivePanelId = api.activePanel?.id ?? null; const shouldActivate = shouldActivateSessionPanel({ sessionPanelExistedBefore, prevTaskId: refs.prevTaskIdRef.current, prevSessionId: refs.prevSessionIdRef.current, currentTaskId: tid, currentSessionId: effectiveSessionId, + currentActivePanelId, }); if (isDebug()) { debug("useAutoSessionTab: activation decision", { @@ -542,6 +558,7 @@ function activateSessionPanel( prevTaskId: refs.prevTaskIdRef.current, prevSessionId: refs.prevSessionIdRef.current, currentTaskId: tid, + currentActivePanelId, activeGroupId: activePanel.group.id, }); } diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts index 68a7eb7fdd..4ab06ffbaf 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts +++ b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts @@ -92,6 +92,7 @@ type SheetItemCtx = { gitStatusByEnvId: Parameters[2]; envIdBySessionId: Parameters[3]; messagesBySession: Parameters[0]; + dismissedAgentErrors: Record; }; function toSheetItem( @@ -135,7 +136,7 @@ function toSheetItem( ctx.messagesBySession, task.primarySessionId, ), - agentErrorMessage: agentErrorMessageForTask(task, ctx.sessionsById, ctx.sessionsByTaskId), + agentErrorMessage: agentErrorMessageForTask(task, ctx.sessionsById, ctx.sessionsByTaskId, ctx), }; } @@ -147,6 +148,7 @@ export function useSheetData(workspaceId: string | null) { const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId); const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId); const messagesBySession = useAppStore((state) => state.messages.bySession); + const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); const { allTasks, allSteps, @@ -176,6 +178,7 @@ export function useSheetData(workspaceId: string | null) { gitStatusByEnvId, envIdBySessionId, messagesBySession, + dismissedAgentErrors, }; return allTasks.map((task) => toSheetItem(task, ctx)); }, [ @@ -189,6 +192,7 @@ export function useSheetData(workspaceId: string | null) { gitStatusByEnvId, envIdBySessionId, messagesBySession, + dismissedAgentErrors, ]); const dialogSteps = useMemo( diff --git a/apps/web/components/task/task-session-sidebar.tsx b/apps/web/components/task/task-session-sidebar.tsx index f257581f72..c1d1d6dde7 100644 --- a/apps/web/components/task/task-session-sidebar.tsx +++ b/apps/web/components/task/task-session-sidebar.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useState, memo } from "react"; import { usePathname, useRouter } from "next/navigation"; import { linkToTask } from "@/lib/links"; -import type { TaskState, TaskSession, TaskSessionState, Repository } from "@/lib/types/http"; +import type { Repository, TaskSession, TaskSessionState, TaskState } from "@/lib/types/http"; import type { TaskPR } from "@/lib/types/github"; import type { KanbanState } from "@/lib/state/slices"; import type { GitStatusEntry } from "@/lib/state/slices/session-runtime/types"; @@ -29,7 +29,7 @@ import { useRepositories } from "@/hooks/domains/workspace/use-repositories"; import { useWorkspacePRs } from "@/hooks/domains/github/use-task-pr"; import { buildPendingFlags, readPendingFlags } from "./task-session-sidebar-aggregate"; import { useShallow } from "zustand/react/shallow"; -import { agentErrorMessageForTask } from "@/lib/task-agent-error"; +import { type AgentErrorOptions, agentErrorMessageForTask } from "@/lib/task-agent-error"; /** * Stabilize a derived array of primary session IDs so the reference only @@ -85,7 +85,7 @@ function toPrInfo(pr: TaskPR | undefined): { number: number; state: string } | u } /** Map a kanban task to a sidebar item with session info and repository metadata. */ -type SidebarCtx = { +type SidebarCtx = AgentErrorOptions & { sessionsById: Record; sessionsByTaskId: Record; gitStatusByEnvId: Record; @@ -160,7 +160,7 @@ function toSidebarItem( isPRReview: task.isPRReview ?? false, isIssueWatch: task.isIssueWatch ?? false, issueInfo: toIssueInfo(task), - agentErrorMessage: agentErrorMessageForTask(task, ctx.sessionsById, ctx.sessionsByTaskId), + agentErrorMessage: agentErrorMessageForTask(task, ctx.sessionsById, ctx.sessionsByTaskId, ctx), }; } @@ -214,6 +214,8 @@ function useSidebarData(workspaceId: string | null) { const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId); const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId); const taskPRsByTaskId = useAppStore((state) => state.taskPRs.byTaskId); + const messagesBySession = useAppStore((state) => state.messages.bySession); + const dismissedAgentErrors = useAppStore((state) => state.dismissedAgentErrors); const archivedState = useArchivedTaskState(); const selectedTaskId = useMemo(() => { @@ -256,6 +258,8 @@ function useSidebarData(workspaceId: string | null) { titleById, workflowNameById, stepTitleById, + dismissedAgentErrors, + messagesBySession, }; const items: SidebarItem[] = allTasks.map((task) => toSidebarItem(task, mapCtx)); if ( @@ -278,6 +282,8 @@ function useSidebarData(workspaceId: string | null) { envIdBySessionId, taskPRsByTaskId, pendingFlags, + dismissedAgentErrors, + messagesBySession, archivedState, ]); diff --git a/apps/web/e2e/tests/layout/pane-resize-right.spec.ts b/apps/web/e2e/tests/layout/pane-resize-right.spec.ts index d2fe6ed784..655b8c6e12 100644 --- a/apps/web/e2e/tests/layout/pane-resize-right.spec.ts +++ b/apps/web/e2e/tests/layout/pane-resize-right.spec.ts @@ -6,6 +6,8 @@ import { getDockviewGroupWidth, resizeColumnViaSplitview, } from "../../helpers/dockview-resize"; +import { KanbanPage } from "../../pages/kanban-page"; +import { SessionPage } from "../../pages/session-page"; test.describe("Right pane resize — viewport-proportional cap", () => { test("resizes past the old 450px hard cap", async ({ testPage, apiClient, seedData }) => { @@ -60,3 +62,72 @@ test.describe("Right pane resize — viewport-proportional cap", () => { expect(narrowWidth).toBeLessThanOrEqual(newCap + 10); }); }); + +test.describe("Right pane width — per-task isolation", () => { + test("a narrow resize in Task A does not leak into Task B", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + await testPage.setViewportSize(WIDE_VIEWPORT); + + // Two tasks, same default layout. Each gets its own env id and its own + // persisted dockview layout in sessionStorage. + await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Right Width Task A", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + const taskB = await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Right Width Task B", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + + const kanban = new KanbanPage(testPage); + await kanban.goto(); + await kanban.taskCardByTitle("Right Width Task A").click(); + await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await session.waitForDockviewReady(); + + // Resize Task A's right column to a deliberately narrow width. The default + // is ~450 on a 1600px viewport, so 240 is unambiguously a user override. + const narrowedA = await resizeColumnViaSplitview(testPage, "right", 240); + expect(narrowedA).toBeLessThan(300); + + // Switch to Task B (no prior resize, default width). Regression: a stale + // global "right" pinned target from Task A's drag used to leak through + // captureRightTarget / enforcePinnedTargets after fromJSON, snapping + // Task B's right column to Task A's narrow width — and the next + // debounced persist would overwrite Task B's saved layout with the + // narrow width, making the leak sticky. + await session.clickTaskInSidebar("Right Width Task B"); + await expect(testPage).toHaveURL((url) => url.pathname.includes(taskB.id), { + timeout: 15_000, + }); + await expect(testPage.locator(".dv-dockview")).toBeVisible({ timeout: 15_000 }); + // Allow fromJSON + fixups-capture + enforcePinnedTargets to settle. + await testPage.waitForTimeout(500); + + const widthB = await getDockviewGroupWidth(testPage, "files"); + expect( + widthB, + `Task B right width ${widthB} should be the default (>350), not Task A's narrow ${narrowedA}`, + ).toBeGreaterThan(350); + }); +}); diff --git a/apps/web/e2e/tests/layout/plan-panel-indicator.spec.ts b/apps/web/e2e/tests/layout/plan-panel-indicator.spec.ts index 0409482bd3..44a055aaf7 100644 --- a/apps/web/e2e/tests/layout/plan-panel-indicator.spec.ts +++ b/apps/web/e2e/tests/layout/plan-panel-indicator.spec.ts @@ -224,9 +224,12 @@ test.describe("Plan panel auto-open + indicator", () => { { timeout: 5_000 }, ); - // Reload + // Reload. After the dockview "preserve restored active tab" change + // (commit 597b35662) Plan stays active on refresh, so session-chat is + // mounted but in the background — foreground it explicitly so the + // page-loaded wait succeeds. await testPage.goto(`/t/${taskId}`); - await session.waitForLoad(); + await session.showSessionContext(); await expect(planTabLocator(testPage)).toBeVisible({ timeout: 15_000 }); await expect(planTabIndicator(testPage)).toHaveCount(0); diff --git a/apps/web/e2e/tests/layout/preview-tab-session-switch.spec.ts b/apps/web/e2e/tests/layout/preview-tab-session-switch.spec.ts index 94c47855a8..06f56a7fd3 100644 --- a/apps/web/e2e/tests/layout/preview-tab-session-switch.spec.ts +++ b/apps/web/e2e/tests/layout/preview-tab-session-switch.spec.ts @@ -265,4 +265,51 @@ test.describe("Preview tab survives session switch", () => { // the session panel is not active.) await expect(fileTabWrapper).toHaveClass(/dv-active-tab/, { timeout: 15_000 }); }); + + test("active center tab is preserved across page refresh", async ({ + testPage, + apiClient, + seedData, + backend, + }) => { + test.setTimeout(120_000); + + const FILE_REFRESH = "refresh-file.ts"; + const git = new GitHelper( + path.join(backend.tmpDir, "repos", "e2e-repo"), + makeGitEnv(backend.tmpDir), + ); + git.createFile(FILE_REFRESH, "// refresh content"); + git.stageAll(); + git.commit("seed refresh"); + + await seedFinishedTask(apiClient, seedData, "Refresh Active Tab Task"); + + const kanban = new KanbanPage(testPage); + await kanban.goto(); + await kanban.taskCardByTitle("Refresh Active Tab Task").click(); + await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); + const session = new SessionPage(testPage); + await session.waitForLoad(); + await session.waitForChatIdle({ timeout: 30_000 }); + + // Open file in preview and ensure it's the active tab in the center group. + await openFileInPreview(testPage, session, FILE_REFRESH); + const fileTabWrapper = tabWrapperByText(testPage, FILE_REFRESH); + await fileTabWrapper.click(); + await expect(fileTabWrapper).toHaveClass(/dv-active-tab/, { timeout: 10_000 }); + + // Refresh the page — Dockview's fromJSON should restore the file tab as + // active. Regression: `useAutoSessionTab`'s first-mount branch used to + // unconditionally call `setActive()` on the session panel after restore, + // overriding the restored active and snapping focus back to the agent tab. + // We can't use `session.waitForLoad()` here because the chat panel is + // intentionally not the active/visible tab after the refresh — that's the + // whole point of the fix. + await testPage.reload(); + await expect(testPage.locator(".dv-dockview")).toBeVisible({ timeout: 15_000 }); + + const restoredFileTabWrapper = tabWrapperByText(testPage, FILE_REFRESH); + await expect(restoredFileTabWrapper).toHaveClass(/dv-active-tab/, { timeout: 15_000 }); + }); }); diff --git a/apps/web/e2e/tests/session/agent-error-indicator.spec.ts b/apps/web/e2e/tests/session/agent-error-indicator.spec.ts index 5ecf46eec9..5544481635 100644 --- a/apps/web/e2e/tests/session/agent-error-indicator.spec.ts +++ b/apps/web/e2e/tests/session/agent-error-indicator.spec.ts @@ -3,7 +3,6 @@ import { waitForSessionDone } from "../../helpers/session"; import { SessionPage } from "../../pages/session-page"; const ERROR_MESSAGE = "peer disconnected before response"; -const ERROR_OCCURRED_AT = "2026-06-14T14:06:40Z"; test.describe("Task agent error indicator", () => { test("shows the last recoverable agent error in the sidebar and chat", async ({ @@ -12,6 +11,10 @@ test.describe("Task agent error indicator", () => { seedData, }) => { const taskTitle = `Recoverable Agent Error ${Date.now()}`; + // Stamp the error in the future so the seeded agent messages from + // /e2e:simple-message (created_at = now) are NOT considered "after" the + // error — otherwise the sidebar icon auto-hides before we can assert it. + const ERROR_OCCURRED_AT = new Date(Date.now() + 60 * 60 * 1000).toISOString(); const task = await apiClient.createTaskWithAgent( seedData.workspaceId, taskTitle, @@ -61,10 +64,13 @@ test.describe("Task agent error indicator", () => { await expect(notice).toContainText("Previous agent error"); await expect(notice).toContainText(ERROR_MESSAGE); - await notice.getByRole("button", { name: "Hide previous agent error" }).click(); - await expect(notice).toBeHidden(); - await errorIcon.hover(); await expect(testPage.getByRole("tooltip")).toContainText(ERROR_MESSAGE); + + // Dismissing the chat notice should also clear the sidebar icon. Both + // surfaces share the dismissal state through the UI store. + await notice.getByRole("button", { name: "Hide previous agent error" }).click(); + await expect(notice).toBeHidden(); + await expect(errorIcon).toBeHidden(); }); }); diff --git a/apps/web/e2e/tests/session/session-resume-dedup.spec.ts b/apps/web/e2e/tests/session/session-resume-dedup.spec.ts index 0a30d35beb..e5208f5a7e 100644 --- a/apps/web/e2e/tests/session/session-resume-dedup.spec.ts +++ b/apps/web/e2e/tests/session/session-resume-dedup.spec.ts @@ -64,8 +64,24 @@ test.describe("Session resume boot-message dedup", () => { timeout: 15_000, }); - // 6. Agent interaction still works after dedup. - await session.sendMessage("/e2e:simple-message"); + // 6. Agent interaction still works after dedup. After two restart+reload+ + // auto-resume cycles, the editor's submit handler can race with WS + // resubscription: the keystroke is accepted by the optimistic input + // but the message never reaches the backend, so neither the user + // prompt nor the agent reply ever appear (no reload can recover them + // because they were never persisted). Verify the user prompt actually + // echoes in the chat; if not, the send was dropped, so re-idle and + // resend once before asserting the reply. + const followupPrompt = "/e2e:simple-message"; + await session.sendMessage(followupPrompt); + const followupEcho = session.chat.getByText(followupPrompt, { exact: false }).nth(1); + try { + await expect(followupEcho).toBeVisible({ timeout: 10_000 }); + } catch { + await session.waitForChatIdle({ timeout: 30_000 }); + await session.sendMessage(followupPrompt); + await expect(followupEcho).toBeVisible({ timeout: 15_000 }); + } await session.expectChatResponseVisible("simple mock response", 1, { timeout: 30_000 }); }); }); diff --git a/apps/web/e2e/tests/terminal/terminal-dockview-ui.spec.ts b/apps/web/e2e/tests/terminal/terminal-dockview-ui.spec.ts index fe20468f93..3e98483d69 100644 --- a/apps/web/e2e/tests/terminal/terminal-dockview-ui.spec.ts +++ b/apps/web/e2e/tests/terminal/terminal-dockview-ui.spec.ts @@ -194,7 +194,11 @@ test.describe("Terminals — dockview UI", () => { await testPage.waitForTimeout(800); await testPage.reload(); - await session.waitForLoad(); + // After the dockview "preserve restored active tab" change (commit + // 597b35662), the Terminal tab the user activated above stays active + // on refresh, so session-chat is in the background — foreground it + // explicitly so the page-loaded wait succeeds. + await session.showSessionContext(); // After reload, both badges must reappear — proves both panels' // store entries (kind=ordinary, seq) were preserved across restore. diff --git a/apps/web/lib/session-last-agent-error.test.ts b/apps/web/lib/session-last-agent-error.test.ts index d3db0107b2..90004e385d 100644 --- a/apps/web/lib/session-last-agent-error.test.ts +++ b/apps/web/lib/session-last-agent-error.test.ts @@ -1,6 +1,11 @@ -import { describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it } from "vitest"; -import { lastAgentErrorDismissKey, readLastAgentError } from "./session-last-agent-error"; +import { + getStoredDismissedAgentErrors, + lastAgentErrorStamp, + readLastAgentError, + setStoredDismissedAgentErrors, +} from "./session-last-agent-error"; const AGENT_ERROR_MESSAGE = "agent process exited"; const AGENT_EXECUTION_ID = "exec-1"; @@ -38,13 +43,40 @@ describe("readLastAgentError", () => { }); }); -describe("lastAgentErrorDismissKey", () => { - it("includes both timestamp and message in the dismissal stamp", () => { - expect( - lastAgentErrorDismissKey("session-1", { - message: AGENT_ERROR_MESSAGE, - occurredAt: OCCURRED_AT, - }), - ).toBe(`kandev:last-agent-error-dismissed:session-1:${OCCURRED_AT}:${AGENT_ERROR_MESSAGE}`); +describe("lastAgentErrorStamp", () => { + it("combines occurredAt and message so a fresh error invalidates a prior dismissal", () => { + expect(lastAgentErrorStamp({ message: AGENT_ERROR_MESSAGE, occurredAt: OCCURRED_AT })).toBe( + `${OCCURRED_AT}:${AGENT_ERROR_MESSAGE}`, + ); + }); + + it("tolerates a missing occurredAt", () => { + expect(lastAgentErrorStamp({ message: AGENT_ERROR_MESSAGE })).toBe(`:${AGENT_ERROR_MESSAGE}`); + }); +}); + +describe("setStoredDismissedAgentErrors", () => { + beforeEach(() => { + window.localStorage.clear(); + }); + + it("merges with existing entries so a concurrent tab's writes are not clobbered", () => { + // Simulate a write from another tab landing first. + setStoredDismissedAgentErrors({ "session-other-tab": "stamp-other" }); + + // This tab then dismisses for a different session using a stale snapshot + // (i.e. one that does not include `session-other-tab`). + setStoredDismissedAgentErrors({ "session-this-tab": "stamp-this" }); + + expect(getStoredDismissedAgentErrors()).toEqual({ + "session-other-tab": "stamp-other", + "session-this-tab": "stamp-this", + }); + }); + + it("overwrites existing entries for the same session id", () => { + setStoredDismissedAgentErrors({ "session-a": "stamp-v1" }); + setStoredDismissedAgentErrors({ "session-a": "stamp-v2" }); + expect(getStoredDismissedAgentErrors()).toEqual({ "session-a": "stamp-v2" }); }); }); diff --git a/apps/web/lib/session-last-agent-error.ts b/apps/web/lib/session-last-agent-error.ts index 8c7cff0ad1..10fd21634b 100644 --- a/apps/web/lib/session-last-agent-error.ts +++ b/apps/web/lib/session-last-agent-error.ts @@ -1,9 +1,33 @@ +import { getLocalStorage, setLocalStorage } from "@/lib/local-storage"; + export type LastAgentError = { message: string; occurredAt?: string; agentExecutionId?: string; }; +// --- Dismissed agent errors (localStorage, global) --- +// +// Tracks the most recent dismissed `last_agent_error` stamp per session so the +// red error icon in the sidebar and the chat banner can share dismissal state +// across components and reloads. Bounded growth: one entry per session that +// ever had an error. + +const DISMISSED_AGENT_ERRORS_KEY = "kandev.dismissedAgentErrors"; + +export function getStoredDismissedAgentErrors(): Record { + return getLocalStorage>(DISMISSED_AGENT_ERRORS_KEY, {}); +} +/** + * Merge `map` into whatever is currently in localStorage so concurrent writes + * from other tabs (or older versions of this tab's state) are not clobbered. + * Entries in `map` win over the on-disk values for the same session. + */ +export function setStoredDismissedAgentErrors(map: Record): void { + const current = getStoredDismissedAgentErrors(); + setLocalStorage(DISMISSED_AGENT_ERRORS_KEY, { ...current, ...map }); +} + export function readLastAgentError(metadata: Record | null | undefined) { if (!metadata) return null; const raw = metadata.last_agent_error; @@ -19,9 +43,14 @@ export function readLastAgentError(metadata: Record | null | un } satisfies LastAgentError; } -export function lastAgentErrorDismissKey(sessionId: string, error: LastAgentError) { - const stamp = `${error.occurredAt ?? ""}:${error.message}`; - return `kandev:last-agent-error-dismissed:${sessionId}:${stamp}`; +/** + * Stable identifier for a specific error event. Two errors share a stamp iff + * they have the same occurredAt timestamp and message. Used to decide whether + * a prior dismissal still applies after a fresh failure replaces the + * `last_agent_error` metadata. + */ +export function lastAgentErrorStamp(error: LastAgentError) { + return `${error.occurredAt ?? ""}:${error.message}`; } function readOptionalString(value: unknown) { diff --git a/apps/web/lib/state/dockview-env-switch-pinned.test.ts b/apps/web/lib/state/dockview-env-switch-pinned.test.ts index 2828b14bec..a9703c4d90 100644 --- a/apps/web/lib/state/dockview-env-switch-pinned.test.ts +++ b/apps/web/lib/state/dockview-env-switch-pinned.test.ts @@ -38,6 +38,8 @@ vi.mock("./layout-manager", () => { // formatWidthsSnapshot debug log it now emits. setPinnedTarget: vi.fn(), getPinnedTarget: vi.fn(() => undefined), + RIGHT_TOP_GROUP: "group-right-top", + RIGHT_BOTTOM_GROUP: "group-right-bottom", }; }); @@ -152,7 +154,10 @@ describe("performEnvSwitch — pinned column resize after fast-path", () => { data: [ { type: "leaf", data: { id: "g1", views: ["sidebar"] }, size: 420 }, { type: "leaf", data: { id: "g2", views: ["chat"] }, size: 760 }, - { type: "leaf", data: { id: "g3", views: ["files"] }, size: 420 }, + // Last leaf MUST carry the pinned right-column group id so + // savedRightColumnWidth detects this as a real right column and + // forwards 420 to applyLayoutFixups. + { type: "leaf", data: { id: "group-right-top", views: ["files"] }, size: 420 }, ], }, height: 600, diff --git a/apps/web/lib/state/dockview-env-switch.test.ts b/apps/web/lib/state/dockview-env-switch.test.ts index 67a39f58c2..401f92a713 100644 --- a/apps/web/lib/state/dockview-env-switch.test.ts +++ b/apps/web/lib/state/dockview-env-switch.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { performEnvSwitch, type EnvSwitchParams } from "./dockview-env-switch"; +import { + performEnvSwitch, + savedRightColumnWidth, + type EnvSwitchParams, +} from "./dockview-env-switch"; +import type { SerializedDockview } from "dockview-react"; vi.mock("@/lib/local-storage", () => ({ getEnvLayout: vi.fn(() => null), @@ -20,6 +25,9 @@ vi.mock("./layout-manager", () => ({ layoutStructuresMatch: vi.fn(() => false), getRootSplitview: vi.fn(() => null), getPinnedWidth: vi.fn(() => 350), + setPinnedTarget: vi.fn(), + RIGHT_TOP_GROUP: "group-right-top", + RIGHT_BOTTOM_GROUP: "group-right-bottom", })); import { getEnvLayout } from "@/lib/local-storage"; @@ -412,3 +420,59 @@ describe("performEnvSwitch fast-path active view restoration", () => { expect(lastRightCall).toBeGreaterThan(lastCenterCall); }); }); + +describe("savedRightColumnWidth", () => { + function makeSaved(children: Array<{ id: string; size: number }>): SerializedDockview { + return { + grid: { + root: { + type: "branch", + data: children.map((c) => ({ + type: "leaf", + data: { id: c.id, views: [] }, + size: c.size, + })), + }, + height: 600, + width: 1600, + orientation: "HORIZONTAL", + }, + panels: {}, + activeGroup: undefined, + } as unknown as SerializedDockview; + } + + it("returns the saved right size for a 3-column layout (sidebar+center+right)", () => { + const saved = makeSaved([ + { id: "group-sidebar", size: 300 }, + { id: "group-center", size: 1000 }, + { id: "group-right-top", size: 300 }, + ]); + expect(savedRightColumnWidth(saved)).toBe(300); + }); + + it("returns the saved right size for a 2-column layout with sidebar hidden", () => { + // Regression: pre-fix this returned undefined (column-count gate), which + // caused the right column to fall back to ~450 default on env switch + // instead of restoring the user's narrow width. + const saved = makeSaved([ + { id: "group-center", size: 1380 }, + { id: "group-right-top", size: 220 }, + ]); + expect(savedRightColumnWidth(saved)).toBe(220); + }); + + it("returns undefined for a 2-column layout where the last child is not a right column", () => { + // 2-column layouts can also be sidebar+center (right hidden); we must NOT + // mistake the center for the right column. + const saved = makeSaved([ + { id: "group-sidebar", size: 300 }, + { id: "group-center", size: 1300 }, + ]); + expect(savedRightColumnWidth(saved)).toBeUndefined(); + }); + + it("returns undefined for null input", () => { + expect(savedRightColumnWidth(null)).toBeUndefined(); + }); +}); diff --git a/apps/web/lib/state/dockview-env-switch.ts b/apps/web/lib/state/dockview-env-switch.ts index 51aeca4464..f972eed274 100644 --- a/apps/web/lib/state/dockview-env-switch.ts +++ b/apps/web/lib/state/dockview-env-switch.ts @@ -18,11 +18,17 @@ import { getPinnedWidth, getRootSplitview, setPinnedTarget, + RIGHT_TOP_GROUP, + RIGHT_BOTTOM_GROUP, } from "./layout-manager"; import type { LayoutState, LayoutGroupIds } from "./layout-manager"; import { ENV_SCOPED_DOCKVIEW_COMPONENTS } from "./dockview-env-scoped-components"; import { createDebugLogger, isDebug } from "@/lib/debug/log"; -import { snapshotColumnWidths, formatWidthsSnapshot } from "./dockview-widths-debug"; +import { + snapshotColumnWidths, + formatWidthsSnapshot, + formatJsonRootSizes, +} from "./dockview-widths-debug"; const debug = createDebugLogger("dockview:env-switch"); const debugWidths = createDebugLogger("dockview:widths"); @@ -335,15 +341,45 @@ function tryFastEnvSwitch(params: EnvSwitchParams): LayoutGroupIds | null { * right column. Forwarded to `applyLayoutFixups` so the fixups pass anchors the * pinned right target to this stable saved width instead of dockview's * transient post-`fromJSON` live size (the dockview-wrong-width drift). + * + * The right column is identified by the presence of RIGHT_TOP_GROUP / + * RIGHT_BOTTOM_GROUP inside the last grid-root child — NOT by column count. + * A task with the sidebar hidden has only 2 grid-root children but the last + * one is still the pinned right branch; column-count gating leaked Task A's + * resized width into Task B's restored layout (per-task width persistence bug). */ export function savedRightColumnWidth(saved: SerializedDockview | null): number | undefined { if (!saved) return undefined; const sizes = extractSavedColumnSizes(saved); - if (!sizes || sizes.length < 3) return undefined; + if (!sizes || sizes.length < 2) return undefined; + if (!savedLastChildIsRightColumn(saved)) return undefined; const w = sizes[sizes.length - 1]; return Number.isFinite(w) && w > 0 ? w : undefined; } +/** True when the last grid-root child contains a pinned right column group. */ +function savedLastChildIsRightColumn(saved: SerializedDockview): boolean { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const root = (saved as any).grid?.root; + if (!root?.data || !Array.isArray(root.data) || root.data.length < 2) return false; + const last = root.data[root.data.length - 1]; + return leafContainsRightGroup(last); +} + +/** True when a serialized leaf-or-branch node contains a pinned right group. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function leafContainsRightGroup(node: any): boolean { + if (!node) return false; + if (node.type === "leaf") { + const id = node.data?.id; + return id === RIGHT_TOP_GROUP || id === RIGHT_BOTTOM_GROUP; + } + if (node.type === "branch" && Array.isArray(node.data)) { + return node.data.some((c: unknown) => leafContainsRightGroup(c)); + } + return false; +} + /** Extract per-column sizes from a saved SerializedDockview grid root. */ function extractSavedColumnSizes(saved: SerializedDockview): number[] | null { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -487,6 +523,10 @@ export function performEnvSwitch(params: EnvSwitchParams): LayoutGroupIds { savedPanelIds, savedShape, }); + debugWidths( + `slow-path-load env=${newEnvId} savedSizes=${formatJsonRootSizes(saved)} ` + + `savedRight=${savedRightColumnWidth(saved as SerializedDockview) ?? "-"}`, + ); } api.fromJSON(saved as SerializedDockview); // Saved layout may carry a stale session panel from a previously-deleted diff --git a/apps/web/lib/state/dockview-layout-builders-fixups.test.ts b/apps/web/lib/state/dockview-layout-builders-fixups.test.ts index 1bf4eb7ff0..6f404a9e79 100644 --- a/apps/web/lib/state/dockview-layout-builders-fixups.test.ts +++ b/apps/web/lib/state/dockview-layout-builders-fixups.test.ts @@ -187,4 +187,29 @@ describe("applyLayoutFixups — pinned target capture", () => { expect(setPinnedTarget).toHaveBeenCalledWith("right", RIGHT_CAP); }); + + it("captures the right target in a 2-column layout with the pinned right column (no sidebar)", () => { + // Regression: a task whose saved layout has the sidebar hidden restores + // as a 2-column splitview [center, right]. Without per-env capture there, + // the stale global right target from a previous task's drag leaks through + // enforcePinnedTargets and snaps the restored column to the wrong width. + // The pinned right groups exist, so the last child IS the right column. + mockSplitview([720, 400]); // idx0 = center, idx1 = right + const api = makeApi([CENTER_GROUP, RIGHT_TOP_GROUP, RIGHT_BOTTOM_GROUP]); + + applyLayoutFixups(api, 420); + + expect(setPinnedTarget).toHaveBeenCalledWith("right", 420); + expect(mockResizeView).toHaveBeenCalledWith(1, 420); + }); + + it("uses the column default for a 2-column pinned right layout when no saved width is given", () => { + mockSplitview([720, 400]); + const api = makeApi([CENTER_GROUP, RIGHT_TOP_GROUP]); + + applyLayoutFixups(api); + + expect(setPinnedTarget).toHaveBeenCalledWith("right", 350); // default + expect(setPinnedTarget).not.toHaveBeenCalledWith("right", 400); // not live + }); }); diff --git a/apps/web/lib/state/dockview-layout-builders.ts b/apps/web/lib/state/dockview-layout-builders.ts index c0ee44f12f..5528bbb2ce 100644 --- a/apps/web/lib/state/dockview-layout-builders.ts +++ b/apps/web/lib/state/dockview-layout-builders.ts @@ -152,12 +152,19 @@ function resolveRightTarget( * For the vscode/preview/plan presets the side column has a generated group id * and is NOT pinned, so there is no saved/default width to fall back on; there * we keep recording the just-restored live width so switching to one of those - * tasks doesn't leak the previous task's right target. + * tasks doesn't leak the previous task's right target. Identified by + * `sv.length >= 3` (sidebar + center + side), since we have no stable group id + * to key off. * - * `sv.length >= 3` excludes the 2-column global-fallback restore (sidebar + - * center, right panels stripped as env-scoped), where the last splitview child - * is the CENTER column — recording its width as the "right" target would - * inflate the real right column once the full layout materializes. */ + * The default-preset branch runs regardless of column count: a task with the + * sidebar hidden has sv.length=2 but the LAST child IS the pinned right + * column. Without per-env capture there, the stale global right target from a + * previous task's drag leaks through `enforcePinnedTargets` and snaps the + * restored column to the wrong width (per-task width persistence bug). + * + * The 2-column global-fallback restore (sidebar + center, right panels + * stripped) is excluded because neither right group exists in `api.groups` + * and `sv.length < 3` — its last splitview child is the CENTER column. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function captureRightTarget(api: DockviewApi, sv: any, savedRightWidth?: number): void { // Constrain the default preset's right column groups (stable well-known IDs). @@ -172,10 +179,12 @@ function captureRightTarget(api: DockviewApi, sv: any, savedRightWidth?: number) group.api.setConstraints({ maximumWidth: rightCap, minimumWidth: LAYOUT_PINNED_MIN_PX }); } } - if (!sv || sv.length < 3) return; + if (!sv || sv.length < 2) return; const idx = sv.length - 1; // Default preset (pinned right column): anchor to saved-or-default, resize the - // column to it, and record it as the target. Never the live size. + // column to it, and record it as the target. Never the live size. Works for + // both 3-column (sidebar+center+right) and 2-column (center+right, sidebar + // hidden) layouts since the right column is always at sv.length-1. if (api.groups.some((g) => g.id === RIGHT_TOP_GROUP || g.id === RIGHT_BOTTOM_GROUP)) { const target = resolveRightTarget(rightCap, measuredWidth, savedRightWidth); const cur = sv.getViewSize(idx); @@ -189,7 +198,10 @@ function captureRightTarget(api: DockviewApi, sv: any, savedRightWidth?: number) setPinnedTarget("right", target); return; } - // Non-default presets: side column is not pinned — keep the live width. + // Non-default presets (vscode/preview/plan): side column has a generated + // group id, so we need `sv.length >= 3` to know the last splitview child is + // the side column (not the center in a 2-column fallback). + if (sv.length < 3) return; const liveRight = sv.getViewSize(idx); if (typeof liveRight === "number" && liveRight > 0) { setPinnedTarget("right", Math.min(liveRight, rightCap)); @@ -210,9 +222,14 @@ function logFixupsCapture(api: DockviewApi, sv: any): void { const sidebarCap = computeSidebarMaxPx(w); const innerW = typeof window !== "undefined" ? window.innerWidth : -1; const liveSidebar = sv?.getViewSize?.(0); - // Threshold matches captureRightTarget (>= 3): in a 2-column layout the last - // child is the center, not a right column, so we don't mislabel it here. - const liveRight = sv && sv.length >= 3 ? sv.getViewSize(sv.length - 1) : undefined; + // A 2-column layout's last child is the right column only when the pinned + // right groups exist (default preset, sidebar hidden); otherwise it's the + // center (global-fallback restore). Mirrors captureRightTarget. + const hasPinnedRight = api.groups.some( + (g) => g.id === RIGHT_TOP_GROUP || g.id === RIGHT_BOTTOM_GROUP, + ); + const rightIdxIsRight = sv && (sv.length >= 3 || (sv.length === 2 && hasPinnedRight)); + const liveRight = rightIdxIsRight ? sv.getViewSize(sv.length - 1) : undefined; const r = (n: number | undefined): string => typeof n === "number" ? String(Math.round(n)) : "-"; debugWidths( diff --git a/apps/web/lib/state/dockview-panel-actions.test.ts b/apps/web/lib/state/dockview-panel-actions.test.ts index 6e976b63db..ae9ef7e71b 100644 --- a/apps/web/lib/state/dockview-panel-actions.test.ts +++ b/apps/web/lib/state/dockview-panel-actions.test.ts @@ -16,14 +16,15 @@ type MockPanel = { api: { setActive: () => void; updateParameters: (p: Record) => void; + moveTo: (opts: { group: { id: string } }) => void; }; setTitle: (t: string) => void; }; -function makeApi(options: { centerGroupId?: string } = {}): DockviewApi { +function makeApi(options: { centerGroupId?: string; extraGroupIds?: string[] } = {}): DockviewApi { const centerId = options.centerGroupId ?? CENTER_GROUP; const panels: MockPanel[] = []; - const groups = [{ id: centerId }]; + const groups = [{ id: centerId }, ...(options.extraGroupIds ?? []).map((id) => ({ id }))]; function makePanel(add: AddPanelOptions & { id: string }): MockPanel { const groupId = @@ -46,6 +47,9 @@ function makeApi(options: { centerGroupId?: string } = {}): DockviewApi { updateParameters(p: Record) { Object.assign(panel.params, p); }, + moveTo({ group }: { group: { id: string } }) { + panel.group = { id: group.id }; + }, }, }; return panel; @@ -61,6 +65,9 @@ function makeApi(options: { centerGroupId?: string } = {}): DockviewApi { getPanel(id: string) { return panels.find((p) => p.id === id); }, + getGroup(id: string) { + return groups.find((g) => g.id === id); + }, addPanel(opts: AddPanelOptions & { id: string }) { const p = makePanel(opts); panels.push(p); @@ -325,6 +332,32 @@ describe("addFileDiffPanel — preview behavior", () => { expect(preview.params.path).toBe(PATH_B); expect(preview.params.promoted).toBeUndefined(); }); + + // Regression: a saved env layout can restore `preview:file-diff` into the + // right column. A subsequent click on a file in the Changes panel should + // relocate the preview into the explicitly requested (center) group rather + // than silently reusing the restored slot. + it("moves an existing preview to the requested group when groupId differs", () => { + const rightTopId = "group-right-top"; + ({ api, actions } = build(makeApi({ extraGroupIds: [rightTopId] }))); + + actions.addFileDiffPanel(PATH_A, { groupId: rightTopId }); + const preview = api.getPanel(PREVIEW_DIFF_ID) as unknown as MockPanel; + expect(preview.group.id).toBe(rightTopId); + + actions.addFileDiffPanel(PATH_B); // defaults to centerGroupId + expect(preview.group.id).toBe(CENTER_GROUP); + expect(preview.params.path).toBe(PATH_B); + }); + + it("leaves the preview in place when groupId already matches", () => { + actions.addFileDiffPanel(PATH_A); + const preview = api.getPanel(PREVIEW_DIFF_ID) as unknown as MockPanel; + expect(preview.group.id).toBe(CENTER_GROUP); + + actions.addFileDiffPanel(PATH_B); + expect(preview.group.id).toBe(CENTER_GROUP); + }); }); describe("addCommitDetailPanel — preview behavior", () => { diff --git a/apps/web/lib/state/dockview-panel-actions.ts b/apps/web/lib/state/dockview-panel-actions.ts index ed5bb24ddb..69a9577563 100644 --- a/apps/web/lib/state/dockview-panel-actions.ts +++ b/apps/web/lib/state/dockview-panel-actions.ts @@ -1,4 +1,4 @@ -import type { DockviewApi } from "dockview-react"; +import type { DockviewApi, DockviewGroupPanel } from "dockview-react"; import { focusOrAddPanel } from "./dockview-layout-builders"; type StoreGet = () => { @@ -86,12 +86,29 @@ type OpenPreviewArgs = { pinnedTabComponent?: string; }; +/** Move the preview panel into the explicitly requested group when it currently + * lives elsewhere — e.g. a saved env layout restored `preview:file-diff` into + * the right column, but the user just clicked a file in the changes panel + * expecting the diff to land in the center group. */ +function movePreviewToRequestedGroup( + preview: ReturnType & object, + api: DockviewApi, + groupId: string, +): void { + if (!groupId || preview.group?.id === groupId) return; + const target = api.getGroup(groupId); + if (!target) return; + // `api.getGroup` returns `IDockviewGroupPanel` but `moveTo` requires the + // concrete `DockviewGroupPanel`; at runtime they're the same object. + preview.api.moveTo({ group: target as DockviewGroupPanel }); +} + /** Update an existing preview panel with new content, materializing promoted items first. */ function updateExistingPreview( preview: ReturnType & object, args: OpenPreviewArgs, ): void { - const { api, type, itemId, title, params, quiet, pinnedTabComponent } = args; + const { api, type, itemId, title, params, groupId, quiet, pinnedTabComponent } = args; const currentItemId = preview.params?.previewItemId as string | undefined; if (preview.params?.promoted && currentItemId && currentItemId !== itemId) { materializePromotedPreview(api, type, pinnedTabComponent ?? PINNED_TAB); @@ -106,6 +123,7 @@ function updateExistingPreview( promoted: keepPromoted || undefined, }); preview.setTitle(title); + movePreviewToRequestedGroup(preview, api, groupId); if (!quiet) preview.api.setActive(); } diff --git a/apps/web/lib/state/dockview-store.ts b/apps/web/lib/state/dockview-store.ts index 1f45d8cd20..46f87bf8d2 100644 --- a/apps/web/lib/state/dockview-store.ts +++ b/apps/web/lib/state/dockview-store.ts @@ -46,7 +46,11 @@ import { preserveChatScrollDuringLayout } from "./dockview-scroll-preserve"; import { measureDockviewContainer } from "./dockview-measure"; import { panelPortalManager } from "@/lib/layout/panel-portal-manager"; import { createDebugLogger, isDebug } from "@/lib/debug/log"; -import { snapshotColumnWidths, formatWidthsSnapshot } from "./dockview-widths-debug"; +import { + snapshotColumnWidths, + formatWidthsSnapshot, + formatJsonRootSizes, +} from "./dockview-widths-debug"; const debugSwitch = createDebugLogger("dockview:store-switch"); const debugSave = createDebugLogger("dockview:save"); @@ -661,7 +665,14 @@ function saveOutgoingEnv( } else { removeEnvMaximizeState(oldEnvId); try { - setEnvLayout(oldEnvId, api.toJSON()); + const json = api.toJSON(); + setEnvLayout(oldEnvId, json); + if (isDebug()) { + debugWidths( + `save-outgoing env=${oldEnvId} ${formatWidthsSnapshot(snapshotColumnWidths(api))} ` + + `jsonSizes=${formatJsonRootSizes(json)}`, + ); + } } catch { /* ignore */ } diff --git a/apps/web/lib/state/dockview-widths-debug.ts b/apps/web/lib/state/dockview-widths-debug.ts index 75cf130a59..2136ea955a 100644 --- a/apps/web/lib/state/dockview-widths-debug.ts +++ b/apps/web/lib/state/dockview-widths-debug.ts @@ -59,3 +59,17 @@ export function formatWidthsSnapshot(snap: ColumnWidthsSnapshot): string { `cols=${snap.columns} api=${snap.apiW}x${snap.apiH} tgt=L${tL}/R${tR}` ); } + +/** Comma-joined top-level grid-root child sizes from a serialized dockview + * layout (`json.grid.root.data[].size`). Used to compare what `api.toJSON()` + * actually serializes against the live splitview widths — they should match, + * but a dockview internal lag/desync would surface here. Returns "-" when the + * shape doesn't look like a serialized dockview layout. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function formatJsonRootSizes(json: any): string { + const children = json?.grid?.root?.data; + if (!Array.isArray(children)) return "-"; + return children + .map((c) => (typeof c?.size === "number" ? String(Math.round(c.size)) : "?")) + .join(","); +} diff --git a/apps/web/lib/state/layout-manager/merger.test.ts b/apps/web/lib/state/layout-manager/merger.test.ts index 64d3663f22..afb3522e3e 100644 --- a/apps/web/lib/state/layout-manager/merger.test.ts +++ b/apps/web/lib/state/layout-manager/merger.test.ts @@ -157,6 +157,40 @@ describe("mergePanelsIntoPreset", () => { ]); expect(panelIdsIn(result, "right")).toEqual(["changes", "files"]); }); +}); + +describe("mergePanelsIntoPreset — preview panel center affinity", () => { + it("keeps file-diff/file-editor/commit-detail previews in the center on default preset", () => { + // Switching back to the "default" preset with file diffs / pinned file + // editors / commit detail panels open in the center group — these are + // main-content surfaces and must follow the chat into center, not get + // stranded in the narrow right "tools" column alongside files/changes. + const currentState = makeLayoutWithSide([{ id: SESSION_ABC, component: "chat" }], "preview", [ + { id: "preview:file-diff", component: "diff-viewer" }, + { id: "preview:file-editor", component: "file-editor" }, + { id: "preview:commit-detail", component: "commit-detail" }, + { id: "file:src/app.ts", component: "file-editor" }, + { id: "diff:file:src/app.ts", component: "diff-viewer" }, + { id: "commit:abc123", component: "commit-detail" }, + ]); + const targetPreset = makeLayoutWithSide([{ id: "chat", component: "chat" }], "right", [ + { id: "files", component: "files" }, + { id: "changes", component: "changes" }, + ]); + + const result = mergePanelsIntoPreset(currentState, targetPreset); + + expect(panelIdsIn(result, "center")).toEqual([ + SESSION_ABC, + "preview:file-diff", + "preview:file-editor", + "preview:commit-detail", + "file:src/app.ts", + "diff:file:src/app.ts", + "commit:abc123", + ]); + expect(panelIdsIn(result, "right")).toEqual(["files", "changes"]); + }); it("falls back to center for side extras when the target preset has no side column", () => { const currentState = makeLayoutWithSide([{ id: SESSION_ABC, component: "chat" }], "right", [ diff --git a/apps/web/lib/state/layout-manager/merger.ts b/apps/web/lib/state/layout-manager/merger.ts index f22fc86e7b..af19b0c7dd 100644 --- a/apps/web/lib/state/layout-manager/merger.ts +++ b/apps/web/lib/state/layout-manager/merger.ts @@ -8,13 +8,23 @@ const PRESET_ONLY_PANELS = new Set(["sidebar"]); /** Components that, when surviving as extras on a layout switch, belong next * to the chat/agent tabs in the CENTER column rather than the narrow side * "tools" column. These are main-content surfaces — the plan, the browser, - * the VS Code editor, and PR detail — whereas files/changes/terminal are - * tools that stay in the side column. Switching from the plan/vscode/preview - * preset back to default must not strand these in the right column. + * the VS Code editor, PR detail, and file/commit/diff previews — whereas + * files/changes/terminal are tools that stay in the side column. Switching + * from the plan/vscode/preview preset back to default must not strand these + * in the right column. * * Matched by component (not id) because some carry dynamic ids — a browser - * panel is `browser:`, not a literal `browser`. */ -const CENTER_EXTRA_COMPONENTS = new Set(["plan", "browser", "vscode", "pr-detail"]); + * panel is `browser:`, not a literal `browser`; a pinned file editor + * is `file:` with component `file-editor`. */ +const CENTER_EXTRA_COMPONENTS = new Set([ + "plan", + "browser", + "vscode", + "pr-detail", + "file-editor", + "commit-detail", + "diff-viewer", +]); /** Collect all panels from a LayoutState, flattened. */ function collectAllPanels(state: LayoutState): LayoutPanel[] { diff --git a/apps/web/lib/state/slices/ui/dismissed-agent-errors-actions.ts b/apps/web/lib/state/slices/ui/dismissed-agent-errors-actions.ts new file mode 100644 index 0000000000..09801497ea --- /dev/null +++ b/apps/web/lib/state/slices/ui/dismissed-agent-errors-actions.ts @@ -0,0 +1,24 @@ +import { + getStoredDismissedAgentErrors, + setStoredDismissedAgentErrors, +} from "@/lib/session-last-agent-error"; +import type { UISlice } from "./types"; + +type ImmerSet = (recipe: (draft: UISlice) => void) => void; + +export function buildDismissedAgentErrors(set: ImmerSet) { + return { + dismissedAgentErrors: getStoredDismissedAgentErrors(), + dismissAgentError: (sessionId: string, stamp: string) => { + if (!sessionId || !stamp) return; + set((draft) => { + draft.dismissedAgentErrors[sessionId] = stamp; + }); + // Persist only the new entry. setStoredDismissedAgentErrors merges into + // the current localStorage snapshot, so a concurrent tab's dismissals + // for OTHER sessions survive, and only this single (sessionId, stamp) + // pair can race with another tab — which is the intended scope. + setStoredDismissedAgentErrors({ [sessionId]: stamp }); + }, + }; +} diff --git a/apps/web/lib/state/slices/ui/types.ts b/apps/web/lib/state/slices/ui/types.ts index 495481b3a3..dd2034f993 100644 --- a/apps/web/lib/state/slices/ui/types.ts +++ b/apps/web/lib/state/slices/ui/types.ts @@ -154,6 +154,12 @@ export type UISliceState = { sidebarTaskPrefs: SidebarTaskPrefsState; /** Unified AppSidebar collapse + section expand state (localStorage). */ appSidebar: AppSidebarState; + /** + * Most recently dismissed `last_agent_error` stamp per sessionId. Shared by + * the chat banner and the sidebar error icon so dismissing the banner also + * hides the icon. Persisted to localStorage. + */ + dismissedAgentErrors: Record; }; export type UISliceActions = { @@ -223,6 +229,8 @@ export type UISliceActions = { toggleAppSidebarSection: (sectionId: string, defaultExpanded?: boolean) => void; setAppSidebarWidth: (width: number) => void; toggleAppSidebarSettingsMode: () => void; + /** Record that `stamp` has been dismissed for `sessionId`. */ + dismissAgentError: (sessionId: string, stamp: string) => void; }; export type { SidebarView, SidebarViewDraft }; diff --git a/apps/web/lib/state/slices/ui/ui-slice.ts b/apps/web/lib/state/slices/ui/ui-slice.ts index 38cb911238..8f4c093dec 100644 --- a/apps/web/lib/state/slices/ui/ui-slice.ts +++ b/apps/web/lib/state/slices/ui/ui-slice.ts @@ -16,6 +16,7 @@ import { setStoredSidebarDraft, setStoredSidebarUserViews, } from "@/lib/local-storage"; +import { buildDismissedAgentErrors } from "./dismissed-agent-errors-actions"; import { DEFAULT_SECTION_EXPANDED, buildAppSidebarActions, @@ -134,6 +135,7 @@ export const defaultUIState: UISliceState = { width: APP_SIDEBAR_EXPANDED_WIDTH, settingsMode: false, }, + dismissedAgentErrors: {}, }; type ImmerSet = Parameters[0]; @@ -554,6 +556,7 @@ export const createUISlice: StateCreator set((draft) => { draft.rightPanel.activeTabBySessionId[sessionId] = tab; diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index 7442ea2951..bf861acf84 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -233,6 +233,7 @@ export type AppState = { kanbanPreviewedTaskId: (typeof defaultUIState)["kanbanPreviewedTaskId"]; sidebarTaskPrefs: (typeof defaultUIState)["sidebarTaskPrefs"]; appSidebar: (typeof defaultUIState)["appSidebar"]; + dismissedAgentErrors: (typeof defaultUIState)["dismissedAgentErrors"]; // GitLab actions setTaskMRs: (mrs: Record) => void; @@ -527,6 +528,7 @@ export type AppState = { toggleAppSidebarSection: UIA["toggleAppSidebarSection"]; setAppSidebarWidth: UIA["setAppSidebarWidth"]; toggleAppSidebarSettingsMode: UIA["toggleAppSidebarSettingsMode"]; + dismissAgentError: UIA["dismissAgentError"]; // Office actions setOfficeAgentProfiles: (agents: AgentProfile[]) => void; addOfficeAgentProfile: (agent: AgentProfile) => void; diff --git a/apps/web/lib/task-agent-error.test.ts b/apps/web/lib/task-agent-error.test.ts index 1530699c0c..a1acfd277f 100644 --- a/apps/web/lib/task-agent-error.test.ts +++ b/apps/web/lib/task-agent-error.test.ts @@ -1,9 +1,14 @@ import { describe, expect, it } from "vitest"; -import type { TaskSession } from "@/lib/types/http"; +import type { Message, TaskSession } from "@/lib/types/http"; import { sessionId, taskId } from "@/lib/types/http"; +import { lastAgentErrorStamp } from "@/lib/session-last-agent-error"; import { agentErrorMessageForTask } from "./task-agent-error"; +const ERROR_OCCURRED_AT = "2026-06-14T10:00:00Z"; +const PRIMARY_ERROR = "primary error"; +const PRIMARY_TASK = { id: "task-1", primarySessionId: "primary" }; + function session(overrides: Partial): TaskSession { return { id: sessionId("session-1"), @@ -19,26 +24,38 @@ function errorMetadata(message: string) { return { last_agent_error: { message, - occurred_at: "2026-06-14T10:00:00Z", + occurred_at: ERROR_OCCURRED_AT, }, }; } +function primarySession(overrides: Partial = {}): TaskSession { + return session({ + id: sessionId("primary"), + metadata: errorMetadata(PRIMARY_ERROR), + ...overrides, + }); +} + +function agentMessage(overrides: Partial): Message { + return { + id: "msg-1", + session_id: sessionId("primary"), + task_id: taskId("task-1"), + author_type: "agent", + content: "", + type: "agent_message", + created_at: "2026-06-14T11:00:00Z", + ...overrides, + } as Message; +} + describe("agentErrorMessageForTask", () => { it("uses the explicit primary session even when it is terminal", () => { - const primary = session({ - id: sessionId("primary"), - state: "COMPLETED", - metadata: errorMetadata("primary error"), - }); - - expect( - agentErrorMessageForTask( - { id: "task-1", primarySessionId: "primary" }, - { primary }, - { "task-1": [] }, - ), - ).toBe("primary error"); + const primary = primarySession({ state: "COMPLETED" }); + expect(agentErrorMessageForTask(PRIMARY_TASK, { primary }, { "task-1": [] })).toBe( + PRIMARY_ERROR, + ); }); it("ignores stale terminal sessions in the fallback path", () => { @@ -63,4 +80,150 @@ describe("agentErrorMessageForTask", () => { ), ).toBe("current failure"); }); + + it("hides the error when the matching stamp is in the dismissed map", () => { + const primary = primarySession(); + const stamp = lastAgentErrorStamp({ + message: PRIMARY_ERROR, + occurredAt: ERROR_OCCURRED_AT, + }); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { dismissedAgentErrors: { primary: stamp } }, + ), + ).toBeNull(); + }); + + it("keeps the error when only an older stamp is dismissed", () => { + const primary = primarySession(); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { dismissedAgentErrors: { primary: "stale-stamp" } }, + ), + ).toBe(PRIMARY_ERROR); + }); + + it("hides the error once an agent message arrives after the error timestamp", () => { + const primary = primarySession(); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { messagesBySession: { primary: [agentMessage({ created_at: "2026-06-14T10:00:01Z" })] } }, + ), + ).toBeNull(); + }); + + it("keeps the error when newer messages are from the user, not the agent", () => { + const primary = primarySession(); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { + messagesBySession: { + primary: [agentMessage({ author_type: "user", created_at: "2026-06-14T10:00:01Z" })], + }, + }, + ), + ).toBe(PRIMARY_ERROR); + }); +}); + +// Regression: string-based comparison of RFC3339 timestamps with mixed +// fractional-second precision (e.g. ".5" vs ".50") sorts incorrectly, which +// could leave a stale error icon visible or clear it too early. Numeric +// Date.parse() comparison treats them as equal moments in time. +describe("agentErrorMessageForTask (timestamp precision)", () => { + it("does not clear the error when an agent message shares the same instant", () => { + const errorAt = "2026-06-14T10:00:00.5Z"; + const messageAt = "2026-06-14T10:00:00.50Z"; // same instant, longer fractional + const primary = primarySession({ + metadata: { last_agent_error: { message: PRIMARY_ERROR, occurred_at: errorAt } }, + }); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { messagesBySession: { primary: [agentMessage({ created_at: messageAt })] } }, + ), + ).toBe(PRIMARY_ERROR); + }); + + it("clears the error when an agent message is strictly later despite shorter fractional precision", () => { + const errorAt = "2026-06-14T10:00:00.999Z"; + const messageAt = "2026-06-14T10:00:01.0Z"; + const primary = primarySession({ + metadata: { last_agent_error: { message: PRIMARY_ERROR, occurred_at: errorAt } }, + }); + expect( + agentErrorMessageForTask( + PRIMARY_TASK, + { primary }, + { "task-1": [primary] }, + { messagesBySession: { primary: [agentMessage({ created_at: messageAt })] } }, + ), + ).toBeNull(); + }); +}); + +// Coverage for the fallback `sessionsByTaskId` path (no primarySessionId). +// shouldHideError is shared with the primary path, but exercising it through +// the fallback loop guards against any regression in the per-branch wiring. +describe("agentErrorMessageForTask (fallback session path)", () => { + const FALLBACK_TASK = { id: "task-1" }; + const FALLBACK_ERROR = "fallback failure"; + + function fallbackSession() { + return session({ + id: sessionId("fallback"), + metadata: errorMetadata(FALLBACK_ERROR), + }); + } + + it("hides the error when the matching stamp is dismissed", () => { + const fallback = fallbackSession(); + const stamp = lastAgentErrorStamp({ + message: FALLBACK_ERROR, + occurredAt: ERROR_OCCURRED_AT, + }); + expect( + agentErrorMessageForTask( + FALLBACK_TASK, + { fallback }, + { "task-1": [fallback] }, + { dismissedAgentErrors: { fallback: stamp } }, + ), + ).toBeNull(); + }); + + it("hides the error once a later agent message arrives", () => { + const fallback = fallbackSession(); + expect( + agentErrorMessageForTask( + FALLBACK_TASK, + { fallback }, + { "task-1": [fallback] }, + { + messagesBySession: { + fallback: [ + agentMessage({ + session_id: sessionId("fallback"), + created_at: "2026-06-14T11:00:00Z", + }), + ], + }, + }, + ), + ).toBeNull(); + }); }); diff --git a/apps/web/lib/task-agent-error.ts b/apps/web/lib/task-agent-error.ts index ce440e9b26..b303e5bda2 100644 --- a/apps/web/lib/task-agent-error.ts +++ b/apps/web/lib/task-agent-error.ts @@ -1,22 +1,60 @@ -import type { TaskSession } from "@/lib/types/http"; -import { readLastAgentError } from "@/lib/session-last-agent-error"; +import type { Message, TaskSession } from "@/lib/types/http"; +import { + type LastAgentError, + lastAgentErrorStamp, + readLastAgentError, +} from "@/lib/session-last-agent-error"; import { isTerminalSessionState } from "@/lib/ws/handlers/agent-session"; +export type AgentErrorOptions = { + /** Most recently dismissed `last_agent_error` stamp per sessionId. */ + dismissedAgentErrors?: Record; + /** Messages keyed by sessionId. Used to auto-hide the icon once the agent + * produces a new message after the error timestamp. */ + messagesBySession?: Record; +}; + export function agentErrorMessageForTask( task: { id: string; primarySessionId?: string | null }, sessionsById: Record, sessionsByTaskId: Record, + options: AgentErrorOptions = {}, ): string | null { if (task.primarySessionId) { const primaryError = readLastAgentError(sessionsById[task.primarySessionId]?.metadata); - if (primaryError) return primaryError.message; + if (primaryError && !shouldHideError(task.primarySessionId, primaryError, options)) { + return primaryError.message; + } } const fallbackSessions = [...(sessionsByTaskId[task.id] ?? [])] .filter((session) => !isTerminalSessionState(session.state)) .sort((a, b) => b.updated_at.localeCompare(a.updated_at)); for (const session of fallbackSessions) { const error = readLastAgentError(session.metadata); - if (error) return error.message; + if (error && !shouldHideError(session.id, error, options)) { + return error.message; + } } return null; } + +function shouldHideError( + sessionId: string, + error: LastAgentError, + options: AgentErrorOptions, +): boolean { + if (options.dismissedAgentErrors?.[sessionId] === lastAgentErrorStamp(error)) return true; + return hasAgentMessageAfter(options.messagesBySession?.[sessionId], error.occurredAt); +} + +function hasAgentMessageAfter( + messages: readonly Message[] | undefined, + occurredAt?: string, +): boolean { + if (!messages || !occurredAt) return false; + const errorMs = Date.parse(occurredAt); + if (Number.isNaN(errorMs)) return false; + return messages.some( + (msg) => msg.author_type === "agent" && Date.parse(msg.created_at) > errorMs, + ); +}