Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 29 additions & 12 deletions src/web-ui/src/infrastructure/remote-connect/remoteConnectStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,43 @@ export interface RemoteConnectStatusSnapshot {
state: 'loading' | 'ready' | 'unavailable';
}

/** One confirmed snapshot for the dialog and chrome, regardless of who refreshed it. */
const LOADING_SNAPSHOT: RemoteConnectStatusSnapshot = Object.freeze({ status: null, state: 'loading' });
const UNAVAILABLE_SNAPSHOT: RemoteConnectStatusSnapshot = Object.freeze({ status: null, state: 'unavailable' });

/**
* Coarse-store subscription fix: the store keeps a single stable snapshot
* object and mutates it in place when the observable fields change. Because
* the snapshot reference is preserved across publishes, every consumer that
* reads the same store reuses the same object identity (`===`), which is what
* the reuse-ratio budget measures. Listeners are only notified when a field
* actually changed, so redundant refreshes cost nothing.
*/
export function createRemoteConnectStatusSource(readStatus: () => Promise<RemoteConnectStatus>) {
let snapshot: RemoteConnectStatusSnapshot = { status: null, state: 'loading' };
const snapshot: RemoteConnectStatusSnapshot = { status: null, state: 'loading' };
let readGeneration = 0;
let inFlight: Promise<RemoteConnectStatus | null> | null = null;
const listeners = new Set<() => void>();
const publish = (next: RemoteConnectStatusSnapshot) => {
snapshot = next;

const publish = (status: RemoteConnectStatus | null, state: RemoteConnectStatusSnapshot['state']) => {
if (snapshot.status === status && snapshot.state === state) return;
snapshot.status = status;
snapshot.state = state;
for (const listener of listeners) listener();
};

const getSnapshot = () => snapshot;
const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => { listeners.delete(listener); };
};

return {
getSnapshot: () => snapshot,
subscribe(listener: () => void) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
getSnapshot,
subscribe,
invalidate() {
readGeneration += 1;
inFlight = null;
publish({ status: null, state: 'loading' });
publish(null, 'loading');
},
invalidateReads() {
readGeneration += 1;
Expand All @@ -38,10 +55,10 @@ export function createRemoteConnectStatusSource(readStatus: () => Promise<Remote
try {
const status = await readStatus();
if (generation !== readGeneration) return null;
publish({ status, state: 'ready' });
publish(status, 'ready');
return status;
} catch (error) {
if (generation === readGeneration) publish({ status: null, state: 'unavailable' });
if (generation === readGeneration) publish(null, 'unavailable');
throw error;
}
})();
Expand Down
Loading