Files
openchamber/packages/ui/src/lib/modelPrefsAutoSave.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

147 lines
4.5 KiB
TypeScript

import { useUIStore } from '@/stores/useUIStore';
import { updateDesktopSettings } from '@/lib/persistence';
import { getRuntimeKey, subscribeRuntimeEndpointWillChange } from '@/lib/runtime-switch';
type ModelRef = { providerID: string; modelID: string };
type ModelPrefsPayload = {
favoriteModels: ModelRef[];
hiddenModels: ModelRef[];
collapsedModelProviders: string[];
recentModels: ModelRef[];
recentAgents: string[];
recentEfforts: Record<string, string[]>;
};
const refsEqual = (a: ModelRef[], b: ModelRef[]): boolean => {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i]?.providerID !== b[i]?.providerID) return false;
if (a[i]?.modelID !== b[i]?.modelID) return false;
}
return true;
};
const stringsEqual = (a: string[], b: string[]): boolean => {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false;
}
return true;
};
const recentEffortsEqual = (a: Record<string, string[]>, b: Record<string, string[]>): boolean => {
if (a === b) return true;
const aKeys = Object.keys(a);
if (aKeys.length !== Object.keys(b).length) return false;
return aKeys.every((key) => Array.isArray(b[key]) && stringsEqual(a[key], b[key]));
};
const snapshotModelPrefs = (): ModelPrefsPayload => {
const state = useUIStore.getState();
return {
favoriteModels: state.favoriteModels,
hiddenModels: state.hiddenModels,
collapsedModelProviders: state.collapsedModelProviders,
recentModels: state.recentModels,
recentAgents: state.recentAgents,
recentEfforts: state.recentEfforts,
};
};
const modelPrefsEqual = (a: ModelPrefsPayload, b: ModelPrefsPayload): boolean => (
refsEqual(a.favoriteModels, b.favoriteModels) &&
refsEqual(a.hiddenModels, b.hiddenModels) &&
stringsEqual(a.collapsedModelProviders, b.collapsedModelProviders) &&
refsEqual(a.recentModels, b.recentModels) &&
stringsEqual(a.recentAgents, b.recentAgents) &&
recentEffortsEqual(a.recentEfforts, b.recentEfforts)
);
const cloneModelPrefs = (prefs: ModelPrefsPayload): ModelPrefsPayload => ({
favoriteModels: prefs.favoriteModels.slice(),
hiddenModels: prefs.hiddenModels.slice(),
collapsedModelProviders: prefs.collapsedModelProviders.slice(),
recentModels: prefs.recentModels.slice(),
recentAgents: prefs.recentAgents.slice(),
recentEfforts: Object.fromEntries(Object.entries(prefs.recentEfforts).map(([key, variants]) => [key, variants.slice()])),
});
export const startModelPrefsAutoSave = () => {
if (typeof window === 'undefined') {
return () => {};
}
let timer: number | null = null;
let lastSent: ModelPrefsPayload | null = null;
let didSkipInitial = false;
let scheduledRuntimeKey: string | null = null;
const flush = () => {
timer = null;
const runtimeKey = scheduledRuntimeKey;
scheduledRuntimeKey = null;
if (!runtimeKey || runtimeKey !== getRuntimeKey()) return;
const payload = snapshotModelPrefs();
if (lastSent && modelPrefsEqual(lastSent, payload)) {
return;
}
lastSent = cloneModelPrefs(payload);
void updateDesktopSettings(payload).catch(() => {});
};
const schedule = () => {
if (!didSkipInitial) {
didSkipInitial = true;
return;
}
if (timer !== null) {
window.clearTimeout(timer);
}
scheduledRuntimeKey = getRuntimeKey();
timer = window.setTimeout(flush, 1200);
};
const unsubscribeRuntime = subscribeRuntimeEndpointWillChange(() => {
if (timer !== null) window.clearTimeout(timer);
timer = null;
scheduledRuntimeKey = null;
lastSent = null;
});
const unsubscribe = useUIStore.subscribe((state, prevState) => {
const next = {
favoriteModels: state.favoriteModels,
hiddenModels: state.hiddenModels,
collapsedModelProviders: state.collapsedModelProviders,
recentModels: state.recentModels,
recentAgents: state.recentAgents,
recentEfforts: state.recentEfforts,
};
const prev = {
favoriteModels: prevState.favoriteModels,
hiddenModels: prevState.hiddenModels,
collapsedModelProviders: prevState.collapsedModelProviders,
recentModels: prevState.recentModels,
recentAgents: prevState.recentAgents,
recentEfforts: prevState.recentEfforts,
};
if (modelPrefsEqual(next, prev)) {
return;
}
schedule();
});
return () => {
unsubscribe();
unsubscribeRuntime();
if (timer !== null) {
window.clearTimeout(timer);
}
};
};