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:
committed by
GitHub
parent
485efc7117
commit
85400459e9
@@ -8,17 +8,26 @@ import { isVSCodeRuntime } from "@/lib/desktop";
|
||||
import { createDeferredSafeJSONStorage } from "./utils/safeStorage";
|
||||
import { useSessionUIStore } from "@/sync/session-ui-store";
|
||||
import { opencodeClient } from "@/lib/opencode/client";
|
||||
import { getRuntimeKey } from "@/lib/runtime-switch";
|
||||
|
||||
type PermissionPolicySnapshot = {
|
||||
sessions: PermissionAutoAcceptMap;
|
||||
revision?: number;
|
||||
};
|
||||
|
||||
const normalizeRevision = (value: unknown): number | undefined => (
|
||||
Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : undefined
|
||||
);
|
||||
|
||||
interface PermissionStore {
|
||||
autoAccept: PermissionAutoAcceptMap;
|
||||
loaded: boolean;
|
||||
saving: boolean;
|
||||
lastAppliedRevision: number;
|
||||
legacyCandidate: PermissionAutoAcceptMap | null;
|
||||
legacyRuntimeKey: string | null;
|
||||
hydrate: () => Promise<void>;
|
||||
applySnapshot: (snapshot: PermissionPolicySnapshot) => void;
|
||||
applySnapshot: (snapshot: PermissionPolicySnapshot, expectedRuntimeKey?: string) => void;
|
||||
reset: () => void;
|
||||
isSessionAutoAccepting: (sessionId: string) => boolean;
|
||||
setSessionAutoAccept: (sessionId: string, enabled: boolean) => Promise<void>;
|
||||
@@ -34,7 +43,7 @@ const readSnapshot = async (response: Response): Promise<PermissionPolicySnapsho
|
||||
for (const [sessionId, enabled] of Object.entries(payload.sessions)) {
|
||||
if (sessionId && typeof enabled === "boolean") sessions[sessionId] = enabled;
|
||||
}
|
||||
return { sessions };
|
||||
return { sessions, revision: normalizeRevision(payload.revision) };
|
||||
};
|
||||
|
||||
const requestSnapshot = async (path: string, init?: RequestInit) => readSnapshot(await runtimeFetch(path, init));
|
||||
@@ -45,15 +54,52 @@ const isAutoAccepting = (
|
||||
sessionId: string,
|
||||
) => autoRespondsPermission({ autoAccept, sessions: [], sessionById, sessionID: sessionId });
|
||||
|
||||
type PermissionOperation = { generation: number; runtimeKey: string; sequence: number };
|
||||
let generation = 0;
|
||||
let operationSequence = 0;
|
||||
let latestStartedSequence = 0;
|
||||
const pendingSavingOperations = new Set<number>();
|
||||
|
||||
const beginOperation = (): PermissionOperation => {
|
||||
const operation = { generation, runtimeKey: getRuntimeKey(), sequence: ++operationSequence };
|
||||
latestStartedSequence = operation.sequence;
|
||||
return operation;
|
||||
};
|
||||
|
||||
const isCurrentOperation = (operation: PermissionOperation) => (
|
||||
operation.generation === generation && operation.runtimeKey === getRuntimeKey()
|
||||
);
|
||||
|
||||
const normalizeSessions = (value: unknown): PermissionAutoAcceptMap => {
|
||||
const sessions: PermissionAutoAcceptMap = {};
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return sessions;
|
||||
for (const [sessionId, enabled] of Object.entries(value)) {
|
||||
if (sessionId && typeof enabled === "boolean") sessions[sessionId] = enabled;
|
||||
}
|
||||
return sessions;
|
||||
};
|
||||
|
||||
export const usePermissionStore = create<PermissionStore>()(persist((set, get) => ({
|
||||
autoAccept: {},
|
||||
loaded: false,
|
||||
saving: false,
|
||||
lastAppliedRevision: -1,
|
||||
legacyCandidate: null,
|
||||
legacyRuntimeKey: null,
|
||||
|
||||
hydrate: async () => {
|
||||
const operation = beginOperation();
|
||||
const legacyCandidate = get().legacyCandidate;
|
||||
let legacyRuntimeKey = get().legacyRuntimeKey;
|
||||
if (legacyCandidate && !legacyRuntimeKey) {
|
||||
legacyRuntimeKey = operation.runtimeKey;
|
||||
set({ legacyRuntimeKey });
|
||||
}
|
||||
let snapshot = await requestSnapshot("/api/permission-auto-accept");
|
||||
const legacyEntries = Object.entries(get().autoAccept)
|
||||
.filter(([sessionId, enabled]) => !sessionId.includes("/") && typeof enabled === "boolean");
|
||||
if (!isCurrentOperation(operation)) return;
|
||||
const legacyEntries = legacyRuntimeKey === operation.runtimeKey
|
||||
? Object.entries(legacyCandidate ?? {})
|
||||
: [];
|
||||
if (Object.keys(snapshot.sessions).length === 0 && legacyEntries.length > 0) {
|
||||
for (const [sessionId, enabled] of legacyEntries) {
|
||||
if (!sessionId || typeof enabled !== "boolean") continue;
|
||||
@@ -65,19 +111,37 @@ export const usePermissionStore = create<PermissionStore>()(persist((set, get) =
|
||||
body: JSON.stringify({ enabled }),
|
||||
},
|
||||
);
|
||||
if (!isCurrentOperation(operation)) return;
|
||||
}
|
||||
}
|
||||
set({ autoAccept: snapshot.sessions, loaded: true });
|
||||
if (!isCurrentOperation(operation)) return;
|
||||
if (snapshot.revision === undefined && operation.sequence !== latestStartedSequence) return;
|
||||
get().applySnapshot(snapshot, operation.runtimeKey);
|
||||
if (legacyRuntimeKey === operation.runtimeKey) {
|
||||
set({ legacyCandidate: null, legacyRuntimeKey: null });
|
||||
}
|
||||
},
|
||||
|
||||
reset: () => set({ autoAccept: {}, loaded: false, saving: false }),
|
||||
reset: () => {
|
||||
generation += 1;
|
||||
latestStartedSequence = 0;
|
||||
pendingSavingOperations.clear();
|
||||
set({ autoAccept: {}, loaded: false, saving: false, lastAppliedRevision: -1 });
|
||||
},
|
||||
|
||||
applySnapshot: (snapshot) => {
|
||||
const sessions: PermissionAutoAcceptMap = {};
|
||||
for (const [sessionId, enabled] of Object.entries(snapshot.sessions ?? {})) {
|
||||
if (sessionId && typeof enabled === "boolean") sessions[sessionId] = enabled;
|
||||
}
|
||||
set({ autoAccept: sessions, loaded: true });
|
||||
applySnapshot: (snapshot, expectedRuntimeKey) => {
|
||||
if (expectedRuntimeKey && expectedRuntimeKey !== getRuntimeKey()) return;
|
||||
const sessions = normalizeSessions(snapshot.sessions);
|
||||
const revision = normalizeRevision(snapshot.revision);
|
||||
set((state) => {
|
||||
if (revision === undefined && state.lastAppliedRevision >= 0) return state;
|
||||
if (revision !== undefined && revision < state.lastAppliedRevision) return state;
|
||||
return {
|
||||
autoAccept: sessions,
|
||||
loaded: true,
|
||||
...(revision !== undefined ? { lastAppliedRevision: revision } : {}),
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
isSessionAutoAccepting: (sessionId) => {
|
||||
@@ -89,6 +153,8 @@ export const usePermissionStore = create<PermissionStore>()(persist((set, get) =
|
||||
|
||||
setSessionAutoAccept: async (sessionId, enabled) => {
|
||||
if (!sessionId) return;
|
||||
const operation = beginOperation();
|
||||
pendingSavingOperations.add(operation.sequence);
|
||||
set({ saving: true });
|
||||
try {
|
||||
const directory = useSessionUIStore.getState().getDirectoryForSession(sessionId)
|
||||
@@ -102,18 +168,40 @@ export const usePermissionStore = create<PermissionStore>()(persist((set, get) =
|
||||
body: JSON.stringify({ enabled, directory }),
|
||||
},
|
||||
);
|
||||
set({ autoAccept: snapshot.sessions, loaded: true });
|
||||
if (isVSCodeRuntime() && enabled) {
|
||||
if (!isCurrentOperation(operation)) return;
|
||||
if (snapshot.revision === undefined && operation.sequence !== latestStartedSequence) return;
|
||||
get().applySnapshot(snapshot, operation.runtimeKey);
|
||||
if (isCurrentOperation(operation) && isVSCodeRuntime() && enabled) {
|
||||
const { reconcileVSCodePendingPermissions } = await import("@/sync/vscode-permission-auto-accept");
|
||||
void reconcileVSCodePendingPermissions(directory).catch(() => undefined);
|
||||
if (isCurrentOperation(operation)) {
|
||||
void reconcileVSCodePendingPermissions(directory).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
set({ saving: false });
|
||||
if (isCurrentOperation(operation)) {
|
||||
pendingSavingOperations.delete(operation.sequence);
|
||||
set({ saving: pendingSavingOperations.size > 0 });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
}), {
|
||||
name: "permission-store",
|
||||
storage: createDeferredSafeJSONStorage(),
|
||||
partialize: (state) => ({ autoAccept: state.autoAccept }),
|
||||
version: 2,
|
||||
migrate: (persisted, version) => {
|
||||
const state = persisted && typeof persisted === "object" ? persisted as Record<string, unknown> : {};
|
||||
if (version < 2) {
|
||||
const legacyCandidate = normalizeSessions(state.autoAccept);
|
||||
return {
|
||||
legacyCandidate: Object.keys(legacyCandidate).length > 0 ? legacyCandidate : null,
|
||||
legacyRuntimeKey: null,
|
||||
};
|
||||
}
|
||||
return state;
|
||||
},
|
||||
partialize: (state) => ({
|
||||
legacyCandidate: state.legacyCandidate,
|
||||
legacyRuntimeKey: state.legacyRuntimeKey,
|
||||
}),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user