"use client"; import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode, } from "react"; import { usePathname } from "next/navigation"; import { useQuery, useQueryClient, type QueryClient, } from "@tanstack/react-query"; import { toast } from "sonner"; import { fetchRuntimeContext } from "../services/runtime-context"; import type { RuntimeContext } from "../types/runtime-context"; import { useI18n, type TranslateFn } from "@/i18n/i18n-context"; import { PENDING_DATA_SCOPE_KEY, RUNTIME_CONTEXT_QUERY_KEY, resetInstanceScopedQueries, } from "../lib/query-keys"; const RUNTIME_CONTEXT_REFETCH_INTERVAL_MS = 5_000; const RUNTIME_CONTEXT_NOTICE_KEY = "tsagent.runtimeContextNotice"; const RUNTIME_CONTEXT_DASHBOARD_CHANGE_KEY = "tsagent.runtimeContextDashboardChange"; const RUNTIME_CONTEXT_DASHBOARD_CHANGE_TTL_MS = 30_000; const DEFAULT_CONTEXT: RuntimeContext = { configured: false, credentialSource: null, activeInstance: null, configRevision: "unknown", dataScopeKey: PENDING_DATA_SCOPE_KEY, hasAnyInstance: false, }; interface RuntimeContextValue { context: RuntimeContext; ready: boolean; } const RuntimeContextState = createContext({ context: DEFAULT_CONTEXT, ready: false, }); export function RuntimeContextProvider({ children }: { children: ReactNode }) { const queryClient = useQueryClient(); const pathname = usePathname(); const previousRef = useRef(null); const { t } = useI18n(); const tRef = useRef(t); tRef.current = t; const { data } = useQuery({ queryKey: RUNTIME_CONTEXT_QUERY_KEY, queryFn: fetchRuntimeContext, staleTime: 0, refetchInterval: RUNTIME_CONTEXT_REFETCH_INTERVAL_MS, refetchOnWindowFocus: "always", refetchOnReconnect: "always", }); useEffect(() => { const notice = window.sessionStorage.getItem(RUNTIME_CONTEXT_NOTICE_KEY); if (!notice) return; window.sessionStorage.removeItem(RUNTIME_CONTEXT_NOTICE_KEY); toast.info(notice, { id: "runtime-context-changed" }); }, []); useEffect(() => { if (!data) return; const previous = previousRef.current; previousRef.current = data; applyRuntimeContextTransition({ previous, current: data, pathname, queryClient, location: window.location, storage: window.sessionStorage, t: tRef.current, }); }, [data, pathname, queryClient]); const value = useMemo( () => ({ context: data ?? DEFAULT_CONTEXT, ready: Boolean(data), }), [data], ); return ( {children} ); } export function useRuntimeContext(): RuntimeContextValue { return useContext(RuntimeContextState); } export function useDataScopeKey(): string { return useRuntimeContext().context.dataScopeKey; } interface RuntimeContextTransitionOptions { previous: RuntimeContext | null; current: RuntimeContext; pathname: string | null; queryClient: QueryClient; location: Pick; storage: Pick; resetQueries?: typeof resetInstanceScopedQueries; now?: number; t?: TranslateFn; } interface DashboardRuntimeContextChange { previousDataScopeKey?: string; targetActiveInstance: string | null; createdAt: number; } export function applyRuntimeContextTransition({ previous, current, pathname, queryClient, location, storage, resetQueries = resetInstanceScopedQueries, now = Date.now(), t, }: RuntimeContextTransitionOptions): boolean { if (!previous || previous.dataScopeKey === current.dataScopeKey) { return false; } resetQueries(queryClient, previous.dataScopeKey); const target = resolveRuntimeContextChangeTarget(pathname); if (!consumeDashboardRuntimeContextChange(storage, previous, current, now)) { storage.setItem( RUNTIME_CONTEXT_NOTICE_KEY, buildRuntimeContextChangeMessage(previous, current, t), ); } location.replace(target ?? location.href); return true; } export function markDashboardRuntimeContextChange( storage: Pick, change: Omit, now = Date.now(), ): void { try { storage.setItem( RUNTIME_CONTEXT_DASHBOARD_CHANGE_KEY, JSON.stringify({ ...change, createdAt: now }), ); } catch { // The marker is only for friendlier copy; losing it must never block a // successful project switch. } } function consumeDashboardRuntimeContextChange( storage: Pick, previous: RuntimeContext, current: RuntimeContext, now: number, ): boolean { let raw: string | null; try { raw = storage.getItem(RUNTIME_CONTEXT_DASHBOARD_CHANGE_KEY); } catch { return false; } if (!raw) return false; let change: DashboardRuntimeContextChange; try { change = JSON.parse(raw) as DashboardRuntimeContextChange; } catch { try { storage.removeItem(RUNTIME_CONTEXT_DASHBOARD_CHANGE_KEY); } catch { // Ignore storage cleanup failures; the TTL keeps stale markers bounded. } return false; } const expired = !Number.isFinite(change.createdAt) || now - change.createdAt > RUNTIME_CONTEXT_DASHBOARD_CHANGE_TTL_MS; const matchesPrevious = !change.previousDataScopeKey || change.previousDataScopeKey === previous.dataScopeKey; const matchesTarget = change.targetActiveInstance === current.activeInstance; try { storage.removeItem(RUNTIME_CONTEXT_DASHBOARD_CHANGE_KEY); } catch { // Ignore storage cleanup failures; the TTL keeps stale markers bounded. } return !expired && matchesPrevious && matchesTarget; } export function resolveRuntimeContextChangeTarget( pathname: string | null, ): string | null { if (!pathname) return null; if (/^\/knowledge-base\/[^/]+(?:\/.*)?$/.test(pathname)) { return "/knowledge-base"; } if (/^\/memory\/[^/]+(?:\/.*)?$/.test(pathname)) { return "/memory"; } const llmProviderDetail = pathname.match( /^\/llm-providers\/([^/]+)(?:\/.*)?$/, ); if (llmProviderDetail && llmProviderDetail[1] !== "new") { return "/llm-providers"; } return null; } export function buildRuntimeContextChangeMessage( previous: RuntimeContext, current: RuntimeContext, t?: TranslateFn, ): string { if (previous.activeInstance !== current.activeInstance) { if (current.activeInstance) { return t ? t("runtime.switchedProject", { name: current.activeInstance }) : `检测到 CLI 切换项目,已刷新到 ${current.activeInstance}`; } return t ? t("runtime.switchedConfig") : "检测到 CLI 切换配置,已刷新到当前凭据"; } if (current.activeInstance) { return t ? t("runtime.projectUpdated") : "项目配置已更新,数据已刷新"; } return t ? t("runtime.configUpdated") : "运行时配置已更新,数据已刷新"; }