feat: add quick chat idle dot indicator (#2750)
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -181,6 +181,11 @@ async function loadWorkspaceState({
|
||||
activeKind: "conversation" as const,
|
||||
activeTerminalTabId: null,
|
||||
lastTerminalTabIdByWorkspace: {},
|
||||
unseenIdleByWorkspace: {},
|
||||
lastSettledAtBySession: {},
|
||||
sessionOwnership: {},
|
||||
syncRevisionByWorkspace: {},
|
||||
tombstonedSessions: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ type AppSidebarNavItemProps = {
|
||||
href?: string;
|
||||
badge?: number;
|
||||
badgeVariant?: "primary" | "muted";
|
||||
dot?: boolean;
|
||||
onClick?: () => void;
|
||||
collapsed: boolean;
|
||||
/** Override the auto-derived active-state from pathname. */
|
||||
@@ -76,6 +77,24 @@ function isPathActive(pathname: string, href: string | undefined, exactMatch: bo
|
||||
return hrefPathname !== "/" && pathname.startsWith(`${hrefPathname}/`);
|
||||
}
|
||||
|
||||
function renderUnseenDot(dot: boolean) {
|
||||
if (!dot) return null;
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
|
||||
data-testid="quick-chat-unseen-dot"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function sidebarBadgeClass(variant: NonNullable<AppSidebarNavItemProps["badgeVariant"]>) {
|
||||
return cn(
|
||||
"rounded-full px-1.5 py-0.5 text-xs",
|
||||
variant === "primary" ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground",
|
||||
);
|
||||
}
|
||||
|
||||
export function AppSidebarNavItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
@@ -89,6 +108,7 @@ export function AppSidebarNavItem({
|
||||
disabled = false,
|
||||
testId,
|
||||
className,
|
||||
dot = false,
|
||||
}: AppSidebarNavItemProps) {
|
||||
const pathname = usePathname();
|
||||
const active = isActive ?? isPathActive(pathname, href, exactMatch);
|
||||
@@ -104,21 +124,15 @@ export function AppSidebarNavItem({
|
||||
|
||||
const inner = (
|
||||
<>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
<span className="relative flex">
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
{renderUnseenDot(dot)}
|
||||
</span>
|
||||
{!collapsed && (
|
||||
<>
|
||||
<span className="flex-1 truncate sidebar-fade-in">{label}</span>
|
||||
{typeof badge === "number" && badge > 0 && (
|
||||
<Badge
|
||||
className={cn(
|
||||
"rounded-full px-1.5 py-0.5 text-xs",
|
||||
badgeVariant === "primary"
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{badge}
|
||||
</Badge>
|
||||
<Badge className={sidebarBadgeClass(badgeVariant)}>{badge}</Badge>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { IMPROVE_KANDEV_WORKSPACE_NAME } from "@/components/improve-kandev-dialo
|
||||
import { linkToTask } from "@/lib/links";
|
||||
import type { Task } from "@/lib/types/http";
|
||||
import { subscribeNewTaskCreationRequests } from "@/lib/desktop/new-task-request";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
import { AppSidebarWorkspaceActions } from "./app-sidebar-workspace-actions";
|
||||
|
||||
// The Office "New issue" dialog only renders on `/office` routes, but this item
|
||||
@@ -42,17 +43,20 @@ type RowActionButtonProps = {
|
||||
icon: TablerIcon;
|
||||
label: string;
|
||||
testId: string;
|
||||
dot?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
function RowActionButton({ icon: Icon, label, testId, onClick }: RowActionButtonProps) {
|
||||
function RowActionButton({
|
||||
icon: Icon,
|
||||
label,
|
||||
testId,
|
||||
onClick,
|
||||
dot = false,
|
||||
}: RowActionButtonProps) {
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false);
|
||||
const hoveredRef = useRef(false);
|
||||
|
||||
const handleTooltipOpenChange = (nextOpen: boolean) => {
|
||||
// Focus is restored to this action after Quick Terminal closes. Keep the
|
||||
// tooltip pointer-driven so that accessibility focus does not leave a
|
||||
// stale popover behind the dialog.
|
||||
if (nextOpen && !hoveredRef.current) return;
|
||||
setTooltipOpen(nextOpen);
|
||||
};
|
||||
@@ -79,7 +83,16 @@ function RowActionButton({ icon: Icon, label, testId, onClick }: RowActionButton
|
||||
data-testid={testId}
|
||||
className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground/70 hover:bg-muted hover:text-foreground cursor-pointer"
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
<span className="relative flex">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{dot && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
|
||||
data-testid="quick-chat-unseen-dot"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">{label}</TooltipContent>
|
||||
@@ -166,6 +179,12 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
|
||||
const setActiveSession = useAppStore((s) => s.setActiveSession);
|
||||
const inOffice = useInOffice();
|
||||
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
|
||||
const quickChatHasUnseenIdle = useAppStore((state) =>
|
||||
selectQuickChatHasUnseenIdle(state, workspaceId),
|
||||
);
|
||||
const quickChatLabel = t(
|
||||
quickChatHasUnseenIdle ? "sidebar:quickChatUnseen" : "sidebar:quickChat",
|
||||
);
|
||||
const handleOpenQuickTerminal = useQuickTerminalLauncher(workspaceId);
|
||||
const [open, setOpen] = useState(false);
|
||||
const isImproveWorkspace = activeWorkspace?.name === IMPROVE_KANDEV_WORKSPACE_NAME;
|
||||
@@ -220,9 +239,10 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
|
||||
/>
|
||||
<RowActionButton
|
||||
icon={IconMessageCircle}
|
||||
label={t("sidebar:quickChat")}
|
||||
label={quickChatLabel}
|
||||
testId="sidebar-quick-chat-shortcut"
|
||||
onClick={handleOpenQuickChat}
|
||||
dot={quickChatHasUnseenIdle}
|
||||
/>
|
||||
<AppSidebarWorkspaceActions
|
||||
workspaceId={workspaceId}
|
||||
|
||||
@@ -9,7 +9,10 @@ const mocks = vi.hoisted(() => ({
|
||||
const state = {
|
||||
workspaces: { activeId: "ws-1" as string | null },
|
||||
office: { inboxCountByWorkspaceId: {} as Record<string, number> },
|
||||
quickChat: { unseenIdleByWorkspace: {} as Record<string, Record<string, true>> },
|
||||
};
|
||||
const QUICK_CHAT_LABEL = "Quick Chat";
|
||||
const QUICK_CHAT_UNSEEN_LABEL = "Quick Chat, new response";
|
||||
let mode: "office" | "kanban" | "unknown" = "kanban";
|
||||
let pathname = "/";
|
||||
|
||||
@@ -50,6 +53,7 @@ describe("AppSidebarPrimaryNav", () => {
|
||||
beforeEach(() => {
|
||||
state.workspaces.activeId = "ws-1";
|
||||
state.office.inboxCountByWorkspaceId = {};
|
||||
state.quickChat.unseenIdleByWorkspace = {};
|
||||
mode = "kanban";
|
||||
pathname = "/";
|
||||
mocks.openQuickChat.mockClear();
|
||||
@@ -60,14 +64,22 @@ describe("AppSidebarPrimaryNav", () => {
|
||||
it("keeps Quick Chat reachable when the sidebar rail is collapsed", () => {
|
||||
renderNav(true);
|
||||
|
||||
screen.getByRole("button", { name: "Quick Chat" }).click();
|
||||
expect(screen.queryByTestId("quick-chat-unseen-dot")).toBeNull();
|
||||
screen.getByRole("button", { name: QUICK_CHAT_LABEL }).click();
|
||||
expect(mocks.openQuickChat).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("renders an unseen marker on the collapsed Quick Chat rail entry", () => {
|
||||
state.quickChat.unseenIdleByWorkspace = { "ws-1": { "session-1": true } };
|
||||
renderNav(true);
|
||||
const quickChat = screen.getByRole("button", { name: QUICK_CHAT_UNSEEN_LABEL });
|
||||
|
||||
expect(quickChat.querySelector('[data-testid="quick-chat-unseen-dot"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("omits the standalone Quick Chat row while expanded", () => {
|
||||
renderNav(false);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Quick Chat" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: QUICK_CHAT_LABEL })).toBeNull();
|
||||
});
|
||||
|
||||
it("no longer carries a Runs row — automations are their own section", () => {
|
||||
@@ -82,8 +94,7 @@ describe("AppSidebarPrimaryNav", () => {
|
||||
it("omits Quick Chat when the rail is collapsed but there is no workspace", () => {
|
||||
state.workspaces.activeId = null;
|
||||
renderNav(true);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Quick Chat" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: QUICK_CHAT_LABEL })).toBeNull();
|
||||
});
|
||||
|
||||
it("links Home to an explicit overview while keeping it active at the root route", () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { IconHome, IconInbox, IconMessageCircle } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectOfficeInboxCount } from "@/lib/state/slices/office/selectors";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
import { useOfficeModeState } from "@/hooks/use-in-office";
|
||||
import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher";
|
||||
import { homeDestinationHref } from "@/lib/navigation/core-destinations";
|
||||
@@ -21,6 +22,12 @@ export function AppSidebarPrimaryNav({ collapsed }: AppSidebarPrimaryNavProps) {
|
||||
const mode = useOfficeModeState();
|
||||
const inOffice = mode === "office";
|
||||
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
|
||||
const quickChatHasUnseenIdle = useAppStore((state) =>
|
||||
selectQuickChatHasUnseenIdle(state, workspaceId),
|
||||
);
|
||||
const quickChatLabel = t(
|
||||
quickChatHasUnseenIdle ? "sidebar:quickChatUnseen" : "sidebar:quickChat",
|
||||
);
|
||||
const homeHref = mode === "unknown" ? undefined : homeDestinationHref({ workspaceId, inOffice });
|
||||
|
||||
return (
|
||||
@@ -47,9 +54,10 @@ export function AppSidebarPrimaryNav({ collapsed }: AppSidebarPrimaryNavProps) {
|
||||
{workspaceId && collapsed && (
|
||||
<AppSidebarNavItem
|
||||
icon={IconMessageCircle}
|
||||
label={t("sidebar:quickChat")}
|
||||
label={quickChatLabel}
|
||||
onClick={handleOpenQuickChat}
|
||||
collapsed={collapsed}
|
||||
dot={quickChatHasUnseenIdle}
|
||||
/>
|
||||
)}
|
||||
<AppSidebarNewTaskItem collapsed={collapsed} />
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useConnectionIssueCopy } from "@/components/app-status-bar/connection-s
|
||||
import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher";
|
||||
import { useQuickTerminalLauncher } from "@/hooks/use-quick-terminal-launcher";
|
||||
import { workspaceHomeHref } from "@/lib/navigation/workspace-home";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type KanbanHeaderMobileProps = {
|
||||
@@ -42,6 +43,39 @@ function MobileBrandLink({ workspaceId }: Pick<KanbanHeaderMobileProps, "workspa
|
||||
);
|
||||
}
|
||||
|
||||
function MobileQuickChatButton({
|
||||
workspaceId,
|
||||
onClick,
|
||||
}: {
|
||||
workspaceId: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const dot = useAppStore((state) => selectQuickChatHasUnseenIdle(state, workspaceId));
|
||||
const quickChatLabel = t(dot ? "sidebar:quickChatUnseen" : "sidebar:quickChat");
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
onClick={onClick}
|
||||
className="!size-11 cursor-pointer"
|
||||
aria-label={quickChatLabel}
|
||||
data-testid="mobile-quick-chat-button"
|
||||
>
|
||||
<span className="relative flex">
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
{dot && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
|
||||
data-testid="quick-chat-unseen-dot"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileHeaderActions({
|
||||
workspaceId,
|
||||
workspaceLabel,
|
||||
@@ -88,16 +122,7 @@ function MobileHeaderActions({
|
||||
</Button>
|
||||
)}
|
||||
{workspaceId && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
onClick={handleOpenQuickChat}
|
||||
className="!size-11 cursor-pointer"
|
||||
aria-label={t("sidebar:quickChat")}
|
||||
data-testid="mobile-quick-chat-button"
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
<MobileQuickChatButton workspaceId={workspaceId} onClick={handleOpenQuickChat} />
|
||||
)}
|
||||
{onSearchChange && (
|
||||
<Button
|
||||
|
||||
@@ -28,6 +28,7 @@ import type { TasksListDisplayOptions } from "./mobile-menu-task-list-options";
|
||||
import { linkToTaskOverview, linkToTasks } from "@/lib/links";
|
||||
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
import { useKanbanDisplaySettings } from "@/hooks/use-kanban-display-settings";
|
||||
import { useReleaseNotes } from "@/hooks/use-release-notes";
|
||||
import { useSystemHealthIndicator } from "@/hooks/use-system-health-indicator";
|
||||
@@ -162,6 +163,12 @@ function useIsHeaderNarrow(ref: RefObject<HTMLElement | null>): boolean {
|
||||
function TabletQuickActions({ workspaceId }: { workspaceId?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
|
||||
const quickChatHasUnseenIdle = useAppStore((state) =>
|
||||
selectQuickChatHasUnseenIdle(state, workspaceId),
|
||||
);
|
||||
const quickChatLabel = t(
|
||||
quickChatHasUnseenIdle ? "sidebar:quickChatUnseen" : "sidebar:quickChat",
|
||||
);
|
||||
const handleOpenQuickTerminal = useQuickTerminalLauncher(workspaceId);
|
||||
if (!workspaceId) return null;
|
||||
|
||||
@@ -182,10 +189,19 @@ function TabletQuickActions({ workspaceId }: { workspaceId?: string }) {
|
||||
size="icon-lg"
|
||||
onClick={handleOpenQuickChat}
|
||||
className="!size-11 cursor-pointer"
|
||||
aria-label={t("sidebar:quickChat")}
|
||||
aria-label={quickChatLabel}
|
||||
data-testid="tablet-quick-chat-button"
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
<span className="relative flex">
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
{quickChatHasUnseenIdle && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
|
||||
data-testid="quick-chat-unseen-dot"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -63,6 +63,7 @@ function makeAppState() {
|
||||
},
|
||||
closeQuickChat: vi.fn(),
|
||||
closeQuickChatSession: vi.fn(),
|
||||
removeQuickChatSession: vi.fn(),
|
||||
setActiveQuickChatSession: vi.fn(),
|
||||
createQuickTerminal: vi.fn(),
|
||||
updateQuickTerminal: vi.fn(),
|
||||
@@ -85,6 +86,7 @@ function makeStore(overrides: Partial<MockStore> = {}): MockStore {
|
||||
activeTerminalTabId: null,
|
||||
closeQuickChat: vi.fn(),
|
||||
closeQuickChatSession: vi.fn(),
|
||||
removeQuickChatSession: vi.fn(),
|
||||
setActiveQuickChatSession: vi.fn(),
|
||||
createQuickTerminal: vi.fn(),
|
||||
updateQuickTerminal: vi.fn(),
|
||||
@@ -274,7 +276,7 @@ describe("useQuickChatModal — persisted config lifecycle", () => {
|
||||
|
||||
await act(async () => result.current.handleConfirmClose());
|
||||
|
||||
expect(mockAppState.closeQuickChatSession).toHaveBeenCalledWith(configSessionId);
|
||||
expect(mockAppState.removeQuickChatSession).toHaveBeenCalledWith(configSessionId);
|
||||
expect(mockDeleteTask).toHaveBeenCalledWith("config-task");
|
||||
});
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ function useQuickChatStore(workspaceId: string) {
|
||||
terminalTabs: s.quickChat.terminalTabs,
|
||||
closeQuickChat: s.closeQuickChat,
|
||||
closeQuickChatSession: s.closeQuickChatSession,
|
||||
removeQuickChatSession: s.removeQuickChatSession,
|
||||
setActiveQuickChatSession: s.setActiveQuickChatSession,
|
||||
createQuickTerminal: s.createQuickTerminal,
|
||||
updateQuickTerminal: s.updateQuickTerminal,
|
||||
@@ -261,12 +262,12 @@ function useQuickChatSessionClose(store: QuickChatStore, resetPendingStarts: ()
|
||||
setSessionToClose(null);
|
||||
const taskId = resolveTaskId(store, sessionId);
|
||||
if (!taskId) {
|
||||
store.closeQuickChatSession(sessionId);
|
||||
store.removeQuickChatSession(sessionId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await deleteQuickChatTask(taskId);
|
||||
store.closeQuickChatSession(sessionId);
|
||||
store.removeQuickChatSession(sessionId);
|
||||
} catch (error) {
|
||||
console.error("Failed to delete quick chat task:", error);
|
||||
toast({
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { IconMessageCircle } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
|
||||
/** Quick Chat action in the mobile task-switcher sheet, with the unseen-idle dot. */
|
||||
export function QuickChatSheetButton({
|
||||
workspaceId,
|
||||
onClick,
|
||||
}: {
|
||||
workspaceId: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hasUnseenIdle = useAppStore((state) => selectQuickChatHasUnseenIdle(state, workspaceId));
|
||||
const quickChatLabel = t(hasUnseenIdle ? "sidebar:quickChatUnseen" : "sidebar:quickChat");
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 cursor-pointer"
|
||||
onClick={onClick}
|
||||
aria-label={quickChatLabel}
|
||||
data-testid="mobile-sheet-quick-chat"
|
||||
>
|
||||
<span className="relative flex">
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
{hasUnseenIdle && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-background"
|
||||
data-testid="quick-chat-unseen-dot"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
{t("task:chat")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, memo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IconCheck, IconMessageCircle, IconNetwork, IconPlus } from "@tabler/icons-react";
|
||||
import { IconCheck, IconNetwork, IconPlus } from "@tabler/icons-react";
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@kandev/ui/sheet";
|
||||
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@kandev/ui/drawer";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { QuickChatSheetButton } from "./quick-chat-sheet-button";
|
||||
import { TaskSwitcher } from "../task-switcher";
|
||||
import type { TaskSwitcherItem, TaskSwitcherProps } from "../task-switcher";
|
||||
import { SidebarFilterBar } from "../sidebar-filter/sidebar-filter-bar";
|
||||
@@ -229,18 +230,7 @@ function TaskSwitcherSurfaceHeader({
|
||||
<SheetTitle className="text-base">{t("task:tasks")}</SheetTitle>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
{workspaceId && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 cursor-pointer"
|
||||
onClick={onQuickChat}
|
||||
data-testid="mobile-sheet-quick-chat"
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
{t("task:chat")}
|
||||
</Button>
|
||||
)}
|
||||
{workspaceId && <QuickChatSheetButton workspaceId={workspaceId} onClick={onQuickChat} />}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sessionStatusTooltip } from "./sessions-dropdown";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const lifecycleMocks = vi.hoisted(() => ({
|
||||
deleteTask: vi.fn(),
|
||||
getWebSocketClient: vi.fn(),
|
||||
removeQuickChatSession: vi.fn(),
|
||||
request: vi.fn(),
|
||||
quickChatSessions: [] as Array<{ sessionId: string; taskId?: string }>,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/kanban-api", () => ({
|
||||
deleteTask: lifecycleMocks.deleteTask,
|
||||
}));
|
||||
vi.mock("@/lib/ws/connection", () => ({
|
||||
getWebSocketClient: lifecycleMocks.getWebSocketClient,
|
||||
}));
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({ removeQuickChatSession: lifecycleMocks.removeQuickChatSession }),
|
||||
useAppStoreApi: () => ({
|
||||
getState: () => ({ quickChat: { sessions: lifecycleMocks.quickChatSessions } }),
|
||||
}),
|
||||
}));
|
||||
|
||||
import { sessionStatusTooltip, useSessionLifecycleActions } from "./sessions-dropdown";
|
||||
|
||||
describe("sessionStatusTooltip", () => {
|
||||
it("prioritizes permission over clarification for input-capable sessions", () => {
|
||||
@@ -39,3 +63,45 @@ describe("sessionStatusTooltip", () => {
|
||||
).toBe("Complete");
|
||||
});
|
||||
});
|
||||
|
||||
describe("useSessionLifecycleActions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
lifecycleMocks.deleteTask.mockResolvedValue(undefined);
|
||||
lifecycleMocks.request.mockResolvedValue(undefined);
|
||||
lifecycleMocks.getWebSocketClient.mockReturnValue({ request: lifecycleMocks.request });
|
||||
lifecycleMocks.quickChatSessions.length = 0;
|
||||
});
|
||||
|
||||
it("deletes the backing task for a Quick Chat session", async () => {
|
||||
lifecycleMocks.quickChatSessions.push({ sessionId: "session-1", taskId: "task-1" });
|
||||
const loadSessions = vi.fn();
|
||||
const { result } = renderHook(() => useSessionLifecycleActions("task-1", loadSessions));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleDeleteSession("session-1");
|
||||
});
|
||||
|
||||
expect(lifecycleMocks.deleteTask).toHaveBeenCalledWith("task-1");
|
||||
expect(lifecycleMocks.request).not.toHaveBeenCalled();
|
||||
expect(lifecycleMocks.removeQuickChatSession).toHaveBeenCalledWith("session-1");
|
||||
expect(loadSessions).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("keeps ordinary session deletion on the session endpoint", async () => {
|
||||
const loadSessions = vi.fn();
|
||||
const { result } = renderHook(() => useSessionLifecycleActions("task-1", loadSessions));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleDeleteSession("session-1");
|
||||
});
|
||||
|
||||
expect(lifecycleMocks.request).toHaveBeenCalledWith(
|
||||
"session.delete",
|
||||
{ session_id: "session-1" },
|
||||
15000,
|
||||
);
|
||||
expect(lifecycleMocks.deleteTask).not.toHaveBeenCalled();
|
||||
expect(loadSessions).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,8 @@ import { performLayoutSwitch } from "@/lib/state/dockview-store";
|
||||
import type { ForegroundActivity, TaskSession, TaskSessionState } from "@/lib/types/http";
|
||||
import { getSessionStateIcon } from "@/lib/ui/state-icons";
|
||||
import { getWebSocketClient } from "@/lib/ws/connection";
|
||||
import { deleteTask } from "@/lib/api/domains/kanban-api";
|
||||
import { resolveSessionDeletionTarget } from "@/lib/session/session-deletion";
|
||||
import { useSessionPendingInput, type PendingInput } from "@/hooks/use-task-pending-input";
|
||||
import { buildAgentLabelsById, resolveAgentLabelFor, sortSessions } from "./session-sort";
|
||||
import { resolveComposerWorkspaceId } from "./chat/composer-workspace";
|
||||
@@ -141,10 +143,12 @@ function useSessionSelectionHandlers(taskId: string | null) {
|
||||
return { handleSelectSession };
|
||||
}
|
||||
|
||||
function useSessionLifecycleActions(
|
||||
export function useSessionLifecycleActions(
|
||||
taskId: string | null,
|
||||
loadSessions: (force?: boolean) => void,
|
||||
) {
|
||||
const removeQuickChatSession = useAppStore((state) => state.removeQuickChatSession);
|
||||
const appStore = useAppStoreApi();
|
||||
const handleResumeSession = useCallback(
|
||||
async (sessionId: string) => {
|
||||
if (!taskId) return;
|
||||
@@ -166,16 +170,27 @@ function useSessionLifecycleActions(
|
||||
|
||||
const handleDeleteSession = useCallback(
|
||||
async (sessionId: string) => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return;
|
||||
if (!taskId) return;
|
||||
try {
|
||||
await client.request("session.delete", { session_id: sessionId }, 15000);
|
||||
const deletionTarget = resolveSessionDeletionTarget(
|
||||
sessionId,
|
||||
taskId,
|
||||
appStore.getState().quickChat.sessions,
|
||||
);
|
||||
if (deletionTarget.kind === "quick-chat-task") {
|
||||
await deleteTask(deletionTarget.taskId);
|
||||
} else {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return;
|
||||
await client.request("session.delete", { session_id: deletionTarget.sessionId }, 15000);
|
||||
}
|
||||
removeQuickChatSession(sessionId);
|
||||
loadSessions(true);
|
||||
} catch (error) {
|
||||
console.error("Failed to delete session:", error);
|
||||
}
|
||||
},
|
||||
[loadSessions],
|
||||
[appStore, loadSessions, removeQuickChatSession, taskId],
|
||||
);
|
||||
|
||||
const handleSetPrimary = useCallback(
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { watchWs } from "../../helpers/causal-waits";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import { sendQuickChatMessage, startQuickChatFromSetup } from "./quick-chat-helpers";
|
||||
|
||||
test.describe("quick chat idle dot", () => {
|
||||
test("marks the mobile header after a closed quick chat turn completes", async ({ testPage }) => {
|
||||
const ws = watchWs(testPage);
|
||||
await testPage.goto("/");
|
||||
await testPage.getByTestId("mobile-quick-chat-button").tap();
|
||||
const dialog = testPage.getByRole("dialog", { name: "Quick Chat" });
|
||||
const created = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/quick-chat") && response.request().method() === "POST",
|
||||
);
|
||||
await startQuickChatFromSetup(dialog, testPage);
|
||||
await expect(
|
||||
testPage.getByRole("status", { name: /Agent is (starting|running)/ }),
|
||||
).not.toBeVisible();
|
||||
const { session_id: sessionId } = (await (await created).json()) as { session_id: string };
|
||||
const button = testPage.getByTestId("mobile-quick-chat-button");
|
||||
const completed = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, testPage, "/slow 8s");
|
||||
await expect(dialog.getByText("Running slow response", { exact: false })).toBeVisible();
|
||||
await dialog.getByTestId("quick-chat-close").tap();
|
||||
await completed;
|
||||
await expect(button.getByTestId("quick-chat-unseen-dot")).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await button.tap();
|
||||
await expect(button.getByTestId("quick-chat-unseen-dot")).toHaveCount(0);
|
||||
// The reopened dialog re-subscribes over WS; wait until the previous
|
||||
// exchange has rendered so the send cannot race a dead subscription.
|
||||
await expect(dialog.getByText("Slow response complete", { exact: false })).toBeVisible({
|
||||
timeout: 15_000,
|
||||
});
|
||||
const secondCompleted = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, testPage, "/slow 8s");
|
||||
await dialog.getByTestId("quick-chat-close").tap();
|
||||
await secondCompleted;
|
||||
await expect(button.getByTestId("quick-chat-unseen-dot")).toBeVisible({ timeout: 15_000 });
|
||||
});
|
||||
|
||||
test("marks the task switcher entry after a closed quick chat turn completes", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const ws = watchWs(testPage);
|
||||
const seeded = await apiClient.seedTask(seedData.workspaceId, "Mobile Quick Chat Idle Dot", {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
await testPage.goto(`/t/${seeded.task_id}`);
|
||||
await new SessionPage(testPage).waitForLoad();
|
||||
|
||||
await testPage.getByTestId("mobile-session-menu").tap();
|
||||
const sheet = testPage.getByRole("dialog", { name: "Tasks" });
|
||||
const entry = sheet.getByTestId("mobile-sheet-quick-chat");
|
||||
await expect(entry.getByTestId("quick-chat-unseen-dot")).toHaveCount(0);
|
||||
|
||||
const created = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/quick-chat") && response.request().method() === "POST",
|
||||
);
|
||||
await entry.tap();
|
||||
const dialog = testPage.getByRole("dialog", { name: "Quick Chat" });
|
||||
await startQuickChatFromSetup(dialog, testPage);
|
||||
const { session_id: sessionId } = (await (await created).json()) as { session_id: string };
|
||||
const completed = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, testPage, "/slow 8s");
|
||||
await dialog.getByTestId("quick-chat-close").tap();
|
||||
|
||||
await completed;
|
||||
await testPage.getByTestId("mobile-session-menu").tap();
|
||||
await expect(entry.getByTestId("quick-chat-unseen-dot")).toBeVisible({ timeout: 15_000 });
|
||||
});
|
||||
});
|
||||
@@ -71,16 +71,19 @@ export async function openQuickChatWithAgent(page: Page, navigateHome = true): P
|
||||
|
||||
export async function sendQuickChatMessage(dialog: Locator, page: Page, text: string) {
|
||||
const editor = dialog.locator(".tiptap.ProseMirror");
|
||||
const modifier = process.platform === "darwin" ? "Meta" : "Control";
|
||||
// With eager init, the agent boots during picker -> tab transition and the
|
||||
// input can briefly toggle disabled while the FE store catches up. Retry the
|
||||
// full edit action so fill() cannot race a contenteditable=false flip.
|
||||
// input can briefly toggle disabled while the FE store catches up. The whole
|
||||
// fill + submit must retry as one unit: after a reopen the conversation can
|
||||
// still be loading, so a fill can land on an editor that remounts (wiping
|
||||
// the text) before the submit click. A successful send clears the editor
|
||||
// synchronously, so each iteration either sends once and exits or sends
|
||||
// nothing and retries.
|
||||
await expect(async () => {
|
||||
await expect(editor).toHaveAttribute("contenteditable", "true", { timeout: 1_000 });
|
||||
await editor.click({ timeout: 1_000 });
|
||||
await editor.fill(text, { timeout: 1_000 });
|
||||
await expect(editor).toHaveText(text, { timeout: 1_000 });
|
||||
await editor.press(`${modifier}+Enter`, { timeout: 1_000 });
|
||||
await dialog.getByTestId("submit-message-button").click({ timeout: 1_000 });
|
||||
await expect(editor).toHaveText("", { timeout: 2_000 });
|
||||
}).toPass({ timeout: 30_000, intervals: [250, 500, 1_000] });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { watchWs } from "../../helpers/causal-waits";
|
||||
import { openQuickChatWithAgent, sendQuickChatMessage } from "./quick-chat-helpers";
|
||||
|
||||
test.describe("quick chat idle dot", () => {
|
||||
test("marks a closed quick chat after a turn completes and re-arms after opening", async ({
|
||||
testPage,
|
||||
}) => {
|
||||
const ws = watchWs(testPage);
|
||||
const created = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/quick-chat") && response.request().method() === "POST",
|
||||
);
|
||||
const dialog = await openQuickChatWithAgent(testPage);
|
||||
const createdBody = (await created).json() as Promise<{ session_id: string }>;
|
||||
const { session_id: sessionId } = await createdBody;
|
||||
const shortcut = testPage.getByTestId("sidebar-quick-chat-shortcut");
|
||||
|
||||
await expect(shortcut.getByTestId("quick-chat-unseen-dot")).toHaveCount(0);
|
||||
const firstCompletion = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, testPage, "/slow 8s");
|
||||
await testPage.keyboard.press("Escape");
|
||||
await firstCompletion;
|
||||
await expect(shortcut.getByTestId("quick-chat-unseen-dot")).toBeVisible();
|
||||
|
||||
await shortcut.click();
|
||||
await expect(shortcut.getByTestId("quick-chat-unseen-dot")).toHaveCount(0);
|
||||
const secondCompletion = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, testPage, "/slow 8s");
|
||||
await testPage.keyboard.press("Escape");
|
||||
await secondCompletion;
|
||||
await expect(shortcut.getByTestId("quick-chat-unseen-dot")).toBeVisible();
|
||||
});
|
||||
|
||||
test("marks the tablet header after a closed quick chat turn completes", async ({
|
||||
tabletTestPage,
|
||||
}) => {
|
||||
const ws = watchWs(tabletTestPage);
|
||||
const created = tabletTestPage.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes("/quick-chat") && response.request().method() === "POST",
|
||||
);
|
||||
const dialog = await openQuickChatWithAgent(tabletTestPage);
|
||||
const { session_id: sessionId } = (await (await created).json()) as { session_id: string };
|
||||
const button = tabletTestPage.getByTestId("tablet-quick-chat-button");
|
||||
|
||||
await expect(button.getByTestId("quick-chat-unseen-dot")).toHaveCount(0);
|
||||
const completed = ws.waitForEvent("session.turn.completed", {
|
||||
where: (payload) => payload.session_id === sessionId,
|
||||
});
|
||||
await sendQuickChatMessage(dialog, tabletTestPage, "/slow 8s");
|
||||
await tabletTestPage.keyboard.press("Escape");
|
||||
await completed;
|
||||
|
||||
await expect(button.getByTestId("quick-chat-unseen-dot")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,9 @@ import {
|
||||
const mockToast = vi.fn().mockReturnValue("toast-1");
|
||||
const mockUpdateToast = vi.fn();
|
||||
const mockRequest = vi.fn();
|
||||
const mockDeleteTask = vi.hoisted(() => vi.fn());
|
||||
const mockRemoveTaskSession = vi.fn();
|
||||
const mockRemoveQuickChatSession = vi.fn();
|
||||
const mockSetActiveSessionAuto = vi.fn();
|
||||
const mockClearActiveSession = vi.fn();
|
||||
const networkErrorMessage = "network down";
|
||||
@@ -21,9 +23,11 @@ function resetSessionActionMocks() {
|
||||
vi.clearAllMocks();
|
||||
mockToast.mockReturnValue("toast-1");
|
||||
mockRequest.mockResolvedValue(undefined);
|
||||
mockDeleteTask.mockResolvedValue(undefined);
|
||||
mockState = {
|
||||
tasks: { activeSessionId: null },
|
||||
taskSessionsByTask: { itemsByTaskId: {} },
|
||||
quickChat: { sessions: [] },
|
||||
setActiveSessionAuto: mockSetActiveSessionAuto,
|
||||
clearActiveSession: mockClearActiveSession,
|
||||
};
|
||||
@@ -37,10 +41,13 @@ vi.mock("@/lib/ws/connection", () => ({
|
||||
getWebSocketClient: () => ({ request: mockRequest }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/kanban-api", () => ({ deleteTask: mockDeleteTask }));
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
removeTaskSession: mockRemoveTaskSession,
|
||||
removeQuickChatSession: mockRemoveQuickChatSession,
|
||||
}),
|
||||
useAppStoreApi: () => ({
|
||||
getState: () => mockState,
|
||||
@@ -73,6 +80,7 @@ describe("session state predicates", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- session action scenarios share one lifecycle fixture.
|
||||
describe("useSessionActions", () => {
|
||||
beforeEach(resetSessionActionMocks);
|
||||
|
||||
@@ -107,6 +115,7 @@ describe("useSessionActions", () => {
|
||||
await waitFor(() => expect(onDeleted).toHaveBeenCalled());
|
||||
expect(mockRequest).toHaveBeenCalledWith("session.delete", { session_id: "s1" }, 15000);
|
||||
expect(mockRemoveTaskSession).toHaveBeenCalledWith("t1", "s1");
|
||||
expect(mockRemoveQuickChatSession).toHaveBeenCalledWith("s1");
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: "Deleting session...",
|
||||
variant: "loading",
|
||||
@@ -117,6 +126,19 @@ describe("useSessionActions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("remove deletes the backing task for a Quick Chat session", async () => {
|
||||
mockState.quickChat = { sessions: [{ sessionId: "s1", taskId: "t1" }] };
|
||||
const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
|
||||
|
||||
const ok = await result.current.remove();
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(mockDeleteTask).toHaveBeenCalledWith("t1");
|
||||
expect(mockRequest).not.toHaveBeenCalled();
|
||||
expect(mockRemoveTaskSession).toHaveBeenCalledWith("t1", "s1");
|
||||
expect(mockRemoveQuickChatSession).toHaveBeenCalledWith("s1");
|
||||
});
|
||||
|
||||
it("remove no-ops when WS request fails (store untouched)", async () => {
|
||||
mockRequest.mockRejectedValueOnce(new Error(networkErrorMessage));
|
||||
const onDeleted = vi.fn();
|
||||
@@ -131,6 +153,7 @@ describe("useSessionActions", () => {
|
||||
it("remove hands off to most-recent remaining session when active was deleted", async () => {
|
||||
mockState = {
|
||||
tasks: { activeSessionId: "s1" },
|
||||
quickChat: { sessions: [] },
|
||||
taskSessionsByTask: {
|
||||
itemsByTaskId: {
|
||||
t1: [
|
||||
@@ -152,6 +175,7 @@ describe("useSessionActions", () => {
|
||||
it("remove clears active session when no other sessions remain", async () => {
|
||||
mockState = {
|
||||
tasks: { activeSessionId: "s1" },
|
||||
quickChat: { sessions: [] },
|
||||
taskSessionsByTask: {
|
||||
itemsByTaskId: { t1: [{ id: "s1", started_at: "2025-01-01T00:00:00Z" }] },
|
||||
},
|
||||
|
||||
@@ -4,6 +4,8 @@ import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { deleteTask } from "@/lib/api/domains/kanban-api";
|
||||
import { resolveSessionDeletionTarget } from "@/lib/session/session-deletion";
|
||||
import { getWebSocketClient } from "@/lib/ws/connection";
|
||||
import type { TaskSessionState } from "@/lib/types/http";
|
||||
|
||||
@@ -30,21 +32,31 @@ export type RemoveSessionOptions = {
|
||||
feedback?: SessionActionFeedback;
|
||||
};
|
||||
|
||||
type WsActionOptions = {
|
||||
timeout?: number;
|
||||
feedback?: SessionActionFeedback;
|
||||
requestOverride?: () => Promise<unknown>;
|
||||
};
|
||||
|
||||
type WsActionFn = (
|
||||
action: string,
|
||||
label: string,
|
||||
payload: Record<string, unknown>,
|
||||
timeout?: number,
|
||||
feedback?: SessionActionFeedback,
|
||||
options?: WsActionOptions,
|
||||
) => Promise<boolean>;
|
||||
|
||||
function useWsAction(): WsActionFn {
|
||||
const { toast, updateToast } = useToast();
|
||||
const { t } = useTranslation("task");
|
||||
return useCallback(
|
||||
async (action, labelKey, payload, timeout = 15000, feedback = "toast") => {
|
||||
async (
|
||||
action,
|
||||
labelKey,
|
||||
payload,
|
||||
{ timeout = 15000, feedback = "toast", requestOverride }: WsActionOptions = {},
|
||||
) => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return false;
|
||||
if (!client && !requestOverride) return false;
|
||||
const toastId =
|
||||
feedback === "toast"
|
||||
? toast({
|
||||
@@ -53,7 +65,7 @@ function useWsAction(): WsActionFn {
|
||||
})
|
||||
: null;
|
||||
try {
|
||||
await client.request(action, payload, timeout);
|
||||
await (requestOverride ? requestOverride() : client!.request(action, payload, timeout));
|
||||
if (toastId) {
|
||||
updateToast(toastId, {
|
||||
title: t("task:sessionActionSuccessful", { action: t(labelKey) }),
|
||||
@@ -84,6 +96,7 @@ function useWsAction(): WsActionFn {
|
||||
export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActionsArgs) {
|
||||
const wsAction = useWsAction();
|
||||
const removeTaskSession = useAppStore((state) => state.removeTaskSession);
|
||||
const removeQuickChatSession = useAppStore((state) => state.removeQuickChatSession);
|
||||
const appStoreApi = useAppStoreApi();
|
||||
|
||||
const setPrimary = useCallback(
|
||||
@@ -93,8 +106,7 @@ export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActio
|
||||
"session.set_primary",
|
||||
"task:sessionActionSetPrimary",
|
||||
{ session_id: sessionId },
|
||||
15000,
|
||||
"inline",
|
||||
{ timeout: 15000, feedback: "inline" },
|
||||
),
|
||||
[sessionId, wsAction],
|
||||
);
|
||||
@@ -113,7 +125,7 @@ export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActio
|
||||
"session.launch",
|
||||
"task:sessionActionResume",
|
||||
{ task_id: taskId, intent: "resume", session_id: sessionId },
|
||||
30000,
|
||||
{ timeout: 30000 },
|
||||
),
|
||||
[sessionId, taskId, wsAction],
|
||||
);
|
||||
@@ -121,12 +133,23 @@ export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActio
|
||||
const remove = useCallback(
|
||||
async (options: RemoveSessionOptions = {}) => {
|
||||
if (!sessionId || !taskId) return false;
|
||||
const deletionTarget = resolveSessionDeletionTarget(
|
||||
sessionId,
|
||||
taskId,
|
||||
appStoreApi.getState().quickChat.sessions,
|
||||
);
|
||||
const ok = await wsAction(
|
||||
"session.delete",
|
||||
"task:sessionActionDelete",
|
||||
{ session_id: sessionId },
|
||||
15000,
|
||||
options.feedback,
|
||||
{
|
||||
timeout: 15000,
|
||||
feedback: options.feedback,
|
||||
requestOverride:
|
||||
deletionTarget.kind === "quick-chat-task"
|
||||
? () => deleteTask(deletionTarget.taskId)
|
||||
: undefined,
|
||||
},
|
||||
);
|
||||
if (!ok) return false;
|
||||
|
||||
@@ -146,10 +169,19 @@ export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActio
|
||||
}
|
||||
|
||||
removeTaskSession(taskId, sessionId);
|
||||
removeQuickChatSession(sessionId);
|
||||
onDeleted?.();
|
||||
return true;
|
||||
},
|
||||
[sessionId, taskId, wsAction, removeTaskSession, appStoreApi, onDeleted],
|
||||
[
|
||||
sessionId,
|
||||
taskId,
|
||||
wsAction,
|
||||
removeTaskSession,
|
||||
removeQuickChatSession,
|
||||
appStoreApi,
|
||||
onDeleted,
|
||||
],
|
||||
);
|
||||
|
||||
return { setPrimary, stop, resume, remove };
|
||||
|
||||
@@ -1,164 +1,240 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
|
||||
const mockListQuickChatSessions = vi.hoisted(() => vi.fn());
|
||||
const mockListQuickTerminalTabs = vi.hoisted(() => vi.fn());
|
||||
const mockUpdateTask = vi.hoisted(() => vi.fn());
|
||||
const mockState = vi.hoisted(() => ({
|
||||
value: {} as {
|
||||
connection: { status: string };
|
||||
syncQuickChatSessions: unknown;
|
||||
syncQuickTerminalTabs: unknown;
|
||||
setTaskSession: unknown;
|
||||
},
|
||||
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ListQuickTerminalTabsResponse } from "@/lib/api/domains/quick-terminal-api";
|
||||
import type { ListQuickChatSessionsResponse } from "@/lib/api/domains/workspace-api";
|
||||
import type { TaskSession } from "@/lib/types/http";
|
||||
const apiMock = vi.hoisted(() => ({
|
||||
listQuickChatSessions: vi.fn(),
|
||||
listQuickTerminalTabs: vi.fn(),
|
||||
}));
|
||||
|
||||
const syncMock = vi.hoisted(() => ({
|
||||
migrateStoredQuickChatNames: vi.fn(),
|
||||
toQuickChatSessions: vi.fn((sessions: unknown[]) => sessions),
|
||||
toQuickTerminalTab: vi.fn((tab: unknown) => tab),
|
||||
}));
|
||||
|
||||
const storeApiMock = vi.hoisted(() => ({
|
||||
getState: () => mockState,
|
||||
}));
|
||||
|
||||
type MockState = {
|
||||
connection: { status: string };
|
||||
quickChat: { syncRevisionByWorkspace: Record<string, number> };
|
||||
taskSessions: { items: Record<string, TaskSession> };
|
||||
setTaskSession: (session: TaskSession) => void;
|
||||
syncQuickChatSessions: (...args: unknown[]) => void;
|
||||
syncQuickTerminalTabs: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
let mockState: MockState;
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (state: typeof mockState.value) => unknown) => selector(mockState.value),
|
||||
useAppStore: (selector: (state: MockState) => unknown) => selector(mockState),
|
||||
useAppStoreApi: () => storeApiMock,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/workspace-api", () => ({
|
||||
listQuickChatSessions: (...args: unknown[]) => mockListQuickChatSessions(...args),
|
||||
listQuickChatSessions: apiMock.listQuickChatSessions,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/quick-terminal-api", () => ({
|
||||
listQuickTerminalTabs: (...args: unknown[]) => mockListQuickTerminalTabs(...args),
|
||||
toQuickTerminalTab: (tab: unknown) => tab,
|
||||
listQuickTerminalTabs: apiMock.listQuickTerminalTabs,
|
||||
toQuickTerminalTab: syncMock.toQuickTerminalTab,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/kanban-api", () => ({
|
||||
updateTask: (...args: unknown[]) => mockUpdateTask(...args),
|
||||
vi.mock("@/lib/local-storage", () => ({ getStoredQuickChatNames: vi.fn(() => ({})) }));
|
||||
vi.mock("@/lib/quick-chat/map-sessions", () => ({
|
||||
toQuickChatSessions: syncMock.toQuickChatSessions,
|
||||
}));
|
||||
vi.mock("@/lib/quick-chat/rename", () => ({
|
||||
migrateStoredQuickChatNames: syncMock.migrateStoredQuickChatNames,
|
||||
}));
|
||||
|
||||
import { useQuickChatResync } from "./use-quick-chat-resync";
|
||||
import { getStoredQuickChatNames, setStoredQuickChatName } from "@/lib/local-storage";
|
||||
|
||||
const syncQuickChatSessions = vi.fn();
|
||||
const syncQuickTerminalTabs = vi.fn();
|
||||
const setTaskSession = vi.fn();
|
||||
|
||||
function setConnection(status: string) {
|
||||
mockState.value = {
|
||||
connection: { status },
|
||||
syncQuickChatSessions,
|
||||
syncQuickTerminalTabs,
|
||||
setTaskSession,
|
||||
};
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((innerResolve) => {
|
||||
resolve = innerResolve;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
window.localStorage.clear();
|
||||
mockUpdateTask.mockResolvedValue(undefined);
|
||||
setConnection("connected");
|
||||
mockListQuickChatSessions.mockResolvedValue({
|
||||
sessions: [
|
||||
{
|
||||
session_id: "session-1",
|
||||
task_id: "task-1",
|
||||
workspace_id: "ws-1",
|
||||
kind: "chat",
|
||||
name: "Chat 1",
|
||||
agent_profile_id: "agent-1",
|
||||
},
|
||||
],
|
||||
task_sessions: [{ id: "session-1", task_id: "task-1" }],
|
||||
});
|
||||
mockListQuickTerminalTabs.mockResolvedValue({ tabs: [] });
|
||||
});
|
||||
function taskSession(state: TaskSession["state"], updatedAt: string): TaskSession {
|
||||
// The resync boundary only reads the stable identity, state, and update timestamp.
|
||||
return {
|
||||
id: "session-1",
|
||||
task_id: "task-1",
|
||||
state,
|
||||
updated_at: updatedAt,
|
||||
} as unknown as TaskSession;
|
||||
}
|
||||
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
const EMPTY_SESSIONS_RESPONSE = { sessions: [], task_sessions: [] };
|
||||
const EMPTY_TABS_RESPONSE = { tabs: [] };
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- resync scenarios share one connection fixture.
|
||||
describe("useQuickChatResync", () => {
|
||||
it("replaces the workspace's tabs with the server's list once connected", async () => {
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
|
||||
await waitFor(() => expect(syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
expect(syncQuickChatSessions).toHaveBeenCalledWith("ws-1", [
|
||||
{
|
||||
kind: "chat",
|
||||
sessionId: "session-1",
|
||||
taskId: "task-1",
|
||||
workspaceId: "ws-1",
|
||||
name: "Chat 1",
|
||||
agentProfileId: "agent-1",
|
||||
},
|
||||
]);
|
||||
expect(syncQuickTerminalTabs).toHaveBeenCalledWith("ws-1", []);
|
||||
beforeEach(() => {
|
||||
mockState = {
|
||||
connection: { status: "connected" },
|
||||
quickChat: { syncRevisionByWorkspace: { [WORKSPACE_ID]: 0 } },
|
||||
setTaskSession: vi.fn(),
|
||||
taskSessions: { items: {} },
|
||||
syncQuickChatSessions: vi.fn(),
|
||||
syncQuickTerminalTabs: vi.fn(),
|
||||
};
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// A tab without its session row renders but cannot subscribe or accept
|
||||
// input, so the rows in the response must land in the store too.
|
||||
it("stores the session rows that came with the list", async () => {
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
afterEach(cleanup);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(setTaskSession).toHaveBeenCalledWith({ id: "session-1", task_id: "task-1" }),
|
||||
);
|
||||
it("discards a superseded response and retries the latest workspace state", async () => {
|
||||
const firstSessions = deferred<ListQuickChatSessionsResponse>();
|
||||
const firstTerminals = deferred<ListQuickTerminalTabsResponse>();
|
||||
const latestSessions = deferred<ListQuickChatSessionsResponse>();
|
||||
const latestTerminals = deferred<ListQuickTerminalTabsResponse>();
|
||||
apiMock.listQuickChatSessions
|
||||
.mockReturnValueOnce(firstSessions.promise)
|
||||
.mockReturnValueOnce(latestSessions.promise);
|
||||
apiMock.listQuickTerminalTabs
|
||||
.mockReturnValueOnce(firstTerminals.promise)
|
||||
.mockReturnValueOnce(latestTerminals.promise);
|
||||
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
await act(async () => {
|
||||
mockState.quickChat.syncRevisionByWorkspace[WORKSPACE_ID] = 1;
|
||||
firstSessions.resolve(EMPTY_SESSIONS_RESPONSE);
|
||||
firstTerminals.resolve(EMPTY_TABS_RESPONSE);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
await waitFor(() => expect(apiMock.listQuickChatSessions).toHaveBeenCalledTimes(2));
|
||||
|
||||
await act(async () => {
|
||||
latestSessions.resolve(EMPTY_SESSIONS_RESPONSE);
|
||||
latestTerminals.resolve(EMPTY_TABS_RESPONSE);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
expect(mockState.syncQuickTerminalTabs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("waits for the socket before trusting any list", () => {
|
||||
setConnection("connecting");
|
||||
it("accepts a snapshot when the workspace has no revision entry yet", async () => {
|
||||
mockState.quickChat.syncRevisionByWorkspace = {};
|
||||
apiMock.listQuickChatSessions.mockResolvedValueOnce(EMPTY_SESSIONS_RESPONSE);
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValueOnce(EMPTY_TABS_RESPONSE);
|
||||
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
expect(mockListQuickChatSessions).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(apiMock.listQuickChatSessions).toHaveBeenCalledTimes(1);
|
||||
expect(mockState.syncQuickTerminalTabs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does nothing without an active workspace", () => {
|
||||
renderHook(() => useQuickChatResync(null));
|
||||
it("does not overwrite a newer live task session with a stale resync row", async () => {
|
||||
const stale = taskSession("RUNNING", "2099-01-01T00:00:00Z");
|
||||
mockState.taskSessions.items[stale.id] = taskSession("IDLE", "2099-01-01T00:01:00Z");
|
||||
apiMock.listQuickChatSessions.mockResolvedValueOnce({
|
||||
sessions: [],
|
||||
task_sessions: [stale],
|
||||
});
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValueOnce(EMPTY_TABS_RESPONSE);
|
||||
|
||||
expect(mockListQuickChatSessions).not.toHaveBeenCalled();
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(mockState.setTaskSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resyncs again after a reconnect, since events were missed while away", async () => {
|
||||
const { rerender } = renderHook(() => useQuickChatResync("ws-1"));
|
||||
await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
it("does not let an exact-second resync row regress a fractional-second live row", async () => {
|
||||
// "2099-01-01T00:00:00.1Z" is newer than "2099-01-01T00:00:00Z" even though a
|
||||
// lexicographic comparison sorts the exact-second string as larger.
|
||||
const stale = taskSession("RUNNING", "2099-01-01T00:00:00Z");
|
||||
mockState.taskSessions.items[stale.id] = taskSession("IDLE", "2099-01-01T00:00:00.1Z");
|
||||
apiMock.listQuickChatSessions.mockResolvedValueOnce({
|
||||
sessions: [],
|
||||
task_sessions: [stale],
|
||||
});
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValueOnce(EMPTY_TABS_RESPONSE);
|
||||
|
||||
setConnection("reconnecting");
|
||||
rerender();
|
||||
setConnection("connected");
|
||||
rerender();
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(mockState.setTaskSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not refetch on unrelated re-renders of the same connection", async () => {
|
||||
const { rerender } = renderHook(() => useQuickChatResync("ws-1"));
|
||||
await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
it("applies a fractional-second resync row newer than an exact-second live row", async () => {
|
||||
const fresh = taskSession("IDLE", "2099-01-01T00:00:00.1Z");
|
||||
mockState.taskSessions.items[fresh.id] = taskSession("RUNNING", "2099-01-01T00:00:00Z");
|
||||
apiMock.listQuickChatSessions.mockResolvedValueOnce({
|
||||
sessions: [],
|
||||
task_sessions: [fresh],
|
||||
});
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValueOnce(EMPTY_TABS_RESPONSE);
|
||||
|
||||
rerender();
|
||||
rerender();
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
expect(mockListQuickChatSessions).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(mockState.setTaskSession).toHaveBeenCalledWith(fresh);
|
||||
});
|
||||
|
||||
it("leaves existing tabs alone when the resync fails", async () => {
|
||||
mockListQuickChatSessions.mockRejectedValueOnce(new Error("offline"));
|
||||
it("stops retrying after the cap when every response observes a newer revision", async () => {
|
||||
// Every fetch captures revision R, then the store bumps to R+1 before the
|
||||
// response is compared, so each attempt is discarded as stale.
|
||||
apiMock.listQuickChatSessions.mockImplementation(() => {
|
||||
const response = Promise.resolve(EMPTY_SESSIONS_RESPONSE);
|
||||
queueMicrotask(() => {
|
||||
mockState.quickChat.syncRevisionByWorkspace[WORKSPACE_ID] += 1;
|
||||
});
|
||||
return response;
|
||||
});
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValue(EMPTY_TABS_RESPONSE);
|
||||
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
|
||||
await waitFor(() => expect(mockListQuickChatSessions).toHaveBeenCalled());
|
||||
expect(syncQuickChatSessions).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useQuickChatResync — legacy rename migration", () => {
|
||||
it("uploads a browser-only rename so it survives and reaches other devices", async () => {
|
||||
setStoredQuickChatName("session-1", "My old local name");
|
||||
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "My old local name" }),
|
||||
);
|
||||
await waitFor(() => expect(getStoredQuickChatNames()).toEqual({}));
|
||||
});
|
||||
|
||||
it("does not re-upload a name the server already has", async () => {
|
||||
setStoredQuickChatName("session-1", "Chat 1");
|
||||
|
||||
renderHook(() => useQuickChatResync("ws-1"));
|
||||
|
||||
await waitFor(() => expect(syncQuickChatSessions).toHaveBeenCalled());
|
||||
expect(mockUpdateTask).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(apiMock.listQuickChatSessions.mock.calls.length).toBe(4));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
expect(apiMock.listQuickChatSessions.mock.calls.length).toBe(4);
|
||||
expect(mockState.syncQuickChatSessions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts a fresh retry budget after reconnecting", async () => {
|
||||
let phase: "first" | "second" = "first";
|
||||
let requestsInPhase = 0;
|
||||
apiMock.listQuickChatSessions.mockImplementation(() => {
|
||||
requestsInPhase += 1;
|
||||
const response = Promise.resolve(EMPTY_SESSIONS_RESPONSE);
|
||||
if (phase === "first" || requestsInPhase === 1) {
|
||||
queueMicrotask(() => {
|
||||
mockState.quickChat.syncRevisionByWorkspace[WORKSPACE_ID] += 1;
|
||||
});
|
||||
}
|
||||
return response;
|
||||
});
|
||||
apiMock.listQuickTerminalTabs.mockResolvedValue(EMPTY_TABS_RESPONSE);
|
||||
|
||||
const rendered = renderHook(() => useQuickChatResync(WORKSPACE_ID));
|
||||
await waitFor(() => expect(apiMock.listQuickChatSessions).toHaveBeenCalledTimes(4));
|
||||
|
||||
act(() => {
|
||||
mockState.connection.status = "disconnected";
|
||||
rendered.rerender();
|
||||
});
|
||||
phase = "second";
|
||||
requestsInPhase = 0;
|
||||
act(() => {
|
||||
mockState.connection.status = "connected";
|
||||
rendered.rerender();
|
||||
});
|
||||
|
||||
await waitFor(() => expect(mockState.syncQuickChatSessions).toHaveBeenCalledTimes(1));
|
||||
expect(apiMock.listQuickChatSessions).toHaveBeenCalledTimes(6);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { listQuickChatSessions } from "@/lib/api/domains/workspace-api";
|
||||
import { listQuickTerminalTabs, toQuickTerminalTab } from "@/lib/api/domains/quick-terminal-api";
|
||||
import { getStoredQuickChatNames } from "@/lib/local-storage";
|
||||
import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions";
|
||||
import { migrateStoredQuickChatNames } from "@/lib/quick-chat/rename";
|
||||
|
||||
/** How many times a resync may refetch after observing a newer revision. */
|
||||
const MAX_RESYNC_RETRIES = 3;
|
||||
const RESYNC_RETRY_DELAY_MS = 50;
|
||||
|
||||
/**
|
||||
* Whether a reconnect snapshot is older than the live row. Parses both
|
||||
* timestamps so an exact-second value ("...00Z") compares correctly against a
|
||||
* newer fractional one ("...00.1Z"); a lexicographic comparison would misorder
|
||||
* them. Mirrors isStaleSessionStateEvent without pulling the handler module
|
||||
* graph (and its i18n init) into the resync hook.
|
||||
*/
|
||||
function isStaleTaskSession(
|
||||
live: { updated_at?: string } | undefined,
|
||||
snapshotUpdatedAt: string | undefined,
|
||||
): boolean {
|
||||
if (!snapshotUpdatedAt || !live?.updated_at) return false;
|
||||
const snapshotTime = Date.parse(snapshotUpdatedAt);
|
||||
const liveTime = Date.parse(live.updated_at);
|
||||
if (Number.isNaN(snapshotTime) || Number.isNaN(liveTime)) return false;
|
||||
return snapshotTime < liveTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps this client's quick-chat tabs in step with the server's list.
|
||||
*
|
||||
@@ -18,6 +40,7 @@ import { migrateStoredQuickChatNames } from "@/lib/quick-chat/rename";
|
||||
* Re-reading the list whenever the socket (re)connects closes that gap.
|
||||
*/
|
||||
export function useQuickChatResync(workspaceId: string | null): void {
|
||||
const store = useAppStoreApi();
|
||||
const connectionStatus = useAppStore((state) => state.connection.status);
|
||||
const syncQuickChatSessions = useAppStore((state) => state.syncQuickChatSessions);
|
||||
const syncQuickTerminalTabs = useAppStore((state) => state.syncQuickTerminalTabs);
|
||||
@@ -34,29 +57,61 @@ export function useQuickChatResync(workspaceId: string | null): void {
|
||||
lastSyncedConnection.current = workspaceId;
|
||||
|
||||
let cancelled = false;
|
||||
Promise.all([listQuickChatSessions(workspaceId), listQuickTerminalTabs(workspaceId)])
|
||||
.then(([response, terminalResponse]) => {
|
||||
if (cancelled) return;
|
||||
const sessions = toQuickChatSessions(response.sessions);
|
||||
// Store the session rows before the tabs. A tab without its row cannot
|
||||
// subscribe or accept input (useSession bails, requireSessionInputMode
|
||||
// throws), so a resync-only tab would otherwise render but be dead.
|
||||
for (const taskSession of response.task_sessions) {
|
||||
setTaskSession(taskSession);
|
||||
const resync = async () => {
|
||||
let retryCount = 0;
|
||||
while (!cancelled) {
|
||||
const revision = store.getState().quickChat.syncRevisionByWorkspace[workspaceId] ?? 0;
|
||||
try {
|
||||
const [response, terminalResponse] = await Promise.all([
|
||||
listQuickChatSessions(workspaceId),
|
||||
listQuickTerminalTabs(workspaceId),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
|
||||
const currentRevision =
|
||||
store.getState().quickChat.syncRevisionByWorkspace[workspaceId] ?? 0;
|
||||
if (currentRevision !== revision) {
|
||||
if (retryCount >= MAX_RESYNC_RETRIES) return;
|
||||
retryCount += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, RESYNC_RETRY_DELAY_MS));
|
||||
continue;
|
||||
}
|
||||
|
||||
const sessions = toQuickChatSessions(response.sessions);
|
||||
// Store the session rows before the tabs. A tab without its row cannot
|
||||
// subscribe or accept input (useSession bails, requireSessionInputMode
|
||||
// throws), so a resync-only tab would otherwise render but be dead.
|
||||
// Rows older than the live row are skipped: a reconnect snapshot must
|
||||
// never regress state a newer WebSocket event already applied.
|
||||
for (const taskSession of response.task_sessions) {
|
||||
const liveSession = store.getState().taskSessions.items[taskSession.id];
|
||||
if (isStaleTaskSession(liveSession, taskSession.updated_at)) continue;
|
||||
setTaskSession(taskSession);
|
||||
}
|
||||
syncQuickChatSessions(workspaceId, sessions);
|
||||
syncQuickTerminalTabs(workspaceId, terminalResponse.tabs.map(toQuickTerminalTab));
|
||||
// Renames made before names were stored server-side live only in this
|
||||
// browser; push them up once so they reach the user's other devices.
|
||||
void migrateStoredQuickChatNames(sessions, getStoredQuickChatNames());
|
||||
return;
|
||||
} catch {
|
||||
// A failed resync must not clear the user's tabs; retry on next connect.
|
||||
if (!cancelled) lastSyncedConnection.current = null;
|
||||
return;
|
||||
}
|
||||
syncQuickChatSessions(workspaceId, sessions);
|
||||
syncQuickTerminalTabs(workspaceId, terminalResponse.tabs.map(toQuickTerminalTab));
|
||||
// Renames made before names were stored server-side live only in this
|
||||
// browser; push them up once so they reach the user's other devices.
|
||||
void migrateStoredQuickChatNames(sessions, getStoredQuickChatNames());
|
||||
})
|
||||
.catch(() => {
|
||||
// A failed resync must not clear the user's tabs; retry on next connect.
|
||||
if (!cancelled) lastSyncedConnection.current = null;
|
||||
});
|
||||
}
|
||||
};
|
||||
void resync();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connectionStatus, workspaceId, setTaskSession, syncQuickChatSessions, syncQuickTerminalTabs]);
|
||||
}, [
|
||||
connectionStatus,
|
||||
workspaceId,
|
||||
store,
|
||||
setTaskSession,
|
||||
syncQuickChatSessions,
|
||||
syncQuickTerminalTabs,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveSessionDeletionTarget } from "./session-deletion";
|
||||
|
||||
describe("resolveSessionDeletionTarget", () => {
|
||||
it("routes a Quick Chat member through its backing task", () => {
|
||||
expect(
|
||||
resolveSessionDeletionTarget("session-1", "fallback-task", [
|
||||
{ sessionId: "session-1", taskId: "task-1", workspaceId: "workspace-1", kind: "chat" },
|
||||
]),
|
||||
).toEqual({ kind: "quick-chat-task", taskId: "task-1" });
|
||||
});
|
||||
|
||||
it("routes an ordinary session through session deletion", () => {
|
||||
expect(resolveSessionDeletionTarget("session-1", "task-1", [])).toEqual({
|
||||
kind: "session",
|
||||
sessionId: "session-1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { QuickChatSession } from "@/lib/state/slices/ui/types";
|
||||
|
||||
export type SessionDeletionTarget =
|
||||
| { kind: "quick-chat-task"; taskId: string }
|
||||
| { kind: "session"; sessionId: string };
|
||||
|
||||
/** Routes Quick Chat members through task deletion and ordinary sessions through session deletion. */
|
||||
export function resolveSessionDeletionTarget(
|
||||
sessionId: string,
|
||||
taskId: string,
|
||||
quickChatSessions: readonly QuickChatSession[],
|
||||
): SessionDeletionTarget {
|
||||
const quickChatSession = quickChatSessions.find((session) => session.sessionId === sessionId);
|
||||
if (quickChatSession) {
|
||||
return { kind: "quick-chat-task", taskId: quickChatSession.taskId ?? taskId };
|
||||
}
|
||||
return { kind: "session", sessionId };
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
defaultSystemState,
|
||||
defaultReviewState,
|
||||
} from "./slices";
|
||||
import { applyStoredQuickChatNames } from "@/lib/state/slices/ui/quick-chat-sync";
|
||||
import { mergeHydratedQuickChatSessions } from "@/lib/state/slices/ui/quick-chat-sync";
|
||||
import type { AgentRuntimeAvailability } from "@/lib/types/agent-runtime";
|
||||
import type { HydrationState } from "./store";
|
||||
import { seedSettledSessionBoundaries } from "@/lib/state/slices/session/turn-actions";
|
||||
@@ -163,13 +163,17 @@ function mergeCodeHostFields(
|
||||
}
|
||||
|
||||
function mergeQuickChatState(initialState: HydrationState): DefaultState["quickChat"] {
|
||||
const quickChat = { ...defaultState.quickChat, ...initialState.quickChat };
|
||||
if (!initialState.quickChat?.sessions) return quickChat;
|
||||
|
||||
return {
|
||||
...quickChat,
|
||||
sessions: applyStoredQuickChatNames(initialState.quickChat.sessions),
|
||||
const { sessions, ...hydratedQuickChat } = initialState.quickChat ?? {};
|
||||
const quickChat = {
|
||||
...defaultState.quickChat,
|
||||
...hydratedQuickChat,
|
||||
unseenIdleByWorkspace: {},
|
||||
lastSettledAtBySession: {},
|
||||
sessionOwnership: {},
|
||||
syncRevisionByWorkspace: {},
|
||||
tombstonedSessions: {},
|
||||
};
|
||||
return sessions ? mergeHydratedQuickChatSessions(quickChat, sessions) : quickChat;
|
||||
}
|
||||
|
||||
function mergeSidebarViewState(initialState: HydrationState): DefaultState["sidebarViews"] {
|
||||
|
||||
@@ -160,18 +160,13 @@ describe("hydrateUI — quick chat lifecycle", () => {
|
||||
expect(result.quickChat.activeTerminalTabId).toBe(TERMINAL_TAB_ID);
|
||||
});
|
||||
|
||||
it("clears stale quick chat sessions when the backend returns none", () => {
|
||||
it("preserves live quick chat sessions omitted by stale hydration", () => {
|
||||
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
|
||||
draft.quickChat = {
|
||||
...draft.quickChat,
|
||||
isOpen: true,
|
||||
activeSessionId: "stale-session",
|
||||
sessions: [
|
||||
{ sessionId: "stale-session", workspaceId: "ws-1", name: "Stale", kind: "chat" },
|
||||
],
|
||||
terminalTabs: [],
|
||||
activeKind: "conversation",
|
||||
activeTerminalTabId: null,
|
||||
lastTerminalTabIdByWorkspace: {},
|
||||
sessions: [{ sessionId: "stale-session", workspaceId: "ws-1", name: "Live", kind: "chat" }],
|
||||
};
|
||||
hydrateUI(draft, {
|
||||
quickChat: {
|
||||
@@ -182,14 +177,15 @@ describe("hydrateUI — quick chat lifecycle", () => {
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.quickChat.sessions).toEqual([]);
|
||||
expect(result.quickChat.isOpen).toBe(false);
|
||||
expect(result.quickChat.activeSessionId).toBeNull();
|
||||
expect(result.quickChat.sessions).toHaveLength(1);
|
||||
expect(result.quickChat.sessions[0].sessionId).toBe("stale-session");
|
||||
expect(result.quickChat.isOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves browser-local terminal tabs when server conversations resync", () => {
|
||||
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
|
||||
draft.quickChat = {
|
||||
...draft.quickChat,
|
||||
isOpen: true,
|
||||
activeSessionId: "chat-1",
|
||||
sessions: [{ sessionId: "chat-1", workspaceId: "ws-1", kind: "chat" }],
|
||||
@@ -215,7 +211,7 @@ describe("hydrateUI — quick chat lifecycle", () => {
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.quickChat.sessions).toEqual([]);
|
||||
expect(result.quickChat.sessions).toHaveLength(1);
|
||||
expect(result.quickChat.terminalTabs).toHaveLength(1);
|
||||
expect(result.quickChat.activeKind).toBe("terminal");
|
||||
expect(result.quickChat.activeTerminalTabId).toBe(TERMINAL_TAB_ID);
|
||||
@@ -227,6 +223,7 @@ describe("hydrateUI — terminal descriptor reconciliation", () => {
|
||||
it("treats an empty server terminal list as authoritative during hydration", () => {
|
||||
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
|
||||
draft.quickChat = {
|
||||
...draft.quickChat,
|
||||
isOpen: true,
|
||||
activeSessionId: null,
|
||||
sessions: [],
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Draft } from "immer";
|
||||
import type { AppState, HydrationState } from "../store";
|
||||
import { migrateSidebarViewDraft, migrateView } from "../slices/ui/ui-slice";
|
||||
import {
|
||||
applyStoredQuickChatNames,
|
||||
mergeHydratedQuickChatSessions,
|
||||
reconcileQuickTerminalTabs,
|
||||
} from "@/lib/state/slices/ui/quick-chat-sync";
|
||||
import { compareUserSettingsRevisions } from "@/lib/settings/user-settings-revision";
|
||||
@@ -445,15 +445,11 @@ export function hydrateUI(draft: Draft<AppState>, state: HydrationState): void {
|
||||
if (state.rightPanel) deepMerge(draft.rightPanel, state.rightPanel);
|
||||
if (state.diffs) deepMerge(draft.diffs, state.diffs);
|
||||
if (state.quickChat) {
|
||||
// Merge quick chat sessions, preserving isOpen from client
|
||||
// SSR snapshots may arrive after live WebSocket updates. Hydration only
|
||||
// adopts previously unseen sessions and never removes or regresses tabs.
|
||||
if (state.quickChat.sessions) {
|
||||
const previousSessions = draft.quickChat.sessions;
|
||||
const previousActiveSessionId = draft.quickChat.activeSessionId;
|
||||
// Local renames live in localStorage and override the SSR-provided name
|
||||
// (which derives from the backend task title). Apply on every hydration
|
||||
// so a renamed chat keeps its local name across reloads and tab switches.
|
||||
draft.quickChat.sessions = applyStoredQuickChatNames(state.quickChat.sessions);
|
||||
restoreQuickChatSelection(draft, previousSessions, previousActiveSessionId);
|
||||
draft.quickChat = mergeHydratedQuickChatSessions(draft.quickChat, state.quickChat.sessions);
|
||||
restoreQuickChatSelection(draft, draft.quickChat.sessions, draft.quickChat.activeSessionId);
|
||||
}
|
||||
if (state.quickChat.terminalTabs) hydrateQuickTerminalState(draft, state.quickChat);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ function makeStore() {
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- related quick-chat session state transitions share a store fixture.
|
||||
describe("typed quick chat sessions", () => {
|
||||
it("registers a shared session without opening the Quick Chat dialog", () => {
|
||||
const store = makeStore();
|
||||
@@ -77,6 +78,53 @@ describe("typed quick chat sessions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves task ownership when reopening or refreshing an existing session", () => {
|
||||
const store = makeStore();
|
||||
store.getState().addQuickChatSession(SESSION_A, WORKSPACE_A, "agent-a", "chat", "task-a");
|
||||
store.getState().closeQuickChat();
|
||||
|
||||
store.getState().openQuickChat(SESSION_A, WORKSPACE_A);
|
||||
store.getState().addQuickChatSession(SESSION_A, WORKSPACE_A);
|
||||
|
||||
expect(store.getState().quickChat.sessionOwnership[SESSION_A]).toEqual({
|
||||
workspaceId: WORKSPACE_A,
|
||||
taskId: "task-a",
|
||||
});
|
||||
});
|
||||
|
||||
it("clears every workspace's unseen markers when the dialog opens", () => {
|
||||
const store = makeStore();
|
||||
store.getState().markQuickChatUnseenIdle("session-a", WORKSPACE_A);
|
||||
store.getState().markQuickChatUnseenIdle("session-b", WORKSPACE_B);
|
||||
|
||||
store.getState().openQuickChat(SESSION_A, WORKSPACE_A);
|
||||
|
||||
expect(store.getState().quickChat.unseenIdleByWorkspace).toEqual({});
|
||||
});
|
||||
|
||||
it("prunes the workspace marker bucket when the active session is selected", () => {
|
||||
const store = makeStore();
|
||||
store.getState().addQuickChatSession(SESSION_A, WORKSPACE_A);
|
||||
store.getState().markQuickChatUnseenIdle(SESSION_A, WORKSPACE_A);
|
||||
|
||||
store.getState().setActiveQuickChatSession(SESSION_A, WORKSPACE_A);
|
||||
|
||||
expect(store.getState().quickChat.unseenIdleByWorkspace).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps unseen markers when opening a session owned by another workspace fails", () => {
|
||||
const store = makeStore();
|
||||
store.getState().addQuickChatSession(SESSION_A, WORKSPACE_A);
|
||||
store.getState().markQuickChatUnseenIdle(SESSION_A, WORKSPACE_A);
|
||||
|
||||
store.getState().openQuickChat(SESSION_A, WORKSPACE_B);
|
||||
|
||||
expect(store.getState().quickChat.isOpen).toBe(false);
|
||||
expect(store.getState().quickChat.unseenIdleByWorkspace).toEqual({
|
||||
[WORKSPACE_A]: { [SESSION_A]: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("opens a configuration setup tab in the unified quick chat store", () => {
|
||||
const store = makeStore();
|
||||
const setupId = getQuickChatSetupSessionId(WORKSPACE_A, "config");
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import type { Draft } from "immer";
|
||||
import { getQuickChatSetupSessionId } from "./quick-chat-session";
|
||||
import {
|
||||
clearMarker,
|
||||
closeQuickChatSession,
|
||||
pruneStaleSettledLedger,
|
||||
reconcileQuickChatSessions,
|
||||
reconcileQuickTerminalTabs,
|
||||
removeQuickChatSession,
|
||||
removeQuickChatSessionsForTask,
|
||||
upsertQuickChatSession,
|
||||
} from "./quick-chat-sync";
|
||||
import type { QuickChatSession, UISlice } from "./types";
|
||||
|
||||
type ImmerSet = (recipe: (draft: Draft<UISlice>) => void) => void;
|
||||
|
||||
function findWorkspaceConfigSession(
|
||||
sessions: UISlice["quickChat"]["sessions"],
|
||||
workspaceId: string,
|
||||
) {
|
||||
return sessions.find(
|
||||
(session) => session.workspaceId === workspaceId && session.kind === "config",
|
||||
);
|
||||
}
|
||||
|
||||
function upsertQuickChatSessionDraft(
|
||||
quickChat: Draft<UISlice["quickChat"]>,
|
||||
session: QuickChatSession,
|
||||
): boolean {
|
||||
const { sessionId, workspaceId, agentProfileId, kind, taskId } = session;
|
||||
const existing = quickChat.sessions.find((session) => session.sessionId === sessionId);
|
||||
if (existing) {
|
||||
if (existing.workspaceId !== workspaceId) return false;
|
||||
if (agentProfileId) existing.agentProfileId = agentProfileId;
|
||||
if (taskId) existing.taskId = taskId;
|
||||
} else {
|
||||
quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId });
|
||||
}
|
||||
const ownedTaskId = taskId ?? existing?.taskId ?? quickChat.sessionOwnership[sessionId]?.taskId;
|
||||
quickChat.sessionOwnership[sessionId] = { workspaceId, taskId: ownedTaskId };
|
||||
quickChat.syncRevisionByWorkspace[workspaceId] =
|
||||
(quickChat.syncRevisionByWorkspace[workspaceId] ?? 0) + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
function openQuickChat(set: ImmerSet) {
|
||||
return (
|
||||
sessionId: string,
|
||||
workspaceId: string,
|
||||
agentProfileId?: string,
|
||||
kind: "chat" | "config" = "chat",
|
||||
taskId?: string,
|
||||
) =>
|
||||
set((draft) => {
|
||||
if (!sessionId) {
|
||||
const existing =
|
||||
kind === "config"
|
||||
? findWorkspaceConfigSession(draft.quickChat.sessions, workspaceId)
|
||||
: undefined;
|
||||
const setupSessionId = getQuickChatSetupSessionId(workspaceId, kind);
|
||||
if (
|
||||
!existing &&
|
||||
!draft.quickChat.sessions.some((session) => session.sessionId === setupSessionId)
|
||||
) {
|
||||
draft.quickChat.sessions.push({ sessionId: setupSessionId, workspaceId, kind });
|
||||
}
|
||||
draft.quickChat.isOpen = true;
|
||||
draft.quickChat.activeSessionId = existing?.sessionId ?? setupSessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
// The dialog is open now, so every workspace's dots are obsolete.
|
||||
draft.quickChat.unseenIdleByWorkspace = {};
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!upsertQuickChatSessionDraft(draft.quickChat, {
|
||||
sessionId,
|
||||
workspaceId,
|
||||
agentProfileId,
|
||||
kind,
|
||||
taskId,
|
||||
})
|
||||
)
|
||||
return;
|
||||
draft.quickChat.isOpen = true;
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
// Only a successful open clears the dots; a rejected cross-workspace open
|
||||
// must not erase markers the user never saw.
|
||||
draft.quickChat.unseenIdleByWorkspace = {};
|
||||
});
|
||||
}
|
||||
|
||||
function addQuickChatSession(set: ImmerSet) {
|
||||
return (
|
||||
sessionId: string,
|
||||
workspaceId: string,
|
||||
agentProfileId?: string,
|
||||
kind: "chat" | "config" = "chat",
|
||||
taskId?: string,
|
||||
) =>
|
||||
set((draft) => {
|
||||
const activeWorkspaceId = draft.quickChat.sessions.find(
|
||||
(session) => session.sessionId === draft.quickChat.activeSessionId,
|
||||
)?.workspaceId;
|
||||
if (
|
||||
!upsertQuickChatSessionDraft(draft.quickChat, {
|
||||
sessionId,
|
||||
workspaceId,
|
||||
agentProfileId,
|
||||
kind,
|
||||
taskId,
|
||||
})
|
||||
)
|
||||
return;
|
||||
if (!draft.quickChat.isOpen || !activeWorkspaceId || activeWorkspaceId === workspaceId) {
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function buildQuickChatActions(set: ImmerSet) {
|
||||
return {
|
||||
addQuickChatSession: addQuickChatSession(set),
|
||||
openQuickChat: openQuickChat(set),
|
||||
closeQuickChat: () =>
|
||||
set((draft) => {
|
||||
draft.quickChat.isOpen = false;
|
||||
}),
|
||||
closeQuickChatSession: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = closeQuickChatSession(draft.quickChat, sessionId);
|
||||
}),
|
||||
setActiveQuickChatSession: (sessionId: string, workspaceId: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (!session || session.workspaceId !== workspaceId) return;
|
||||
draft.quickChat.unseenIdleByWorkspace = clearMarker(
|
||||
draft.quickChat.unseenIdleByWorkspace,
|
||||
workspaceId,
|
||||
sessionId,
|
||||
);
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
}),
|
||||
renameQuickChatSession: (sessionId: string, name: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (!session) return;
|
||||
session.name = name;
|
||||
draft.quickChat.syncRevisionByWorkspace[session.workspaceId] =
|
||||
(draft.quickChat.syncRevisionByWorkspace[session.workspaceId] ?? 0) + 1;
|
||||
}),
|
||||
syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions);
|
||||
}),
|
||||
syncQuickTerminalTabs: (workspaceId: string, tabs: UISlice["quickChat"]["terminalTabs"]) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = reconcileQuickTerminalTabs(draft.quickChat, workspaceId, tabs);
|
||||
}),
|
||||
upsertQuickChatSessionFromEvent: (session: QuickChatSession) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = upsertQuickChatSession(draft.quickChat, session);
|
||||
}),
|
||||
removeQuickChatSessionsForTask: (taskId: string) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = removeQuickChatSessionsForTask(draft.quickChat, taskId);
|
||||
}),
|
||||
removeQuickChatSession: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = removeQuickChatSession(draft.quickChat, sessionId);
|
||||
}),
|
||||
markQuickChatUnseenIdle: (sessionId: string, workspaceId: string) =>
|
||||
set((draft) => {
|
||||
draft.quickChat.unseenIdleByWorkspace[workspaceId] = {
|
||||
...draft.quickChat.unseenIdleByWorkspace[workspaceId],
|
||||
[sessionId]: true,
|
||||
};
|
||||
}),
|
||||
clearQuickChatUnseenIdle: (sessionId?: string, workspaceId?: string) =>
|
||||
set((draft) => {
|
||||
if (!sessionId || !workspaceId) {
|
||||
draft.quickChat.unseenIdleByWorkspace = {};
|
||||
return;
|
||||
}
|
||||
draft.quickChat.unseenIdleByWorkspace = clearMarker(
|
||||
draft.quickChat.unseenIdleByWorkspace,
|
||||
workspaceId,
|
||||
sessionId,
|
||||
);
|
||||
}),
|
||||
recordQuickChatSettled: (sessionId: string, updatedAt: string) => {
|
||||
let recorded = false;
|
||||
set((draft) => {
|
||||
if (!updatedAt) return;
|
||||
// Compare parsed epochs, not strings: an exact-second value ("...00Z")
|
||||
// must not be treated as newer than a fractional one ("...00.1Z").
|
||||
const updatedTime = Date.parse(updatedAt);
|
||||
if (Number.isNaN(updatedTime)) return;
|
||||
const existing = draft.quickChat.lastSettledAtBySession[sessionId];
|
||||
if (existing) {
|
||||
const existingTime = Date.parse(existing);
|
||||
if (!Number.isNaN(existingTime) && updatedTime <= existingTime) return;
|
||||
}
|
||||
draft.quickChat.lastSettledAtBySession = pruneStaleSettledLedger({
|
||||
...draft.quickChat.lastSettledAtBySession,
|
||||
[sessionId]: updatedAt,
|
||||
});
|
||||
recorded = true;
|
||||
});
|
||||
return recorded;
|
||||
},
|
||||
setQuickChatInitialPrompt: (sessionId: string, prompt?: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (session) session.initialPrompt = prompt;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import {
|
||||
reconcileQuickTerminalTabs,
|
||||
reconcileQuickChatSessions,
|
||||
mergeHydratedQuickChatSessions,
|
||||
removeQuickChatSession,
|
||||
removeQuickChatSessionsForTask,
|
||||
upsertQuickChatSession,
|
||||
} from "./quick-chat-sync";
|
||||
@@ -38,6 +40,11 @@ function state(sessions: QuickChatSession[], overrides: Partial<QuickChatState>
|
||||
activeKind: "conversation" as const,
|
||||
activeTerminalTabId: null,
|
||||
lastTerminalTabIdByWorkspace: {},
|
||||
unseenIdleByWorkspace: {},
|
||||
lastSettledAtBySession: {},
|
||||
sessionOwnership: {},
|
||||
syncRevisionByWorkspace: {},
|
||||
tombstonedSessions: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -353,6 +360,32 @@ describe("upsertQuickChatSession", () => {
|
||||
|
||||
expect(after.sessions[0].name).toBe("Mine");
|
||||
});
|
||||
|
||||
it("accepts a session once its tombstone has expired", () => {
|
||||
const expiredAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
|
||||
const before = state([], {
|
||||
tombstonedSessions: { a: { workspaceId: WS, tombstonedAt: expiredAt } },
|
||||
});
|
||||
|
||||
const after = upsertQuickChatSession(before, chat("a"));
|
||||
|
||||
expect(after.sessions.map((s) => s.sessionId)).toEqual(["a"]);
|
||||
expect(after.tombstonedSessions).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeHydratedQuickChatSessions", () => {
|
||||
it("accepts a session when its tombstone has expired", () => {
|
||||
const expiredAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
|
||||
const before = state([], {
|
||||
tombstonedSessions: { a: { workspaceId: WS, tombstonedAt: expiredAt } },
|
||||
});
|
||||
|
||||
const after = mergeHydratedQuickChatSessions(before, [chat("a")]);
|
||||
|
||||
expect(after.sessions.map((session) => session.sessionId)).toEqual(["a"]);
|
||||
expect(after.tombstonedSessions).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeQuickChatSessionsForTask", () => {
|
||||
@@ -374,6 +407,31 @@ describe("removeQuickChatSessionsForTask", () => {
|
||||
expect(after.activeSessionId).toBeNull();
|
||||
});
|
||||
|
||||
it("removes lifecycle state using ownership after its tab has disappeared", () => {
|
||||
const before = state([], {
|
||||
sessionOwnership: { removed: { workspaceId: WS, taskId: "task-removed" } },
|
||||
unseenIdleByWorkspace: { [WS]: { removed: true } },
|
||||
lastSettledAtBySession: { removed: "2026-08-17T07:00:00Z" },
|
||||
});
|
||||
|
||||
const after = removeQuickChatSessionsForTask(before, "task-removed");
|
||||
|
||||
expect(after.sessionOwnership).toEqual({});
|
||||
expect(after.unseenIdleByWorkspace).toEqual({});
|
||||
expect(after.lastSettledAtBySession).toEqual({});
|
||||
});
|
||||
|
||||
it("clears a pre-existing unseen marker when the session is removed directly", () => {
|
||||
const before = state([chat("a")], {
|
||||
unseenIdleByWorkspace: { [WS]: { a: true } },
|
||||
});
|
||||
|
||||
const after = removeQuickChatSession(before, "a");
|
||||
|
||||
expect(after.unseenIdleByWorkspace).toEqual({});
|
||||
expect(after.sessions.map((s) => s.sessionId)).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns the same state when no tab is affected", () => {
|
||||
const before = state([chat("a")]);
|
||||
|
||||
|
||||
@@ -2,79 +2,270 @@ import { getStoredQuickChatNames } from "@/lib/local-storage";
|
||||
import { isQuickChatSetupSessionId } from "./quick-chat-session";
|
||||
import type { QuickChatSession, QuickChatState, QuickTerminalTab } from "./types";
|
||||
|
||||
/**
|
||||
* Applies locally stored tab renames over a server-provided session list.
|
||||
*
|
||||
* Renames live in localStorage, so the backend task title is only a fallback.
|
||||
* Boot hydration and runtime resync both go through here so a reload and a
|
||||
* WebSocket-driven refresh label the same tab the same way.
|
||||
*/
|
||||
const QUICK_CHAT_LIFECYCLE_RETENTION_MS = 60 * 60 * 1000;
|
||||
const SETTLED_LEDGER_MAX_ENTRIES = 500;
|
||||
|
||||
/** Applies locally stored tab renames over a server-provided session list. */
|
||||
export function applyStoredQuickChatNames(sessions: QuickChatSession[]): QuickChatSession[] {
|
||||
const storedNames = getStoredQuickChatNames();
|
||||
return sessions.map((session) => {
|
||||
const localName = storedNames[session.sessionId];
|
||||
return {
|
||||
...session,
|
||||
kind: session.kind ?? "chat",
|
||||
...(localName ? { name: localName } : {}),
|
||||
};
|
||||
return { ...session, kind: session.kind ?? "chat", ...(localName ? { name: localName } : {}) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconciles one workspace's quick-chat tabs against the server's list.
|
||||
*
|
||||
* Quick chats are shared state: they are created and closed from any device,
|
||||
* but a client only ever learned about them from its own boot payload. Without
|
||||
* this reconcile, two long-lived clients drift — each keeps tabs the other
|
||||
* never saw, and keeps tabs whose task the other already deleted.
|
||||
*
|
||||
* Membership is the server's call; position is not. Tabs already on screen keep
|
||||
* their order and new ones are appended, because the server sorts by latest
|
||||
* activity and that changes as sessions run — adopting it wholesale would
|
||||
* reshuffle the strip under the user's cursor on every reconnect. The activity
|
||||
* order still decides the initial restore, when there is nothing on screen yet.
|
||||
*
|
||||
* Local-only state is preserved: unstarted "New chat" setup tabs (which have no
|
||||
* backing task yet) and per-session drafts on tabs that survive.
|
||||
*/
|
||||
export function pruneStaleSettledLedger(
|
||||
bySession: Record<string, string>,
|
||||
now = Date.now(),
|
||||
): Record<string, string> {
|
||||
const retained = Object.entries(bySession)
|
||||
.filter(([, updatedAt]) => {
|
||||
const timestamp = Date.parse(updatedAt);
|
||||
return Number.isFinite(timestamp) && now - timestamp <= QUICK_CHAT_LIFECYCLE_RETENTION_MS;
|
||||
})
|
||||
.sort(([, left], [, right]) => Date.parse(right) - Date.parse(left))
|
||||
.slice(0, SETTLED_LEDGER_MAX_ENTRIES);
|
||||
return Object.fromEntries(retained);
|
||||
}
|
||||
|
||||
function pruneTombstones(
|
||||
tombstones: QuickChatState["tombstonedSessions"],
|
||||
now = Date.now(),
|
||||
): QuickChatState["tombstonedSessions"] {
|
||||
return Object.fromEntries(
|
||||
Object.entries(tombstones).filter(([, tombstone]) => {
|
||||
const timestamp = Date.parse(tombstone.tombstonedAt);
|
||||
return Number.isFinite(timestamp) && now - timestamp <= QUICK_CHAT_LIFECYCLE_RETENTION_MS;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function indexSessionOwnership(
|
||||
ownership: QuickChatState["sessionOwnership"],
|
||||
sessions: QuickChatSession[],
|
||||
): QuickChatState["sessionOwnership"] {
|
||||
const next = { ...ownership };
|
||||
for (const session of sessions) {
|
||||
if (!isQuickChatSetupSessionId(session.sessionId)) {
|
||||
next[session.sessionId] = { workspaceId: session.workspaceId, taskId: session.taskId };
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function withRevision(state: QuickChatState, workspaceId: string): QuickChatState {
|
||||
return {
|
||||
...state,
|
||||
syncRevisionByWorkspace: {
|
||||
...state.syncRevisionByWorkspace,
|
||||
[workspaceId]: (state.syncRevisionByWorkspace[workspaceId] ?? 0) + 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function clearMarker(
|
||||
byWorkspace: QuickChatState["unseenIdleByWorkspace"],
|
||||
workspaceId: string,
|
||||
sessionId: string,
|
||||
): QuickChatState["unseenIdleByWorkspace"] {
|
||||
const markers = byWorkspace[workspaceId];
|
||||
if (!markers?.[sessionId]) return byWorkspace;
|
||||
const { [sessionId]: _removed, ...remaining } = markers;
|
||||
if (Object.keys(remaining).length === 0) {
|
||||
const { [workspaceId]: _workspace, ...otherWorkspaces } = byWorkspace;
|
||||
return otherWorkspaces;
|
||||
}
|
||||
return { ...byWorkspace, [workspaceId]: remaining };
|
||||
}
|
||||
|
||||
function withLifecyclePruning(
|
||||
state: QuickChatState,
|
||||
removedIds: Set<string>,
|
||||
tombstone: boolean,
|
||||
): QuickChatState {
|
||||
if (removedIds.size === 0) return state;
|
||||
let markers = state.unseenIdleByWorkspace;
|
||||
const ownership = { ...state.sessionOwnership };
|
||||
const tombstones = { ...state.tombstonedSessions };
|
||||
const lastSettledAtBySession = { ...state.lastSettledAtBySession };
|
||||
const sessions = state.sessions.filter((session) => !removedIds.has(session.sessionId));
|
||||
for (const sessionId of removedIds) {
|
||||
const session = state.sessions.find((item) => item.sessionId === sessionId);
|
||||
const owner = session
|
||||
? { workspaceId: session.workspaceId, taskId: session.taskId }
|
||||
: ownership[sessionId];
|
||||
if (!owner) continue;
|
||||
markers = clearMarker(markers, owner.workspaceId, sessionId);
|
||||
delete ownership[sessionId];
|
||||
delete lastSettledAtBySession[sessionId];
|
||||
if (tombstone && !isQuickChatSetupSessionId(sessionId)) {
|
||||
tombstones[sessionId] = {
|
||||
workspaceId: owner.workspaceId,
|
||||
tombstonedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
const next = withValidActiveSession(
|
||||
{
|
||||
...state,
|
||||
unseenIdleByWorkspace: markers,
|
||||
lastSettledAtBySession,
|
||||
sessionOwnership: ownership,
|
||||
tombstonedSessions: pruneTombstones(tombstones),
|
||||
},
|
||||
sessions,
|
||||
);
|
||||
return { ...next, lastSettledAtBySession: pruneStaleSettledLedger(next.lastSettledAtBySession) };
|
||||
}
|
||||
|
||||
/** Reconciles one workspace's quick-chat tabs against the server's authoritative list. */
|
||||
export function reconcileQuickChatSessions(
|
||||
state: QuickChatState,
|
||||
workspaceId: string,
|
||||
serverSessions: QuickChatSession[],
|
||||
): QuickChatState {
|
||||
const otherWorkspaces = state.sessions.filter((session) => session.workspaceId !== workspaceId);
|
||||
const localSetupTabs = state.sessions.filter(
|
||||
const named = applyStoredQuickChatNames(serverSessions);
|
||||
const serverIds = new Set(named.map((session) => session.sessionId));
|
||||
const knownIds = new Set([
|
||||
...state.sessions
|
||||
.filter((session) => session.workspaceId === workspaceId)
|
||||
.map((session) => session.sessionId),
|
||||
...Object.entries(state.sessionOwnership)
|
||||
.filter(([, owner]) => owner.workspaceId === workspaceId)
|
||||
.map(([sessionId]) => sessionId),
|
||||
]);
|
||||
const omittedIds = new Set(
|
||||
[...knownIds].filter(
|
||||
(sessionId) => !serverIds.has(sessionId) && !isQuickChatSetupSessionId(sessionId),
|
||||
),
|
||||
);
|
||||
const clearedTombstones = Object.fromEntries(
|
||||
Object.entries(state.tombstonedSessions).filter(
|
||||
([sessionId, tombstone]) =>
|
||||
tombstone.workspaceId !== workspaceId || !serverIds.has(sessionId),
|
||||
),
|
||||
);
|
||||
const withoutOmitted = withLifecyclePruning(
|
||||
{ ...state, tombstonedSessions: clearedTombstones },
|
||||
omittedIds,
|
||||
true,
|
||||
);
|
||||
const otherWorkspaces = withoutOmitted.sessions.filter(
|
||||
(session) => session.workspaceId !== workspaceId,
|
||||
);
|
||||
const setupTabs = withoutOmitted.sessions.filter(
|
||||
(session) =>
|
||||
session.workspaceId === workspaceId && isQuickChatSetupSessionId(session.sessionId),
|
||||
);
|
||||
const named = applyStoredQuickChatNames(serverSessions);
|
||||
const serverById = new Map(named.map((session) => [session.sessionId, session]));
|
||||
|
||||
// Tabs still on the server, in the order this client already shows them.
|
||||
const survivors = state.sessions
|
||||
.filter(
|
||||
(session) => session.workspaceId === workspaceId && serverById.has(session.sessionId),
|
||||
// Client-only fields (e.g. an unsent draft) survive via the spread below.
|
||||
)
|
||||
const survivors = withoutOmitted.sessions
|
||||
.filter((session) => session.workspaceId === workspaceId && serverById.has(session.sessionId))
|
||||
.map((session) => ({ ...session, ...serverById.get(session.sessionId) }));
|
||||
const survivorIds = new Set(survivors.map((session) => session.sessionId));
|
||||
const added = named.filter((session) => !survivorIds.has(session.sessionId));
|
||||
|
||||
return withValidActiveSession(state, [
|
||||
const sessions = [
|
||||
...otherWorkspaces,
|
||||
...survivors,
|
||||
...added,
|
||||
...localSetupTabs,
|
||||
]);
|
||||
...named.filter((session) => !survivorIds.has(session.sessionId)),
|
||||
...setupTabs,
|
||||
];
|
||||
const next = withValidActiveSession(withoutOmitted, sessions);
|
||||
return withRevision(
|
||||
{ ...next, sessionOwnership: indexSessionOwnership(next.sessionOwnership, sessions) },
|
||||
workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconciles one workspace's server-owned terminal descriptors. A local tab
|
||||
* that is still creating its descriptor is retained briefly so a socket
|
||||
* reconnect cannot erase it before the POST response lands; every established
|
||||
* descriptor follows the server list, including deletions from another client.
|
||||
*/
|
||||
/** Merges boot hydration without removing tabs or overwriting newer local fields. */
|
||||
export function mergeHydratedQuickChatSessions(
|
||||
state: QuickChatState,
|
||||
sessions: QuickChatSession[],
|
||||
): QuickChatState {
|
||||
const tombstonedSessions = pruneTombstones(state.tombstonedSessions);
|
||||
const hydrated = applyStoredQuickChatNames(sessions).filter(
|
||||
(session) => !tombstonedSessions[session.sessionId],
|
||||
);
|
||||
const existingIds = new Set(state.sessions.map((session) => session.sessionId));
|
||||
const added = hydrated.filter((session) => !existingIds.has(session.sessionId));
|
||||
return {
|
||||
...state,
|
||||
sessions: [...state.sessions, ...added],
|
||||
sessionOwnership: indexSessionOwnership(state.sessionOwnership, added),
|
||||
tombstonedSessions,
|
||||
};
|
||||
}
|
||||
|
||||
/** Adds or updates a tab observed on the wire without stealing focus. */
|
||||
export function upsertQuickChatSession(
|
||||
state: QuickChatState,
|
||||
session: QuickChatSession,
|
||||
): QuickChatState {
|
||||
if (state.tombstonedSessions[session.sessionId]) {
|
||||
// A tombstone expires after its retention window even when no later
|
||||
// removal or reconciliation prunes it; otherwise the rejection below
|
||||
// would discard this session forever.
|
||||
const tombstones = pruneTombstones(state.tombstonedSessions);
|
||||
if (tombstones[session.sessionId]) return state;
|
||||
state = { ...state, tombstonedSessions: tombstones };
|
||||
}
|
||||
const [named] = applyStoredQuickChatNames([session]);
|
||||
const index = state.sessions.findIndex((item) => item.sessionId === named.sessionId);
|
||||
const sessions =
|
||||
index === -1
|
||||
? [...state.sessions, named]
|
||||
: state.sessions.map((item, itemIndex) =>
|
||||
itemIndex === index ? { ...item, ...named } : item,
|
||||
);
|
||||
return withRevision(
|
||||
{
|
||||
...state,
|
||||
sessions,
|
||||
sessionOwnership: indexSessionOwnership(state.sessionOwnership, [named]),
|
||||
},
|
||||
named.workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
/** Drops every known quick-chat session backed by a deleted task. */
|
||||
export function removeQuickChatSessionsForTask(
|
||||
state: QuickChatState,
|
||||
taskId: string,
|
||||
): QuickChatState {
|
||||
const removedIds = new Set(
|
||||
Object.entries(state.sessionOwnership)
|
||||
.filter(([, owner]) => owner.taskId === taskId)
|
||||
.map(([sessionId]) => sessionId),
|
||||
);
|
||||
for (const session of state.sessions)
|
||||
if (session.taskId === taskId) removedIds.add(session.sessionId);
|
||||
const next = withLifecyclePruning(state, removedIds, true);
|
||||
const workspaceIds = new Set(
|
||||
[...removedIds].map(
|
||||
(sessionId) =>
|
||||
state.sessionOwnership[sessionId]?.workspaceId ??
|
||||
state.sessions.find((session) => session.sessionId === sessionId)?.workspaceId,
|
||||
),
|
||||
);
|
||||
return [...workspaceIds]
|
||||
.filter((workspaceId): workspaceId is string => Boolean(workspaceId))
|
||||
.reduce(withRevision, next);
|
||||
}
|
||||
|
||||
/** Removes one server-backed quick-chat session and blocks late lifecycle events. */
|
||||
export function removeQuickChatSession(state: QuickChatState, sessionId: string): QuickChatState {
|
||||
const session = state.sessions.find((item) => item.sessionId === sessionId);
|
||||
const owner = session
|
||||
? { workspaceId: session.workspaceId, taskId: session.taskId }
|
||||
: state.sessionOwnership[sessionId];
|
||||
if (!owner) return state;
|
||||
return withRevision(withLifecyclePruning(state, new Set([sessionId]), true), owner.workspaceId);
|
||||
}
|
||||
|
||||
/** Closes a local quick-chat tab without creating a server-event tombstone. */
|
||||
export function closeQuickChatSession(state: QuickChatState, sessionId: string): QuickChatState {
|
||||
return withLifecyclePruning(state, new Set([sessionId]), false);
|
||||
}
|
||||
|
||||
/** Reconciles one workspace's server-owned terminal descriptors. */
|
||||
export function reconcileQuickTerminalTabs(
|
||||
state: QuickChatState,
|
||||
workspaceId: string,
|
||||
@@ -89,85 +280,49 @@ export function reconcileQuickTerminalTabs(
|
||||
tab.status === "connecting" &&
|
||||
!tab.sessionId,
|
||||
);
|
||||
|
||||
const nextTabs = [
|
||||
...otherWorkspaces,
|
||||
...[...serverTabs].sort((a, b) => a.sequence - b.sequence),
|
||||
...pendingLocal,
|
||||
];
|
||||
const validIds = new Set(nextTabs.map((tab) => tab.tabId));
|
||||
const lastTerminalTabIdByWorkspace = { ...state.lastTerminalTabIdByWorkspace };
|
||||
for (const [workspace, tabId] of Object.entries(lastTerminalTabIdByWorkspace)) {
|
||||
if (!validIds.has(tabId)) delete lastTerminalTabIdByWorkspace[workspace];
|
||||
}
|
||||
|
||||
const next: QuickChatState = {
|
||||
...state,
|
||||
terminalTabs: nextTabs,
|
||||
lastTerminalTabIdByWorkspace,
|
||||
};
|
||||
const lastTerminalTabIdByWorkspace = Object.fromEntries(
|
||||
Object.entries(state.lastTerminalTabIdByWorkspace).filter(([, tabId]) => validIds.has(tabId)),
|
||||
);
|
||||
const next = { ...state, terminalTabs: nextTabs, lastTerminalTabIdByWorkspace };
|
||||
if (next.activeKind !== "terminal") return next;
|
||||
|
||||
const active = nextTabs.find((tab) => tab.tabId === next.activeTerminalTabId);
|
||||
if (active) {
|
||||
next.lastTerminalTabIdByWorkspace[active.workspaceId] = active.tabId;
|
||||
return next;
|
||||
}
|
||||
|
||||
const previousWorkspaceId =
|
||||
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId ??
|
||||
workspaceId;
|
||||
if (active)
|
||||
return {
|
||||
...next,
|
||||
lastTerminalTabIdByWorkspace: {
|
||||
...lastTerminalTabIdByWorkspace,
|
||||
[active.workspaceId]: active.tabId,
|
||||
},
|
||||
};
|
||||
const replacement = nextTabs
|
||||
.filter((tab) => tab.workspaceId === previousWorkspaceId)
|
||||
.filter((tab) => tab.workspaceId === workspaceId)
|
||||
.sort((a, b) => a.sequence - b.sequence)[0];
|
||||
if (replacement) {
|
||||
next.activeTerminalTabId = replacement.tabId;
|
||||
next.lastTerminalTabIdByWorkspace[replacement.workspaceId] = replacement.tabId;
|
||||
return next;
|
||||
}
|
||||
|
||||
const conversation = next.sessions.find((session) => session.workspaceId === previousWorkspaceId);
|
||||
next.activeKind = "conversation";
|
||||
next.activeTerminalTabId = null;
|
||||
next.activeSessionId = conversation?.sessionId ?? null;
|
||||
next.isOpen = conversation ? next.isOpen : false;
|
||||
return next;
|
||||
if (replacement)
|
||||
return {
|
||||
...next,
|
||||
activeTerminalTabId: replacement.tabId,
|
||||
lastTerminalTabIdByWorkspace: {
|
||||
...lastTerminalTabIdByWorkspace,
|
||||
[replacement.workspaceId]: replacement.tabId,
|
||||
},
|
||||
};
|
||||
const conversation = next.sessions.find((session) => session.workspaceId === workspaceId);
|
||||
return {
|
||||
...next,
|
||||
activeKind: "conversation",
|
||||
activeTerminalTabId: null,
|
||||
activeSessionId: conversation?.sessionId ?? null,
|
||||
isOpen: conversation ? next.isOpen : false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds or updates a single quick-chat tab observed on the wire.
|
||||
*
|
||||
* Passive by design: it never changes which tab is active or opens the modal,
|
||||
* because the event describes something the user did on another device.
|
||||
*/
|
||||
export function upsertQuickChatSession(
|
||||
state: QuickChatState,
|
||||
session: QuickChatSession,
|
||||
): QuickChatState {
|
||||
const [named] = applyStoredQuickChatNames([session]);
|
||||
const index = state.sessions.findIndex((item) => item.sessionId === named.sessionId);
|
||||
if (index === -1) {
|
||||
return { ...state, sessions: [...state.sessions, named] };
|
||||
}
|
||||
const sessions = [...state.sessions];
|
||||
sessions[index] = { ...sessions[index], ...named };
|
||||
return { ...state, sessions };
|
||||
}
|
||||
|
||||
/** Drops the tabs backed by a task that no longer exists. */
|
||||
export function removeQuickChatSessionsForTask(
|
||||
state: QuickChatState,
|
||||
taskId: string,
|
||||
): QuickChatState {
|
||||
const remaining = state.sessions.filter((session) => session.taskId !== taskId);
|
||||
if (remaining.length === state.sessions.length) return state;
|
||||
return withValidActiveSession(state, remaining);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-points `activeSessionId` when the tab it named is gone, mirroring what a
|
||||
* local tab close does: fall back to another tab in the same workspace, and
|
||||
* close the modal only when nothing is left to show.
|
||||
*/
|
||||
function preserveTerminalSelection(
|
||||
state: QuickChatState,
|
||||
sessions: QuickChatSession[],
|
||||
@@ -175,18 +330,15 @@ function preserveTerminalSelection(
|
||||
if (state.activeKind !== "terminal") return null;
|
||||
const active = state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId);
|
||||
if (active) return { ...state, sessions };
|
||||
|
||||
const previousWorkspaceId =
|
||||
Object.entries(state.lastTerminalTabIdByWorkspace).find(
|
||||
([, tabId]) => tabId === state.activeTerminalTabId,
|
||||
)?.[0] ??
|
||||
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId;
|
||||
const workspaceId = Object.entries(state.lastTerminalTabIdByWorkspace).find(
|
||||
([, tabId]) => tabId === state.activeTerminalTabId,
|
||||
)?.[0];
|
||||
const terminal = state.terminalTabs.find(
|
||||
(tab) => !previousWorkspaceId || tab.workspaceId === previousWorkspaceId,
|
||||
(tab) => !workspaceId || tab.workspaceId === workspaceId,
|
||||
);
|
||||
if (!terminal) {
|
||||
const conversation =
|
||||
sessions.find((session) => session.workspaceId === previousWorkspaceId) ??
|
||||
sessions.find((session) => session.workspaceId === workspaceId) ??
|
||||
sessions.find((session) => session.sessionId === state.activeSessionId) ??
|
||||
sessions[0];
|
||||
return {
|
||||
@@ -215,30 +367,23 @@ function withValidActiveSession(
|
||||
): QuickChatState {
|
||||
const terminalSelection = preserveTerminalSelection(state, sessions);
|
||||
if (terminalSelection) return terminalSelection;
|
||||
const active = state.activeSessionId;
|
||||
// No tab was ever selected: leave it unset rather than silently promoting one
|
||||
// on a background resync. Same invariant `hydrateUI` guards on.
|
||||
if (!active) return { ...state, sessions };
|
||||
if (sessions.some((session) => session.sessionId === active)) {
|
||||
if (
|
||||
!state.activeSessionId ||
|
||||
sessions.some((session) => session.sessionId === state.activeSessionId)
|
||||
)
|
||||
return { ...state, sessions };
|
||||
}
|
||||
const previousWorkspaceId =
|
||||
state.sessions.find((session) => session.sessionId === active)?.workspaceId ??
|
||||
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId;
|
||||
const fallback =
|
||||
sessions.find((session) => session.workspaceId === previousWorkspaceId) ?? sessions[0];
|
||||
const terminalFallback = state.terminalTabs.find(
|
||||
(tab) => tab.workspaceId === previousWorkspaceId,
|
||||
);
|
||||
if (!fallback && terminalFallback) {
|
||||
const workspaceId = state.sessions.find(
|
||||
(session) => session.sessionId === state.activeSessionId,
|
||||
)?.workspaceId;
|
||||
const fallback = sessions.find((session) => session.workspaceId === workspaceId);
|
||||
const terminalFallback = state.terminalTabs.find((tab) => tab.workspaceId === workspaceId);
|
||||
if (!fallback && terminalFallback)
|
||||
return {
|
||||
...state,
|
||||
sessions,
|
||||
activeKind: "terminal",
|
||||
activeTerminalTabId: terminalFallback.tabId,
|
||||
isOpen: state.isOpen,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
sessions,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
|
||||
const EMPTY_UNSEEN_IDLE: Record<string, true> = {};
|
||||
|
||||
/** Reports whether the requested workspace has any unseen quick-chat idle markers. */
|
||||
export function selectQuickChatHasUnseenIdle(
|
||||
state: AppState,
|
||||
workspaceId: string | null | undefined,
|
||||
): boolean {
|
||||
if (!workspaceId) return false;
|
||||
return (
|
||||
Object.keys(state.quickChat?.unseenIdleByWorkspace?.[workspaceId] ?? EMPTY_UNSEEN_IDLE).length >
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { StoreApi } from "zustand";
|
||||
import { maybeMarkQuickChatUnseenIdle } from "@/lib/ws/handlers/quick-chat-unseen";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import { createAppStore } from "@/lib/state/store";
|
||||
import { selectQuickChatHasUnseenIdle } from "./quick-chat-unseen-selectors";
|
||||
type QuickChatWithUnseenMarkers = {
|
||||
unseenIdleByWorkspace: Record<string, Record<string, true>>;
|
||||
};
|
||||
const SESSION_ID = "session-1";
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
const SETTLED_AT = "2099-01-01T00:00:00Z";
|
||||
const OTHER_SESSION_ID = "session-2";
|
||||
const OTHER_WORKSPACE_ID = "workspace-2";
|
||||
|
||||
describe("quick chat unseen idle markers", () => {
|
||||
it("clears all markers when opening quick chat", () => {
|
||||
const store = createAppStore();
|
||||
store.setState({
|
||||
quickChat: {
|
||||
...store.getState().quickChat,
|
||||
unseenIdleByWorkspace: { [WORKSPACE_ID]: { [SESSION_ID]: true } },
|
||||
} as never,
|
||||
});
|
||||
|
||||
store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
|
||||
expect(
|
||||
(store.getState().quickChat as unknown as QuickChatWithUnseenMarkers).unseenIdleByWorkspace,
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("scopes markers to their workspace and clears an individual session", () => {
|
||||
const store = createAppStore();
|
||||
|
||||
store.getState().markQuickChatUnseenIdle("session-a", "workspace-a");
|
||||
store.getState().markQuickChatUnseenIdle("session-b", "workspace-b");
|
||||
store.getState().clearQuickChatUnseenIdle("session-a", "workspace-a");
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), "workspace-a")).toBe(false);
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), "workspace-b")).toBe(true);
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function settle(store: StoreApi<AppState>, sessionId: string, updatedAt: string) {
|
||||
maybeMarkQuickChatUnseenIdle(store, sessionId, {
|
||||
previousState: "RUNNING",
|
||||
fallbackPreviousState: undefined,
|
||||
newState: "IDLE",
|
||||
updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
describe("quick chat unseen idle WebSocket scheduling", () => {
|
||||
it("marks a closed quick chat after an active-to-settled transition", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(true);
|
||||
});
|
||||
|
||||
it("suppresses a completion observed while quick chat is open", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
store.getState().closeQuickChat();
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("suppresses a completion outside the visible quick-chat dialog workspace", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().addQuickChatSession(OTHER_SESSION_ID, OTHER_WORKSPACE_ID);
|
||||
|
||||
settle(store, OTHER_SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), OTHER_WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not re-mark after a cleared duplicate completion", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
store.getState().clearQuickChatUnseenIdle(SESSION_ID, WORKSPACE_ID);
|
||||
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not re-mark the state_changed echo of a turn completion the user viewed", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
// The turn.completed path records completed_at into the settled ledger.
|
||||
store.getState().recordQuickChatSettled(SESSION_ID, "2099-01-01T00:00:00Z");
|
||||
store.getState().markQuickChatUnseenIdle(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().closeQuickChat();
|
||||
// The corresponding state_changed arrives moments later with a newer
|
||||
// session updated_at; it is the same logical completion.
|
||||
settle(store, SESSION_ID, "2099-01-01T00:00:01Z");
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("marks a genuinely new settle that lands outside the echo grace window", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().recordQuickChatSettled(SESSION_ID, "2099-01-01T00:00:00Z");
|
||||
store.getState().markQuickChatUnseenIdle(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().closeQuickChat();
|
||||
|
||||
settle(store, SESSION_ID, "2099-01-01T00:10:00Z");
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not mark a completion received before its tab is known", () => {
|
||||
const store = createAppStore();
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not mark a late completion for a removed quick chat", () => {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().removeQuickChatSession(SESSION_ID);
|
||||
|
||||
settle(store, SESSION_ID, SETTLED_AT);
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -137,6 +137,16 @@ export type QuickChatSession = {
|
||||
|
||||
export type QuickChatActiveKind = "conversation" | "terminal";
|
||||
|
||||
export type QuickChatSessionOwnership = {
|
||||
taskId?: string;
|
||||
workspaceId: string;
|
||||
};
|
||||
|
||||
export type QuickChatSessionTombstone = {
|
||||
workspaceId: string;
|
||||
tombstonedAt: string;
|
||||
};
|
||||
|
||||
export type QuickChatState = {
|
||||
isOpen: boolean;
|
||||
sessions: QuickChatSession[];
|
||||
@@ -145,6 +155,11 @@ export type QuickChatState = {
|
||||
activeKind: QuickChatActiveKind;
|
||||
activeTerminalTabId: string | null;
|
||||
lastTerminalTabIdByWorkspace: Record<string, string>;
|
||||
unseenIdleByWorkspace: Record<string, Record<string, true>>;
|
||||
lastSettledAtBySession: Record<string, string>;
|
||||
sessionOwnership: Record<string, QuickChatSessionOwnership>;
|
||||
syncRevisionByWorkspace: Record<string, number>;
|
||||
tombstonedSessions: Record<string, QuickChatSessionTombstone>;
|
||||
};
|
||||
|
||||
export type SessionFailureNotification = {
|
||||
@@ -335,6 +350,12 @@ export type UISliceActions = {
|
||||
upsertQuickChatSessionFromEvent: (session: QuickChatSession) => void;
|
||||
/** Drops tabs whose backing task was deleted (possibly on another device). */
|
||||
removeQuickChatSessionsForTask: (taskId: string) => void;
|
||||
markQuickChatUnseenIdle: (sessionId: string, workspaceId: string) => void;
|
||||
clearQuickChatUnseenIdle: (sessionId?: string, workspaceId?: string) => void;
|
||||
/** Records a settle generation and returns whether it was not previously observed. */
|
||||
recordQuickChatSettled: (sessionId: string, updatedAt: string) => boolean;
|
||||
/** Removes a server-backed quick-chat session and suppresses late task events. */
|
||||
removeQuickChatSession: (sessionId: string) => void;
|
||||
setQuickChatInitialPrompt: (sessionId: string, prompt?: string) => void;
|
||||
setSessionFailureNotification: (n: SessionFailureNotification | null) => void;
|
||||
setTaskDeletedNotification: (n: TaskDeletedNotification | null) => void;
|
||||
|
||||
@@ -20,19 +20,9 @@ import { buildSidebarViewActions } from "./sidebar-view-actions";
|
||||
import { DEFAULT_VIEW } from "./sidebar-view-builtins";
|
||||
import type { SidebarView, SidebarViewDraft, SortSpec } from "./sidebar-view-types";
|
||||
import type { SystemHealthResponse } from "@/lib/types/health";
|
||||
import type { ActiveDocument, QuickChatSession, UISlice, UISliceState } from "./types";
|
||||
import { getQuickChatSetupSessionId } from "./quick-chat-session";
|
||||
import {
|
||||
reconcileQuickChatSessions,
|
||||
reconcileQuickTerminalTabs,
|
||||
removeQuickChatSessionsForTask,
|
||||
upsertQuickChatSession,
|
||||
} from "./quick-chat-sync";
|
||||
import {
|
||||
activateConversationDraft,
|
||||
activateWorkspaceFallback,
|
||||
buildQuickTerminalActions,
|
||||
} from "./quick-terminal-actions";
|
||||
import type { ActiveDocument, UISlice, UISliceState } from "./types";
|
||||
import { buildQuickChatActions } from "./quick-chat-actions";
|
||||
import { buildQuickTerminalActions } from "./quick-terminal-actions";
|
||||
|
||||
/** Default sidebar view state: the single built-in "All tasks" view, active, no draft. */
|
||||
function createDefaultSidebarState(): UISliceState["sidebarViews"] {
|
||||
@@ -128,6 +118,11 @@ export const defaultUIState: UISliceState = {
|
||||
activeKind: "conversation",
|
||||
activeTerminalTabId: null,
|
||||
lastTerminalTabIdByWorkspace: {},
|
||||
unseenIdleByWorkspace: {},
|
||||
lastSettledAtBySession: {},
|
||||
sessionOwnership: {},
|
||||
syncRevisionByWorkspace: {},
|
||||
tombstonedSessions: {},
|
||||
},
|
||||
sessionFailureNotification: null,
|
||||
taskDeletedNotification: null,
|
||||
@@ -333,165 +328,6 @@ function buildNotificationActions(set: ImmerSet) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Finds this workspace's quick-chat "config" session, if one is already open. */
|
||||
function findWorkspaceConfigSession(
|
||||
sessions: UISliceState["quickChat"]["sessions"],
|
||||
workspaceId: string,
|
||||
) {
|
||||
return sessions.find(
|
||||
(session) => session.workspaceId === workspaceId && session.kind === "config",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the `openQuickChat` action: opens (creating if needed) a quick-chat
|
||||
* session, reusing an existing workspace config session for `kind: "config"`
|
||||
* rather than creating a duplicate.
|
||||
*/
|
||||
function buildOpenQuickChatAction(set: ImmerSet) {
|
||||
return (
|
||||
sessionId: string,
|
||||
workspaceId: string,
|
||||
agentProfileId?: string,
|
||||
kind: "chat" | "config" = "chat",
|
||||
taskId?: string,
|
||||
) =>
|
||||
set((draft) => {
|
||||
if (!sessionId) {
|
||||
const existingConfigSession =
|
||||
kind === "config"
|
||||
? findWorkspaceConfigSession(draft.quickChat.sessions, workspaceId)
|
||||
: undefined;
|
||||
if (existingConfigSession) {
|
||||
draft.quickChat.isOpen = true;
|
||||
draft.quickChat.activeSessionId = existingConfigSession.sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
return;
|
||||
}
|
||||
const setupSessionId = getQuickChatSetupSessionId(workspaceId, kind);
|
||||
if (!draft.quickChat.sessions.some((session) => session.sessionId === setupSessionId)) {
|
||||
draft.quickChat.sessions.push({ sessionId: setupSessionId, workspaceId, kind });
|
||||
}
|
||||
draft.quickChat.isOpen = true;
|
||||
draft.quickChat.activeSessionId = setupSessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
return;
|
||||
}
|
||||
const existing = draft.quickChat.sessions.find((session) => session.sessionId === sessionId);
|
||||
if (existing) {
|
||||
if (existing.workspaceId !== workspaceId) return;
|
||||
if (agentProfileId) existing.agentProfileId = agentProfileId;
|
||||
if (taskId) existing.taskId = taskId;
|
||||
} else {
|
||||
draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId });
|
||||
}
|
||||
draft.quickChat.isOpen = true;
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
});
|
||||
}
|
||||
|
||||
/** Builds the remaining quick-chat session CRUD actions (add/remove/rename/close). */
|
||||
function buildQuickChatActions(set: ImmerSet) {
|
||||
return {
|
||||
addQuickChatSession: (
|
||||
sessionId: string,
|
||||
workspaceId: string,
|
||||
agentProfileId?: string,
|
||||
kind: "chat" | "config" = "chat",
|
||||
taskId?: string,
|
||||
) =>
|
||||
set((draft) => {
|
||||
const activeWorkspaceId = draft.quickChat.sessions.find(
|
||||
(session) => session.sessionId === draft.quickChat.activeSessionId,
|
||||
)?.workspaceId;
|
||||
const shouldActivate =
|
||||
!draft.quickChat.isOpen || !activeWorkspaceId || activeWorkspaceId === workspaceId;
|
||||
const existing = draft.quickChat.sessions.find(
|
||||
(session) => session.sessionId === sessionId,
|
||||
);
|
||||
if (existing) {
|
||||
if (existing.workspaceId !== workspaceId) return;
|
||||
if (agentProfileId) existing.agentProfileId = agentProfileId;
|
||||
if (taskId) existing.taskId = taskId;
|
||||
} else {
|
||||
draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId });
|
||||
}
|
||||
if (shouldActivate) {
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
}
|
||||
}),
|
||||
openQuickChat: buildOpenQuickChatAction(set),
|
||||
closeQuickChat: () =>
|
||||
set((draft) => {
|
||||
draft.quickChat.isOpen = false;
|
||||
}),
|
||||
closeQuickChatSession: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
const closingSession = draft.quickChat.sessions.find(
|
||||
(session) => session.sessionId === sessionId,
|
||||
);
|
||||
draft.quickChat.sessions = draft.quickChat.sessions.filter(
|
||||
(session) => session.sessionId !== sessionId,
|
||||
);
|
||||
if (
|
||||
draft.quickChat.activeKind !== "conversation" ||
|
||||
draft.quickChat.activeSessionId !== sessionId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const nextSession = draft.quickChat.sessions.find(
|
||||
(session) => session.workspaceId === closingSession?.workspaceId,
|
||||
);
|
||||
if (nextSession) {
|
||||
activateConversationDraft(
|
||||
draft.quickChat,
|
||||
nextSession.sessionId,
|
||||
nextSession.workspaceId,
|
||||
);
|
||||
} else {
|
||||
activateWorkspaceFallback(draft.quickChat, closingSession?.workspaceId);
|
||||
}
|
||||
}),
|
||||
setActiveQuickChatSession: (sessionId: string, workspaceId: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (!session || session.workspaceId !== workspaceId) return;
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
draft.quickChat.activeKind = "conversation";
|
||||
}),
|
||||
// Optimistic only. Persisting the name is `persistQuickChatRename`'s job,
|
||||
// so the backing task title stays the shared source of truth.
|
||||
renameQuickChatSession: (sessionId: string, name: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (session) session.name = name;
|
||||
}),
|
||||
syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions);
|
||||
}),
|
||||
syncQuickTerminalTabs: (workspaceId: string, tabs: UISliceState["quickChat"]["terminalTabs"]) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = reconcileQuickTerminalTabs(draft.quickChat, workspaceId, tabs);
|
||||
}),
|
||||
upsertQuickChatSessionFromEvent: (session: QuickChatSession) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = upsertQuickChatSession(draft.quickChat, session);
|
||||
}),
|
||||
removeQuickChatSessionsForTask: (taskId: string) =>
|
||||
set((draft) => {
|
||||
draft.quickChat = removeQuickChatSessionsForTask(draft.quickChat, taskId);
|
||||
}),
|
||||
setQuickChatInitialPrompt: (sessionId: string, prompt?: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (session) session.initialPrompt = prompt;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], [], UISlice> = (
|
||||
set,
|
||||
get,
|
||||
|
||||
@@ -360,6 +360,10 @@ export type AppState = KanbanSlice & {
|
||||
syncQuickTerminalTabs: UIA["syncQuickTerminalTabs"];
|
||||
upsertQuickChatSessionFromEvent: UIA["upsertQuickChatSessionFromEvent"];
|
||||
removeQuickChatSessionsForTask: UIA["removeQuickChatSessionsForTask"];
|
||||
markQuickChatUnseenIdle: UIA["markQuickChatUnseenIdle"];
|
||||
clearQuickChatUnseenIdle: UIA["clearQuickChatUnseenIdle"];
|
||||
recordQuickChatSettled: UIA["recordQuickChatSettled"];
|
||||
removeQuickChatSession: UIA["removeQuickChatSession"];
|
||||
closeQuickChat: () => void;
|
||||
closeQuickChatSession: (sessionId: string) => void;
|
||||
setActiveQuickChatSession: (sessionId: string, workspaceId: string) => void;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createAppStore } from "@/lib/state/store";
|
||||
import { selectQuickChatHasUnseenIdle } from "@/lib/state/slices/ui/quick-chat-unseen-selectors";
|
||||
import type { TaskSession } from "@/lib/types/http";
|
||||
import type { TaskSessionStateChangedPayload } from "@/lib/types/backend";
|
||||
import { registerTaskSessionHandlers } from "./agent-session";
|
||||
|
||||
const SESSION_ID = "session-1";
|
||||
const TASK_ID = "task-1";
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
const RUNNING_AT = "2099-01-01T00:00:00Z";
|
||||
const SETTLED_AT = "2099-01-01T00:01:00Z";
|
||||
|
||||
const ACTIVE_STATES = ["STARTING", "RUNNING"] as const;
|
||||
const SETTLED_STATES = ["IDLE", "WAITING_FOR_INPUT", "COMPLETED", "FAILED", "CANCELLED"] as const;
|
||||
function taskSession(state: TaskSession["state"], updatedAt: string): TaskSession {
|
||||
// The WebSocket handler only requires the stable state-transition fields.
|
||||
return {
|
||||
id: SESSION_ID,
|
||||
task_id: TASK_ID,
|
||||
state,
|
||||
updated_at: updatedAt,
|
||||
} as unknown as TaskSession;
|
||||
}
|
||||
|
||||
function stateChange(
|
||||
newState: TaskSession["state"],
|
||||
updatedAt: string | undefined,
|
||||
): TaskSessionStateChangedPayload {
|
||||
return {
|
||||
task_id: TASK_ID,
|
||||
session_id: SESSION_ID,
|
||||
new_state: newState,
|
||||
updated_at: updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function handleStateChange(
|
||||
store: ReturnType<typeof createAppStore>,
|
||||
payload: TaskSessionStateChangedPayload,
|
||||
): void {
|
||||
registerTaskSessionHandlers(store)["session.state_changed"]!({
|
||||
id: "event-1",
|
||||
type: "notification",
|
||||
action: "session.state_changed",
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
function storeWithQuickChat(state: TaskSession["state"] = "RUNNING") {
|
||||
const store = createAppStore();
|
||||
store.getState().addQuickChatSession(SESSION_ID, WORKSPACE_ID);
|
||||
store.getState().setTaskSession(taskSession(state, RUNNING_AT));
|
||||
return store;
|
||||
}
|
||||
|
||||
describe("quick-chat session state-change handler", () => {
|
||||
for (const previousState of ACTIVE_STATES) {
|
||||
it.each(SETTLED_STATES)(
|
||||
`marks a closed ${previousState} quick chat when it settles to %s`,
|
||||
(newState) => {
|
||||
const store = storeWithQuickChat(previousState);
|
||||
|
||||
handleStateChange(store, stateChange(newState, SETTLED_AT));
|
||||
|
||||
expect(selectQuickChatHasUnseenIdle(store.getState(), WORKSPACE_ID)).toBe(true);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
it("does not mark reverse, dialog-open, replay, or timestamp-less transitions", () => {
|
||||
const reverse = storeWithQuickChat("IDLE");
|
||||
handleStateChange(reverse, stateChange("FAILED", SETTLED_AT));
|
||||
expect(selectQuickChatHasUnseenIdle(reverse.getState(), WORKSPACE_ID)).toBe(false);
|
||||
|
||||
const open = storeWithQuickChat();
|
||||
open.getState().openQuickChat(SESSION_ID, WORKSPACE_ID);
|
||||
handleStateChange(open, stateChange("IDLE", SETTLED_AT));
|
||||
open.getState().closeQuickChat();
|
||||
handleStateChange(open, stateChange("IDLE", SETTLED_AT));
|
||||
expect(selectQuickChatHasUnseenIdle(open.getState(), WORKSPACE_ID)).toBe(false);
|
||||
|
||||
const missingTimestamp = storeWithQuickChat();
|
||||
handleStateChange(missingTimestamp, stateChange("IDLE", undefined));
|
||||
expect(selectQuickChatHasUnseenIdle(missingTimestamp.getState(), WORKSPACE_ID)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,7 @@ const CANCELLATION_EVENT = "session.cancellation_changed";
|
||||
const RECOVERABLE_ERROR_MESSAGE = "peer disconnected before response";
|
||||
const RECOVERABLE_ERROR_AT = "2026-06-14T14:06:40Z";
|
||||
const TASK_ROOT = "/task-root";
|
||||
const IDLE_AT = "2026-08-17T07:00:00Z";
|
||||
|
||||
function makeMessage(payload: TaskSessionStateChangedPayload) {
|
||||
return {
|
||||
@@ -133,6 +134,7 @@ function assertRealStoreActivityRouting() {
|
||||
expect(deriveSessionInputMode(store.getState().taskSessions.items["s-2"])).toBe("direct");
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- state transition contracts use the shared store fixture.
|
||||
describe("session.state_changed handler", () => {
|
||||
let store: ReturnType<typeof makeStore>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -225,6 +227,61 @@ describe("session.state_changed handler", () => {
|
||||
|
||||
expect(store.getState().setSessionFailureNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks a closed quick chat from an active-to-settled event using old_state", () => {
|
||||
const markQuickChatUnseenIdle = vi.fn();
|
||||
const recordQuickChatSettled = vi.fn(() => true);
|
||||
store = makeStore({
|
||||
quickChat: {
|
||||
isOpen: false,
|
||||
activeSessionId: null,
|
||||
sessions: [{ sessionId: "s-1", workspaceId: "workspace-1" }],
|
||||
},
|
||||
markQuickChatUnseenIdle,
|
||||
recordQuickChatSettled,
|
||||
taskSessions: { items: {} },
|
||||
});
|
||||
handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!;
|
||||
|
||||
handler(
|
||||
makeMessage({
|
||||
task_id: "t-1",
|
||||
session_id: "s-1",
|
||||
old_state: "RUNNING",
|
||||
new_state: "IDLE",
|
||||
updated_at: IDLE_AT,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(recordQuickChatSettled).toHaveBeenCalledWith("s-1", IDLE_AT);
|
||||
expect(markQuickChatUnseenIdle).toHaveBeenCalledWith("s-1", "workspace-1");
|
||||
});
|
||||
|
||||
it("does not mark an active-to-settled event for a session outside quick chat", () => {
|
||||
const markQuickChatUnseenIdle = vi.fn();
|
||||
const recordQuickChatSettled = vi.fn(() => true);
|
||||
store = makeStore({
|
||||
quickChat: { isOpen: false, activeSessionId: null, sessions: [] },
|
||||
markQuickChatUnseenIdle,
|
||||
recordQuickChatSettled,
|
||||
taskSessions: {
|
||||
items: { "s-1": { id: "s-1", task_id: "t-1", state: "RUNNING" } },
|
||||
},
|
||||
});
|
||||
handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!;
|
||||
|
||||
handler(
|
||||
makeMessage({
|
||||
task_id: "t-1",
|
||||
session_id: "s-1",
|
||||
new_state: "IDLE",
|
||||
updated_at: IDLE_AT,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(recordQuickChatSettled).toHaveBeenCalledWith("s-1", IDLE_AT);
|
||||
expect(markQuickChatUnseenIdle).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("session.state_changed cancellation snapshot", () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable max-lines -- comprehensive session-state handler; merge with main pushed it past 600. */
|
||||
import type { StoreApi } from "zustand";
|
||||
import { createDebugLogger } from "@/lib/debug/log";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
@@ -14,6 +15,7 @@ import type { QueueStatusChangedPayload } from "@/lib/types/backend";
|
||||
import { syncKanbanPrimarySessionState } from "@/lib/ws/handlers/agent-session-kanban-sync";
|
||||
import { parseContextWindowEntry } from "@/lib/state/slices/session-runtime/context-window";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { maybeMarkQuickChatUnseenIdle } from "@/lib/ws/handlers/quick-chat-unseen";
|
||||
|
||||
const debug = createDebugLogger("session:state");
|
||||
|
||||
@@ -742,6 +744,12 @@ export function registerTaskSessionHandlers(store: StoreApi<AppState>): WsHandle
|
||||
newState: newState ?? "-",
|
||||
});
|
||||
|
||||
maybeMarkQuickChatUnseenIdle(store, sessionId, {
|
||||
previousState: existingSession?.state,
|
||||
fallbackPreviousState: payload.old_state as TaskSessionState | undefined,
|
||||
newState,
|
||||
updatedAt: payload.updated_at,
|
||||
});
|
||||
upsertTaskSessionList(store, taskId, sessionId, payload, sessionUpdate);
|
||||
syncKanbanPrimarySessionState(store, taskId, sessionId, newState);
|
||||
extractContextWindow(store, sessionId, payload);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { StoreApi } from "zustand";
|
||||
import type { TaskSessionState } from "@/lib/types/http";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
|
||||
const ACTIVE_STATES: ReadonlySet<TaskSessionState> = new Set(["STARTING", "RUNNING"]);
|
||||
const SETTLED_STATES: ReadonlySet<TaskSessionState> = new Set([
|
||||
"IDLE",
|
||||
"WAITING_FOR_INPUT",
|
||||
"COMPLETED",
|
||||
"FAILED",
|
||||
"CANCELLED",
|
||||
]);
|
||||
|
||||
/**
|
||||
* How long a `session.state_changed` settle may lag the `session.turn.completed`
|
||||
* for the same logical completion before it counts as new activity. The backend
|
||||
* emits the turn event first and the session-row update a few milliseconds
|
||||
* later, so the state_changed that follows a turn completion is its echo, not a
|
||||
* second completion — marking it again would re-arm a dot the user already
|
||||
* viewed. Genuine later completions land seconds or minutes afterwards and are
|
||||
* unaffected.
|
||||
*/
|
||||
const TURN_STATE_ECHO_GRACE_MS = 2000;
|
||||
|
||||
/** Whether the settle is the state_changed echo of the completion just recorded. */
|
||||
function isTurnCompletionEcho(lastSettledAt: string | undefined, updatedAt: string): boolean {
|
||||
if (!lastSettledAt) return false;
|
||||
const settleTime = Date.parse(updatedAt);
|
||||
const lastTime = Date.parse(lastSettledAt);
|
||||
if (!Number.isFinite(settleTime) || !Number.isFinite(lastTime)) return false;
|
||||
const delta = settleTime - lastTime;
|
||||
return delta >= 0 && delta <= TURN_STATE_ECHO_GRACE_MS;
|
||||
}
|
||||
|
||||
export function maybeMarkQuickChatUnseenIdle(
|
||||
store: StoreApi<AppState>,
|
||||
sessionId: string,
|
||||
transition: {
|
||||
previousState: TaskSessionState | undefined;
|
||||
fallbackPreviousState: TaskSessionState | undefined;
|
||||
newState: TaskSessionState | undefined;
|
||||
updatedAt: string | undefined;
|
||||
},
|
||||
): void {
|
||||
const { previousState, fallbackPreviousState, newState, updatedAt } = transition;
|
||||
const priorState = previousState ?? fallbackPreviousState;
|
||||
if (
|
||||
!priorState ||
|
||||
!newState ||
|
||||
!ACTIVE_STATES.has(priorState) ||
|
||||
!SETTLED_STATES.has(newState) ||
|
||||
!updatedAt
|
||||
)
|
||||
return;
|
||||
const quickChat = store.getState().quickChat;
|
||||
// The settle ledger is consulted before recording so a state_changed that
|
||||
// echoes a turn completion (recorded moments earlier with a slightly older
|
||||
// timestamp) is recognized as the same logical completion instead of new.
|
||||
if (isTurnCompletionEcho(quickChat.lastSettledAtBySession?.[sessionId], updatedAt)) return;
|
||||
if (!store.getState().recordQuickChatSettled(sessionId, updatedAt)) return;
|
||||
const session = quickChat.sessions.find((item) => item.sessionId === sessionId);
|
||||
if (session && !quickChat.isOpen)
|
||||
store.getState().markQuickChatUnseenIdle(sessionId, session.workspaceId);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi, type Mock } from "vitest";
|
||||
import { create } from "zustand";
|
||||
import { immer } from "zustand/middleware/immer";
|
||||
import { createSessionSlice } from "@/lib/state/slices/session/session-slice";
|
||||
@@ -13,13 +13,32 @@ const TURN_COMPLETED = "session.turn.completed";
|
||||
const NOTIFICATION = "notification";
|
||||
const TURN_STARTED_AT = "2026-07-23T10:00:00.000Z";
|
||||
const TURN_COMPLETED_AT = "2026-07-23T10:01:00.000Z";
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
|
||||
function makeStore() {
|
||||
return create<SessionSlice>()(
|
||||
type TurnTestState = SessionSlice & {
|
||||
quickChat: {
|
||||
isOpen: boolean;
|
||||
activeSessionId: string | null;
|
||||
sessions: Array<{ sessionId: string; workspaceId: string }>;
|
||||
};
|
||||
markQuickChatUnseenIdle: Mock;
|
||||
recordQuickChatSettled: (sessionId: string, updatedAt: string) => boolean;
|
||||
};
|
||||
|
||||
function makeStore(
|
||||
quickChat: TurnTestState["quickChat"] = { isOpen: false, activeSessionId: null, sessions: [] },
|
||||
) {
|
||||
const settledLedger: Record<string, string> = {};
|
||||
return create<TurnTestState>()(
|
||||
immer((set) => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...(createSessionSlice as any)(set),
|
||||
quickChat: { sessions: [] },
|
||||
...(createSessionSlice as unknown as (storeSet: typeof set) => SessionSlice)(set),
|
||||
quickChat,
|
||||
markQuickChatUnseenIdle: vi.fn(),
|
||||
recordQuickChatSettled: (sessionId: string, updatedAt: string) => {
|
||||
if (!updatedAt || settledLedger[sessionId] >= updatedAt) return false;
|
||||
settledLedger[sessionId] = updatedAt;
|
||||
return true;
|
||||
},
|
||||
availableCommands: { bySessionId: {} },
|
||||
prepareProgress: { bySessionId: {} },
|
||||
})),
|
||||
@@ -61,6 +80,7 @@ function settleViaUpsertTaskSessionFromEvent(store: ReturnType<typeof makeStore>
|
||||
store.getState().upsertTaskSessionFromEvent(TASK_ID, IDLE_SESSION);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- turn handler contract tests share the store fixture.
|
||||
describe("session turn WebSocket handlers", () => {
|
||||
it("keeps a completed turn inactive when its delayed started event arrives", () => {
|
||||
const store = makeStore();
|
||||
@@ -201,6 +221,65 @@ describe("session turn WebSocket handlers", () => {
|
||||
|
||||
expect(flush).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("marks a closed quick chat once and suppresses all dialog-open completions", () => {
|
||||
const quickChat = {
|
||||
isOpen: false,
|
||||
activeSessionId: null,
|
||||
sessions: [{ sessionId: SESSION_ID, workspaceId: WORKSPACE_ID }],
|
||||
};
|
||||
const store = makeStore(quickChat);
|
||||
|
||||
send(store, TURN_COMPLETED, turn("turn-1", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
send(store, TURN_COMPLETED, turn("turn-1", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
|
||||
expect(store.getState().markQuickChatUnseenIdle).toHaveBeenCalledTimes(1);
|
||||
expect(store.getState().markQuickChatUnseenIdle).toHaveBeenCalledWith(SESSION_ID, WORKSPACE_ID);
|
||||
|
||||
store.setState({
|
||||
quickChat: {
|
||||
...quickChat,
|
||||
isOpen: true,
|
||||
activeSessionId: "other-session",
|
||||
sessions: [
|
||||
...quickChat.sessions,
|
||||
{ sessionId: "other-session", workspaceId: WORKSPACE_ID },
|
||||
],
|
||||
},
|
||||
});
|
||||
send(store, TURN_COMPLETED, turn("turn-2", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
|
||||
expect(store.getState().markQuickChatUnseenIdle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not re-mark an older replay after the settled ledger recorded the completion", () => {
|
||||
const store = makeStore({
|
||||
isOpen: false,
|
||||
activeSessionId: null,
|
||||
sessions: [{ sessionId: SESSION_ID, workspaceId: WORKSPACE_ID }],
|
||||
});
|
||||
|
||||
send(store, TURN_COMPLETED, turn("turn-1", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
// A delayed replay of an older completion arrives with a fresh turn id.
|
||||
send(store, TURN_COMPLETED, turn("turn-2", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
|
||||
expect(store.getState().markQuickChatUnseenIdle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("suppresses a completion in another workspace while the dialog is open", () => {
|
||||
const store = makeStore({
|
||||
isOpen: true,
|
||||
activeSessionId: "session-a",
|
||||
sessions: [
|
||||
{ sessionId: "session-a", workspaceId: "workspace-a" },
|
||||
{ sessionId: SESSION_ID, workspaceId: "workspace-b" },
|
||||
],
|
||||
});
|
||||
|
||||
send(store, TURN_COMPLETED, turn("turn-1", TURN_STARTED_AT, TURN_COMPLETED_AT));
|
||||
|
||||
expect(store.getState().markQuickChatUnseenIdle).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("settled boundary WS guard", () => {
|
||||
|
||||
@@ -71,6 +71,11 @@ export function registerTurnsHandlers(
|
||||
if (!payload.session_id || !payload.id) {
|
||||
return;
|
||||
}
|
||||
const wasCompleted = store
|
||||
.getState()
|
||||
.turns.bySession[
|
||||
payload.session_id
|
||||
]?.some((turn) => turn.id === payload.id && Boolean(turn.completed_at));
|
||||
messageScheduler?.flush();
|
||||
debug("turn.completed", {
|
||||
sessionId: payload.session_id,
|
||||
@@ -97,6 +102,24 @@ export function registerTurnsHandlers(
|
||||
payload.metadata,
|
||||
payload.updated_at,
|
||||
);
|
||||
const quickChat = store.getState().quickChat;
|
||||
const quickChatSession = quickChat.sessions.find(
|
||||
(session) => session.sessionId === payload.session_id,
|
||||
);
|
||||
if (quickChatSession && !quickChat.isOpen && !wasCompleted) {
|
||||
// Share the settled ledger with the state_changed path so a replay of
|
||||
// the same completion (reconnect, delayed event) cannot re-mark after
|
||||
// the user already saw the dot. completed_at is the stable identity of
|
||||
// this completion; a missing value falls through to the mark.
|
||||
if (
|
||||
!payload.completed_at ||
|
||||
store.getState().recordQuickChatSettled(payload.session_id, payload.completed_at)
|
||||
) {
|
||||
store
|
||||
.getState()
|
||||
.markQuickChatUnseenIdle(payload.session_id, quickChatSession.workspaceId);
|
||||
}
|
||||
}
|
||||
// Surface a notice when the turn finished with no agent output.
|
||||
maybeEmitEmptyTurnNotice(store, payload);
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
"queuedPromptCount_other": "{{count}} queued prompts",
|
||||
"wipQueuePosition": "Position {{position}} of {{total}} in {{step}} queue",
|
||||
"quickChat": "Quick Chat",
|
||||
"quickChatUnseen": "Quick Chat, new response",
|
||||
"quickTerminal": "Quick terminal",
|
||||
"quickChatTerminals": "Terminals",
|
||||
"quickChatNewAgent": "New Agent",
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
"queuedPromptCount_other": "{{count}} qũēũēď ƥŕōḿƥţś",
|
||||
"wipQueuePosition": "Ƥōśĩţĩōń {{position}} ōƒ {{total}} ĩń {{step}} qũēũē",
|
||||
"quickChat": "Qũĩćķ Ćĥàţ",
|
||||
"quickChatUnseen": "Qũĩćķ Ćĥàţ, ńēŵ řēśƥōńśē",
|
||||
"quickTerminal": "Qũĩćķ ţēŕḿĩńàĺ",
|
||||
"quickChatTerminals": "Ţēŕḿĩńàĺś",
|
||||
"quickChatNewAgent": "Ńēŵ Àĝēńţ",
|
||||
|
||||
@@ -70,6 +70,7 @@
|
||||
"queuedPromptCount_other": "{{count}} prompts em fila",
|
||||
"wipQueuePosition": "Posição {{position}} de {{total}} na fila de {{step}}",
|
||||
"quickChat": "Chat rápido",
|
||||
"quickChatUnseen": "Chat rápido, nova resposta",
|
||||
"quickTerminal": "Terminal rápido",
|
||||
"quickChatTerminals": "Terminais",
|
||||
"quickChatNewAgent": "Novo agente",
|
||||
|
||||
@@ -72,6 +72,7 @@
|
||||
"queuedPromptCount_other": "{{count}} 条排队提示",
|
||||
"wipQueuePosition": "{{step}} 队列中的第 {{position}} 项,共 {{total}} 项",
|
||||
"quickChat": "快速聊天",
|
||||
"quickChatUnseen": "快速聊天,有新回复",
|
||||
"quickTerminal": "快速终端",
|
||||
"quickChatTerminals": "终端",
|
||||
"quickChatNewAgent": "新建智能体",
|
||||
|
||||
@@ -72,6 +72,7 @@
|
||||
"queuedPromptCount_other": "{{count}} 條排隊提示",
|
||||
"wipQueuePosition": "{{step}} 佇列中的第 {{position}} 項,共 {{total}} 項",
|
||||
"quickChat": "快速聊天",
|
||||
"quickChatUnseen": "快速聊天,有新回覆",
|
||||
"quickTerminal": "快速終端",
|
||||
"quickChatTerminals": "終端",
|
||||
"quickChatNewAgent": "新建代理程式",
|
||||
|
||||
@@ -72,6 +72,7 @@
|
||||
"queuedPromptCount_other": "{{count}} 條排隊提示",
|
||||
"wipQueuePosition": "{{step}} 佇列中的第 {{position}} 項,共 {{total}} 項",
|
||||
"quickChat": "快速聊天",
|
||||
"quickChatUnseen": "快速聊天,有新回覆",
|
||||
"quickTerminal": "快速終端",
|
||||
"quickChatTerminals": "終端",
|
||||
"quickChatNewAgent": "新建代理程式",
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
---
|
||||
spec: docs/specs/quick-chat-idle-dot/spec.md
|
||||
created: 2026-08-16
|
||||
status: complete
|
||||
---
|
||||
|
||||
# Implementation Plan: Quick Chat Idle Dot
|
||||
|
||||
## Overview
|
||||
|
||||
A red dot on the five Quick Chat entry icons (sidebar rail item, sidebar
|
||||
shortcut, tablet header button, mobile header button, mobile task-switcher
|
||||
sheet button) whenever a quick chat session completes a turn while the dialog
|
||||
is closed. Purely frontend: `session.state_changed` and `session.turn.completed`
|
||||
are broadcast to every connected client (their payloads carry no
|
||||
`workspace_id`, so the gateway's workspace-broadcast path falls back to global
|
||||
delivery), so the client observes every completion with no new WS
|
||||
subscriptions or backend changes; per-workspace dots rely on session-tab
|
||||
membership and the selector, not transport scoping. Implementation order:
|
||||
unseen-idle state in the UI slice → marking hooks in the two WS handlers → dot
|
||||
rendering in the entry components → E2E.
|
||||
|
||||
---
|
||||
|
||||
## Frontend
|
||||
|
||||
### State — `apps/web/lib/state/slices/ui/`
|
||||
|
||||
- `types.ts` (`QuickChatState`): add
|
||||
`unseenIdleByWorkspace: Record<string, Record<string, true>>` — workspace id
|
||||
→ session id → marker. Workspace ownership lives in the key, so it survives
|
||||
hydration of a different workspace's session list (see Hydration — non-destructive union).
|
||||
Also add `lastSettledAtBySession: Record<string, string>` — session id →
|
||||
`updated_at` of the last observed settle transition (replay guard for
|
||||
`session.state_changed` marking; see Marking hooks).
|
||||
Also add `syncRevisionByWorkspace: Record<string, number>` — per-workspace mutation epoch, incremented by EVERY local server-backed tab mutation that could make an in-flight resync response stale: WS-driven upserts (`upsertQuickChatSessionFromEvent`), `addQuickChatSession` (insert AND existing-row update), the `openQuickChat` push/existing branches, `removeQuickChatSession` (direct-delete success path), `removeQuickChatSessionsForTask`, AND the optimistic rename flow (`renameQuickChatSession` / `persistQuickChatRename` — bumped BEFORE the server request, so a resync in flight cannot apply the old server name after the optimistic rename). The reconnect resync (`useQuickChatResync`) captures it before issuing the HTTP list fetch and DISCARDS a stale response (revision moved while in flight) — checked before EVERY response side effect, including `setTaskSession` for the returned `task_sessions` rows — so neither a WS-upserted tab, a locally-deleted tab, nor an optimistic rename can be clobbered by an older list. Also add returned `task_sessions` rows are guarded PER-ROW by `updated_at`: `useQuickChatResync` skips applying any returned row whose live store row has a NEWER `updated_at` (the live WS row wins). This is workspace-precise — `session.state_changed` broadcasts globally with no `workspace_id`, and an unrelated workspace's state traffic must NOT discard a valid resync response.
|
||||
Also add `tombstonedSessions: Record<string, { workspaceId: string; tombstonedAt: string }>` — client
|
||||
tombstones for deleted session identities (value carries the workspace AND
|
||||
an ISO timestamp so the 60-minute age-prune is implementable), set by `removeQuickChatSession`,
|
||||
`removeQuickChatSessionsForTask`, AND the Quick Chat dialog's delete-tab flow
|
||||
(`use-quick-chat-modal.ts` `handleConfirmClose` calls `removeQuickChatSession`
|
||||
after the successful `deleteQuickChatTask` — NOT bare `closeQuickChatSession`,
|
||||
which does not tombstone; setup-tab closes keep `closeQuickChatSession` since
|
||||
setup ids never receive task events). `syncQuickChatFromTaskEvent` /
|
||||
`upsertQuickChatSessionFromEvent` SKIP tombstoned session ids, so a
|
||||
late/out-of-order `task.created`/`task.updated` cannot resurrect a deleted
|
||||
tab (DeleteSession publishes no `session.deleted` broadcast, and the task
|
||||
lifecycle subscription is ordered independently of the HTTP resync).
|
||||
Tombstone clearing is POSITIVE-CONFIRMATION ONLY: a tombstone is cleared
|
||||
solely when an authoritative workspace list for the SAME workspace
|
||||
(`workspaceId` stored with the tombstone) positively CONTAINS the session
|
||||
(it is legitimately live again); an omission NEVER clears it (an older
|
||||
task event can still be in flight after the list), and another workspace's
|
||||
list NEVER touches it. Age-pruned like the ledger (60-minute retention
|
||||
bound, keyed on `tombstonedAt`).
|
||||
Also add `sessionOwnership: Record<string, { taskId?: string; workspaceId: string }>` —
|
||||
durable in-memory sessionId → task/workspace index, populated at EVERY
|
||||
session-insertion path — the INITIAL BOOT path (`mergeQuickChatState` in
|
||||
`apps/web/lib/state/default-state.ts`: `createAppStore` runs `mergeInitialState`
|
||||
before composing the store, so boot-loaded sessions never pass through
|
||||
`hydrateUI`), `addQuickChatSession`, `upsertQuickChatSessionFromEvent`
|
||||
(BOTH branches of the central `upsertQuickChatSession` reducer — a task
|
||||
event updating an existing row also refreshes its ownership via the
|
||||
centralized `indexSessionOwnership` helper),
|
||||
the `openQuickChat` real-session push branch (`ui-slice.ts` pushes a freshly
|
||||
started session directly, not via `addQuickChatSession`), `reconcileQuickChatSessions`
|
||||
(inserted/adopted server sessions, and refreshed for survivors), and
|
||||
`hydrateUI` — and pruned on `closeQuickChatSession`,
|
||||
`removeQuickChatSessionsForTask`, and revision-guarded reconcile/resync (NOT by hydration).
|
||||
Without it, `removeQuickChatSessionsForTask(taskId)` — the only signal for
|
||||
task delete/archive — cannot clean a marker once the session row left the
|
||||
current `sessions` list (e.g. marked workspace-A session, workspace-B
|
||||
hydration replaces A's row, then A's task-deleted event: the reducer finds
|
||||
nothing and A's marker survives until a later A sync). Boot-loaded,
|
||||
`openQuickChat`, or reconcile tabs whose ownership entry is missing have the
|
||||
same hole on task deletion.
|
||||
- `ui-slice.ts` (`defaultUIState.quickChat`): default `unseenIdleByWorkspace: {}`.
|
||||
- `ui-slice.ts` actions:
|
||||
- `markQuickChatUnseenIdle(sessionId: string, workspaceId: string)` — sets `unseenIdleByWorkspace[workspaceId][sessionId] = true`.
|
||||
- `clearQuickChatUnseenIdle()` — clears all workspaces (used by `openQuickChat`).
|
||||
- `clearQuickChatUnseenIdle(sessionId: string, workspaceId: string)` — deletes one entry.
|
||||
- `removeQuickChatSession(sessionId: string)` — LOOKUP PRECEDENCE is `quickChat.sessions` THEN `sessionOwnership` (an ownership entry is authoritative ownership, NOT unknown, even when the row is absent after cross-workspace hydration): removes the tab (whichever workspace), the marker from the owning workspace's map, the `sessionOwnership` entry, tombstones non-setup ids, bumps `syncRevisionByWorkspace`, runs the ledger age-prune, and re-points the active tab / closes the modal exactly like `closeQuickChatSession` when the removed session was active. A genuinely unknown id (no row, no ownership, not setup-prefixed) is a no-op.
|
||||
- **Generic session-delete hook**: the backend has no dedicated `session.deleted` notification (DeleteSession publishes only the deleted-session error event), so the frontend delete flows are the cleanup points: `useSessionActions.remove` (`apps/web/hooks/domains/session/use-session-actions.ts:148`) calls `removeQuickChatSession(sessionId)` after `removeTaskSession(taskId, sessionId)`, AND `sessions-dropdown.tsx`'s `handleDeleteSession` (direct `client.request("session.delete")` + `loadSessions(true)`) calls `removeQuickChatSession(sessionId)` after a successful delete (before the refresh). The Quick Chat modal's `handleConfirmClose` routes the NON-setup branch through `removeQuickChatSession` (after successful `deleteQuickChatTask`, and ALSO for the no-taskId case — a non-setup id whose taskId cannot be resolved is still cleaned and tombstoned via the ownership lookup, not left to bare `closeQuickChatSession`); only setup-tab closes keep `closeQuickChatSession`. Without these, deleting a quick chat session from any surface leaves the tab, marker, and ownership entry until a later resync, and a delayed global state event keeps contributing to the stale tab.
|
||||
- `buildOpenQuickChatAction`: clear all markers on open (`clearQuickChatUnseenIdle()`); populate `sessionOwnership` for the real-session push branch (a freshly started session is inserted directly into `quickChat.sessions`, bypassing `addQuickChatSession`).
|
||||
- `buildQuickChatActions`:
|
||||
- `setActiveQuickChatSession`: clear that session's marker (workspace from the tab entry).
|
||||
- `closeQuickChatSession`: clear the closing session's marker.
|
||||
- `removeQuickChatSessionsForTask`: clear markers for the removed sessions via the `sessionOwnership` index (session ids by taskId → delete their markers from their workspace maps, drop their ownership entries), THEN filter the current sessions list — works even when the session row is absent from the list after cross-workspace hydration (reducer in `quick-chat-sync.ts`, workspace-scoped).
|
||||
- `syncQuickChatSessions`: `reconcileQuickChatSessions` in `quick-chat-sync.ts` drops that workspace's markers for sessions the server list no longer contains, populates/refreshes ownership for inserted/adopted sessions and survivors, TOMBSTONES each omitted non-setup session (with workspace + timestamp) BEFORE dropping its ownership, and clears tombstones ONLY for same-workspace sessions POSITIVELY present in the list (omission and other workspaces never clear). The OMISSION IDENTITY SET is the union of the prior workspace's session rows AND the workspace-scoped `sessionOwnership` entries — a session known only through `sessionOwnership` (its row was dropped by a cross-workspace hydration) is still omitted-and-tombstoned when the hydrated list lacks it; otherwise an empty A-list sync after a B-hydration would prune A's ownership without a tombstone and a delayed task event could re-upsert the deleted tab.
|
||||
- **Public store surface**: `apps/web/lib/state/store.ts` manually enumerates the quick chat actions on `AppState` (the section declares individual `UIA["…"]` entries, not `UISliceActions`); the four new root actions (`markQuickChatUnseenIdle`, `clearQuickChatUnseenIdle`, `recordQuickChatSettled`, `removeQuickChatSession`) MUST be added to that explicit list or components/handlers selecting them from `useAppStore` will not typecheck.
|
||||
- **Code-quality limits (AGENTS.md)**: `ui-slice.ts` is already 568/600 lines and `buildQuickChatActions` ~98/100 — the new ownership-index, tombstone, revision-epoch, ledger-pruning, marker-cleanup, and `removeQuickChatSession` transitions MUST be extracted into `quick-chat-sync.ts` or a dedicated `quick-chat-lifecycle.ts` module (pure reducers/helpers + thin action wrappers), keeping `ui-slice.ts` ≤600 lines and every function ≤100 lines (enforced by `apps/web/eslint.config.mjs`).
|
||||
- New selector `apps/web/lib/state/slices/ui/quick-chat-unseen-selectors.ts`:
|
||||
`selectQuickChatHasUnseenIdle(state: AppState, workspaceId: string | null | undefined): boolean` — true when the workspace's marker map is non-empty; returns false for nullish or unknown workspace ids (every entry-point caller passes `string | null | undefined` — `useAppStore((s) => s.workspaces.activeId)` and the header `workspaceId?` props). Stable empty fallback, no fresh literals.
|
||||
- Boot payload + typed fixtures: `apps/web/app/page.tsx` (`loadWorkspaceState` → `initialState.quickChat`), the `QuickChatState` builders in `apps/web/lib/state/slices/ui/quick-chat-sync.test.ts`, and the full-state `draft.quickChat` assignments in `apps/web/lib/state/hydration/hydrator.test.ts` gain ALL FIVE fields with empty defaults (`unseenIdleByWorkspace: {}`, `lastSettledAtBySession: {}`, `sessionOwnership: {}`, `syncRevisionByWorkspace: {}`, `tombstonedSessions: {}`) — the boot payload must explicitly reset every ephemeral map, and full-typed `QuickChatState` constructions must carry every required field.
|
||||
- Hydration is a NON-DESTRUCTIVE MERGE (workspace-keyed): `hydrateUI` (`apps/web/lib/state/hydration/hydrator.ts`) merges the hydrated sessions list into `draft.quickChat.sessions` — UNION: sessions absent from the live list are ADDED (ownership indexed for them); sessions already present KEEP the live tab's fields (live wins on overlap — `QuickChatSession` has no `updated_at`, `StateHydrator` re-hydrates on every SSR `initialState` change, and a stale SSR payload captured before a `task.updated` or the optimistic rename must not regress the newer live name/taskId); tombstoned ids filtered OUT — and NEVER prunes markers/ownership and NEVER tombstones omissions (it only unions sessions and filters existing tombstones; it neither creates nor clears them). `StateHydrator` re-hydrates on every SSR `initialState` change (`state-hydrator.tsx:19-24`), and an SSR list captured before either a local delete OR a WS-upserted live tab must not destroy the current truth: pruning markers/ownership, tombstoning omitted sessions, and positive tombstone clearing happen ONLY on the revision-guarded resync path (`syncQuickChatSessions` → reconcile, after `useQuickChatResync`'s epoch + task-session-revision checks). The hydrated workspace (for ownership population and tombstone filtering) derives from `state.workspaces?.activeId` (boot payload provides it via `buildBaseState`, verified `apps/web/app/page.tsx:63-67`); when absent (partial payload) hydration still merges sessions but skips workspace-scoped side effects fail-safe.
|
||||
|
||||
### Marking hooks — WS handlers
|
||||
|
||||
- `apps/web/lib/ws/handlers/agent-session.ts` (`registerTaskSessionHandlers`, `session.state_changed`): after the existing fan-out, call a local `maybeMarkQuickChatUnseenIdle(store, sessionId, previousState, newState)` that marks only when (a) the session id is in `store.getState().quickChat.sessions` (its workspace id comes from that tab entry), (b) `!store.getState().quickChat.isOpen`, and (c) the transition is a settle transition (previous STARTING/RUNNING → new IDLE/WAITING_FOR_INPUT/COMPLETED/FAILED/CANCELLED; previous state = store row FIRST, falling back to the payload's typed `old_state` only when no row exists — boot hydration drops `task_sessions`). The REPLAY guard is a per-session settle-generation ledger, NOT the store row: `quickChat.lastSettledAtBySession: Record<sessionId, string>` records the `updated_at` of EVERY settle transition observed for ANY session (kanban and quick chat alike, regardless of `isOpen` and regardless of quick-chat membership — recording happens BEFORE the membership check), and a settle marks only when its `updated_at` is newer than the ledger entry (or no entry). The ledger is a MONOTONIC MAX per session: a settle with `updatedAt <= recordedAt` is suppressed AND never overwrites the entry — an out-of-order delayed older settle must not regress the ledger, or a later replay of the newer event would falsely mark after the dialog cleared the dot. Recording before membership is required for the event-before-tab guarantee: a settle that arrives before its tab exists records the generation, so adding the tab later and replaying the original event cannot mark (the ledger already has that `updated_at`). The store row is unreliable for replay detection because `hydrateSession` runs `deepMerge(draft.taskSessions, state.taskSessions)` unconditionally — an in-flight SSR snapshot can regress a settled row back to RUNNING. A settle whose payload lacks `updated_at` has NO stable generation (the fallback persistence path can publish without it — `persistStrictTaskSessionState` passes nil when the refreshed row's `UpdatedAt` is zero and the publisher omits the key): it FAILS CLOSED — never marks and never records the ledger, because a replayable ungenerationed settle must not raise a dot. The ledger is age-bounded: the pure helper `pruneStaleSettledLedger(bySession, now)` (60-minute retention window — far longer than the event-before-tab tab-upsert, reconnect, and hydration-regression replay windows) runs at `recordQuickChatSettled` AND at `closeQuickChatSession`, `removeQuickChatSessionsForTask`, `reconcileQuickChatSessions`, and `hydrateUI` pruning; entries younger than the window are never dropped on those paths (still needed for the replay window), older entries are evicted, so a long-lived client cannot accumulate a key per settled kanban session. The ledger is ALSO size-capped at a documented maximum (500 entries): when the cap is exceeded, the oldest entries by timestamp are evicted — the practical replay window is seconds, so the cap only ever evicts entries far older than any realistic replay, and age window + size cap bound memory deterministically regardless of workload. Define the two state sets locally (do not import from `hooks/domains/session/use-session-messages.ts` — avoid a `hooks → lib/ws` import edge).
|
||||
- `apps/web/lib/ws/handlers/turns.ts` (`registerTurnsHandlers`, `session.turn.completed`): capture `const wasCompleted = turns.bySession[sessionId]?.some(t => t.id === payload.id && t.completed_at)` BEFORE the existing `addTurn`/`completeTurn` calls (both mutate the store, so a post-mutation check would see every delivery as already completed); then, after `completeTurn`, mark only when (a) quick chat session, (b) dialog closed, and (c) `!wasCompleted` — a re-delivered completion of an already-recorded turn must not mark (spec re-delivery failure mode). All `session.turn.completed` events are treated uniformly: `AbandonOpenTurns` (resume/startup cleanup, rejected-message cleanup) publishes the same payload shape with no abandonment discriminator (`had_output` is forced true), so an abandoned closure marks like any completion — accepted, see spec failure mode.
|
||||
- **Receipt-time semantics (spec failure mode)**: both handlers evaluate `quickChat.isOpen` at handling time. `session.state_changed` and `session.turn.completed` arrive over separate event-bus subscriptions, and the gateway broadcasts both to every connected client (payloads carry no `workspace_id` — see `routeBroadcast`/`BroadcastToWorkspace` fallback), so their relative order is not guaranteed; a completion handled while the dialog is open never marks, one handled after it closed marks.
|
||||
|
||||
### Entry-point dots
|
||||
|
||||
- `apps/web/components/app-sidebar/app-sidebar-nav-item.tsx`: add `dot?: boolean` prop; when true, wrap the icon in a `relative` span with an absolutely positioned dot (`h-2 w-2 rounded-full bg-red-500 ring-2 ring-background`, top-right corner, `aria-hidden`, `data-testid="quick-chat-unseen-dot"`).
|
||||
- `apps/web/components/app-sidebar/app-sidebar-primary-nav.tsx`: Quick Chat nav item gets `dot={selectQuickChatHasUnseenIdle(state, workspaceId)}` (only rendered when collapsed).
|
||||
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx`: `RowActionButton` gains an optional `dot?: boolean` (same absolute dot over the `h-3.5 w-3.5` icon); the Quick Chat shortcut passes the selector result.
|
||||
- `apps/web/components/kanban/kanban-header.tsx` (`TabletQuickActions`): wrap the `IconMessageCircle` in a relative span with the dot when the selector is true.
|
||||
- `apps/web/components/kanban/kanban-header-mobile.tsx`: same for the mobile button.
|
||||
- `apps/web/components/task/mobile/session-task-switcher-sheet.tsx` (`TaskSwitcherSurfaceHeader`, `mobile-sheet-quick-chat`): same for the mobile task-switcher sheet button.
|
||||
|
||||
No i18n impact: the dot is `aria-hidden` and carries no copy; labels/tooltips are unchanged.
|
||||
|
||||
---
|
||||
|
||||
## Tests
|
||||
|
||||
- **Marking via `session.state_changed`** — `apps/web/lib/ws/handlers/agent-session.test.ts` (extend existing describe blocks; store builder gains `quickChat` state):
|
||||
- table-driven over BOTH accepted active sources × every accepted settle target — for each S ∈ {STARTING, RUNNING} and T ∈ {IDLE, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED}: S→T marks when closed + tab exists, AND a replay of the same event (identical `updated_at`, row or ledger already settled) does NOT mark; plus the reverse (any settled → active) never marks.
|
||||
- dialog OPEN + RUNNING→IDLE → no marker (event-before-close ordering); the settle still records `lastSettledAtBySession` so a replay after close does not mark either.
|
||||
- no store row + payload `old_state: RUNNING` → IDLE → marker set (old_state fallback; boot hydration has no task-session row for quick chat tabs); with `old_state` absent → falls back to the store row.
|
||||
- non-quick-chat (kanban) session + closed + RUNNING→IDLE → no marker.
|
||||
- stale-hydration between replay: settle RUNNING→IDLE (mark) → `openQuickChat` clears → simulate `hydrateSession` regressing the task-session row back to RUNNING (`deepMerge`) → replay the ORIGINAL event verbatim (same `old_state`, same `updated_at`) → NO mark, because the ledger records the earlier settle (row regression is irrelevant).
|
||||
- ledger re-arm: settle at t1 (mark) → open clears → new settle at t2 > t1 → mark again; replaying t2 after another clear → no mark.
|
||||
- MISSING `updated_at` (fail-closed): settle without `updated_at`, closed + tab exists → NO mark and NO ledger record; after row regression + replay of the same event → still no mark — an ungenerationed settle must never raise a dot.
|
||||
- ledger bound: an entry within the 60-minute retention window still suppresses an event-before-tab replay; `pruneStaleSettledLedger` with a fixed `now` evicts entries older than the window; re-arm still works after eviction of the old entry; eviction also runs on close/remove/reconcile/hydration paths (young entries preserved there).
|
||||
- ledger monotonic max: settle t1 → settle t2 (t2 > t1) → `openQuickChat` clears → `deepMerge` regresses the row → a DELAYED t1 arrives → no mark AND the ledger stays t2 (never regressed); replaying t2 → still no mark.
|
||||
- ledger size cap: inserting beyond the 500-entry cap evicts the oldest entries by timestamp; entries within the cap are retained (event-before-tab replay still suppressed).
|
||||
- eviction-then-replay pin (accepted behavior, spec failure mode): a `state_changed` duplicate delivered AFTER its generation was age-evicted or cap-evicted marks like a new settle — pins the qualified re-delivery guarantee (suppression holds within the ledger retention only).
|
||||
- **Abandoned closures (accepted behavior, spec failure mode)** — `turns.test.ts`: a `session.turn.completed` whose `completed_at` equals `started_at` (the backend's `isAbandonedTurnCompletion` shape) for a known quick-chat tab with the dialog closed marks like any completion — pins the intentional decision NOT to filter on the discriminator. The session did settle idle and the state_changed settle transition raises the same signal.
|
||||
- **Re-arm (spec scenario 5)** — `agent-session.test.ts` or `turns.test.ts`: quick chat session marks, `openQuickChat` clears all, dialog closes, a second NEW `session.turn.completed` (or RUNNING→IDLE) arrives → marker is set again. Pins that clear-on-open does not permanently disarm a session.
|
||||
- **Event-before-tab + re-delivery (spec failure modes)** — `agent-session.test.ts` / `turns.test.ts`: a settle or turn-completed event for a session absent from `quickChat.sessions` does not mark; for `state_changed` the settle generation is still RECORDED (membership-agnostic ledger), so after the tab is later added via `upsertQuickChatSessionFromEvent`/`addQuickChatSession`, replaying the original event does NOT mark; kanban sessions never render a marker (membership still fails) and their replay stays suppressed. For `turn.completed` this pins the pre-mutation `wasCompleted` snapshot: first delivery of a turn → marks (if closed + tab exists); duplicate delivery → no mark (turn already recorded); duplicate after `openQuickChat` cleared the marker → marker stays cleared.
|
||||
- **Receipt-time ordering** — `agent-session.test.ts` / `turns.test.ts`: handler-level determinism for both orderings — event handled while dialog open → no mark; same event handled after dialog closed → mark (close-before-event). The separate `TurnCompleted`/`TaskSessionStateChanged` gateway subscriptions make cross-channel order undefined, so the handlers must be order-independent per event.
|
||||
- **Marking via `session.turn.completed`** — `apps/web/lib/ws/handlers/turns.test.ts`:
|
||||
- quick chat session + dialog closed → marker set.
|
||||
- quick chat session + dialog open → no marker.
|
||||
- non-quick-chat session → no marker.
|
||||
- **State actions + selector** — new `apps/web/lib/state/slices/ui/quick-chat-unseen.test.ts` and `quick-chat-unseen-selectors.test.ts`:
|
||||
- `markQuickChatUnseenIdle(sessionId, workspaceId)` sets in that workspace's map; `clearQuickChatUnseenIdle()` clears all workspaces; `clearQuickChatUnseenIdle(sessionId, workspaceId)` clears one.
|
||||
- `openQuickChat` clears all markers.
|
||||
- `setActiveQuickChatSession` clears that session's marker.
|
||||
- `closeQuickChatSession` clears the closing session's marker + ownership entry and runs the ledger age-prune.
|
||||
- generic session-delete regression: a quick chat session removed via `useSessionActions.remove`'s success path OR `sessions-dropdown.tsx`'s `handleDeleteSession` → tab, marker, and ownership entry all removed, ledger pruned; a delayed `session.state_changed`/`turn.completed` for the deleted session does NOT mark (membership fails); deleting a non-quick-chat session is a no-op.
|
||||
- `removeQuickChatSessionsForTask` clears markers of that task's sessions only (workspace-scoped).
|
||||
- `syncQuickChatSessions` reconcile drops that workspace's markers for sessions absent from the server list; two-workspace case: markers in A and B, sync A → only A pruned.
|
||||
- ownership-index regression: mark workspace-A session → hydrate B (A's marker AND `sessionOwnership` entry preserved) → `removeQuickChatSessionsForTask(A-task)` → A's marker removed and ownership entry dropped even though A's session row is absent from the current sessions list; deleting B's task does not touch A's markers; `closeQuickChatSession` / revision-guarded reconcile/resync drop ownership entries for the removed sessions; hydration PRESERVES A's ownership entry (non-destructive).
|
||||
- ownership-index insertion regressions: a tab inserted via the `openQuickChat` real-session push branch, a session inserted/adopted by `reconcileQuickChatSessions`, and a session loaded at INITIAL BOOT (`mergeQuickChatState`), each gain ownership entries at insertion; for all three, mark → `removeQuickChatSessionsForTask` → marker and ownership removed (cross-device resync included; the boot case: boot-loaded A session → mark → hydrate B (A row dropped) → delete A task → marker removed).
|
||||
- selector: true for a non-empty marker map of the workspace; false for other workspaces, for nullish/unknown workspace ids, and when nothing marked; stable empty fallback.
|
||||
- resync staleness regression: a deferred `listQuickChatSessions` response with an intervening WS task/session event (tab upserted + marker set, epoch bumped) is DISCARDED by `useQuickChatResync` — the tab and marker survive, reconcile never runs with the stale list; a response with no intervening mutation applies normally; a response arriving after reconnect without mutations still reconciles.
|
||||
- delete-vs-resync regression: a resync fetch started before a direct session delete (tab removed, epoch bumped) returns the old list afterward → discarded, the deleted tab is NOT re-added (reconcile never runs with the stale list).
|
||||
- tombstone regressions: after `removeQuickChatSession` / `removeQuickChatSessionsForTask` / the modal delete-tab flow, a late `task.created`/`task.updated` (or `upsertQuickChatSessionFromEvent`) for the tombstoned session id is IGNORED — no tab re-added, marker stays gone; a tombstone is cleared ONLY by a same-workspace authoritative list that POSITIVELY contains the session (then a genuinely new event applies); an authoritative list OMITTING the session does NOT clear it (delayed-old-event-after-authoritative-omission); a workspace-B list never clears a workspace-A tombstone; tombstones age-prune like the ledger (60 minutes, keyed on `tombstonedAt` — timestamp present and pruned).
|
||||
- reconcile-omission tombstone: a session omitted by a resync list is tombstoned BEFORE its ownership drops — a delayed `task.created`/`task.updated` after the omission is still blocked (deletion observed via list before the `task.deleted` event; cross-device `session.delete` covered). The omission set is the union of the workspace's session rows AND its `sessionOwnership` entries: A → hydrate B (A's rows dropped, ownership kept) → sync/hydrate A with an EMPTY list → A's ownership-only sessions are tombstoned before pruning, and a late task event for one is still blocked.
|
||||
- removal precedence: `removeQuickChatSession` on a row-absent-but-ownership-known session cleans marker + ownership + tombstones + bumps the revision (no stale-response re-add); the modal's non-setup no-taskId branch routes through the same cleanup (tombstone) instead of bare `closeQuickChatSession`.
|
||||
- hydration regressions: hydration is NON-DESTRUCTIVE — a deferred `StateHydrator` run with an SSR list captured before a local delete does NOT re-admit a deleted tab (tombstoned ids filtered) NOR clear its tombstone; an SSR list captured before a WS-upserted live tab does NOT drop or tombstone it (union merge preserves it; later lifecycle events still apply); an SSR list captured before a `task.updated` or the OPTIMISTIC RENAME does NOT overwrite the live tab's newer name/taskId (live wins on overlap); partial hydration payload without an active workspace id still merges sessions fail-safe. All pruning/tombstoning/positive-clearing is exercised on the revision-guarded resync.
|
||||
- task-session row-freshness regression: a deferred resync response with stale `task_sessions` (captured before a `session.state_changed` RUNNING→IDLE) applies ONLY the rows that are still fresh — the older RUNNING row for that session is SKIPPED (its live row has a newer `updated_at`), while other rows and the tab list apply; an unrelated workspace's `session.state_changed` traffic does NOT discard a valid resync response.
|
||||
- rename-vs-resync regression: an optimistic rename bumps the epoch before `persistQuickChatRename`; a resync in flight is discarded and cannot revert the tab to the old server name.
|
||||
- ownership-refresh regression: updating an EXISTING quick chat session row via `openQuickChat` (existing branch) or `addQuickChatSession` (existing branch) with a new/changed `taskId` refreshes its `sessionOwnership` entry — `removeQuickChatSessionsForTask` with the new taskId removes the marker; a row whose ownership lacks or has a stale taskId is covered.
|
||||
- **Resync-driven pruning (non-destructive hydration)** — `apps/web/lib/state/hydration/hydrator.test.ts` + resync tests: hydration is a NON-DESTRUCTIVE union (fixtures compile with all fields; hydrating with a server session list that omits a marked session does NOT prune anything and does NOT resurrect re-upserted tabs); pruning of that workspace's markers/ownership for omitted sessions, omission-tombstoning (union identity set incl. ownership-only sessions), and positive tombstone clearing are exercised on the REVISION-GUARDED resync (`syncQuickChatSessions`/reconcile) — including the A/B cross-workspace cases (B-only resync preserves A's marker while pruning B's removed sessions; a later A resync behaves correctly with A retained and with A omitted).
|
||||
- **Ephemeral reset (spec scenario 8)** — `mergeInitialState` unit test (or the hydration tests): a previous client state carrying markers and ledger entries, merged with a boot payload that omits them, yields an empty `unseenIdleByWorkspace` and `lastSettledAtBySession` — pins that a page reload (fresh store from default + boot payload) shows no dot.
|
||||
- **Component rendering**:
|
||||
- `apps/web/components/app-sidebar/app-sidebar-primary-nav.test.tsx`: collapsed rail Quick Chat item renders the dot when the selector is true, not otherwise.
|
||||
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx`: Quick Chat shortcut renders the dot when unseen, not otherwise.
|
||||
- `apps/web/components/kanban/kanban-header-mobile.test.tsx`: mobile button dot.
|
||||
- `apps/web/components/task/mobile/session-task-switcher-sheet.test.tsx`: `mobile-sheet-quick-chat` button dot.
|
||||
- Tablet header (`kanban-header.tsx`) covered by the E2E tablet case.
|
||||
|
||||
Command form (from `apps/`): `pnpm --filter @kandev/web test -- --run <file1> <file2> …` per task, then the full touched-file set.
|
||||
|
||||
---
|
||||
|
||||
## E2E Tests
|
||||
|
||||
New specs under `apps/web/e2e/tests/chat/` using the existing helpers
|
||||
(`quick-chat-helpers.ts`: `openQuickChatWithAgent`, `sendQuickChatMessage`) and
|
||||
`helpers/causal-waits.ts` `watchWs`. All dot assertions MUST be scoped to the
|
||||
entry under test — `getByTestId("quick-chat-unseen-dot")` matches every entry
|
||||
simultaneously once a marker is active (strict-mode ambiguous), so each
|
||||
assertion uses the named button's locator, e.g.
|
||||
`shortcut.getByTestId("quick-chat-unseen-dot")`, and surfaces are asserted
|
||||
individually:
|
||||
|
||||
- **Desktop (chromium)** — `quick-chat-idle-dot.spec.ts`: GIVEN no quick chat,
|
||||
THEN no dot on `sidebar-quick-chat-shortcut`. Capture `session_id` (and
|
||||
`task_id`) from the `POST /api/v1/workspaces/<id>/quick-chat` response
|
||||
(pattern: `entity-reference-composer.spec.ts` — the shared helpers return
|
||||
only the dialog). Call `watchWs(page)` before the first `goto`, then arm
|
||||
`const completed = ws.waitForEvent("session.turn.completed", { where: (p) => p.session_id === sessionId })`
|
||||
BEFORE sending `/slow 8s` (the wait must be armed before the event fires —
|
||||
`watchWs` buffers nothing, the gateway has no replay); send, close the
|
||||
dialog, await `completed`, THEN the dot is visible on the shortcut. Reopen →
|
||||
dot gone. Re-arm: arm a SECOND `waitForEvent` for the same session, send the
|
||||
second message WHILE the dialog is open, close the dialog while it is
|
||||
pending, await `completed`, THEN the dot reappears (spec scenario 5 — the
|
||||
composer only accepts input while the dialog is open).
|
||||
- **Tablet (chromium)** — same lifecycle against `tablet-quick-chat-button`
|
||||
using the `tabletTestPage` fixture (900×900, `hasTouch: true`); a fine-pointer
|
||||
desktop context at ~1024 renders compact desktop, not the tablet header.
|
||||
- **Mobile (mobile-chrome)** — `mobile-quick-chat-idle-dot.spec.ts` (the
|
||||
`mobile-chrome` project collects only `mobile-*.spec.ts`): same lifecycle
|
||||
against `mobile-quick-chat-button` (tap-driven, `quick-chat-close`), plus the
|
||||
sheet entry — navigation must happen BEFORE the marker exists (markers are
|
||||
ephemeral and lost on `page.goto`): seed a task
|
||||
(`apiClient.seedTask`, pattern `mobile-quick-chat-entry.spec.ts`), navigate
|
||||
to `/t/${taskId}` and wait for the session page, tap `mobile-sheet-quick-chat`
|
||||
(opens the Quick Chat setup dialog), select an agent, arm the waitForResponse
|
||||
for `POST /api/v1/workspaces/<id>/quick-chat` immediately BEFORE clicking
|
||||
`quick-chat-start` (that click issues the POST; the sheet tap itself does
|
||||
not), capture `session_id` from the response, send `/slow 8s` and close the
|
||||
dialog, await the completion, then reopen the sheet and assert the dot on
|
||||
`mobile-sheet-quick-chat`.
|
||||
|
||||
Run (single shell, from `apps/web`): `pnpm e2e:raw -g "quick chat idle dot" &&
|
||||
pnpm e2e:raw --project=mobile-chrome -g "quick chat idle dot"`.
|
||||
|
||||
---
|
||||
|
||||
## Verification Results
|
||||
|
||||
Targeted state, hydration, handler, and component tests passed. Typecheck and lint passed.
|
||||
Desktop/tablet Chromium and mobile-chrome idle-dot E2E runs passed.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Waves
|
||||
|
||||
Sequential (state → handlers → UI → E2E; each builds on the previous).
|
||||
|
||||
- [x] [task-01-unseen-idle-state](task-01-unseen-idle-state.md)
|
||||
- [x] [task-02-ws-marking-hooks](task-02-ws-marking-hooks.md)
|
||||
- [x] [task-03-entry-point-dots](task-03-entry-point-dots.md)
|
||||
- [x] [task-04-idle-dot-e2e](task-04-idle-dot-e2e.md)
|
||||
|
||||
## Open Questions
|
||||
|
||||
None.
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
id: "01-unseen-idle-state"
|
||||
title: "Unseen-idle state in the UI slice"
|
||||
status: complete
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/quick-chat-idle-dot/spec.md"
|
||||
---
|
||||
|
||||
# Task 01: Unseen-idle state in the UI slice
|
||||
|
||||
Add the client-only unseen marker to the quick chat UI state, its actions, and
|
||||
the per-workspace selector. Markers are keyed by workspace
|
||||
(`unseenIdleByWorkspace[workspaceId][sessionId]`) so workspace ownership
|
||||
survives hydration of a different workspace's session list.
|
||||
|
||||
- **Acceptance:**
|
||||
1. `QuickChatState.unseenIdleByWorkspace` defaults to `{}` and survives unrelated ui-slice writes; `lastSettledAtBySession` defaults to `{}` (the state_changed replay-guard ledger, written by task 02).
|
||||
2. Every structural `QuickChatState` site compiles and carries ALL FIVE fields with empty defaults: the boot payload in `apps/web/app/page.tsx`, the typed fixture builders in `quick-chat-sync.test.ts`, the full-state `draft.quickChat` assignments in `apps/web/lib/state/hydration/hydrator.test.ts`, AND `defaultUIState.quickChat` — `unseenIdleByWorkspace: {}`, `lastSettledAtBySession: {}`, `sessionOwnership: {}`, `syncRevisionByWorkspace: {}`, `tombstonedSessions: {}`.
|
||||
3. `markQuickChatUnseenIdle(sessionId, workspaceId)` sets `unseenIdleByWorkspace[workspaceId][sessionId] = true`; `clearQuickChatUnseenIdle()` clears all workspaces; `clearQuickChatUnseenIdle(sessionId, workspaceId)` clears one entry.
|
||||
4. Opening quick chat, activating a session, closing a session tab, removing a task's sessions, and server-reconciling the session list all clear the right markers (scenarios 4, 6, 7 in the spec).
|
||||
5. `selectQuickChatHasUnseenIdle(state, workspaceId: string | null | undefined)` is true exactly when that workspace's marker map is non-empty; false for nullish/unknown workspace ids; stable empty fallback (no fresh literals).
|
||||
6. Reconcile is workspace-scoped: markers in workspace A and B, then `syncQuickChatSessions(A, …)` — A's pruned markers clear, B's markers are preserved.
|
||||
7. `hydrateUI` is a NON-DESTRUCTIVE union: hydrated sessions absent from the live list are added (ownership indexed), overlapping sessions KEEP the live tab's fields (live wins — a stale SSR payload captured before a `task.updated` or the optimistic rename must not regress the newer live name/taskId), tombstoned ids are filtered; a marked session omitted by the hydrated list is NOT pruned by hydration and a later `upsertQuickChatSessionFromEvent` re-adding the tab is not suppressed by hydration; other workspaces' marker maps are untouched. Marker/ownership pruning for omitted sessions happens on the revision-guarded resync (verified for a later A resync both with A's session retained and with it omitted).
|
||||
8. Ephemeral reset (spec scenario 8): a `mergeInitialState`/hydration unit test proves that markers, ledger entries, ownership, revision counters, and tombstones from a previous client state are empty/default after merging a boot payload that omits them (fresh store from default + boot payload = no dot after reload).
|
||||
9. `sessionOwnership` index (sessionId → { taskId?, workspaceId }) is populated at EVERY insertion path: the initial boot path (`mergeQuickChatState` in `apps/web/lib/state/default-state.ts`), `addQuickChatSession`, `upsertQuickChatSessionFromEvent`, the `openQuickChat` real-session push branch, `reconcileQuickChatSessions` (inserted/adopted + refreshed survivors), and `hydrateUI`; pruned by `closeQuickChatSession`, `removeQuickChatSessionsForTask`, `removeQuickChatSession`, and revision-guarded reconcile/resync (NOT by hydration). `removeQuickChatSessionsForTask(taskId)` removes markers via the index (works even when the session row is absent from the current `sessions` list after cross-workspace hydration): mark A → hydrate B (A's marker and ownership preserved) → remove A's task → A's marker gone, B's markers untouched. Regressions for the boot-loaded, direct-POST-open, and reconcile-added insertion paths: mark → remove task → marker and ownership removed.
|
||||
10. `removeQuickChatSession(sessionId)` removes the tab (if present), marker, and ownership entry via the sessions-then-ownership lookup, tombstones non-setup ids, bumps the revision, and re-points the active tab / closes the modal like `closeQuickChatSession`; the generic session-delete flows — `useSessionActions.remove` (after `removeTaskSession`), `sessions-dropdown.tsx`'s `handleDeleteSession` (after the direct `session.delete`), AND the modal's non-setup delete-tab/no-taskId branches — call it, so deleting a quick chat session from ANY surface cleans tab + marker + ownership immediately (a delayed global state event for the deleted session never marks).
|
||||
11. The four new root actions are declared on `AppState` in `apps/web/lib/state/store.ts` (explicit quick-chat section), so `useAppStore` selections typecheck.
|
||||
12. Ownership pruning happens on the REVISION-GUARDED RESYNC, scoped per workspace: `reconcileQuickChatSessions` prunes `sessionOwnership` ONLY for entries whose `workspaceId === hydratedWorkspace` AND whose session is absent from the server list; other workspaces' ownership entries survive (a later task-deleted event for them can still clean their markers via the index). Hydration does not prune ownership.
|
||||
13. `syncRevisionByWorkspace` is incremented by every WS-driven session mutation; `useQuickChatResync` discards a stale list response (revision moved while the HTTP fetch was in flight) so a deferred response cannot clobber a WS-upserted tab/marker; regression covers deferred-response-with-intervening-event.
|
||||
14. `sessions-dropdown.tsx`'s `handleDeleteSession` calls `removeQuickChatSession` on success (before refresh) and NOT on request failure; covered by a focused `sessions-dropdown.test.ts` (or an extracted lifecycle hook test).
|
||||
15. `syncRevisionByWorkspace` is incremented by EVERY local server-backed tab mutation (WS upserts incl. both upsert branches, `addQuickChatSession` insert/existing-update, `openQuickChat` push/existing branches, `removeQuickChatSession`, `removeQuickChatSessionsForTask`, AND the optimistic rename flow — bumped BEFORE `persistQuickChatRename`); `useQuickChatResync` guards the returned `task_sessions` rows PER-ROW by `updated_at` (a returned row whose live store row is newer is skipped, so a deferred response never overwrites a newer `session.state_changed` row) and discards a stale tab list via the epoch — checked before EVERY response side effect including `setTaskSession`; unrelated-workspace state traffic never discards a valid response. A deferred list can neither clobber a WS-upserted tab, re-add a locally-deleted tab, revert an optimistic rename, nor overwrite a newer session row.
|
||||
16. `tombstonedSessions` (sessionId → { workspaceId, tombstonedAt }) is set by `removeQuickChatSession`, `removeQuickChatSessionsForTask`, and revision-guarded reconcile/resync OMISSION of a non-setup session, AND the Quick Chat dialog delete-tab flow (`use-quick-chat-modal.ts` `handleConfirmClose` calls `removeQuickChatSession` after the successful `deleteQuickChatTask`; setup-tab closes keep `closeQuickChatSession`); `syncQuickChatFromTaskEvent`/`upsertQuickChatSessionFromEvent` skip tombstoned ids. A tombstone clears ONLY on a same-workspace authoritative list that POSITIVELY contains the session; omission never clears (delayed old events after the list stay blocked — including omission-then-late-event) and other workspaces' lists never touch it; age-pruned like the ledger (60 minutes, keyed on `tombstonedAt`).
|
||||
17. Updating an EXISTING quick chat session row (`openQuickChat` / `addQuickChatSession` existing branches AND the central `upsertQuickChatSession` reducer's existing branch via `indexSessionOwnership`) with a new/changed `taskId` refreshes its `sessionOwnership` entry (ownership refresh is an invariant of every session-row update, not just insertion).
|
||||
18. Hydration is a NON-DESTRUCTIVE MERGE: the hydrated sessions list unions with the existing list (LIVE WINS on overlap — a stale SSR payload must not regress a newer live name/taskId; tombstoned ids filtered; ownership populated for newly added sessions); hydration NEVER prunes markers/ownership and NEVER tombstones omissions — a deferred `StateHydrator` run with an SSR list captured before a local delete does not re-admit the tab nor clear its tombstone, and an SSR list captured before a WS-upserted live tab does not drop or tombstone it. All pruning, omission-tombstoning, and positive tombstone clearing happen on the revision-guarded resync (union omission identity set: workspace session rows AND workspace-scoped `sessionOwnership` entries — A → hydrate B → resync A empty → ownership-only sessions tombstoned before pruning; late task events still blocked).
|
||||
19. The boot payload's `initialState.quickChat` explicitly resets ALL five ephemeral fields to empty defaults; every full-typed `QuickChatState` construction carries all five required fields (`unseenIdleByWorkspace`, `lastSettledAtBySession`, `sessionOwnership`, `syncRevisionByWorkspace`, `tombstonedSessions`).
|
||||
20. `removeQuickChatSession` lookup precedence is `quickChat.sessions` THEN `sessionOwnership` (ownership is authoritative even when the row is absent): a row-absent-but-ownership-known session is cleaned (marker + ownership + tombstone + revision bump); the modal's non-setup no-taskId branch routes through the same cleanup instead of bare `closeQuickChatSession`; a genuinely unknown id is a no-op.
|
||||
|
||||
- **Verification:**
|
||||
```sh
|
||||
cd apps && pnpm --filter @kandev/web test -- --run \
|
||||
lib/state/slices/ui/quick-chat-unseen.test.ts \
|
||||
lib/state/slices/ui/quick-chat-unseen-selectors.test.ts \
|
||||
lib/state/slices/ui/quick-chat-session.test.ts \
|
||||
lib/state/slices/ui/quick-chat-sync.test.ts \
|
||||
lib/state/slices/ui/ui-slice.test.ts \
|
||||
lib/state/hydration/hydrator.test.ts \
|
||||
hooks/domains/session/use-session-actions.test.ts \
|
||||
components/task/sessions-dropdown.test.ts \
|
||||
hooks/use-quick-chat-resync.test.ts \
|
||||
&& pnpm --filter @kandev/web run typecheck
|
||||
```
|
||||
|
||||
- **Files likely touched:**
|
||||
- `apps/web/lib/state/slices/ui/types.ts` — `QuickChatState` fields (`unseenIdleByWorkspace: Record<string, Record<string, true>>`, `lastSettledAtBySession: Record<string, string>`, `sessionOwnership: Record<string, { taskId?: string; workspaceId: string }>`) + action signatures.
|
||||
- `apps/web/lib/state/slices/ui/ui-slice.ts` — default state (all three fields), `markQuickChatUnseenIdle(sessionId, workspaceId)`, `clearQuickChatUnseenIdle()` / `clearQuickChatUnseenIdle(sessionId, workspaceId)`, `removeQuickChatSession(sessionId)` (tab + marker + ownership + ledger prune + active-tab fallback), `recordQuickChatSettled(sessionId, updatedAt)` (ledger writer; prunes entries older than the 60-minute retention window via pure helper `pruneStaleSettledLedger(bySession, now)`), ownership population in `addQuickChatSession` / `upsertQuickChatSessionFromEvent` / the `openQuickChat` real-session push branch (`buildOpenQuickChatAction`), ownership pruning in `closeQuickChatSession`, hook into `setActiveQuickChatSession`.
|
||||
- `apps/web/hooks/domains/session/use-session-actions.ts` — `remove` success path calls `removeQuickChatSession(sessionId)` after `removeTaskSession(taskId, sessionId)`.
|
||||
- `apps/web/components/task/sessions-dropdown.tsx` — `handleDeleteSession` calls `removeQuickChatSession(sessionId)` after the successful direct `session.delete` (before `loadSessions(true)`).
|
||||
- `apps/web/hooks/use-quick-chat-resync.ts` — captures `syncRevisionByWorkspace[workspaceId]` before the HTTP fetch, discards a stale tab list when the epoch moved, and applies the returned `task_sessions` rows PER-ROW: a row whose live store row has a newer `updated_at` is skipped (checking BEFORE every side effect, including `setTaskSession`).
|
||||
|
||||
- `apps/web/components/quick-chat/use-quick-chat-modal.ts` (or the rename helper) — the optimistic rename flow bumps `syncRevisionByWorkspace` before `persistQuickChatRename`.
|
||||
- `apps/web/components/quick-chat/use-quick-chat-modal.ts` — `handleConfirmClose` routes the NON-setup branch through `removeQuickChatSession(sessionId)` (tombstones) after the successful `deleteQuickChatTask`, and the non-setup no-taskId branch uses the same cleanup (via the ownership lookup); only setup-tab closes keep `closeQuickChatSession`.
|
||||
- `apps/web/lib/state/slices/ui/ui-slice.ts` — default state (all five fields) and THIN action wrappers only: the ownership-index, tombstone, revision-epoch, ledger-pruning, marker-cleanup, and `removeQuickChatSession` state transitions are EXTRACTED into `quick-chat-sync.ts` / a dedicated `quick-chat-lifecycle.ts` module (pure reducers + helpers) so `ui-slice.ts` stays ≤600 lines and every function ≤100 lines (AGENTS.md caps, enforced by `apps/web/eslint.config.mjs`).
|
||||
- `apps/web/lib/ws/handlers/quick-chat.ts` — `syncQuickChatFromTaskEvent` (and the `upsertQuickChatSessionFromEvent` path) skips tombstoned session ids.
|
||||
- `apps/web/lib/state/store.ts` — the four new root actions are added to AppState's EXPLICIT quick-chat action declarations (the section enumerates individual `UIA["…"]` entries; components/handlers select them from `useAppStore`).
|
||||
- `apps/web/hooks/domains/session/use-session-actions.test.ts` — the mocked `useAppStore` gains `removeQuickChatSession`; assert it is called after `removeTaskSession` on success and NOT on WS failure.
|
||||
- `apps/web/lib/state/slices/ui/quick-chat-sync.ts` — `reconcileQuickChatSessions` prunes that workspace's markers AND ownership entries for sessions no longer in the server list, and populates/refreshes ownership for inserted/adopted sessions and survivors; `removeQuickChatSessionsForTask` prunes markers and ownership via the `sessionOwnership` index (by taskId) before filtering sessions; new pure helpers `pruneUnseenIdleMarkers(byWorkspace, workspaceId, keepSessionIds)` (revision-guarded reconcile/remove only — hydrateUI never prunes) and `pruneStaleSettledLedger(bySession, now)` (shared with the ledger action).
|
||||
- `apps/web/lib/state/hydration/hydrator.ts` — `hydrateUI` performs a NON-DESTRUCTIVE union (new hydrated sessions added with ownership indexed; overlapping sessions keep the LIVE tab's fields — live wins on overlap; tombstoned ids filtered); no marker/ownership pruning, no omission tombstoning (those live in the revision-guarded resync).
|
||||
- `apps/web/lib/state/default-state.ts` — `mergeQuickChatState` populates `sessionOwnership` for boot-loaded sessions (initial boot bypasses `hydrateUI`).
|
||||
- `apps/web/app/page.tsx` — boot payload `initialState.quickChat` explicitly gains ALL FIVE fields with empty defaults: `unseenIdleByWorkspace: {}`, `lastSettledAtBySession: {}`, `sessionOwnership: {}`, `syncRevisionByWorkspace: {}`, `tombstonedSessions: {}`.
|
||||
- `apps/web/lib/state/slices/ui/quick-chat-sync.test.ts` — typed `QuickChatState` builder gains `unseenIdleByWorkspace: {}`, `lastSettledAtBySession: {}`, `sessionOwnership: {}`, `syncRevisionByWorkspace: {}`, `tombstonedSessions: {}`, .
|
||||
- `apps/web/lib/state/hydration/hydrator.test.ts` — full-state `draft.quickChat` assignments gain `unseenIdleByWorkspace: {}`, `lastSettledAtBySession: {}`, `sessionOwnership: {}`, `syncRevisionByWorkspace: {}`, `tombstonedSessions: {}`, .
|
||||
- `apps/web/lib/state/slices/ui/quick-chat-unseen-selectors.ts` — new selector accepting `string | null | undefined` (returns false for nullish), mirroring the empty-fallback pattern of `lib/state/slices/office/selectors.ts`.
|
||||
- New tests: `quick-chat-unseen.test.ts`, `quick-chat-unseen-selectors.test.ts` next to the sources; resync-staleness coverage in a new `hooks/use-quick-chat-resync.test.ts` (deferred response + intervening WS tab mutation → tab list discarded; deferred response + intervening `session.state_changed` → the stale returned row for that session is SKIPPED via the per-row `updated_at` guard while fresh rows apply; unrelated-workspace state traffic does NOT discard the response; deferred response vs optimistic rename → discarded, tab keeps the new name); `components/task/sessions-dropdown.test.ts` gains the delete-cleanup cases (cleanup on success before refresh, none on failure); modal delete-tab regression (successful `deleteQuickChatTask` → `removeQuickChatSession` tombstones; local close followed by delayed/missing `task.deleted` then late `task.updated` → tab NOT resurrected); tombstone clearing semantics (positive-confirmation-only on the revision-guarded resync; omission retains; A-deleted/B-resync never clears A's tombstone; age-prune).
|
||||
|
||||
- **Dependencies:** None.
|
||||
- **Parallelism:** sequential.
|
||||
|
||||
- **Inputs:**
|
||||
- Spec: What bullets 2–4, State machine table (workspace-keyed), Scenarios 4/6/7.
|
||||
- Plan: "State" section.
|
||||
- Existing patterns: `apps/web/lib/state/slices/ui/ui-slice.ts` (`buildQuickChatActions`, `buildOpenQuickChatAction`), `apps/web/lib/state/slices/ui/quick-chat-sync.ts` reducers, office selector empty-fallback constants.
|
||||
|
||||
- **Output contract:** summary, files changed, tests run with counts, blockers, risks; update task + plan statuses in the same conversation.
|
||||
|
||||
## Results
|
||||
|
||||
Implemented workspace-scoped ephemeral markers, settlement deduplication, lifecycle cleanup,
|
||||
hydration defaults, and selector coverage. Targeted state and hydration tests passed.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
id: "02-ws-marking-hooks"
|
||||
title: "WS handler marking hooks"
|
||||
status: complete
|
||||
wave: 1
|
||||
depends_on: ["01-unseen-idle-state"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/quick-chat-idle-dot/spec.md"
|
||||
---
|
||||
|
||||
# Task 02: WS handler marking hooks
|
||||
|
||||
Mark quick chat sessions as unseen-idle in the two globally broadcast WS
|
||||
handlers, guarded by dialog-open state and session membership.
|
||||
|
||||
- **Acceptance:**
|
||||
1. `session.state_changed` marks a quick chat session when the transition settles an active session (STARTING/RUNNING → IDLE/WAITING_FOR_INPUT/COMPLETED/FAILED/CANCELLED), the session id is in `quickChat.sessions`, and the dialog is closed; it never marks for non-settle transitions, replays, kanban sessions, or an open dialog. Previous state resolves from the store row FIRST, falling back to the payload's `old_state` only when no row exists (boot hydration drops `task_sessions`). The replay guard is the per-session settle-generation ledger `quickChat.lastSettledAtBySession`, recorded on EVERY settle transition BEFORE the quick-chat membership check (membership-agnostic — kanban sessions record too) and regardless of `isOpen`; a settle marks only when its `updated_at` is newer than the ledger entry. The ledger is a MONOTONIC MAX per session: `updatedAt <= recordedAt` is suppressed and never overwrites, so an out-of-order delayed older settle cannot regress the ledger (otherwise a later replay of the newer event would falsely mark after clear). Recording-before-membership is what makes event-before-tab replay-safe: a settle that arrives before its tab exists records the generation, so adding the tab later and replaying the original event cannot mark. A settle whose payload lacks `updated_at` has no stable generation (the backend fallback persistence path can publish without it) and FAILS CLOSED: never marks and never records. The ledger is age-bounded — `pruneStaleSettledLedger(bySession, now)` (60-minute window) runs at `recordQuickChatSettled`, at close/remove/reconcile, and opportunistically during hydration — age-eviction only, entries younger than the window are never dropped — so a long-lived client cannot accumulate a key per settled kanban session. The ledger is needed because `hydrateSession`'s unconditional `deepMerge(draft.taskSessions, …)` can regress a settled row back to RUNNING.
|
||||
2. `session.turn.completed` captures `wasCompleted` (turn id already recorded completed in `turns.bySession[sessionId]`) BEFORE `addTurn`/`completeTurn` and marks only when the quick chat session's tab exists, the dialog is closed, and `!wasCompleted`; never marks kanban sessions, an open dialog, or re-delivered completions of an already-completed turn.
|
||||
3. Both stay idempotent (repeated events do not duplicate state). All `session.turn.completed` events are treated uniformly: the abandonment discriminator EXISTS in the payload (`completed_at === started_at`, per `isAbandonedTurnCompletion`) but is INTENTIONALLY ignored — an abandoned closure marks like any completion (accepted, spec failure mode); no filtering by `had_output`, timestamps, or other fields.
|
||||
4. Re-arm (spec scenario 5): after `openQuickChat` clears all markers and the dialog closes, a second NEW settle/turn-completed event for the same session marks it again.
|
||||
5. Event-before-tab + re-delivery (spec failure modes): a settle or turn-completed event for a session absent from `quickChat.sessions` never marks it — including when the tab is added afterwards via `upsertQuickChatSessionFromEvent`/`addQuickChatSession`, when the same turn-completed is delivered again (pre-mutation `wasCompleted` snapshot: the first delivery recorded the turn), and when a duplicate arrives after `openQuickChat` cleared the marker (a replayed completion must not re-arm it).
|
||||
6. Receipt-time semantics (spec failure mode): the handlers evaluate `quickChat.isOpen` at handling time; the two broadcast channels are separate event-bus subscriptions (both fanned out to all connected clients — the payloads carry no `workspace_id`), so each handler must be order-independent — event handled while open → no mark; same event handled after close → mark.
|
||||
|
||||
- **Verification:**
|
||||
```sh
|
||||
cd apps && pnpm --filter @kandev/web test -- --run \
|
||||
lib/ws/handlers/agent-session.test.ts \
|
||||
lib/ws/handlers/turns.test.ts
|
||||
```
|
||||
|
||||
- **Files likely touched:**
|
||||
- `apps/web/lib/ws/handlers/agent-session.ts` — `maybeMarkQuickChatUnseenIdle(store, sessionId, previousState, newState)` + call site in `session.state_changed`; local STARTING/RUNNING and IDLE/WAITING_FOR_INPUT/COMPLETED/FAILED/CANCELLED sets (do NOT import `isTurnSettleTransition` from `hooks/domains/session/use-session-messages.ts` — keeps `lib/ws` free of a hooks import edge; the sets match its definitions).
|
||||
- `apps/web/lib/ws/handlers/turns.ts` — quick-chat + closed-dialog guard in `session.turn.completed` (after `completeTurn`).
|
||||
- `apps/web/lib/ws/handlers/agent-session.test.ts`, `apps/web/lib/ws/handlers/turns.test.ts` — the production hooks call ROOT store actions (`markQuickChatUnseenIdle(sessionId, workspaceId)`, `recordQuickChatSettled(sessionId, updatedAt)`, `clearQuickChatUnseenIdle`) plus `quickChat` state, so the existing builders MUST be extended with the exact wiring: `turns.test.ts`'s `makeStore()` (currently `SessionSlice` + `quickChat: { sessions: [] }`) and `agent-session.test.ts`'s `makeStore()` mock (currently no quickChat state at all) each gain `quickChat: { isOpen, sessions, unseenIdleByWorkspace, lastSettledAtBySession }` and the three root actions — either wired from the real ui-slice (`createAppStore`) or as `vi.fn()` mocks that mutate a fixture `quickChat` object (specify which; the mock approach matches the existing convention and lets tests assert both the marker map and the ledger). Include: the settle-transition matrix table-driven over BOTH active sources × every accepted target — for each S ∈ {STARTING, RUNNING} and T ∈ {IDLE, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED}: S→T marks when closed + tab exists, AND a replay of the same event (identical `updated_at`) does NOT mark; reverse (settled → active) never marks; re-arm (mark → `openQuickChat` → close → second NEW event with newer `updated_at` → marked again; replaying that second event after another clear → no mark); event-before-tab (settle with no tab → ledger recorded but no mark → `upsertQuickChatSessionFromEvent` adds the tab → replay the original event → still no mark; kanban session settle → ledger recorded, never a marker); stale-hydration between replay (settle → open clears → `deepMerge` regresses the row to RUNNING → replay the original event verbatim → no mark, ledger suppresses); turn-completed re-delivery with the pre-mutation `wasCompleted` snapshot (first delivery of a turn → marks when closed + tab exists; duplicate → no mark; duplicate after `openQuickChat` cleared → marker stays cleared); state_changed old_state fallback (known tab, no store row, `old_state: RUNNING` → IDLE → marks; with `old_state` absent → falls back to the store row); missing `updated_at` fail-closed (settle without `updated_at`, closed + tab exists → no mark, no ledger record; row regression + replay → still no mark); ledger bound (entry within the 60-minute window suppresses an event-before-tab replay; `pruneStaleSettledLedger(bySession, fixedNow)` evicts entries older than the window; eviction also runs on close/remove/reconcile/hydration paths with young entries preserved; re-arm still works after eviction); ledger monotonic max (settle t1 → settle t2 → open clears → row regressed → delayed t1 → no mark AND ledger stays t2; replay t2 → still no mark); ledger size cap (inserting beyond the 500-entry cap evicts the oldest entries by timestamp; entries within the cap retained); eviction-then-replay pin (a duplicate delivered after its generation was age-evicted or cap-evicted marks like a new settle — accepted, spec-qualified re-delivery guarantee); settle while open records the ledger but marks nothing, and its replay after close does not mark; receipt-time orderings (event while open → no mark; same event after close → mark); abandoned closure (turn.completed with `completed_at === started_at` for a known tab + closed dialog → marks — pins the intentional non-filtering).
|
||||
|
||||
- **Dependencies:** task 01 (actions `markQuickChatUnseenIdle` must exist).
|
||||
- **Parallelism:** sequential.
|
||||
|
||||
- **Inputs:**
|
||||
- Spec: What bullet 2, Failure modes (WS disconnect, event-before-tab).
|
||||
- Plan: "Marking hooks" section.
|
||||
- Existing code: `apps/web/lib/ws/handlers/agent-session.ts` (`registerTaskSessionHandlers` shape, `isStaleSessionStateEvent` guard, `existingSession?.state` before upsert), `apps/web/lib/ws/handlers/turns.ts` (`session.turn.completed` flow), `apps/web/hooks/domains/session/use-session-messages.ts` (`ACTIVE_SESSION_STATES` / `SETTLED_SESSION_STATES` values to mirror).
|
||||
|
||||
- **Output contract:** summary, files changed, tests run with counts, blockers, risks; update task + plan statuses in the same conversation.
|
||||
|
||||
## Results
|
||||
|
||||
Implemented state-transition and turn-completion marker hooks. Handler tests passed.
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
id: "03-entry-point-dots"
|
||||
title: "Entry-point dot rendering"
|
||||
status: complete
|
||||
wave: 2
|
||||
depends_on: ["01-unseen-idle-state"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/quick-chat-idle-dot/spec.md"
|
||||
---
|
||||
|
||||
# Task 03: Entry-point dot rendering
|
||||
|
||||
Render the decorative red dot on the five Quick Chat entry icons — sidebar
|
||||
rail item, sidebar shortcut, tablet header button, mobile header button, and
|
||||
mobile task-switcher sheet button — driven by
|
||||
`selectQuickChatHasUnseenIdle` for the active workspace.
|
||||
|
||||
- **Acceptance:**
|
||||
1. The sidebar rail Quick Chat item (`app-sidebar-primary-nav.tsx`, collapsed) shows the dot when the active workspace has an unseen idle session and not otherwise.
|
||||
2. The sidebar Quick Chat shortcut (`app-sidebar-new-task-item.tsx`, `sidebar-quick-chat-shortcut`) shows the dot on the `h-3.5 w-3.5` icon when unseen, not otherwise.
|
||||
3. The tablet header button (`tablet-quick-chat-button`), the mobile header button (`mobile-quick-chat-button`), and the mobile task-switcher sheet button (`mobile-sheet-quick-chat` in `session-task-switcher-sheet.tsx`) show the dot when unseen, not otherwise.
|
||||
4. The dot is `aria-hidden` with `data-testid="quick-chat-unseen-dot"`, positioned in the icon's top-right corner, and does not change button size, labels, or tooltips.
|
||||
|
||||
- **Verification:**
|
||||
```sh
|
||||
cd apps && pnpm --filter @kandev/web test -- --run \
|
||||
components/app-sidebar/app-sidebar-primary-nav.test.tsx \
|
||||
components/app-sidebar/app-sidebar-new-task-item.test.tsx \
|
||||
components/kanban/kanban-header-mobile.test.tsx \
|
||||
components/task/mobile/session-task-switcher-sheet.test.tsx
|
||||
```
|
||||
|
||||
- **Files likely touched:**
|
||||
- `apps/web/components/app-sidebar/app-sidebar-nav-item.tsx` — `dot?: boolean` prop; relative icon wrapper + absolute dot.
|
||||
- `apps/web/components/app-sidebar/app-sidebar-primary-nav.tsx` — pass `dot` to the Quick Chat nav item.
|
||||
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx` — `RowActionButton` `dot?: boolean`; pass to the Quick Chat shortcut.
|
||||
- `apps/web/components/kanban/kanban-header.tsx` (`TabletQuickActions`) — dot over `IconMessageCircle`.
|
||||
- `apps/web/components/kanban/kanban-header-mobile.tsx` — dot over `IconMessageCircle`.
|
||||
- `apps/web/components/task/mobile/session-task-switcher-sheet.tsx` (`TaskSwitcherSurfaceHeader`) — `dot` prop threading through the sheet header; dot over `IconMessageCircle` on `mobile-sheet-quick-chat`.
|
||||
- Tests: `app-sidebar-primary-nav.test.tsx`, `app-sidebar-new-task-item.test.tsx`, `kanban-header-mobile.test.tsx`, `session-task-switcher-sheet.test.tsx` — extend store fixtures with `quickChat.sessions` + `unseenIdleByWorkspace` (+ `lastSettledAtBySession` where the fixture constructs full `QuickChatState`). Note the existing mocked app-store states are minimal (e.g. `app-sidebar-primary-nav.test.tsx:9-12`, `app-sidebar-new-task-item.test.tsx:28-40`): they must gain `quickChat: { isOpen, sessions, unseenIdleByWorkspace, lastSettledAtBySession }` or the component's `selectQuickChatHasUnseenIdle` call reads undefined state.
|
||||
|
||||
- **Dependencies:** task 01 (selector `selectQuickChatHasUnseenIdle(state, workspaceId: string | null | undefined)` — callers pass nullish ids; the selector returns false for them). Task 02 is not required for rendering (the marker actions are consumed by tests), but the feature is only observable end-to-end after task 02 lands.
|
||||
- **Parallelism:** sequential.
|
||||
|
||||
- **Inputs:**
|
||||
- Spec: What bullets 1 and 5 (dot placement, decorative).
|
||||
- Plan: "Entry-point dots" section.
|
||||
- Existing patterns: dot styling like `agent-card-error-dot` (`h-2 w-2 rounded-full bg-red-500`) with a surface ring (`ring-2 ring-background`) so it reads over any background; `RowActionButton` body at `app-sidebar-new-task-item.tsx:48`.
|
||||
|
||||
- **Output contract:** summary, files changed, tests run with counts, blockers, risks; update task + plan statuses in the same conversation.
|
||||
|
||||
## Results
|
||||
|
||||
Rendered decorative markers on sidebar, tablet, mobile header, and task-switcher entries.
|
||||
Component tests passed.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
id: "04-idle-dot-e2e"
|
||||
title: "Idle dot E2E"
|
||||
status: complete
|
||||
wave: 3
|
||||
depends_on: ["02-ws-marking-hooks", "03-entry-point-dots"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/quick-chat-idle-dot/spec.md"
|
||||
---
|
||||
|
||||
# Task 04: Idle dot E2E
|
||||
|
||||
Playwright coverage for the dot lifecycle on the desktop, tablet, and mobile
|
||||
Quick Chat entry points.
|
||||
|
||||
- **Acceptance:**
|
||||
1. Chromium (desktop) `quick-chat-idle-dot.spec.ts`: no dot initially on `sidebar-quick-chat-shortcut`; after opening quick chat with the mock agent, sending `/slow 8s`, closing the dialog, and the session's `session.turn.completed` WS event firing, the dot is visible on the shortcut; reopening the dialog removes it; re-arm (spec scenario 5): arm a second completion wait, send a second message WHILE the dialog is open (the composer only accepts input while open), close the dialog while it is pending, await the completion, THEN the dot is visible again.
|
||||
2. Chromium (tablet) same lifecycle against `tablet-quick-chat-button`, using the `tabletTestPage` fixture (900×900, `hasTouch: true`) — a fine-pointer desktop context at ~1024 renders compact desktop, not the tablet header.
|
||||
3. Mobile-chrome `mobile-quick-chat-idle-dot.spec.ts` (the `mobile-chrome` project collects only `mobile-*.spec.ts`): same lifecycle against `mobile-quick-chat-button` (tap-driven, `quick-chat-close`), plus the task-switcher sheet entry — markers are ephemeral and lost on `page.goto`, so navigation must precede marker creation: seed a task (`apiClient.seedTask`, pattern `mobile-quick-chat-entry.spec.ts`), navigate to `/t/${taskId}` and wait for the session page, tap `mobile-sheet-quick-chat` (opens the Quick Chat setup dialog), select an agent, arm the waitForResponse for `POST /api/v1/workspaces/<id>/quick-chat` immediately BEFORE clicking `quick-chat-start` (the sheet tap opens setup; the POST fires on `quick-chat-start` — see `quick-chat-helpers.ts:53-56`), capture `session_id` from the response, send `/slow 8s`, close the dialog, await the completion, reopen the sheet, and assert the dot on `mobile-sheet-quick-chat`.
|
||||
|
||||
- **Verification:**
|
||||
```sh
|
||||
cd apps/web && pnpm e2e:raw -g "quick chat idle dot" \
|
||||
&& pnpm e2e:raw --project=mobile-chrome -g "quick chat idle dot"
|
||||
```
|
||||
(Fresh worktree bootstrap when deps are missing: `cd apps && pnpm install --frozen-lockfile` first.)
|
||||
|
||||
- **Files likely touched:**
|
||||
- `apps/web/e2e/tests/chat/quick-chat-idle-dot.spec.ts` — new desktop/tablet spec.
|
||||
- `apps/web/e2e/tests/chat/mobile-quick-chat-idle-dot.spec.ts` — new mobile spec (name must match `mobile-*.spec.ts` for the `mobile-chrome` project); includes the `mobile-sheet-quick-chat` assertion via the task switcher sheet flow from `mobile-quick-chat-entry.spec.ts`.
|
||||
- Reuse `apps/web/e2e/tests/chat/quick-chat-helpers.ts` (`openQuickChatWithAgent`, `sendQuickChatMessage`) and `apps/web/e2e/helpers/causal-waits.ts` (`watchWs`). Capture `session_id` AND `task_id` from the `POST /api/v1/workspaces/<id>/quick-chat` response yourself (pattern: `apps/web/e2e/tests/chat/entity-reference-composer.spec.ts:201-213` — the shared helpers return only the dialog).
|
||||
- Tablet fixtures: `tabletTestPage` from `apps/web/e2e/fixtures/test-base.ts` (or a context with viewport <1024 and `hasTouch: true`).
|
||||
|
||||
- **WS arming order (required, see `causal-waits.ts`):** call `watchWs(page)` BEFORE the first `page.goto()`, then arm each `const completed = ws.waitForEvent("session.turn.completed", { where: (p) => p.session_id === sessionId })` BEFORE the message send that triggers it. `watchWs` buffers nothing and the gateway has no replay on subscribe — a wait armed after the event fires times out. First cycle: send `/slow 8s`, close the dialog while `completed` is pending, then `await completed` and assert the dot. Re-arm cycle: reopen (dot clears), arm a fresh `waitForEvent`, send the second message while the dialog is open, close the dialog, `await completed`, assert the dot again.
|
||||
- **Scoped dot locators (required):** `quick-chat-unseen-dot` is rendered by all five entry points simultaneously once a marker is active, so every assertion must scope it under the entry under test — e.g. `testPage.getByTestId("sidebar-quick-chat-shortcut").getByTestId("quick-chat-unseen-dot")` — never a page-level `getByTestId("quick-chat-unseen-dot")` (Playwright strict mode). Assert each surface individually where the spec requires it.
|
||||
- **Session capture:** capture `session_id` from the `POST /api/v1/workspaces/<id>/quick-chat` response for the WS predicates (see `apps/web/lib/api/domains/workspace-api.ts`; the response also carries `task_id`). In the mobile sheet flow the quick chat is started from the sheet, so the capture must wrap that launch, and the `/t/${taskId}` navigation must happen BEFORE any marker is created (markers are ephemeral, lost on `page.goto`).
|
||||
|
||||
- **Dependencies:** tasks 02 and 03 (the dot must appear from real WS events).
|
||||
- **Parallelism:** sequential.
|
||||
|
||||
- **Inputs:**
|
||||
- Spec: Scenarios 1, 2, 3, 4, 5.
|
||||
- Plan: "E2E Tests" section.
|
||||
- Existing patterns: `apps/web/e2e/tests/chat/message-queue.spec.ts` (`/slow` command + `Agent is (starting|running)` status wait), `apps/web/e2e/tests/chat/mobile-quick-chat-entry.spec.ts` (mobile tap + `quick-chat-close`), `apps/web/e2e/playwright.config.ts` (project `testMatch` conventions), `apps/web/e2e/README.md` (project selection, causal waits).
|
||||
|
||||
- **Output contract:** summary, files changed, commands + outcomes, blockers, risks; update task + plan statuses in the same conversation.
|
||||
|
||||
## Results
|
||||
|
||||
Added desktop, tablet, mobile-header, and mobile task-switcher lifecycle coverage. Chromium
|
||||
and mobile-chrome targeted E2E runs passed.
|
||||
@@ -284,6 +284,7 @@ System pages (Radarr/Sonarr-style) for status, disk usage, database maintenance,
|
||||
| [claude-fork-review-allowlist](claude-fork-review-allowlist/spec.md) | building |
|
||||
| [workflow-settings-autosave](workflow-settings-autosave/spec.md) | archived; superseded by settings-manual-save |
|
||||
| [mobile-quick-chat-topbar](mobile-quick-chat-topbar/spec.md) | building |
|
||||
| [quick-chat-idle-dot](quick-chat-idle-dot/spec.md) | draft |
|
||||
| [native-code-review](native-code-review/spec.md) | building |
|
||||
| [missing-task-route-recovery](missing-task-route-recovery/spec.md) | draft |
|
||||
| [browser-inspect-annotations-save](browser-inspect-annotations-save/spec.md) | shipped |
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
status: draft
|
||||
created: 2026-08-16
|
||||
owner: kandev
|
||||
---
|
||||
|
||||
# Quick Chat Idle Dot
|
||||
|
||||
## Why
|
||||
|
||||
Quick chat sessions keep running after the user closes the dialog. A session's
|
||||
turn can finish while the chat window is out of view, and nothing tells the
|
||||
user the agent has answered. Replies are missed until the user happens to
|
||||
reopen the dialog.
|
||||
|
||||
## What
|
||||
|
||||
- Each Quick Chat entry icon in the active workspace — the sidebar rail Quick
|
||||
Chat item, the sidebar Quick Chat shortcut, the tablet kanban header button,
|
||||
the mobile kanban header button, and the mobile task-switcher sheet button —
|
||||
shows a small red dot in the icon's corner while the Quick Chat dialog is
|
||||
closed and at least one quick chat session of that workspace has completed a
|
||||
turn (or settled to idle) since the dialog was last open.
|
||||
- A turn that completes while the dialog is open does NOT raise a dot; the
|
||||
user is looking at the chat window.
|
||||
- Opening the Quick Chat dialog clears every dot. Closing it re-arms tracking:
|
||||
a later turn completion while closed raises the dot again.
|
||||
- The dot is per-workspace: only sessions belonging to the active workspace
|
||||
contribute to that workspace's entry icons.
|
||||
- A session whose tab is closed or whose backing task is deleted stops
|
||||
contributing immediately.
|
||||
- The dot is decorative (`aria-hidden`). Button labels, tooltips, and the
|
||||
dialog itself are unchanged.
|
||||
|
||||
## State machine
|
||||
|
||||
The unseen marker is a client-only, ephemeral flag keyed per (workspace,
|
||||
session id): `unseenIdleByWorkspace[workspaceId][sessionId]`. Workspace
|
||||
ownership lives in the key, so it survives hydration of a different
|
||||
workspace's session list.
|
||||
|
||||
| State | Transition | Trigger | Actor |
|
||||
|---|---|---|---|
|
||||
| unmarked | marked | `session.state_changed` settles an active session (STARTING/RUNNING → IDLE/WAITING_FOR_INPUT/COMPLETED/FAILED/CANCELLED) or `session.turn.completed` arrives, while the dialog is closed, for a session known to `quickChat.sessions` (workspace taken from that tab entry) | WS handler |
|
||||
| marked | unmarked | dialog opens (`openQuickChat`) — all workspaces | user |
|
||||
| marked | unmarked | session becomes the active dialog tab | user |
|
||||
| marked | unmarked | session tab closed or backing task deleted | user / sync |
|
||||
| marked | unmarked | revision-guarded server resync removes the session from its workspace's list | resync |
|
||||
|
||||
## Failure modes
|
||||
|
||||
- **WS disconnected**: `session.state_changed` / `session.turn.completed` are
|
||||
live broadcasts; a turn that completes while the socket is down is never
|
||||
delivered and no dot is raised. There is no backfill. The dot is a
|
||||
best-effort cue, not a reliable delivery ledger.
|
||||
- **Race: event before tab**: a settle event for a session whose tab is not
|
||||
yet in `quickChat.sessions` (e.g. the `task.created` tab arrives after the
|
||||
session already settled) does not raise a dot. The user never saw that chat
|
||||
window, so no dot is the conservative outcome.
|
||||
- **Re-delivery**: a re-delivered `session.turn.completed` (reconnect replay,
|
||||
duplicate broadcast) for a turn already recorded as completed does not raise
|
||||
a dot — not after the tab arrives, and not after the dialog was opened and
|
||||
cleared the marker. Only a genuinely new turn completion raises the dot.
|
||||
For `session.state_changed` the same guarantee holds within the settle
|
||||
ledger's retention: the generation (`updated_at`) is kept per session for a
|
||||
60-minute window (max 500 sessions); a duplicate delivered after its
|
||||
generation was evicted (aged out or capped out) MAY raise a dot — accepted
|
||||
bounded-memory tradeoff, since practical replay windows are seconds; the dot
|
||||
self-heals on the next dialog open.
|
||||
- **Abandoned turns**: `AbandonOpenTurns` (session resume/startup cleanup,
|
||||
rejected-message cleanup) publishes `session.turn.completed` for orphan
|
||||
turns whose `completed_at` equals `started_at` — the backend already
|
||||
recognizes this shape (`isAbandonedTurnCompletion` in
|
||||
`apps/backend/internal/backendapp/gateway.go`), so a discriminator EXISTS in
|
||||
the payload. The marker treats these uniformly with live completions and
|
||||
deliberately does NOT filter on it: the session did settle to idle, and the
|
||||
`session.state_changed` settle transition raises the same signal, so
|
||||
excluding abandoned closures would not prevent the dot anyway. This is an
|
||||
intentional product decision, pinned by a test; filtering is out of scope.
|
||||
- **Receipt-time semantics**: the marker reflects events handled while the
|
||||
dialog is closed, not the instant the turn completed. `session.state_changed`
|
||||
and `session.turn.completed` travel over separate event-bus subscriptions
|
||||
and the gateway broadcasts both to every connected client (the payloads
|
||||
carry no `workspace_id`, so the workspace-broadcast path falls back to
|
||||
global delivery); per-workspace dots rely on session-tab membership and the
|
||||
selector, not transport scoping. Their relative order is not guaranteed; a
|
||||
completion notification handled while the dialog is open never marks, and
|
||||
one handled after the dialog closed marks, even if the turn itself finished
|
||||
earlier. The false-positive window is one notification round-trip and
|
||||
self-heals on the next dialog open.
|
||||
|
||||
## Scenarios
|
||||
|
||||
- **GIVEN** no quick chat session in the active workspace, **WHEN** the app
|
||||
renders, **THEN** no Quick Chat entry icon shows a dot.
|
||||
- **GIVEN** a quick chat session with a running turn and the dialog closed,
|
||||
**WHEN** the turn completes (the session settles to an idle state), **THEN**
|
||||
a red dot appears on every Quick Chat entry icon of that workspace.
|
||||
- **GIVEN** a quick chat session with a running turn, **WHEN** the turn
|
||||
completes while the dialog is open, **THEN** no dot appears for that turn.
|
||||
- **GIVEN** a dot showing, **WHEN** the user opens the Quick Chat dialog,
|
||||
**THEN** the dot disappears.
|
||||
- **GIVEN** a dot cleared by opening the dialog, **WHEN** the same session
|
||||
later completes another turn while the dialog is closed, **THEN** the dot
|
||||
reappears.
|
||||
- **GIVEN** an unseen idle session in workspace A and none in workspace B,
|
||||
**WHEN** the user switches to workspace B, **THEN** workspace B's entry
|
||||
icons show no dot.
|
||||
- **GIVEN** a dot contributed by one session, **WHEN** that session's tab is
|
||||
closed or its backing task is deleted, **THEN** the dot disappears.
|
||||
- **GIVEN** a quick chat session tab that has never completed a turn,
|
||||
**WHEN** the page reloads, **THEN** no dot shows (markers are ephemeral and
|
||||
not persisted).
|
||||
|
||||
## Out of scope
|
||||
|
||||
- No persistence: markers reset on page reload (scenario above).
|
||||
- No new copy, tooltips, sounds, or banner notifications.
|
||||
- No dot on the command-palette Quick Chat item or the config-chat floating
|
||||
panel.
|
||||
- No backend changes: the existing global broadcasts of
|
||||
`session.state_changed` and `session.turn.completed` are the only signals.
|
||||
- No change to quick chat session creation, tab sync, or dialog behavior.
|
||||
Reference in New Issue
Block a user