perf(webui): restore cached threads and load mention catalogs on demand
This commit is contained in:
1 parent
c370e2a5a5
commit
1a78ae2b99
13 files changed
+316
-65
No files matched your search
+20
-40
@@ -57,45 +57,21 @@
|
|||||||
color: #fafafa;
|
color: #fafafa;
|
||||||
}
|
}
|
||||||
|
|
||||||
.boot-splash {
|
.startup-shell { position: relative; height: 100%; }
|
||||||
display: flex;
|
.startup-header { display: flex; justify-content: space-between; padding: 5px 13px; }
|
||||||
height: 100%;
|
.startup-control-shadow {
|
||||||
align-items: center;
|
width: 28px; height: 28px; border-radius: 8px; background: rgba(0,0,0,0.025);
|
||||||
justify-content: center;
|
|
||||||
}
|
}
|
||||||
|
.startup-composer {
|
||||||
.boot-splash-inner {
|
position: absolute; inset-inline: 16px; bottom: max(24px, env(safe-area-inset-bottom));
|
||||||
display: flex;
|
box-sizing: border-box; max-width: 768px; margin-inline: auto;
|
||||||
align-items: center;
|
height: 96px; border-radius: 24px; background: rgba(0,0,0,0.025);
|
||||||
gap: 10px;
|
|
||||||
color: rgba(255, 255, 255, 0.74);
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
}
|
||||||
|
.startup-status {
|
||||||
html:not(.dark) .boot-splash-inner {
|
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||||
color: rgba(10, 10, 10, 0.64);
|
overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
|
||||||
}
|
|
||||||
|
|
||||||
.boot-dot {
|
|
||||||
width: 8px;
|
|
||||||
height: 8px;
|
|
||||||
border-radius: 9999px;
|
|
||||||
background: currentColor;
|
|
||||||
opacity: 0.75;
|
|
||||||
animation: boot-pulse 1s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes boot-pulse {
|
|
||||||
0%,
|
|
||||||
100% {
|
|
||||||
transform: scale(0.9);
|
|
||||||
opacity: 0.45;
|
|
||||||
}
|
|
||||||
50% {
|
|
||||||
transform: scale(1);
|
|
||||||
opacity: 0.85;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
html.dark :is(.startup-control-shadow, .startup-composer) { background: rgba(255,255,255,0.035); }
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
@@ -124,12 +100,16 @@
|
|||||||
</head>
|
</head>
|
||||||
<body class="bg-background text-foreground antialiased">
|
<body class="bg-background text-foreground antialiased">
|
||||||
<div id="root">
|
<div id="root">
|
||||||
<div class="boot-splash">
|
<main class="startup-shell" aria-busy="true">
|
||||||
<div class="boot-splash-inner">
|
<div class="startup-header" aria-hidden="true">
|
||||||
<span class="boot-dot" aria-hidden="true"></span>
|
<span class="startup-control-shadow"></span>
|
||||||
|
<span class="startup-control-shadow"></span>
|
||||||
|
</div>
|
||||||
|
<div class="startup-composer" aria-hidden="true"></div>
|
||||||
|
<div class="startup-status" role="status">
|
||||||
<span data-boot-copy>Loading nanobot…</span>
|
<span data-boot-copy>Loading nanobot…</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
|||||||
+15
-15
@@ -18,6 +18,9 @@ import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/com
|
|||||||
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
|
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
|
||||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||||
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
||||||
|
import { StartupShell } from "@/components/StartupShell";
|
||||||
|
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
|
||||||
|
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||||
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||||
import type { SettingsExitGuard } from "@/components/settings/contracts";
|
import type { SettingsExitGuard } from "@/components/settings/contracts";
|
||||||
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
|
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
|
||||||
@@ -133,7 +136,8 @@ type ShellRoute = {
|
|||||||
settingsSection: SettingsSectionKey;
|
settingsSection: SettingsSectionKey;
|
||||||
temporary?: boolean;
|
temporary?: boolean;
|
||||||
};
|
};
|
||||||
const ThreadShell = lazy(() => import("@/components/thread/ThreadShell").then(
|
const loadThreadShell = () => import("@/components/thread/ThreadShell");
|
||||||
|
const ThreadShell = lazy(() => loadThreadShell().then(
|
||||||
(module) => ({ default: module.ThreadShell }),
|
(module) => ({ default: module.ThreadShell }),
|
||||||
));
|
));
|
||||||
const loadSettingsView = () => import("@/components/settings/SettingsView");
|
const loadSettingsView = () => import("@/components/settings/SettingsView");
|
||||||
@@ -917,6 +921,7 @@ export default function App() {
|
|||||||
const bootstrapWithSecret = useCallback(
|
const bootstrapWithSecret = useCallback(
|
||||||
(secret: string) => {
|
(secret: string) => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
|
||||||
(async () => {
|
(async () => {
|
||||||
setState({ status: "loading" });
|
setState({ status: "loading" });
|
||||||
try {
|
try {
|
||||||
@@ -924,6 +929,7 @@ export default function App() {
|
|||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (secret) saveSecret(secret);
|
if (secret) saveSecret(secret);
|
||||||
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
||||||
|
activateReloadCache(url);
|
||||||
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, "browser");
|
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, "browser");
|
||||||
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
|
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
|
||||||
const client = new NanobotClient({
|
const client = new NanobotClient({
|
||||||
@@ -955,6 +961,8 @@ export default function App() {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (isBootstrapAuthRequired(e)) {
|
if (isBootstrapAuthRequired(e)) {
|
||||||
|
clearReloadCache();
|
||||||
|
webuiThreadCache.clear();
|
||||||
setState({ status: "auth", failed: !!secret });
|
setState({ status: "auth", failed: !!secret });
|
||||||
} else {
|
} else {
|
||||||
setState({
|
setState({
|
||||||
@@ -979,6 +987,8 @@ export default function App() {
|
|||||||
await refreshReadyClient(client, state.runtimeSurface);
|
await refreshReadyClient(client, state.runtimeSurface);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isBootstrapAuthRequired(e)) {
|
if (isBootstrapAuthRequired(e)) {
|
||||||
|
clearReloadCache();
|
||||||
|
webuiThreadCache.clear();
|
||||||
setState({ status: "auth", failed: !!bootstrapSecretRef.current });
|
setState({ status: "auth", failed: !!bootstrapSecretRef.current });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -992,19 +1002,7 @@ export default function App() {
|
|||||||
}, [bootstrapWithSecret]);
|
}, [bootstrapWithSecret]);
|
||||||
|
|
||||||
if (state.status === "loading") {
|
if (state.status === "loading") {
|
||||||
return (
|
return <StartupShell />;
|
||||||
<div className="flex h-full w-full items-center justify-center">
|
|
||||||
<div className="flex flex-col items-center gap-3 animate-in fade-in-0 duration-300">
|
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
|
||||||
<span className="relative flex h-2 w-2">
|
|
||||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-foreground/40" />
|
|
||||||
<span className="relative inline-flex h-2 w-2 rounded-full bg-foreground/60" />
|
|
||||||
</span>
|
|
||||||
{t("app.loading.connecting")}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (state.status === "auth") {
|
if (state.status === "auth") {
|
||||||
return (
|
return (
|
||||||
@@ -1039,6 +1037,8 @@ export default function App() {
|
|||||||
state.client.close();
|
state.client.close();
|
||||||
}
|
}
|
||||||
clearSavedSecret();
|
clearSavedSecret();
|
||||||
|
clearReloadCache();
|
||||||
|
webuiThreadCache.clear();
|
||||||
setState({ status: "auth" });
|
setState({ status: "auth" });
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2842,7 +2842,7 @@ function Shell({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<ThreadVisibilityContext.Provider value={view === "chat"}>
|
<ThreadVisibilityContext.Provider value={view === "chat"}>
|
||||||
<Suspense fallback={<SurfaceLoadingFallback label={t("chat.loading")} />}>
|
<Suspense fallback={<StartupShell embedded />}>
|
||||||
<PaneWorkbench
|
<PaneWorkbench
|
||||||
panes={renderedWorkbenchPanes}
|
panes={renderedWorkbenchPanes}
|
||||||
activePaneKey={renderedActivePaneKey}
|
activePaneKey={renderedActivePaneKey}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
/** Quiet layout placeholders while the authenticated application starts. */
|
||||||
|
export function StartupShell({ embedded = false }: { embedded?: boolean }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const Root = embedded ? "section" : "main";
|
||||||
|
return (
|
||||||
|
<Root className="startup-shell" aria-busy="true">
|
||||||
|
<div className="startup-header" aria-hidden="true">
|
||||||
|
<span className="startup-control-shadow" />
|
||||||
|
<span className="startup-control-shadow" />
|
||||||
|
</div>
|
||||||
|
<div className="startup-composer" aria-hidden="true" />
|
||||||
|
<span className="startup-status" role="status">{t("app.loading.connecting")}</span>
|
||||||
|
</Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -211,6 +211,7 @@ interface ThreadComposerProps {
|
|||||||
recentRoundUsage?: readonly ComposerRoundUsage[];
|
recentRoundUsage?: readonly ComposerRoundUsage[];
|
||||||
variant?: "thread" | "hero";
|
variant?: "thread" | "hero";
|
||||||
slashCommands?: SlashCommand[];
|
slashCommands?: SlashCommand[];
|
||||||
|
onMentionSearch?: () => void;
|
||||||
cliApps?: CliAppInfo[];
|
cliApps?: CliAppInfo[];
|
||||||
mcpPresets?: McpPresetInfo[];
|
mcpPresets?: McpPresetInfo[];
|
||||||
sessions?: ChatSummary[];
|
sessions?: ChatSummary[];
|
||||||
@@ -912,6 +913,7 @@ export function ThreadComposer({
|
|||||||
recentRoundUsage = [],
|
recentRoundUsage = [],
|
||||||
variant = "thread",
|
variant = "thread",
|
||||||
slashCommands = [],
|
slashCommands = [],
|
||||||
|
onMentionSearch,
|
||||||
cliApps = [],
|
cliApps = [],
|
||||||
mcpPresets = [],
|
mcpPresets = [],
|
||||||
sessions = [],
|
sessions = [],
|
||||||
@@ -1301,6 +1303,11 @@ export function ThreadComposer({
|
|||||||
};
|
};
|
||||||
}, [cliAppMenuDismissed, cursorPosition, interactionDisabled, value]);
|
}, [cliAppMenuDismissed, cursorPosition, interactionDisabled, value]);
|
||||||
|
|
||||||
|
const mentionSearchActive = cliAppMention !== null;
|
||||||
|
useEffect(() => {
|
||||||
|
if (mentionSearchActive) onMentionSearch?.();
|
||||||
|
}, [mentionSearchActive, onMentionSearch]);
|
||||||
|
|
||||||
const availableSessionMentions = useMemo(
|
const availableSessionMentions = useMemo(
|
||||||
() => sessionMentionOptions(sessions),
|
() => sessionMentionOptions(sessions),
|
||||||
[sessions],
|
[sessions],
|
||||||
|
|||||||
@@ -541,6 +541,7 @@ interface PendingFirstMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface InstalledSettingItemsOptions<Payload, Item> {
|
interface InstalledSettingItemsOptions<Payload, Item> {
|
||||||
|
enabled: boolean;
|
||||||
getToken: () => string;
|
getToken: () => string;
|
||||||
eventName: string;
|
eventName: string;
|
||||||
fetchPayload: (token: string) => Promise<Payload>;
|
fetchPayload: (token: string) => Promise<Payload>;
|
||||||
@@ -549,6 +550,7 @@ interface InstalledSettingItemsOptions<Payload, Item> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function useInstalledSettingItems<Payload, Item>({
|
function useInstalledSettingItems<Payload, Item>({
|
||||||
|
enabled,
|
||||||
getToken,
|
getToken,
|
||||||
eventName,
|
eventName,
|
||||||
fetchPayload,
|
fetchPayload,
|
||||||
@@ -583,14 +585,14 @@ function useInstalledSettingItems<Payload, Item>({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const queueRefresh = () => {
|
const queueRefresh = () => {
|
||||||
if (document.visibilityState === "hidden" || refreshQueued) return;
|
if (!enabled || document.visibilityState === "hidden" || refreshQueued) return;
|
||||||
refreshQueued = true;
|
refreshQueued = true;
|
||||||
queueMicrotask(() => {
|
queueMicrotask(() => {
|
||||||
refreshQueued = false;
|
refreshQueued = false;
|
||||||
if (!cancelled) void refresh();
|
if (!cancelled) void refresh();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
void refresh();
|
if (enabled) void refresh();
|
||||||
|
|
||||||
const refreshOnChanged = (event: Event) => {
|
const refreshOnChanged = (event: Event) => {
|
||||||
const payload = (event as CustomEvent<unknown>).detail;
|
const payload = (event as CustomEvent<unknown>).detail;
|
||||||
@@ -606,16 +608,12 @@ function useInstalledSettingItems<Payload, Item>({
|
|||||||
queueRefresh();
|
queueRefresh();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener("focus", queueRefresh);
|
|
||||||
document.addEventListener("visibilitychange", queueRefresh);
|
|
||||||
window.addEventListener(eventName, refreshOnChanged);
|
window.addEventListener(eventName, refreshOnChanged);
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
window.removeEventListener("focus", queueRefresh);
|
|
||||||
document.removeEventListener("visibilitychange", queueRefresh);
|
|
||||||
window.removeEventListener(eventName, refreshOnChanged);
|
window.removeEventListener(eventName, refreshOnChanged);
|
||||||
};
|
};
|
||||||
}, [eventName, fetchPayload, getToken, isPayload, selectItems]);
|
}, [enabled, eventName, fetchPayload, getToken, isPayload, selectItems]);
|
||||||
|
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
@@ -698,7 +696,10 @@ export function ThreadShell({
|
|||||||
}, [client]);
|
}, [client]);
|
||||||
const [booting, setBooting] = useState(false);
|
const [booting, setBooting] = useState(false);
|
||||||
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
|
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
|
||||||
|
const [mentionCatalogsRequested, setMentionCatalogsRequested] = useState(false);
|
||||||
|
const requestMentionCatalogs = useCallback(() => setMentionCatalogsRequested(true), []);
|
||||||
const cliApps = useInstalledSettingItems({
|
const cliApps = useInstalledSettingItems({
|
||||||
|
enabled: mentionCatalogsRequested,
|
||||||
getToken,
|
getToken,
|
||||||
eventName: CLI_APPS_CHANGED_EVENT,
|
eventName: CLI_APPS_CHANGED_EVENT,
|
||||||
fetchPayload: fetchInstalledCliApps,
|
fetchPayload: fetchInstalledCliApps,
|
||||||
@@ -706,6 +707,7 @@ export function ThreadShell({
|
|||||||
selectItems: installedCliAppsFromPayload,
|
selectItems: installedCliAppsFromPayload,
|
||||||
});
|
});
|
||||||
const mcpPresets = useInstalledSettingItems({
|
const mcpPresets = useInstalledSettingItems({
|
||||||
|
enabled: mentionCatalogsRequested,
|
||||||
getToken,
|
getToken,
|
||||||
eventName: MCP_PRESETS_CHANGED_EVENT,
|
eventName: MCP_PRESETS_CHANGED_EVENT,
|
||||||
fetchPayload: fetchMcpPresets,
|
fetchPayload: fetchMcpPresets,
|
||||||
@@ -899,6 +901,11 @@ export function ThreadShell({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
|
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (displayMessages.some((message) => message.cliApps?.length || message.mcpPresets?.length)) {
|
||||||
|
requestMentionCatalogs();
|
||||||
|
}
|
||||||
|
}, [displayMessages, requestMentionCatalogs]);
|
||||||
const composerContextUsage = useMemo(
|
const composerContextUsage = useMemo(
|
||||||
() => latestComposerContextUsage(displayMessages),
|
() => latestComposerContextUsage(displayMessages),
|
||||||
[displayMessages],
|
[displayMessages],
|
||||||
@@ -1725,6 +1732,7 @@ export function ThreadShell({
|
|||||||
recentRoundUsage={composerRoundUsage}
|
recentRoundUsage={composerRoundUsage}
|
||||||
variant={composerVariant}
|
variant={composerVariant}
|
||||||
slashCommands={availableSlashCommands}
|
slashCommands={availableSlashCommands}
|
||||||
|
onMentionSearch={requestMentionCatalogs}
|
||||||
cliApps={cliApps}
|
cliApps={cliApps}
|
||||||
mcpPresets={mcpPresets}
|
mcpPresets={mcpPresets}
|
||||||
sessions={mentionSessions}
|
sessions={mentionSessions}
|
||||||
@@ -1774,6 +1782,7 @@ export function ThreadShell({
|
|||||||
recentRoundUsage={composerRoundUsage}
|
recentRoundUsage={composerRoundUsage}
|
||||||
variant="hero"
|
variant="hero"
|
||||||
slashCommands={availableSlashCommands}
|
slashCommands={availableSlashCommands}
|
||||||
|
onMentionSearch={requestMentionCatalogs}
|
||||||
cliApps={cliApps}
|
cliApps={cliApps}
|
||||||
mcpPresets={mcpPresets}
|
mcpPresets={mcpPresets}
|
||||||
sessions={mentionSessions}
|
sessions={mentionSessions}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
|||||||
import { deriveTitle } from "@/lib/format";
|
import { deriveTitle } from "@/lib/format";
|
||||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||||
|
import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
|
||||||
import type {
|
import type {
|
||||||
ChatSummary,
|
ChatSummary,
|
||||||
SessionAutomationJob,
|
SessionAutomationJob,
|
||||||
@@ -214,7 +215,7 @@ export function useSessions(): {
|
|||||||
getSessionAutomations: (key: string) => Promise<SessionAutomationJob[]>;
|
getSessionAutomations: (key: string) => Promise<SessionAutomationJob[]>;
|
||||||
} {
|
} {
|
||||||
const { client, token } = useClient();
|
const { client, token } = useClient();
|
||||||
const [sessions, setSessions] = useState<ChatSummary[]>([]);
|
const [sessions, setSessions] = useState<ChatSummary[]>(readReloadSessions);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const tokenRef = useRef(token);
|
const tokenRef = useRef(token);
|
||||||
@@ -223,6 +224,10 @@ export function useSessions(): {
|
|||||||
const refreshInFlightRef = useRef<Promise<void> | null>(null);
|
const refreshInFlightRef = useRef<Promise<void> | null>(null);
|
||||||
tokenRef.current = token;
|
tokenRef.current = token;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (sessions.length || !loading) writeReloadCache("sessions", sessions.slice(0, 200));
|
||||||
|
}, [sessions, loading]);
|
||||||
|
|
||||||
const refresh = useCallback((): Promise<void> => {
|
const refresh = useCallback((): Promise<void> => {
|
||||||
refreshPendingRef.current = true;
|
refreshPendingRef.current = true;
|
||||||
if (refreshInFlightRef.current) return refreshInFlightRef.current;
|
if (refreshInFlightRef.current) return refreshInFlightRef.current;
|
||||||
|
|||||||
@@ -369,7 +369,7 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
|||||||
throw new Error(`Invalid WebUI thread projection event: ${value.event}`);
|
throw new Error(`Invalid WebUI thread projection event: ${value.event}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload {
|
export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload {
|
||||||
if (!isRecord(value) || typeof value.schemaVersion !== "number") {
|
if (!isRecord(value) || typeof value.schemaVersion !== "number") {
|
||||||
throw new Error("Invalid WebUI thread response");
|
throw new Error("Invalid WebUI thread response");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import type { ChatSummary, WorkspaceScopePayload } from "./types";
|
||||||
|
|
||||||
|
const PREFIX = "nanobot.reload.v1.";
|
||||||
|
const MAX_CHARS = 512 * 1024;
|
||||||
|
let scope: string | null = null;
|
||||||
|
|
||||||
|
/** Enable tab-local replay only after bootstrap authenticates the gateway. */
|
||||||
|
export function activateReloadCache(wsUrl: string): void {
|
||||||
|
const url = new URL(wsUrl, window.location.href);
|
||||||
|
scope = `${url.origin}${url.pathname}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readReloadCache(name: string): unknown {
|
||||||
|
if (!scope) return undefined;
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(PREFIX + name);
|
||||||
|
if (!raw || raw.length > MAX_CHARS) return undefined;
|
||||||
|
const stored: unknown = JSON.parse(raw);
|
||||||
|
return isRecord(stored) && stored.scope === scope ? stored.value : undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeReloadCache(name: string, value: unknown): void {
|
||||||
|
if (!scope) return;
|
||||||
|
try {
|
||||||
|
const raw = JSON.stringify({ scope, value });
|
||||||
|
if (raw.length <= MAX_CHARS) sessionStorage.setItem(PREFIX + name, raw);
|
||||||
|
else sessionStorage.removeItem(PREFIX + name);
|
||||||
|
} catch {
|
||||||
|
// Storage can be unavailable or full; in-memory replay remains usable.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeReloadCache(name: string): void {
|
||||||
|
try { sessionStorage.removeItem(PREFIX + name); } catch { /* Storage is optional. */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearReloadCache(): void {
|
||||||
|
scope = null;
|
||||||
|
removeReloadCache("sessions");
|
||||||
|
removeReloadCache("thread");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readReloadSessions(): ChatSummary[] {
|
||||||
|
const value = readReloadCache("sessions");
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return value.flatMap((row): ChatSummary[] => {
|
||||||
|
if (!isRecord(row) || typeof row.key !== "string" || typeof row.channel !== "string"
|
||||||
|
|| typeof row.chatId !== "string" || typeof row.preview !== "string") return [];
|
||||||
|
const workspaceScope = readWorkspaceScope(row.workspaceScope);
|
||||||
|
return [{
|
||||||
|
key: row.key, channel: row.channel, chatId: row.chatId, preview: row.preview,
|
||||||
|
title: typeof row.title === "string" ? row.title : undefined,
|
||||||
|
createdAt: typeof row.createdAt === "string" ? row.createdAt : null,
|
||||||
|
updatedAt: typeof row.updatedAt === "string" ? row.updatedAt : null,
|
||||||
|
...(typeof row.modelPreset === "string" ? { modelPreset: row.modelPreset } : {}),
|
||||||
|
...(typeof row.runStartedAt === "number" ? { runStartedAt: row.runStartedAt } : {}),
|
||||||
|
...(workspaceScope ? { workspaceScope } : {}),
|
||||||
|
}];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readWorkspaceScope(value: unknown): WorkspaceScopePayload | undefined {
|
||||||
|
if (!isRecord(value) || typeof value.project_path !== "string"
|
||||||
|
|| (value.access_mode !== "full" && value.access_mode !== "restricted")
|
||||||
|
|| typeof value.restrict_to_workspace !== "boolean") return undefined;
|
||||||
|
return {
|
||||||
|
project_path: value.project_path,
|
||||||
|
access_mode: value.access_mode,
|
||||||
|
restrict_to_workspace: value.restrict_to_workspace,
|
||||||
|
...(typeof value.project_name === "string" ? { project_name: value.project_name } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
import { MemoryLruCache } from "./memory-lru-cache";
|
import { MemoryLruCache } from "./memory-lru-cache";
|
||||||
|
import { parseWebuiThreadPayload } from "./api";
|
||||||
|
import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";
|
||||||
import type { WebuiThreadPersistedPayload } from "./types";
|
import type { WebuiThreadPersistedPayload } from "./types";
|
||||||
|
|
||||||
/** Process-local canonical replay cache used for stale-while-revalidate session entry. */
|
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
|
||||||
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
|
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
|
||||||
constructor(
|
constructor(
|
||||||
maxBytes = 16 * 1024 * 1024,
|
maxBytes = 16 * 1024 * 1024,
|
||||||
@@ -9,6 +11,40 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
|
|||||||
) {
|
) {
|
||||||
super(maxBytes, maxEntries);
|
super(maxBytes, maxEntries);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override get(key: string): WebuiThreadPersistedPayload | undefined {
|
||||||
|
const cached = super.get(key);
|
||||||
|
if (cached) return cached;
|
||||||
|
const stored = readReloadCache("thread");
|
||||||
|
if (!stored || typeof stored !== "object" || !("key" in stored)
|
||||||
|
|| stored.key !== key || !("body" in stored)) return undefined;
|
||||||
|
try {
|
||||||
|
const body = parseWebuiThreadPayload(stored.body);
|
||||||
|
this.set(key, body);
|
||||||
|
return super.get(key);
|
||||||
|
} catch {
|
||||||
|
removeReloadCache("thread");
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override set(key: string, body: WebuiThreadPersistedPayload): void {
|
||||||
|
super.set(key, body);
|
||||||
|
if (super.get(key)) writeReloadCache("thread", { key, body });
|
||||||
|
}
|
||||||
|
|
||||||
|
override delete(key: string): void {
|
||||||
|
super.delete(key);
|
||||||
|
const stored = readReloadCache("thread");
|
||||||
|
if (stored && typeof stored === "object" && "key" in stored && stored.key === key) {
|
||||||
|
removeReloadCache("thread");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override clear(): void {
|
||||||
|
super.clear();
|
||||||
|
removeReloadCache("thread");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const webuiThreadCache = new WebuiThreadCache();
|
export const webuiThreadCache = new WebuiThreadCache();
|
||||||
@@ -351,6 +351,16 @@ describe("App layout", () => {
|
|||||||
vi.unstubAllGlobals();
|
vi.unstubAllGlobals();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("shows only layout shadows while bootstrap is pending", () => {
|
||||||
|
vi.mocked(fetchBootstrap).mockReturnValueOnce(new Promise(() => {}));
|
||||||
|
render(<App />);
|
||||||
|
expect(screen.getByRole("main")).toHaveAttribute("aria-busy", "true");
|
||||||
|
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("link")).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole("status")).toHaveClass("startup-status");
|
||||||
|
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it("shows the auth form without an invalid-password error on first load", async () => {
|
it("shows the auth form without an invalid-password error on first load", async () => {
|
||||||
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
|
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
|
||||||
new Error("bootstrap failed: HTTP 401"),
|
new Error("bootstrap failed: HTTP 401"),
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { activateReloadCache, clearReloadCache, readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
|
||||||
|
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
|
||||||
|
import { canonicalThreadPayload } from "./thread-test-payload";
|
||||||
|
|
||||||
|
afterEach(() => { clearReloadCache(); vi.restoreAllMocks(); });
|
||||||
|
|
||||||
|
const thread = canonicalThreadPayload({ schemaVersion: 3, revision: "rev-1", messages: [
|
||||||
|
{ id: "a", role: "assistant", content: "Saved answer", createdAt: 1 },
|
||||||
|
] })!;
|
||||||
|
|
||||||
|
describe("tab reload cache", () => {
|
||||||
|
it("restores authenticated replay into a fresh cache and retains it for another reload", () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/?token=old");
|
||||||
|
new WebuiThreadCache().set("websocket:a", thread);
|
||||||
|
activateReloadCache("ws://localhost:8765/?token=renewed");
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toEqual(thread);
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toEqual(thread);
|
||||||
|
expect(new WebuiThreadCache().get("websocket:b")).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not restore another gateway's data or data after logout", () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
new WebuiThreadCache().set("websocket:a", thread);
|
||||||
|
activateReloadCache("ws://localhost:8888/");
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
|
||||||
|
clearReloadCache();
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes deleted sessions and ignores malformed replay", () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
const cache = new WebuiThreadCache();
|
||||||
|
cache.set("websocket:a", thread);
|
||||||
|
cache.delete("websocket:a");
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
|
||||||
|
writeReloadCache("thread", { key: "websocket:a", body: { projection: "events", events: [{}] } });
|
||||||
|
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps memory caching working when storage fails", () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("quota"); });
|
||||||
|
const cache = new WebuiThreadCache();
|
||||||
|
cache.set("websocket:a", thread);
|
||||||
|
expect(cache.get("websocket:a")).toEqual(thread);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not persist oversized replay and validates session summaries", () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
writeReloadCache("thread", { key: "large", body: "x".repeat(600_000) });
|
||||||
|
expect(sessionStorage.getItem("nanobot.reload.v1.thread")).toBeNull();
|
||||||
|
writeReloadCache("sessions", [{ key: "bad" }, {
|
||||||
|
key: "websocket:a", channel: "websocket", chatId: "a", preview: "Answer", title: "Topic",
|
||||||
|
}]);
|
||||||
|
expect(readReloadSessions()).toEqual([{
|
||||||
|
key: "websocket:a", channel: "websocket", chatId: "a", preview: "Answer", title: "Topic",
|
||||||
|
createdAt: null, updatedAt: null,
|
||||||
|
}]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4475,6 +4475,29 @@ describe("ThreadShell", () => {
|
|||||||
expect(screen.queryByText("from chat a")).not.toBeInTheDocument();
|
expect(screen.queryByText("from chat a")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("loads mention catalogs only on demand and ignores window focus", async () => {
|
||||||
|
render(wrap(makeClient(), <ThreadShell
|
||||||
|
session={session("lazy-mentions")}
|
||||||
|
title="Lazy mentions"
|
||||||
|
onToggleSidebar={() => {}}
|
||||||
|
onGoHome={() => {}}
|
||||||
|
onNewChat={() => {}}
|
||||||
|
/>));
|
||||||
|
const input = await screen.findByLabelText("Message input");
|
||||||
|
const catalogCalls = () => vi.mocked(fetch).mock.calls.filter(([url]) =>
|
||||||
|
/cli-apps|mcp-presets/.test(String(url)));
|
||||||
|
fireEvent.change(input, { target: { value: "hello", selectionStart: 5 } });
|
||||||
|
fireEvent(window, new Event("focus"));
|
||||||
|
expect(catalogCalls()).toHaveLength(0);
|
||||||
|
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
|
||||||
|
await waitFor(() => expect(catalogCalls()).toHaveLength(2));
|
||||||
|
fireEvent(window, new Event("focus"));
|
||||||
|
fireEvent.change(input, { target: { value: "@app", selectionStart: 4 } });
|
||||||
|
fireEvent.change(input, { target: { value: "", selectionStart: 0 } });
|
||||||
|
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
|
||||||
|
expect(catalogCalls()).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
it("updates @ CLI app suggestions when settings broadcasts an install", async () => {
|
it("updates @ CLI app suggestions when settings broadcasts an install", async () => {
|
||||||
const client = makeClient();
|
const client = makeClient();
|
||||||
render(wrap(
|
render(wrap(
|
||||||
@@ -4549,6 +4572,7 @@ describe("ThreadShell", () => {
|
|||||||
));
|
));
|
||||||
|
|
||||||
const input = await screen.findByLabelText("Message input");
|
const input = await screen.findByLabelText("Message input");
|
||||||
|
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
|
||||||
await waitFor(() => expect(fetch).toHaveBeenCalledWith(
|
await waitFor(() => expect(fetch).toHaveBeenCalledWith(
|
||||||
"/api/settings/cli-apps?installed_only=1",
|
"/api/settings/cli-apps?installed_only=1",
|
||||||
expect.anything(),
|
expect.anything(),
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
|
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
|
||||||
import * as api from "@/lib/api";
|
import * as api from "@/lib/api";
|
||||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||||
|
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
|
||||||
import { ClientProvider } from "@/providers/ClientProvider";
|
import { ClientProvider } from "@/providers/ClientProvider";
|
||||||
import { canonicalThreadPayload } from "./thread-test-payload";
|
import { canonicalThreadPayload } from "./thread-test-payload";
|
||||||
|
|
||||||
@@ -72,6 +73,27 @@ function wrap(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("useSessions", () => {
|
describe("useSessions", () => {
|
||||||
|
it("shows tab-cached sessions while revalidating and removes server-deleted rows", async () => {
|
||||||
|
activateReloadCache("ws://localhost:8765/");
|
||||||
|
writeReloadCache("sessions", [{
|
||||||
|
key: "websocket:cached", channel: "websocket", chatId: "cached", preview: "Saved answer",
|
||||||
|
createdAt: null, updatedAt: null,
|
||||||
|
}]);
|
||||||
|
let finish!: (rows: Awaited<ReturnType<typeof api.listSessions>>) => void;
|
||||||
|
vi.mocked(api.listSessions).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
|
||||||
|
const { result, unmount } = renderHook(() => useSessions(), { wrapper: wrap(fakeClient()) });
|
||||||
|
try {
|
||||||
|
expect(result.current.sessions[0]?.key).toBe("websocket:cached");
|
||||||
|
expect(result.current.loading).toBe(true);
|
||||||
|
await act(async () => finish([]));
|
||||||
|
expect(result.current.sessions).toEqual([]);
|
||||||
|
expect(result.current.loading).toBe(false);
|
||||||
|
} finally {
|
||||||
|
unmount();
|
||||||
|
clearReloadCache();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("coalesces a burst across tasks and preserves unchanged session identities", async () => {
|
it("coalesces a burst across tasks and preserves unchanged session identities", async () => {
|
||||||
const row = { key: "websocket:burst", channel: "websocket", chatId: "burst",
|
const row = { key: "websocket:burst", channel: "websocket", chatId: "burst",
|
||||||
createdAt: "2026-09-08", updatedAt: "2026-09-08", preview: "Stable" };
|
createdAt: "2026-09-08", updatedAt: "2026-09-08", preview: "Stable" };
|
||||||
|
|||||||
Reference in new issue
Block a user