"use client"; import { createContext, useCallback, useContext, useEffect, useRef, type ReactNode, } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { getSubspaceScopeId, useSubspaceHistory, } from "@/hooks/use-subspace-history"; import { clearActiveSubspace, readActiveSubspace, writeActiveSubspace, } from "@/lib/subspace-history"; import { useDataScopeKey } from "@/providers/runtime-context-provider"; type ActiveSubspaceStorage = Pick< Storage, "getItem" | "setItem" | "removeItem" >; const unavailableSessionStorage: ActiveSubspaceStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {}, }; export function getSessionStorage(): ActiveSubspaceStorage { try { return window.sessionStorage; } catch { return unavailableSessionStorage; } } export interface SubspaceContextValue { subspace: string | null; setSubspace: (subspace: string) => void; clearSubspace: () => void; history: string[]; addToHistory: (subspace: string) => void; clearHistory: () => void; } export const SubspaceContext = createContext(null); /** * Strict accessor — throws when called outside of a SubspaceProvider. Use this * inside subtrees that always sit under the provider (e.g. DocumentsClient). */ export function useSubspace(): SubspaceContextValue { const context = useContext(SubspaceContext); if (!context) { throw new Error("useSubspace must be used within a SubspaceProvider"); } return context; } /** * Optional accessor — returns null when no SubspaceProvider is mounted. Use * this in components that may render both inside and outside the KB detail * layout (e.g. KBHeader, which is also used on the KB list page). */ export function useSubspaceOptional(): SubspaceContextValue | null { return useContext(SubspaceContext); } interface SubspaceProviderProps { knowledgeBaseName: string; children: ReactNode; } export interface ActiveSubspaceReconcileState { scopeId: string | null; pendingRestore: string | null; } export type ActiveSubspaceReconcileResult = { state: ActiveSubspaceReconcileState; effect: | { type: "restore"; subspace: string } | { type: "persist"; subspace: string } | { type: "clear" } | { type: "none" }; }; export function reconcileActiveSubspace( state: ActiveSubspaceReconcileState, scopeId: string, urlSubspace: string | null, storedSubspace: string | null, ): ActiveSubspaceReconcileResult { if (state.scopeId !== scopeId) { if (urlSubspace) { return { state: { scopeId, pendingRestore: null }, effect: { type: "persist", subspace: urlSubspace }, }; } if (storedSubspace) { return { state: { scopeId, pendingRestore: storedSubspace }, effect: { type: "restore", subspace: storedSubspace }, }; } return { state: { scopeId, pendingRestore: null }, effect: { type: "clear" }, }; } if (state.pendingRestore && !urlSubspace) { return { state, effect: { type: "none" } }; } if (urlSubspace) { return { state: { scopeId, pendingRestore: null }, effect: { type: "persist", subspace: urlSubspace }, }; } return { state: { scopeId, pendingRestore: null }, effect: { type: "clear" }, }; } /** * Subspace state container backed by the URL as the single source of truth. * The `?subspace=` query parameter drives every read; writes only call * router.replace and let the URL change propagate. A per-tab sessionStorage * preference is reconciled into the URL once per runtime/KB identity so * revisiting without a query string lands on the previously chosen scope. */ export function SubspaceProvider({ knowledgeBaseName, children, }: SubspaceProviderProps) { const searchParams = useSearchParams(); const searchParamsKey = searchParams.toString(); const pathname = usePathname(); const router = useRouter(); const dataScopeKey = useDataScopeKey(); const { history, addToHistory, clearHistory } = useSubspaceHistory( dataScopeKey, knowledgeBaseName, ); const activeScopeId = getSubspaceScopeId(dataScopeKey, knowledgeBaseName); // URL is the single source of truth — derive directly, no local state. const subspace = searchParams.get("subspace"); // Reconcile once per runtime/KB identity. A pending restore suppresses the // persistence branch until router.replace has replayed it into the URL. const reconcileRef = useRef({ scopeId: null, pendingRestore: null, }); useEffect(() => { const storage = getSessionStorage(); const stored = reconcileRef.current.scopeId !== activeScopeId && !subspace ? readActiveSubspace(storage, dataScopeKey, knowledgeBaseName) : null; const result = reconcileActiveSubspace( reconcileRef.current, activeScopeId, subspace, stored, ); reconcileRef.current = result.state; if (result.effect.type === "restore") { const params = new URLSearchParams(searchParamsKey); params.set("subspace", result.effect.subspace); router.replace(`${pathname}?${params.toString()}`); return; } if (result.effect.type === "persist") { writeActiveSubspace( storage, dataScopeKey, knowledgeBaseName, result.effect.subspace, ); addToHistory(result.effect.subspace); return; } if (result.effect.type === "clear") { clearActiveSubspace(storage, dataScopeKey, knowledgeBaseName); } }, [ activeScopeId, dataScopeKey, knowledgeBaseName, subspace, searchParamsKey, pathname, router, addToHistory, ]); const setSubspace = useCallback( (next: string) => { const trimmed = next.trim(); if (!trimmed) return; const params = new URLSearchParams(searchParamsKey); params.set("subspace", trimmed); router.replace(`${pathname}?${params.toString()}`); }, [searchParamsKey, pathname, router], ); const clearSubspace = useCallback(() => { const params = new URLSearchParams(searchParamsKey); params.delete("subspace"); const query = params.toString(); router.replace(query ? `${pathname}?${query}` : pathname); }, [searchParamsKey, pathname, router]); return ( {children} ); }