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
This commit is contained in:
Bohdan Triapitsyn
2026-07-21 20:52:20 +03:00
committed by GitHub
parent 485efc7117
commit 85400459e9
197 changed files with 10835 additions and 3400 deletions
@@ -21,6 +21,7 @@ import {
useIsGitRepo,
useGitLoadingStatus,
} from '@/stores/useGitStore';
import { getRuntimeKey } from '@/lib/runtime-switch';
type SyncAction = 'fetch' | 'pull' | 'push' | 'sync' | null;
type CommitAction = 'commit' | 'commitAndPush' | null;
@@ -202,6 +203,7 @@ export const MobileChangesSurface: React.FC<MobileChangesSurfaceProps> = ({ onCl
}
let cancelled = false;
const runtimeKey = getRuntimeKey();
setDiffLoadError(null);
void git.getGitFileDiff(currentDirectory, { path: route.path, staged: route.staged || undefined })
.then((response) => {
@@ -210,7 +212,7 @@ export const MobileChangesSurface: React.FC<MobileChangesSurfaceProps> = ({ onCl
original: response.original ?? '',
modified: response.modified ?? '',
isBinary: response.isBinary,
});
}, runtimeKey);
})
.catch((error) => {
if (cancelled) return;
+13 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, mock, test } from 'bun:test';
import { loadMobileConnections, upsertMobileConnection, validateMobileConnectionSession, type MobileRelayConfig } from './mobileConnections';
import { loadMobileConnections, migrateLegacyInlineTokenRecords, upsertMobileConnection, validateMobileConnectionSession, type MobileRelayConfig } from './mobileConnections';
const originalFetch = globalThis.fetch;
const originalWindow = globalThis.window;
@@ -40,6 +40,18 @@ const testRelay: MobileRelayConfig = {
};
describe('mobile connection storage', () => {
test('removes inline tokens only after each secure migration succeeds', async () => {
const result = await migrateLegacyInlineTokenRecords([
{ id: 'ok', url: 'http://ok.example', clientToken: 'token-ok' },
{ id: 'failed', url: 'http://failed.example', clientToken: 'token-failed' },
], async (url) => url.includes('ok.example'));
expect(result.migrated).toBe(1);
expect(result.failed).toBe(1);
expect(result.records[0]).toEqual({ id: 'ok', url: 'http://ok.example', hasToken: true });
expect(result.records[1]).toEqual({ id: 'failed', url: 'http://failed.example', clientToken: 'token-failed' });
});
test('entries persisted before candidates migrate to a single direct candidate', async () => {
try {
installTestWindow();
+37 -4
View File
@@ -691,6 +691,30 @@ const deleteSecureToken = async (key: string): Promise<void> => {
// One-time migration: a legacy localStorage record on native might still carry an
// inline `clientToken`. Move it into the secure store and strip the metadata.
export const migrateLegacyInlineTokenRecords = async (
records: unknown[],
migrateToken: (url: string, token: string) => Promise<boolean>,
): Promise<{ records: unknown[]; migrated: number; failed: number }> => {
let migrated = 0;
let failed = 0;
const next = await Promise.all(records.map(async (item) => {
if (!item || typeof item !== 'object') return item;
const record = item as Record<string, unknown>;
const url = typeof record.url === 'string' ? record.url : null;
const token = typeof record.clientToken === 'string' ? record.clientToken.trim() : '';
if (!url || !token) return item;
if (!await migrateToken(url, token)) {
failed += 1;
return item;
}
migrated += 1;
const { clientToken: _removed, ...metadata } = record;
void _removed;
return { ...metadata, hasToken: true };
}));
return { records: next, migrated, failed };
};
const migrateLegacyInlineTokens = async (): Promise<void> => {
if (typeof window === 'undefined' || !isCapacitorApp()) return;
let parsed: unknown;
@@ -707,11 +731,20 @@ const migrateLegacyInlineTokens = async (): Promise<void> => {
&& Boolean((item as { clientToken: string }).clientToken.trim()));
if (legacy.length === 0) return;
logStorage('secure:migrate-start', { count: legacy.length });
for (const { url, clientToken } of legacy) {
await writeSecureToken(getConnectionStorageKey(url), clientToken);
const result = await migrateLegacyInlineTokenRecords(parsed, async (url, token) => {
const key = getConnectionStorageKey(url);
if (!await writeSecureToken(key, token)) return false;
return await readSecureToken(key) === token;
});
if (result.migrated > 0) {
try {
window.localStorage.setItem(MOBILE_CONNECTIONS_STORAGE_KEY, JSON.stringify(result.records));
} catch (error) {
console.warn('[mobile-storage] failed to finalize secure token migration', error);
return;
}
}
writeConnections(readConnections());
logStorage('secure:migrate-done', { count: legacy.length });
logStorage('secure:migrate-done', { migrated: result.migrated, failed: result.failed });
};
export const loadMobileConnections = async (): Promise<MobileSavedConnection[]> => {
+4 -1
View File
@@ -5,6 +5,7 @@ import { useUIStore } from '@/stores/useUIStore';
import { resolveGlobalSessionDirectory, useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useNotificationStore } from '@/sync/notification-store';
import { getRuntimeKey } from '@/lib/runtime-switch';
/**
* Builds the lightweight session overview the native iOS widgets render (home medium,
@@ -26,6 +27,8 @@ export interface MobileWidgetSession {
}
export interface MobileWidgetSnapshot {
/** Runtime instance that owns all session IDs and paths in this snapshot. */
runtimeKey: string;
/** Count of sessions needing attention — same signal that drives the app-icon badge. */
attentionCount: number;
/** Most-recently-updated top-level sessions, newest first (capped for the medium widget). */
@@ -97,7 +100,7 @@ export const buildMobileWidgetSnapshot = (): MobileWidgetSnapshot => {
.slice(0, RECENT_LIMIT)
.map(({ id, title, unread, project }) => ({ id, title, unread, project }));
return { attentionCount, recentSessions };
return { runtimeKey: getRuntimeKey(), attentionCount, recentSessions };
};
const SNAPSHOT_GLOBAL_KEY = '__OPENCHAMBER_WIDGET_SNAPSHOT__';
@@ -7,9 +7,15 @@ import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
import { useAutoReviewStore } from '@/stores/useAutoReviewStore';
import { useUIStore } from '@/stores/useUIStore';
import { usePermissionStore } from '@/stores/permissionStore';
import { useFileSearchStore } from '@/stores/useFileSearchStore';
import { useGitStore } from '@/stores/useGitStore';
import { useGitHubPrStatusStore } from '@/stores/useGitHubPrStatusStore';
import { useSessionFoldersStore } from '@/stores/useSessionFoldersStore';
import { useFilesViewTabsStore } from '@/stores/useFilesViewTabsStore';
import { useTerminalStore } from '@/stores/useTerminalStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { resetStreamingState } from '@/sync/streaming';
import { useGlobalSessionStatusStore } from '@/sync/global-session-status';
import { syncDesktopSettings } from '@/lib/persistence';
// Same-device transport switch (LAN⇄relay for one paired device): rebind the SDK
@@ -47,7 +53,13 @@ export const resetAppForRuntimeEndpointChange = (detail: RuntimeEndpointChangedD
// Cross-project session list (mobile sessions sheet & co) belongs to the
// previous instance — drop it so stale sessions can't linger after a switch.
useGlobalSessionsStore.getState().resetForRuntimeSwitch();
useGlobalSessionStatusStore.setState({ statusById: new Map() });
usePermissionStore.getState().reset();
useFileSearchStore.getState().resetForRuntimeSwitch();
useGitStore.getState().resetForRuntimeSwitch(detail.runtimeKey);
useGitHubPrStatusStore.getState().resetForRuntimeSwitch();
useSessionFoldersStore.getState().resetForRuntimeSwitch(detail.runtimeKey);
useFilesViewTabsStore.getState().resetForRuntimeSwitch(detail.runtimeKey);
useSessionUIStore.getState().restoreForRuntimeSwitch(detail.runtimeKey);
useUIStore.getState().restoreForRuntimeSwitch(detail.runtimeKey);
resetStreamingState();