| 1 | import { useState } from "react"; |
| 2 | import type { Translator } from "../lib/i18n"; |
| 3 | import { useCommittedCommand } from "../lib/useCommittedCommand"; |
| 4 | import type { useSessionOperations } from "./useSessionOperations"; |
| 5 | |
| 6 | export type SessionClearCommandsInput = { |
| 7 | activeTabId: string | undefined; |
| 8 | activeSessionIdentity: string; |
| 9 | remote: boolean; |
| 10 | t: Translator; |
| 11 | notice: (text: string, level?: "info" | "warn") => void; |
| 12 | operations: ReturnType<typeof useSessionOperations>; |
| 13 | refreshDock(): void; |
| 14 | ports: { |
| 15 | clearSession(): Promise<void>; |
| 16 | clearRemoteSession(tabId: string): Promise<void>; |
| 17 | retryRemoteHydration(): Promise<void>; |
| 18 | }; |
| 19 | }; |
| 20 | |
| 21 | /** |
| 22 | * Owns the clear-context decision surface: the pending flag, its cancel and |
| 23 | * the confirm chain — target capture at click time, sessionRuntimeOwner |
| 24 | * execution under the session operations authority, dock refresh plus notice |
| 25 | * on commit, and a warning notice on failure. Tab switches and session |
| 26 | * replacement still reset the flag through the returned setter. The runtime |
| 27 | * owner chunk stays lazy behind the confirm. |
| 28 | */ |
| 29 | export function useSessionClearCommands(input: SessionClearCommandsInput) { |
| 30 | const { activeTabId, activeSessionIdentity, t, notice, operations, ports } = input; |
| 31 | const [clearContextPending, setClearContextPending] = useState(false); |
| 32 | |
| 33 | const cancelClearContext = useCommittedCommand(() => { |
| 34 | setClearContextPending(false); |
| 35 | }); |
| 36 | |
| 37 | const confirmClearContext = useCommittedCommand(async () => { |
| 38 | const target = activeTabId ? { tabId: activeTabId, sessionKey: activeSessionIdentity } : null; |
| 39 | if (!target) return; |
| 40 | setClearContextPending(false); |
| 41 | const outcome = await operations(target, "clear-context", { remote: input.remote }, async (operationInput, authority) => |
| 42 | (await import("./sessionRuntimeOwner")).executeClearSession(target, operationInput, ports, authority), |
| 43 | ); |
| 44 | if (outcome.status === "completed") { |
| 45 | input.refreshDock(); |
| 46 | notice(t("clearContext.done")); |
| 47 | } else if (outcome.status === "failed") { |
| 48 | const message = outcome.error instanceof Error ? outcome.error.message : String(outcome.error); |
| 49 | notice(message || t("clearContext.failed"), "warn"); |
| 50 | } |
| 51 | }); |
| 52 | |
| 53 | return { clearContextPending, setClearContextPending, cancelClearContext, confirmClearContext }; |
| 54 | } |
| 55 |