"use client"; import { useEffect, useState, useSyncExternalStore } from "react"; import { RECOVERY_PRINCIPAL_CHANGED, recoveryPrincipal } from "@/lib/recovery-principal"; import { subscribeSessionChanges } from "@/lib/session-events"; import { listWorkspaces, type ChatWorkspaceRegistration } from "@/lib/workspaces-api"; import { readCachedChatWorkspaces, writeCachedChatWorkspaces, workspaceCacheGeneration, } from "@/lib/chat-workspaces-cache"; type WorkspaceList = { owner: string | null; rows: ChatWorkspaceRegistration[]; error: string }; let latestRequest = 0; function subscribePrincipal(notify: () => void) { window.addEventListener(RECOVERY_PRINCIPAL_CHANGED, notify); return () => window.removeEventListener(RECOVERY_PRINCIPAL_CHANGED, notify); } function initialList(owner: string | null): WorkspaceList { return { owner, rows: readCachedChatWorkspaces(owner), error: "" }; } export function useChatWorkspaces() { const owner = useSyncExternalStore(subscribePrincipal, recoveryPrincipal, () => null); const [list, setList] = useState(() => initialList(owner)); useEffect(() => { let alive = true; let requested = 0; async function refresh() { const request = ++latestRequest; const generation = workspaceCacheGeneration(); requested = request; const current = () => alive && request === requested && recoveryPrincipal() === owner && generation === workspaceCacheGeneration(); try { const rows = await listWorkspaces(true); if (!current()) return; const next = { owner, rows: rows.filter((row) => row.kind === "workspace"), error: "" }; if (owner && request === latestRequest) writeCachedChatWorkspaces(owner, next.rows); setList(next); } catch (err) { if (current()) setList((last) => ({ ...last, error: err instanceof Error ? err.message : String(err), })); } } setList(initialList(owner)); void refresh(); const unsubscribe = subscribeSessionChanges(refresh); return () => { alive = false; unsubscribe(); }; }, [owner]); const visible = list.owner === owner ? list : initialList(owner); return { workspaces: visible.rows, error: visible.error }; }