Files
openchamber/packages/ui/src/hooks/usePwaManifestSync.ts
T
Bohdan Triapitsyn 85400459e9 perf: overhaul session loading, caching, and runtime isolation (#2360)
Improve OpenChamber responsiveness under large session workloads while fixing
cache, synchronization, and persistence correctness across runtimes, projects,
directories, and worktrees.

- prioritize selected and visible sessions during bootstrap and defer
  non-critical enrichment work
- reduce redundant message loading, event processing, store publication, and
  hidden sidebar work
- prevent stale session and message requests from overwriting newer
  authoritative state
- preserve existing data when authoritative fetches fail instead of treating
  failures as successful empty responses
- scope session materialization, messages, drafts, queues, todos, pins,
  permissions, folders, tabs, Git state, and pull request data by runtime and
  directory identity
- harden runtime switching, reconnect, cleanup, mutation reconciliation, and
  persisted-state ordering
- preserve live subagent Task linkage when metadata arrives after an older
  message request or while streaming parts are suspended
- coalesce overlapping tail refreshes without losing newer refresh demand
- improve cold-session loading by moving deferrable work out of the critical
  bootstrap path
- isolate URL authentication, mobile credentials, native secrets, and other
  runtime-owned state across endpoint changes
- bound long-lived caches and remove avoidable allocations from event and
  rendering hot paths
- limit virtualization to archive collections where it improves rendering
  without disrupting active sidebar layout
- stabilize session folders, pin ordering, expanded state, and persisted
  sidebar behavior
- open skill files through the same secure editor and outside-workspace grant
  flow used by file navigation, including worktree sessions
- expand regression coverage for stale completions, runtime collisions,
  reconnect behavior, persistence races, authoritative empty results, and
  subagent refresh ordering
- document the updated synchronization, cache ownership, performance, and
  runtime-isolation invariants
2026-07-21 20:52:20 +03:00

93 lines
2.5 KiB
TypeScript

import React from 'react';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useSessions } from '@/sync/sync-context';
import { isWebRuntime } from '@/lib/desktop';
import { PWA_RECENT_SESSIONS_STORAGE_KEY } from '@/lib/pwa';
type RecentSessionShortcut = {
sessionId: string;
title: string;
};
type ManifestSyncWindow = Window & {
__OPENCHAMBER_UPDATE_PWA_MANIFEST__?: () => void;
};
const MAX_RECENT_SHORTCUTS = 3;
const normalizeRecentTitle = (value: string | undefined, fallback: string): string => {
if (typeof value !== 'string') {
return fallback;
}
const normalized = value.trim().replace(/\s+/g, ' ');
if (!normalized) {
return fallback;
}
return normalized.slice(0, 48);
};
const buildRecentShortcuts = (
sessions: Array<{ id: string; title?: string }>,
currentSessionId: string | null,
): RecentSessionShortcut[] => {
const ordered = currentSessionId
? [
...sessions.filter((session) => session.id === currentSessionId),
...sessions.filter((session) => session.id !== currentSessionId),
]
: sessions;
const shortcuts: RecentSessionShortcut[] = [];
const seen = new Set<string>();
for (const session of ordered) {
const sessionId = typeof session.id === 'string' ? session.id.trim() : '';
if (!sessionId || seen.has(sessionId)) {
continue;
}
seen.add(sessionId);
shortcuts.push({
sessionId,
title: normalizeRecentTitle(session.title, `Session ${shortcuts.length + 1}`),
});
if (shortcuts.length >= MAX_RECENT_SHORTCUTS) {
break;
}
}
return shortcuts;
};
export const usePwaManifestSync = () => {
const sessions = useSessions();
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const recentShortcuts = React.useMemo(() => {
return buildRecentShortcuts(sessions, currentSessionId);
}, [currentSessionId, sessions]);
const signature = React.useMemo(() => JSON.stringify(recentShortcuts), [recentShortcuts]);
const hasRecentShortcuts = recentShortcuts.length > 0;
React.useEffect(() => {
if (typeof window === 'undefined' || !isWebRuntime()) {
return;
}
try {
if (!hasRecentShortcuts) {
localStorage.removeItem(PWA_RECENT_SESSIONS_STORAGE_KEY);
} else {
localStorage.setItem(PWA_RECENT_SESSIONS_STORAGE_KEY, signature);
}
} catch {
return;
}
const win = window as ManifestSyncWindow;
win.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.();
}, [hasRecentShortcuts, signature]);
};