From cecfbcf648908ec186902ad328f1909a02847b0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= Date: Wed, 6 May 2026 01:28:13 +0100 Subject: [PATCH] refactor(web): extract shared use-session-actions hook from SessionTab Move WS-level session lifecycle handlers (set primary, stop, resume, delete) into hooks/domains/session/use-session-actions so the same logic can power both the dockview tab context menu and upcoming mobile controls. Dockview-specific panel removal stays local in SessionTab via the onDeleted callback. --- apps/web/components/task/session-tab.tsx | 102 ++--------- .../session/use-session-actions.test.ts | 163 ++++++++++++++++++ .../domains/session/use-session-actions.ts | 112 ++++++++++++ 3 files changed, 290 insertions(+), 87 deletions(-) create mode 100644 apps/web/hooks/domains/session/use-session-actions.test.ts create mode 100644 apps/web/hooks/domains/session/use-session-actions.ts diff --git a/apps/web/components/task/session-tab.tsx b/apps/web/components/task/session-tab.tsx index b8b1be84f3..0412d78606 100644 --- a/apps/web/components/task/session-tab.tsx +++ b/apps/web/components/task/session-tab.tsx @@ -21,22 +21,16 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@kandev/ui/alert-dialog"; -import { useAppStore, useAppStoreApi } from "@/components/state-provider"; -import { useToast } from "@/components/toast-provider"; -import { getWebSocketClient } from "@/lib/ws/connection"; +import { useAppStore } from "@/components/state-provider"; +import { + useSessionActions, + isSessionStoppable as isStoppable, + isSessionDeletable as isDeletable, + isSessionResumable as isResumable, +} from "@/hooks/domains/session/use-session-actions"; import type { TaskSessionState } from "@/lib/types/http"; import { useTabMaximizeOnDoubleClick } from "./use-tab-maximize"; -function isStoppable(s: TaskSessionState) { - return s === "RUNNING" || s === "STARTING" || s === "WAITING_FOR_INPUT"; -} -function isDeletable(s: TaskSessionState) { - return s !== "RUNNING" && s !== "STARTING"; -} -function isResumable(s: TaskSessionState) { - return s === "COMPLETED" || s === "FAILED" || s === "CANCELLED"; -} - function useSessionTabState(sessionId: string | undefined) { const isPrimary = useAppStore((state) => { const activeTaskId = state.tasks.activeTaskId; @@ -98,86 +92,20 @@ function useSessionTabActions( api: IDockviewPanelHeaderProps["api"], containerApi: IDockviewPanelHeaderProps["containerApi"], ) { - const { toast, updateToast } = useToast(); - const removeTaskSession = useAppStore((state) => state.removeTaskSession); - const appStoreApi = useAppStoreApi(); - - const wsAction = useCallback( - async ( - action: string, - label: string, - payload: Record, - timeout = 15000, - ): Promise => { - const client = getWebSocketClient(); - if (!client) return false; - const toastId = toast({ title: `${label}...`, variant: "loading" }); - try { - await client.request(action, payload, timeout); - updateToast(toastId, { title: `${label} successful`, variant: "success" }); - return true; - } catch (error) { - const msg = error instanceof Error ? error.message : "Unknown error"; - updateToast(toastId, { title: `${label} failed`, description: msg, variant: "error" }); - return false; - } - }, - [toast, updateToast], - ); - - const handleSetPrimary = useCallback( - () => sessionId && wsAction("session.set_primary", "Set primary", { session_id: sessionId }), - [sessionId, wsAction], - ); - const handleStop = useCallback( - () => sessionId && wsAction("session.stop", "Stopping session", { session_id: sessionId }), - [sessionId, wsAction], - ); - const handleResume = useCallback( - () => - sessionId && - taskId && - wsAction( - "session.launch", - "Resuming session", - { task_id: taskId, intent: "resume", session_id: sessionId }, - 30000, - ), - [sessionId, taskId, wsAction], - ); - const handleDelete = useCallback(async () => { - if (!sessionId || !taskId) return; - // Only mutate local state once the backend confirms the delete — otherwise - // a transient WS failure leaves the UI desynced from the server. - const ok = await wsAction("session.delete", "Deleting session", { session_id: sessionId }); - if (!ok) return; - - // Switch the active session BEFORE removing from the store so - // useAutoSessionTab doesn't re-create this panel with the deleted session's ID. - // Hand off to the most-recently-started remaining session — store ordering - // is unspecified, so sort explicitly rather than rely on array position. - const state = appStoreApi.getState(); - if (state.tasks.activeSessionId === sessionId) { - const sessions = state.taskSessionsByTask.itemsByTaskId[taskId] ?? []; - const remaining = sessions - .filter((s) => s.id !== sessionId) - .sort((a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime()); - if (remaining.length > 0) { - state.setActiveSessionAuto(taskId, remaining[0].id); - } else { - state.clearActiveSession(); - } - } - - removeTaskSession(taskId, sessionId); + const onDeleted = useCallback(() => { const panel = containerApi.getPanel(api.id); if (panel) containerApi.removePanel(panel); - }, [sessionId, taskId, wsAction, removeTaskSession, api.id, containerApi, appStoreApi]); + }, [api.id, containerApi]); + const { + setPrimary: handleSetPrimary, + stop: handleStop, + resume: handleResume, + remove: handleDelete, + } = useSessionActions({ sessionId, taskId, onDeleted }); const handleCloseOthers = useCallback(() => { const toClose = api.group.panels.filter((p) => p.id !== api.id); for (const panel of toClose) containerApi.removePanel(panel); }, [api, containerApi]); - return { handleSetPrimary, handleStop, handleResume, handleDelete, handleCloseOthers }; } diff --git a/apps/web/hooks/domains/session/use-session-actions.test.ts b/apps/web/hooks/domains/session/use-session-actions.test.ts new file mode 100644 index 0000000000..48a037a62e --- /dev/null +++ b/apps/web/hooks/domains/session/use-session-actions.test.ts @@ -0,0 +1,163 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderHook, waitFor } from "@testing-library/react"; +import { + isSessionStoppable, + isSessionDeletable, + isSessionResumable, + useSessionActions, +} from "./use-session-actions"; + +const mockToast = vi.fn().mockReturnValue("toast-1"); +const mockUpdateToast = vi.fn(); +const mockRequest = vi.fn(); +const mockRemoveTaskSession = vi.fn(); +const mockSetActiveSessionAuto = vi.fn(); +const mockClearActiveSession = vi.fn(); + +let mockState: Record = {}; + +vi.mock("@/components/toast-provider", () => ({ + useToast: () => ({ toast: mockToast, updateToast: mockUpdateToast }), +})); + +vi.mock("@/lib/ws/connection", () => ({ + getWebSocketClient: () => ({ request: mockRequest }), +})); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: Record) => unknown) => + selector({ + removeTaskSession: mockRemoveTaskSession, + }), + useAppStoreApi: () => ({ + getState: () => mockState, + }), +})); + +describe("session state predicates", () => { + it("isSessionStoppable returns true for active states", () => { + expect(isSessionStoppable("RUNNING")).toBe(true); + expect(isSessionStoppable("STARTING")).toBe(true); + expect(isSessionStoppable("WAITING_FOR_INPUT")).toBe(true); + expect(isSessionStoppable("COMPLETED")).toBe(false); + expect(isSessionStoppable("FAILED")).toBe(false); + }); + + it("isSessionDeletable returns false for in-flight states", () => { + expect(isSessionDeletable("RUNNING")).toBe(false); + expect(isSessionDeletable("STARTING")).toBe(false); + expect(isSessionDeletable("WAITING_FOR_INPUT")).toBe(true); + expect(isSessionDeletable("COMPLETED")).toBe(true); + expect(isSessionDeletable("FAILED")).toBe(true); + }); + + it("isSessionResumable returns true for terminal states", () => { + expect(isSessionResumable("COMPLETED")).toBe(true); + expect(isSessionResumable("FAILED")).toBe(true); + expect(isSessionResumable("CANCELLED")).toBe(true); + expect(isSessionResumable("RUNNING")).toBe(false); + expect(isSessionResumable("STARTING")).toBe(false); + }); +}); + +describe("useSessionActions", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockToast.mockReturnValue("toast-1"); + mockRequest.mockResolvedValue(undefined); + mockState = { + tasks: { activeSessionId: null }, + taskSessionsByTask: { itemsByTaskId: {} }, + setActiveSessionAuto: mockSetActiveSessionAuto, + clearActiveSession: mockClearActiveSession, + }; + }); + + it("setPrimary dispatches session.set_primary with session id", async () => { + const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" })); + await result.current.setPrimary(); + expect(mockRequest).toHaveBeenCalledWith("session.set_primary", { session_id: "s1" }, 15000); + }); + + it("stop dispatches session.stop", async () => { + const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" })); + await result.current.stop(); + expect(mockRequest).toHaveBeenCalledWith("session.stop", { session_id: "s1" }, 15000); + }); + + it("resume dispatches session.launch with intent=resume and 30s timeout", async () => { + const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" })); + await result.current.resume(); + expect(mockRequest).toHaveBeenCalledWith( + "session.launch", + { task_id: "t1", intent: "resume", session_id: "s1" }, + 30000, + ); + }); + + it("remove deletes via WS, removes from store, and runs onDeleted callback", async () => { + const onDeleted = vi.fn(); + const { result } = renderHook(() => + useSessionActions({ sessionId: "s1", taskId: "t1", onDeleted }), + ); + await result.current.remove(); + await waitFor(() => expect(onDeleted).toHaveBeenCalled()); + expect(mockRequest).toHaveBeenCalledWith("session.delete", { session_id: "s1" }, 15000); + expect(mockRemoveTaskSession).toHaveBeenCalledWith("t1", "s1"); + }); + + it("remove no-ops when WS request fails (store untouched)", async () => { + mockRequest.mockRejectedValueOnce(new Error("network down")); + const onDeleted = vi.fn(); + const { result } = renderHook(() => + useSessionActions({ sessionId: "s1", taskId: "t1", onDeleted }), + ); + await result.current.remove(); + expect(mockRemoveTaskSession).not.toHaveBeenCalled(); + expect(onDeleted).not.toHaveBeenCalled(); + }); + + it("remove hands off to most-recent remaining session when active was deleted", async () => { + mockState = { + tasks: { activeSessionId: "s1" }, + taskSessionsByTask: { + itemsByTaskId: { + t1: [ + { id: "s1", started_at: "2025-01-01T00:00:00Z" }, + { id: "s2", started_at: "2025-01-02T00:00:00Z" }, + { id: "s3", started_at: "2025-01-03T00:00:00Z" }, + ], + }, + }, + setActiveSessionAuto: mockSetActiveSessionAuto, + clearActiveSession: mockClearActiveSession, + }; + const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" })); + await result.current.remove(); + expect(mockSetActiveSessionAuto).toHaveBeenCalledWith("t1", "s3"); + expect(mockClearActiveSession).not.toHaveBeenCalled(); + }); + + it("remove clears active session when no other sessions remain", async () => { + mockState = { + tasks: { activeSessionId: "s1" }, + taskSessionsByTask: { + itemsByTaskId: { t1: [{ id: "s1", started_at: "2025-01-01T00:00:00Z" }] }, + }, + setActiveSessionAuto: mockSetActiveSessionAuto, + clearActiveSession: mockClearActiveSession, + }; + const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" })); + await result.current.remove(); + expect(mockClearActiveSession).toHaveBeenCalled(); + expect(mockSetActiveSessionAuto).not.toHaveBeenCalled(); + }); + + it("actions no-op when sessionId is missing", async () => { + const { result } = renderHook(() => useSessionActions({ sessionId: null, taskId: "t1" })); + await result.current.setPrimary(); + await result.current.stop(); + await result.current.remove(); + expect(mockRequest).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/hooks/domains/session/use-session-actions.ts b/apps/web/hooks/domains/session/use-session-actions.ts new file mode 100644 index 0000000000..1124af35e8 --- /dev/null +++ b/apps/web/hooks/domains/session/use-session-actions.ts @@ -0,0 +1,112 @@ +"use client"; + +import { useCallback } from "react"; +import { useAppStore, useAppStoreApi } from "@/components/state-provider"; +import { useToast } from "@/components/toast-provider"; +import { getWebSocketClient } from "@/lib/ws/connection"; +import type { TaskSessionState } from "@/lib/types/http"; + +export function isSessionStoppable(s: TaskSessionState): boolean { + return s === "RUNNING" || s === "STARTING" || s === "WAITING_FOR_INPUT"; +} +export function isSessionDeletable(s: TaskSessionState): boolean { + return s !== "RUNNING" && s !== "STARTING"; +} +export function isSessionResumable(s: TaskSessionState): boolean { + return s === "COMPLETED" || s === "FAILED" || s === "CANCELLED"; +} + +type SessionActionsArgs = { + sessionId: string | null | undefined; + taskId: string | null; + /** Optional callback after a successful delete (e.g. close a tab/panel). */ + onDeleted?: () => void; +}; + +type WsActionFn = ( + action: string, + label: string, + payload: Record, + timeout?: number, +) => Promise; + +function useWsAction(): WsActionFn { + const { toast, updateToast } = useToast(); + return useCallback( + async (action, label, payload, timeout = 15000) => { + const client = getWebSocketClient(); + if (!client) return false; + const toastId = toast({ title: `${label}...`, variant: "loading" }); + try { + await client.request(action, payload, timeout); + updateToast(toastId, { title: `${label} successful`, variant: "success" }); + return true; + } catch (error) { + const msg = error instanceof Error ? error.message : "Unknown error"; + updateToast(toastId, { title: `${label} failed`, description: msg, variant: "error" }); + return false; + } + }, + [toast, updateToast], + ); +} + +/** + * Shared lifecycle actions for a session (set-primary, stop, resume, delete). + * Handles backend coordination + local store cleanup. Caller can pass + * `onDeleted` to perform UI-specific teardown (e.g. dockview panel removal). + */ +export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActionsArgs) { + const wsAction = useWsAction(); + const removeTaskSession = useAppStore((state) => state.removeTaskSession); + const appStoreApi = useAppStoreApi(); + + const setPrimary = useCallback( + () => sessionId && wsAction("session.set_primary", "Set primary", { session_id: sessionId }), + [sessionId, wsAction], + ); + + const stop = useCallback( + () => sessionId && wsAction("session.stop", "Stopping session", { session_id: sessionId }), + [sessionId, wsAction], + ); + + const resume = useCallback( + () => + sessionId && + taskId && + wsAction( + "session.launch", + "Resuming session", + { task_id: taskId, intent: "resume", session_id: sessionId }, + 30000, + ), + [sessionId, taskId, wsAction], + ); + + const remove = useCallback(async () => { + if (!sessionId || !taskId) return; + const ok = await wsAction("session.delete", "Deleting session", { session_id: sessionId }); + if (!ok) return; + + // Switch the active session BEFORE removing from the store so callers + // observing activeSessionId don't briefly point at a deleted session. + const state = appStoreApi.getState(); + if (state.tasks.activeSessionId === sessionId) { + const sessions = state.taskSessionsByTask.itemsByTaskId[taskId] ?? []; + const remaining = sessions + .filter((s) => s.id !== sessionId) + .sort((a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime()); + if (remaining.length > 0) { + state.setActiveSessionAuto(taskId, remaining[0].id); + } else { + state.clearActiveSession(); + } + } + + removeTaskSession(taskId, sessionId); + onDeleted?.(); + }, [sessionId, taskId, wsAction, removeTaskSession, appStoreApi, onDeleted]); + + return { setPrimary, stop, resume, remove }; +}