diff --git a/application/state/useExternalMcpToggleState.test.ts b/application/state/useExternalMcpToggleState.test.ts index 116e81074..961c820b7 100644 --- a/application/state/useExternalMcpToggleState.test.ts +++ b/application/state/useExternalMcpToggleState.test.ts @@ -787,4 +787,130 @@ describe('External MCP manual enable privacy gate', () => { restoreStorage(); } }); + + it('ref-counts a single 3s poller across multiple mounted hooks, pauses when hidden, and syncs on visible', async (t) => { + const React = await import('react'); + const { act, create } = await import('react-test-renderer'); + const { useExternalMcpToggleState } = await import('./useExternalMcpToggleState.ts'); + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'], now: 10_000 }); + const restoreStorage = installMemoryLocalStorage(); + const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window'); + const previousDocument = Object.getOwnPropertyDescriptor(globalThis, 'document'); + const previousAct = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + const events = new EventTarget(); + const visibilityListeners = new Set<() => void>(); + let visibilityState: DocumentVisibilityState = 'visible'; + let statusCalls = 0; + let runtimeEnabled = true; + + const bridge = { + externalMcpGetStatus: async () => { + statusCalls += 1; + return { ok: true, enabled: runtimeEnabled, error: null }; + }, + }; + + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true }); + Object.defineProperty(globalThis, 'window', { + value: { + netcatty: bridge, + location: { hash: '#/settings' }, + addEventListener: events.addEventListener.bind(events), + removeEventListener: events.removeEventListener.bind(events), + dispatchEvent: events.dispatchEvent.bind(events), + setInterval, + clearInterval, + }, + configurable: true, + }); + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { + get visibilityState() { return visibilityState; }, + get hidden() { return visibilityState === 'hidden'; }, + addEventListener(type: string, listener: () => void) { + if (type === 'visibilitychange') visibilityListeners.add(listener); + }, + removeEventListener(type: string, listener: () => void) { + if (type === 'visibilitychange') visibilityListeners.delete(listener); + }, + }, + }); + + const setVisibility = async (next: DocumentVisibilityState) => { + visibilityState = next; + await act(async () => { + for (const listener of [...visibilityListeners]) listener(); + }); + }; + + let hookA!: ReturnType; + let hookB!: ReturnType; + const CaptureA = () => { hookA = useExternalMcpToggleState(); return null; }; + const CaptureB = () => { hookB = useExternalMcpToggleState(); return null; }; + const DualMount = ({ showSecond }: { showSecond: boolean }) => ( + React.createElement( + React.Fragment, + null, + React.createElement(CaptureA), + showSecond ? React.createElement(CaptureB) : null, + ) + ); + + let renderer: ReturnType | undefined; + try { + resetExternalMcpStartupReadyForTests(); + globalThis.localStorage.setItem(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED, 'true'); + + // Mount two instances simultaneously (AppView + Settings > AI): only 1 immediate poll + 1 3s interval + await act(async () => { + renderer = create(React.createElement(DualMount, { showSecond: true })); + }); + assert.equal(hookA.enabled, true); + assert.equal(hookB.enabled, true); + assert.equal(statusCalls, 1, 'mounting two hooks must share one initial poll'); + + await act(async () => t.mock.timers.tick(EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS)); + assert.equal(statusCalls, 2, 'one 3s tick must fire exactly one status check across both hooks'); + + // Unmounting the second instance keeps the shared poller running + await act(async () => { + renderer!.update(React.createElement(DualMount, { showSecond: false })); + }); + await act(async () => t.mock.timers.tick(EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS)); + assert.equal(statusCalls, 3); + + // Re-mount second instance, then hide document: polling pauses completely + await act(async () => { + renderer!.update(React.createElement(DualMount, { showSecond: true })); + }); + await setVisibility('hidden'); + await act(async () => t.mock.timers.tick(30_000)); + assert.equal(statusCalls, 3, 'hidden document must not poll externalMcpGetStatus'); + + // Runtime idles off while hidden; returning to visible immediately catches up and updates both hooks + runtimeEnabled = false; + await setVisibility('visible'); + assert.equal(statusCalls, 4, 'returning to visible must immediately check runtime status'); + assert.equal(hookA.enabled, false); + assert.equal(hookB.enabled, false); + assert.equal(readExternalMcpStoredEnabled(), false); + + // Once disabled, polling stops completely + await act(async () => t.mock.timers.tick(30_000)); + assert.equal(statusCalls, 4, 'disabled switch must stop polling'); + } finally { + if (renderer) await act(async () => renderer!.unmount()); + assert.equal(visibilityListeners.size, 0, 'visibility listener must detach when ref-count reaches 0'); + resetExternalMcpStartupReadyForTests(); + if (previousDocument) Object.defineProperty(globalThis, 'document', previousDocument); + else Reflect.deleteProperty(globalThis, 'document'); + if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow); + else Reflect.deleteProperty(globalThis, 'window'); + if (previousAct) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previousAct); + else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + restoreStorage(); + t.mock.timers.reset(); + } + }); }); diff --git a/application/state/useExternalMcpToggleState.ts b/application/state/useExternalMcpToggleState.ts index 5a08047ab..be24e7485 100644 --- a/application/state/useExternalMcpToggleState.ts +++ b/application/state/useExternalMcpToggleState.ts @@ -42,6 +42,98 @@ let externalMcpStartupReadyWaitResolve: (() => void) | null = null; /** Bumps on every intentional enable/disable so stale startup applies lose. */ let externalMcpEnableGeneration = 0; let externalMcpConfigError: string | null = null; +// Module-level ref-counted runtime status poller so multiple mounted hook +// instances (AppView + Settings > AI) share a single 3s timer and pause while hidden. +let externalMcpPollRefs = 0; +let externalMcpPollIntervalId: ReturnType | null = null; +let externalMcpPollInFlight = false; +let externalMcpPollGeneration = 0; +let externalMcpPollVisibilityDocument: Document | null = null; + +function isExternalMcpDocumentHidden(): boolean { + if (typeof document === 'undefined') return false; + if (typeof document.visibilityState === 'string') { + return document.visibilityState === 'hidden'; + } + return document.hidden === true; +} + +async function syncExternalMcpRuntimeStatus(): Promise { + if (externalMcpPollRefs <= 0 || externalMcpPollInFlight || isExternalMcpDocumentHidden()) { + return; + } + const generation = externalMcpPollGeneration; + externalMcpPollInFlight = true; + try { + // Wait until App has finished startup reconcile so a still-disabled runtime + // is not mistaken for "user turned it off / idle timeout". + await waitForExternalMcpStartupReady(); + if (generation !== externalMcpPollGeneration || externalMcpPollRefs <= 0 || isExternalMcpDocumentHidden()) { + return; + } + const status = await netcattyBridge.get()?.externalMcpGetStatus?.(); + if (generation !== externalMcpPollGeneration || externalMcpPollRefs <= 0) { + return; + } + // Only clear the shared switch for an intentional runtime-off (idle / + // explicit disable). Start failures set error and should keep preference. + if (status?.ok && !status.enabled && !status.error) { + localStorageAdapter.writeBoolean(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED, false); + emitAIStateChanged(STORAGE_KEY_AI_EXTERNAL_MCP_ENABLED); + } + } catch { + // Keep the user's stored switch state during transient bridge errors. + } finally { + externalMcpPollInFlight = false; + } +} + +function syncExternalMcpPollTimer(): void { + const shouldPoll = externalMcpPollRefs > 0 && !isExternalMcpDocumentHidden(); + if (shouldPoll) { + if (externalMcpPollIntervalId === null) { + externalMcpPollIntervalId = setInterval(() => { + void syncExternalMcpRuntimeStatus(); + }, EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS); + } + } else if (externalMcpPollIntervalId !== null) { + clearInterval(externalMcpPollIntervalId); + externalMcpPollIntervalId = null; + } +} + +function handleExternalMcpVisibilityChange(): void { + if (isExternalMcpDocumentHidden()) { + externalMcpPollGeneration += 1; + syncExternalMcpPollTimer(); + return; + } + syncExternalMcpPollTimer(); + void syncExternalMcpRuntimeStatus(); +} + +function attachExternalMcpVisibilityListener(): void { + if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') { + return; + } + if (externalMcpPollVisibilityDocument === document) return; + if ( + externalMcpPollVisibilityDocument + && typeof externalMcpPollVisibilityDocument.removeEventListener === 'function' + ) { + externalMcpPollVisibilityDocument.removeEventListener('visibilitychange', handleExternalMcpVisibilityChange); + } + document.addEventListener('visibilitychange', handleExternalMcpVisibilityChange); + externalMcpPollVisibilityDocument = document; +} + +function detachExternalMcpVisibilityListener(): void { + if (!externalMcpPollVisibilityDocument) return; + if (typeof externalMcpPollVisibilityDocument.removeEventListener === 'function') { + externalMcpPollVisibilityDocument.removeEventListener('visibilitychange', handleExternalMcpVisibilityChange); + } + externalMcpPollVisibilityDocument = null; +} function getWindowHash(hash?: string): string { if (typeof hash === 'string') return hash; @@ -81,6 +173,14 @@ export function resetExternalMcpStartupReadyForTests(): void { externalMcpEnableGeneration = 0; externalMcpConfigError = null; externalMcpStartupSyncPromise = null; + if (externalMcpPollIntervalId !== null) { + clearInterval(externalMcpPollIntervalId); + externalMcpPollIntervalId = null; + } + detachExternalMcpVisibilityListener(); + externalMcpPollRefs = 0; + externalMcpPollInFlight = false; + externalMcpPollGeneration = 0; } export function getExternalMcpEnableGenerationForTests(): number { @@ -763,35 +863,26 @@ export function useExternalMcpToggleState() { useEffect(() => { // Peer windows must never auto-clear the shared stored switch from runtime status. if (isPeerSessionWindow || !enabled) return; - let cancelled = false; - const syncRuntimeStatus = async () => { - try { - // Wait until App has finished startup reconcile so a still-disabled runtime - // is not mistaken for "user turned it off / idle timeout". - await waitForExternalMcpStartupReady(); - if (cancelled) return; - const status = await netcattyBridge.get()?.externalMcpGetStatus?.(); - if (cancelled) return; - // Only clear the shared switch for an intentional runtime-off (idle / - // explicit disable). Start failures set error and should keep preference. - if (status?.ok && !status.enabled && !status.error) { - persistEnabled(false); - } - } catch { - // Keep the user's stored switch state during transient bridge errors. + externalMcpPollRefs += 1; + if (externalMcpPollRefs === 1) { + externalMcpPollGeneration += 1; + attachExternalMcpVisibilityListener(); + syncExternalMcpPollTimer(); + void syncExternalMcpRuntimeStatus(); + } else if (!isExternalMcpDocumentHidden() && externalMcpPollIntervalId === null) { + syncExternalMcpPollTimer(); + } + + return () => { + externalMcpPollRefs = Math.max(0, externalMcpPollRefs - 1); + if (externalMcpPollRefs === 0) { + externalMcpPollGeneration += 1; + detachExternalMcpVisibilityListener(); + syncExternalMcpPollTimer(); } }; - - const intervalId = window.setInterval(() => { - void syncRuntimeStatus(); - }, EXTERNAL_MCP_RUNTIME_STATUS_POLL_MS); - void syncRuntimeStatus(); - return () => { - cancelled = true; - window.clearInterval(intervalId); - }; - }, [enabled, isPeerSessionWindow, persistEnabled]); + }, [enabled, isPeerSessionWindow]); return { enabled, setEnabled, error }; } diff --git a/application/state/useMonitorRuntime.ts b/application/state/useMonitorRuntime.ts index beb472966..7c232478a 100644 --- a/application/state/useMonitorRuntime.ts +++ b/application/state/useMonitorRuntime.ts @@ -159,18 +159,32 @@ export function useMonitorRuntime() { retryVersion, ]); // Poll every second while anything is monitored (here or in another window); - // otherwise only every 10 s to notice monitors started elsewhere. Starting a - // panel here publishes demand and reads a snapshot immediately, and flipping - // `hasRunningPanels` restarts this loop at the fast cadence. + // otherwise only every 10 s to notice monitors started elsewhere. Pause + // renderer polling while hidden and run an immediate catch-up poll on return + // to visible (main-process sampling stays untouched). const hasRunningPanels = running.size > 0; useEffect(() => { const bridge = netcattyBridge.get(); let disposed = false; let pending = false; + let resyncOnIdle = false; let remoteRunning = false; let timer: ReturnType | null = null; + const isHidden = () => { + if (typeof document === "undefined") return false; + if (typeof document.visibilityState === "string") { + return document.visibilityState === "hidden"; + } + return document.hidden === true; + }; + const clearTimer = () => { + if (timer) { + clearTimeout(timer); + timer = null; + } + }; const poll = async () => { - if (pending || !bridge?.monitorSnapshot) return; + if (disposed || pending || isHidden() || !bridge?.monitorSnapshot) return; pending = true; try { const snapshot = await bridge.monitorSnapshot(getMonitorHistoryCursor()); @@ -196,15 +210,41 @@ export function useMonitorRuntime() { } }; const schedule = () => { - if (disposed) return; + if (disposed || isHidden()) return; + if (resyncOnIdle) { + resyncOnIdle = false; + void poll().finally(schedule); + return; + } + clearTimer(); timer = setTimeout(() => { + timer = null; void poll().finally(schedule); }, hasRunningPanels || remoteRunning ? 1000 : 10_000); }; - void poll().finally(schedule); + const handleVisibilityChange = () => { + if (disposed) return; + if (isHidden()) { + resyncOnIdle = false; + clearTimer(); + return; + } + clearTimer(); + if (pending) { + resyncOnIdle = true; + return; + } + void poll().finally(schedule); + }; + const doc = typeof document !== "undefined" ? document : null; + doc?.addEventListener?.("visibilitychange", handleVisibilityChange); + if (!isHidden()) { + void poll().finally(schedule); + } return () => { disposed = true; - if (timer) clearTimeout(timer); + clearTimer(); + doc?.removeEventListener?.("visibilitychange", handleVisibilityChange); }; }, [hasRunningPanels]); } diff --git a/application/state/useMonitorRuntime.visibility.test.tsx b/application/state/useMonitorRuntime.visibility.test.tsx new file mode 100644 index 000000000..95c2969af --- /dev/null +++ b/application/state/useMonitorRuntime.visibility.test.tsx @@ -0,0 +1,195 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import React, { act } from "react"; +import { create, type ReactTestRenderer } from "react-test-renderer"; +import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; +import { + AppSettingsRuntimeContext, + AppVaultRuntimeContext, + type AppSettingsRuntime, + type AppVaultContextValue, +} from "./appRuntimeBridge"; +import { useMonitorRuntime } from "./useMonitorRuntime"; + +const MOCK_VAULT_CONTEXT = { + hosts: [], + keys: [], + identities: [], + groupConfigs: [], + proxyProfiles: [], + knownHosts: [], + isInitialized: true, +} as unknown as AppVaultContextValue; + +const MOCK_SETTINGS_CONTEXT = { + terminalSettings: { verifyHostKeys: true, keepaliveInterval: 30, keepaliveCountMax: 10 }, +} as unknown as AppSettingsRuntime; + +function wrapWithProviders(node: React.ReactElement) { + return React.createElement( + AppVaultRuntimeContext.Provider, + { value: MOCK_VAULT_CONTEXT }, + React.createElement( + AppSettingsRuntimeContext.Provider, + { value: MOCK_SETTINGS_CONTEXT }, + node, + ), + ); +} + +function installDomGlobals(initialVisibility: DocumentVisibilityState = "visible") { + const previous = new Map(); + const setGlobal = (key: string, value: unknown) => { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + }; + + const visibilityListeners = new Set<() => void>(); + const windowListeners = new Map void>>(); + const backing = new Map(); + const storage: Storage = { + get length() { return backing.size; }, + clear() { backing.clear(); }, + getItem(key) { return backing.get(key) ?? null; }, + key(index) { return Array.from(backing.keys())[index] ?? null; }, + removeItem(key) { backing.delete(key); }, + setItem(key, value) { backing.set(key, value); }, + }; + let visibilityState: DocumentVisibilityState = initialVisibility; + + setGlobal("IS_REACT_ACT_ENVIRONMENT", true); + setGlobal("localStorage", storage); + setGlobal("window", { + addEventListener(type: string, listener: () => void) { + let set = windowListeners.get(type); + if (!set) { + set = new Set(); + windowListeners.set(type, set); + } + set.add(listener); + }, + removeEventListener(type: string, listener: () => void) { + windowListeners.get(type)?.delete(listener); + }, + dispatchEvent() { return true; }, + }); + setGlobal("document", { + get visibilityState() { return visibilityState; }, + get hidden() { return visibilityState === "hidden"; }, + addEventListener(type: string, listener: () => void) { + if (type === "visibilitychange") visibilityListeners.add(listener); + }, + removeEventListener(type: string, listener: () => void) { + if (type === "visibilitychange") visibilityListeners.delete(listener); + }, + }); + + return { + visibilityListeners, + async setVisibility(next: DocumentVisibilityState) { + visibilityState = next; + await act(async () => { + for (const listener of [...visibilityListeners]) listener(); + }); + }, + restore() { + for (const [key, desc] of previous.entries()) { + if (desc) Object.defineProperty(globalThis, key, desc); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; +} + +test("useMonitorRuntime pauses monitorSnapshot polling when hidden and catches up immediately on visible", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 }); + const env = installDomGlobals("visible"); + + let snapshotCalls = 0; + let updateCalls = 0; + + t.mock.method(netcattyBridge, "get", () => ({ + monitorUpdate: async () => { + updateCalls += 1; + return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} }; + }, + monitorSnapshot: async () => { + snapshotCalls += 1; + return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} }; + }, + monitorStopAll: async () => undefined, + })); + + function Probe() { + useMonitorRuntime(); + return null; + } + + let root: ReactTestRenderer | undefined; + try { + await act(async () => { + root = create(wrapWithProviders(React.createElement(Probe))); + }); + assert.equal(snapshotCalls, 1, "initial visible poll should run on mount"); + const initialUpdateCalls = updateCalls; + + // Idle polling interval is 10s while visible + await act(async () => t.mock.timers.tick(10_000)); + assert.equal(snapshotCalls, 2); + + // Hide document: renderer polling pauses, main-process demand is untouched + await env.setVisibility("hidden"); + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(snapshotCalls, 2, "hidden document must not poll monitorSnapshot"); + assert.equal(updateCalls, initialUpdateCalls, "main-process monitorUpdate must stay untouched"); + + // Return to visible: immediate catch-up poll + resumes 10s timer + await env.setVisibility("visible"); + assert.equal(snapshotCalls, 3, "returning to visible must immediately poll monitorSnapshot"); + + await act(async () => t.mock.timers.tick(10_000)); + assert.equal(snapshotCalls, 4, "polling must resume after returning to visible"); + } finally { + await act(async () => { root?.unmount(); }); + assert.equal(env.visibilityListeners.size, 0, "visibility listener must detach on unmount"); + env.restore(); + t.mock.timers.reset(); + } +}); + +test("useMonitorRuntime mounted while hidden waits until visible to poll", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 }); + const env = installDomGlobals("hidden"); + + let snapshotCalls = 0; + + t.mock.method(netcattyBridge, "get", () => ({ + monitorUpdate: async () => ({ epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} }), + monitorSnapshot: async () => { + snapshotCalls += 1; + return { epoch: 1, runtimeId: "rt-1", panels: {}, hosts: {}, history: {} }; + }, + monitorStopAll: async () => undefined, + })); + + function Probe() { + useMonitorRuntime(); + return null; + } + + let root: ReactTestRenderer | undefined; + try { + await act(async () => { + root = create(wrapWithProviders(React.createElement(Probe))); + }); + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(snapshotCalls, 0, "mounted while hidden must not poll monitorSnapshot"); + + await env.setVisibility("visible"); + assert.equal(snapshotCalls, 1, "becoming visible must trigger catch-up poll"); + } finally { + await act(async () => { root?.unmount(); }); + env.restore(); + t.mock.timers.reset(); + } +}); diff --git a/application/state/usePortForwardingState.heartbeat.test.tsx b/application/state/usePortForwardingState.heartbeat.test.tsx new file mode 100644 index 000000000..b909bf09c --- /dev/null +++ b/application/state/usePortForwardingState.heartbeat.test.tsx @@ -0,0 +1,174 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import React, { act } from "react"; +import { create, type ReactTestRenderer } from "react-test-renderer"; +import { netcattyBridge } from "../../infrastructure/services/netcattyBridge"; +import { + resetPortForwardingStateForTests, + shouldRunPortForwardingHeartbeat, + usePortForwardingState, + type UsePortForwardingStateResult, +} from "./usePortForwardingState"; + +function installDomGlobals() { + const previous = new Map(); + const setGlobal = (key: string, value: unknown) => { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + }; + + const backing = new Map(); + const storage: Storage = { + get length() { return backing.size; }, + clear() { backing.clear(); }, + getItem(key) { return backing.get(key) ?? null; }, + key(index) { return Array.from(backing.keys())[index] ?? null; }, + removeItem(key) { backing.delete(key); }, + setItem(key, value) { backing.set(key, value); }, + }; + + const visibilityListeners = new Set<() => void>(); + let visibilityState: DocumentVisibilityState = "visible"; + + setGlobal("IS_REACT_ACT_ENVIRONMENT", true); + setGlobal("localStorage", storage); + setGlobal("window", { + addEventListener() {}, + removeEventListener() {}, + dispatchEvent() { return true; }, + }); + setGlobal("document", { + get visibilityState() { return visibilityState; }, + get hidden() { return visibilityState === "hidden"; }, + addEventListener(type: string, listener: () => void) { + if (type === "visibilitychange") visibilityListeners.add(listener); + }, + removeEventListener(type: string, listener: () => void) { + if (type === "visibilitychange") visibilityListeners.delete(listener); + }, + }); + + return { + visibilityListeners, + async setVisibility(next: DocumentVisibilityState) { + visibilityState = next; + await act(async () => { + for (const listener of [...visibilityListeners]) listener(); + }); + }, + restore() { + for (const [key, desc] of previous.entries()) { + if (desc) Object.defineProperty(globalThis, key, desc); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; +} + +test("usePortForwardingState disarms heartbeat with 0 rules, arms dynamically on rule add, pauses when hidden, and reconciles on visible", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "setInterval", "Date"], now: 10_000 }); + const env = installDomGlobals(); + resetPortForwardingStateForTests(); + + let listCalls = 0; + let failList = false; + + t.mock.method(netcattyBridge, "get", () => ({ + listPortForwards: async () => { + listCalls += 1; + if (failList) throw new Error("backend unavailable"); + return []; + }, + subscribePortForwardRuntime: async () => ({ epoch: "e1", revision: 0, tunnels: [] }), + onPortForwardRuntime: () => () => undefined, + unsubscribePortForwardRuntime: async () => undefined, + stopPortForwardByRuleId: async () => ({ stopped: 0, failed: 0, errors: [] }), + })); + + let api!: UsePortForwardingStateResult; + function Probe() { + api = usePortForwardingState(); + return null; + } + + let root: ReactTestRenderer | undefined; + try { + await act(async () => { + root = create(React.createElement(Probe)); + }); + + // Startup init + runtime subscription run initial syncs, after which + // snapshotAvailable is true and globalRules is empty -> heartbeat disarms. + const baselineCalls = listCalls; + assert.equal(shouldRunPortForwardingHeartbeat(), false); + + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(listCalls, baselineCalls, "0 rules + healthy snapshot must not run 4s heartbeat"); + + // Dynamically adding a rule arms the 4s heartbeat without remounting. + let createdId = ""; + await act(async () => { + const created = api.addRule({ + label: "Web", + type: "local", + localPort: 8080, + remoteHost: "127.0.0.1", + remotePort: 80, + hostId: "host-1", + bindAddress: "127.0.0.1", + }); + createdId = created.id; + }); + assert.equal(shouldRunPortForwardingHeartbeat(), true); + + await act(async () => t.mock.timers.tick(4_000)); + assert.equal(listCalls, baselineCalls + 1, "heartbeat should fire after rule is added"); + + // Hiding the document pauses the 4s heartbeat. + await env.setVisibility("hidden"); + assert.equal(shouldRunPortForwardingHeartbeat(), false); + const hiddenCalls = listCalls; + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(listCalls, hiddenCalls, "hidden document must not fire heartbeat ticks"); + + // Returning to visible triggers immediate reconcileWithBackend() and resumes 4s ticks. + await env.setVisibility("visible"); + assert.equal(listCalls, hiddenCalls + 1, "returning to visible must immediately reconcile"); + await act(async () => t.mock.timers.tick(4_000)); + assert.equal(listCalls, hiddenCalls + 2, "4s heartbeat must resume after returning to visible"); + + // Deleting the last rule dynamically disarms the heartbeat again. + await act(async () => { + api.deleteRule(createdId); + }); + assert.equal(shouldRunPortForwardingHeartbeat(), false); + const afterDeleteCalls = listCalls; + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(listCalls, afterDeleteCalls, "deleting last rule must disarm heartbeat"); + + // Snapshot unavailable keeps heartbeat armed even with 0 rules until recovery. + await act(async () => { root?.unmount(); }); + resetPortForwardingStateForTests(); + failList = true; + listCalls = 0; + + await act(async () => { + root = create(React.createElement(Probe)); + }); + assert.equal(shouldRunPortForwardingHeartbeat(), true, "unavailable snapshot must keep heartbeat armed"); + const unavailableBaseline = listCalls; + + failList = false; + await act(async () => t.mock.timers.tick(4_000)); + assert.equal(listCalls, unavailableBaseline + 1, "recovery heartbeat tick must fire when snapshot was unavailable"); + assert.equal(shouldRunPortForwardingHeartbeat(), false, "heartbeat must disarm once snapshot recovers with 0 rules"); + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(listCalls, unavailableBaseline + 1); + } finally { + await act(async () => { root?.unmount(); }); + assert.equal(env.visibilityListeners.size, 0, "visibility listener must detach on unmount"); + resetPortForwardingStateForTests(); + env.restore(); + t.mock.timers.reset(); + } +}); diff --git a/application/state/usePortForwardingState.ts b/application/state/usePortForwardingState.ts index ac4b57c4a..f70049c22 100644 --- a/application/state/usePortForwardingState.ts +++ b/application/state/usePortForwardingState.ts @@ -43,9 +43,21 @@ let reconnectCancelListenerRefs = 0; let reconnectCancelCleanup: (() => void) | undefined; let heartbeatRefs = 0; let heartbeatIntervalId: ReturnType | undefined; +let heartbeatTickInFlight = false; +let heartbeatVisibilityDocument: Document | null = null; let runtimeSubscriptionRefs = 0; let runtimeSubscriptionCleanup: (() => void) | undefined; +const HEARTBEAT_INTERVAL_MS = 4_000; + +const isPortForwardingDocumentHidden = (): boolean => { + if (typeof document === "undefined") return false; + if (typeof document.visibilityState === "string") { + return document.visibilityState === "hidden"; + } + return document.hidden === true; +}; + export type { ViewMode }; export type SortMode = "manual" | "az" | "za" | "newest" | "oldest"; @@ -123,6 +135,104 @@ const listeners = new Set<(rules: PortForwardingRule[]) => void>(); // Store Actions const notifyListeners = () => { listeners.forEach((listener) => listener(globalRules)); + syncPortForwardingHeartbeatTimer(); +}; + +export const shouldRunPortForwardingHeartbeat = (): boolean => ( + heartbeatRefs > 0 + && !isPortForwardingDocumentHidden() + && (globalRules.length > 0 || hasActivePortForwardRuntime() || !snapshotAvailable) +); + +const runPortForwardingHeartbeatTick = async (): Promise => { + if (heartbeatTickInFlight || heartbeatRefs <= 0 || isPortForwardingDocumentHidden()) { + return; + } + heartbeatTickInFlight = true; + try { + const reconciliation = await reconcileWithBackend(); + snapshotAvailable = reconciliation.snapshotAvailable; + if (!reconciliation.snapshotAvailable) { + // Snapshot failure must surface as unknown/stale — never as inactive. + applyRuntimeSnapshotProjection(new Set(), false); + return; + } + // Always re-derive the visible state from the live connection map. + // Runtime phases stay in memory only. + const normalizedRules = normalizeRulesWithConnections( + globalRules, + { + reconciledGoneRuleIds: new Set(reconciliation.gone), + snapshotAvailable: true, + }, + ); + if (havePortForwardingRuntimeStatesChanged(globalRules, normalizedRules)) { + setRuntimeProjection(normalizedRules); + } else if (hasPortForwardingRuntimePresenceChanged(reconciliation)) { + globalRules = normalizedRules; + notifyListeners(); + } + } finally { + heartbeatTickInFlight = false; + syncPortForwardingHeartbeatTimer(); + } +}; + +const syncPortForwardingHeartbeatTimer = (): void => { + if (shouldRunPortForwardingHeartbeat()) { + if (heartbeatIntervalId === undefined) { + heartbeatIntervalId = setInterval(() => { + void runPortForwardingHeartbeatTick(); + }, HEARTBEAT_INTERVAL_MS); + } + } else if (heartbeatIntervalId !== undefined) { + clearInterval(heartbeatIntervalId); + heartbeatIntervalId = undefined; + } +}; + +const handlePortForwardingVisibilityChange = (): void => { + if (isPortForwardingDocumentHidden()) { + syncPortForwardingHeartbeatTimer(); + return; + } + syncPortForwardingHeartbeatTimer(); + if (shouldRunPortForwardingHeartbeat()) { + void runPortForwardingHeartbeatTick(); + } +}; + +const attachPortForwardingVisibilityListener = (): void => { + if (typeof document === "undefined" || typeof document.addEventListener !== "function") { + return; + } + if (heartbeatVisibilityDocument === document) return; + if (heartbeatVisibilityDocument && typeof heartbeatVisibilityDocument.removeEventListener === "function") { + heartbeatVisibilityDocument.removeEventListener("visibilitychange", handlePortForwardingVisibilityChange); + } + document.addEventListener("visibilitychange", handlePortForwardingVisibilityChange); + heartbeatVisibilityDocument = document; +}; + +const detachPortForwardingVisibilityListener = (): void => { + if (!heartbeatVisibilityDocument) return; + if (typeof heartbeatVisibilityDocument.removeEventListener === "function") { + heartbeatVisibilityDocument.removeEventListener("visibilitychange", handlePortForwardingVisibilityChange); + } + heartbeatVisibilityDocument = null; +}; + +export const resetPortForwardingStateForTests = (): void => { + if (heartbeatIntervalId !== undefined) { + clearInterval(heartbeatIntervalId); + heartbeatIntervalId = undefined; + } + detachPortForwardingVisibilityListener(); + heartbeatRefs = 0; + heartbeatTickInFlight = false; + globalRules = []; + isInitialized = false; + snapshotAvailable = false; }; const persistPortForwardingConfig = (rules: PortForwardingRule[]) => { @@ -333,6 +443,7 @@ const initializeStore = async () => { snapshotAvailable, })); } + syncPortForwardingHeartbeatTimer(); }; const subscribeToPortForwardRuntime = (): (() => void) => { @@ -367,6 +478,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => { snapshotAvailable = reconciliation.snapshotAvailable; if (!reconciliation.snapshotAvailable) { applyRuntimeSnapshotProjection(new Set(), false); + syncPortForwardingHeartbeatTimer(); return; } applyRuntimeSnapshotProjection( @@ -374,10 +486,12 @@ const subscribeToPortForwardRuntime = (): (() => void) => { true, reconciliation.appeared, ); + syncPortForwardingHeartbeatTimer(); } catch { if (disposed) return; snapshotAvailable = false; applyRuntimeSnapshotProjection(new Set(), false); + syncPortForwardingHeartbeatTimer(); } }; @@ -399,6 +513,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => { snapshotAvailable = reconciliation.snapshotAvailable; if (!reconciliation.snapshotAvailable) { applyRuntimeSnapshotProjection(new Set(), false); + syncPortForwardingHeartbeatTimer(); return; } applyRuntimeSnapshotProjection( @@ -406,6 +521,7 @@ const subscribeToPortForwardRuntime = (): (() => void) => { true, reconciliation.appeared, ); + syncPortForwardingHeartbeatTimer(); }); }); @@ -524,47 +640,20 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => { }, []); // Periodic heartbeat: reconcile renderer state with the backend every 4s. - // Ref-counted — same pattern as the reconnect cancel listener. + // Ref-counted and dynamically armed only while visible and needed (rules + // configured, active runtime tunnels, or runtime snapshot not yet available). useEffect(() => { heartbeatRefs++; - let intervalId: ReturnType | undefined; if (heartbeatRefs === 1) { - const HEARTBEAT_INTERVAL_MS = 4_000; - - const tick = async () => { - const reconciliation = await reconcileWithBackend(); - snapshotAvailable = reconciliation.snapshotAvailable; - if (!reconciliation.snapshotAvailable) { - // Snapshot failure must surface as unknown/stale — never as inactive. - applyRuntimeSnapshotProjection(new Set(), false); - return; - } - // Always re-derive the visible state from the live connection map. - // Runtime phases stay in memory only. - const normalizedRules = normalizeRulesWithConnections( - globalRules, - { - reconciledGoneRuleIds: new Set(reconciliation.gone), - snapshotAvailable: true, - }, - ); - if (havePortForwardingRuntimeStatesChanged(globalRules, normalizedRules)) { - setRuntimeProjection(normalizedRules); - } else if (hasPortForwardingRuntimePresenceChanged(reconciliation)) { - globalRules = normalizedRules; - notifyListeners(); - } - }; - - intervalId = setInterval(tick, HEARTBEAT_INTERVAL_MS); - heartbeatIntervalId = intervalId; + attachPortForwardingVisibilityListener(); } + syncPortForwardingHeartbeatTimer(); return () => { - heartbeatRefs--; - if (heartbeatRefs === 0 && heartbeatIntervalId !== undefined) { - clearInterval(heartbeatIntervalId); - heartbeatIntervalId = undefined; + heartbeatRefs = Math.max(0, heartbeatRefs - 1); + if (heartbeatRefs === 0) { + detachPortForwardingVisibilityListener(); } + syncPortForwardingHeartbeatTimer(); }; }, []); @@ -831,6 +920,14 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => { const selectedRule = rules.find((r) => r.id === selectedRuleId); + const stopRuleTunnels = useCallback(async (ruleId: string) => { + try { + return await stopAndCleanupRuleAndWait(ruleId); + } finally { + syncPortForwardingHeartbeatTimer(); + } + }, []); + return { rules, selectedRuleId, @@ -857,7 +954,7 @@ export const usePortForwardingState = (): UsePortForwardingStateResult => { stopTunnel, startAllTunnels, stopAllTunnels, - stopRuleTunnels: stopAndCleanupRuleAndWait, + stopRuleTunnels, hasRuntimeTunnel, hasAnyRuntimeTunnel, diff --git a/application/state/useServerStats.recovery.test.ts b/application/state/useServerStats.recovery.test.ts index 3e2335c4a..0cc7bde59 100644 --- a/application/state/useServerStats.recovery.test.ts +++ b/application/state/useServerStats.recovery.test.ts @@ -94,3 +94,88 @@ test('stats reply after disabling cannot publish or schedule recovery', async t t.mock.timers.reset(); } }); + +test('server stats pauses while document is hidden, preserves cached stats, and catches up on visible', async t => { + t.mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'], now: 10_000 }); + const originalActEnvironment = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + const originalDocument = Object.getOwnPropertyDescriptor(globalThis, 'document'); + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true }); + + const visibilityListeners = new Set<() => void>(); + let visibilityState: DocumentVisibilityState = 'visible'; + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { + get visibilityState() { return visibilityState; }, + get hidden() { return visibilityState === 'hidden'; }, + addEventListener(type: string, listener: () => void) { + if (type === 'visibilitychange') visibilityListeners.add(listener); + }, + removeEventListener(type: string, listener: () => void) { + if (type === 'visibilitychange') visibilityListeners.delete(listener); + }, + }, + }); + + const setVisibility = async (next: DocumentVisibilityState) => { + visibilityState = next; + await act(async () => { + for (const listener of [...visibilityListeners]) listener(); + }); + }; + + let calls = 0; + t.mock.method(netcattyBridge, 'get', () => ({ + getServerStats: async () => { + calls += 1; + return { success: true, stats: { cpu: 20 + calls } }; + }, + })); + + let current: ReturnType; + function Probe() { + current = useServerStats({ + sessionId: 'visibility-pause', + enabled: true, + refreshInterval: 5, + isSupportedOs: true, + isConnected: true, + }); + return null; + } + + let root: ReactTestRenderer; + try { + await act(async () => { root = create(React.createElement(Probe)); }); + assert.equal(visibilityListeners.size, 1); + + // Warmup initial fetch at 2000ms + await act(async () => t.mock.timers.tick(2000)); + assert.equal(calls, 1); + assert.equal(current!.stats.cpu, 21); + + // Transition to hidden: polling pauses and cached stats stay intact + await setVisibility('hidden'); + await act(async () => t.mock.timers.tick(60_000)); + assert.equal(calls, 1, 'hidden window must not poll server stats'); + assert.equal(current!.stats.cpu, 21, 'cached stats must be preserved while hidden'); + + // Return to visible: immediate catch-up fetch (0ms) + resumes 5s polling + await setVisibility('visible'); + await act(async () => t.mock.timers.tick(0)); + assert.equal(calls, 2, 'returning to visible must trigger immediate catch-up fetch'); + assert.equal(current!.stats.cpu, 22); + + await act(async () => t.mock.timers.tick(5000)); + assert.equal(calls, 3, 'periodic polling must resume after returning to visible'); + assert.equal(current!.stats.cpu, 23); + } finally { + await act(async () => root?.unmount()); + assert.equal(visibilityListeners.size, 0, 'visibility listener must detach when all sessions unmount'); + if (originalDocument) Object.defineProperty(globalThis, 'document', originalDocument); + else Reflect.deleteProperty(globalThis, 'document'); + if (originalActEnvironment) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', originalActEnvironment); + else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT'); + t.mock.timers.reset(); + } +}); diff --git a/application/state/useServerStats.ts b/application/state/useServerStats.ts index 523724def..bff898b03 100644 --- a/application/state/useServerStats.ts +++ b/application/state/useServerStats.ts @@ -114,6 +114,41 @@ interface SharedServerStatsSession { const CONSECUTIVE_FAILURE_LIMIT = 3; const serverStatsSessions = new Map(); let nextClientId = 1; +let attachedVisibilityDocument: Document | null = null; + +function isServerStatsDocumentHidden(): boolean { + if (typeof document === 'undefined') return false; + if (typeof document.visibilityState === 'string') { + return document.visibilityState === 'hidden'; + } + return document.hidden === true; +} + +function handleServerStatsVisibilityChange(): void { + for (const session of serverStatsSessions.values()) { + reconcileSharedServerStatsSession(session); + } +} + +function ensureServerStatsVisibilityListener(): void { + if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') { + return; + } + if (attachedVisibilityDocument === document) return; + if (attachedVisibilityDocument && typeof attachedVisibilityDocument.removeEventListener === 'function') { + attachedVisibilityDocument.removeEventListener('visibilitychange', handleServerStatsVisibilityChange); + } + document.addEventListener('visibilitychange', handleServerStatsVisibilityChange); + attachedVisibilityDocument = document; +} + +function maybeDetachServerStatsVisibilityListener(): void { + if (serverStatsSessions.size > 0 || !attachedVisibilityDocument) return; + if (typeof attachedVisibilityDocument.removeEventListener === 'function') { + attachedVisibilityDocument.removeEventListener('visibilitychange', handleServerStatsVisibilityChange); + } + attachedVisibilityDocument = null; +} function createEmptyServerStats(): ServerStats { return { @@ -281,6 +316,7 @@ async function fetchSharedServerStats(session: SharedServerStatsSession, force = } if (session.givenUp && !force) return; if (getActiveServerStatsClients(session).length === 0) return; + if (!force && isServerStatsDocumentHidden()) return; const bridge = netcattyBridge.get(); if (!bridge?.getServerStats) return; @@ -348,13 +384,13 @@ async function fetchSharedServerStats(session: SharedServerStatsSession, force = function reconcileSharedServerStatsSession(session: SharedServerStatsSession): void { const activeClients = getActiveServerStatsClients(session); - if (activeClients.length === 0) { - // Pause polling only. Keep the last successful stats so remounting Overview - // (or re-enabling a terminal stats strip) can paint immediately instead of - // flashing "No system overview data yet." Still clear give-up / failure so a - // later resume can auto-retry (old reset wiped stats + flags together). - // Invalidate a request before pausing: a late reply must not publish data - // or re-arm failure/retry timers after disconnect/disable. + if (activeClients.length === 0 || isServerStatsDocumentHidden()) { + // Pause polling only. Keep the last successful stats so remounting Overview, + // re-enabling a terminal stats strip, or returning from a hidden window + // can paint immediately instead of flashing "No system overview data yet." + // Still clear give-up / failure so a later resume can auto-retry (old reset + // wiped stats + flags together). Invalidate a request before pausing: a late + // reply must not publish data or re-arm failure/retry timers after pause. if (session.pollingActive || session.inflight || session.givenUp) { session.fetchGeneration += 1; } @@ -398,6 +434,7 @@ function maybeDisposeSharedServerStatsSession(session: SharedServerStatsSession) clearServerStatsTimers(session); session.fetchGeneration += 1; serverStatsSessions.delete(session.sessionId); + maybeDetachServerStatsVisibilityListener(); } export function useServerStats({ @@ -420,6 +457,7 @@ export function useServerStats({ const clientId = clientIdRef.current; if (clientId === null) return; + ensureServerStatsVisibilityListener(); const listener: ServerStatsListener = (nextState) => { setState(nextState); }; diff --git a/infrastructure/services/CloudSyncManager.ts b/infrastructure/services/CloudSyncManager.ts index 2b87ff784..dcdc8d8d9 100644 --- a/infrastructure/services/CloudSyncManager.ts +++ b/infrastructure/services/CloudSyncManager.ts @@ -204,7 +204,6 @@ export class CloudSyncManager { private adapters: Map = new Map(); private eventListeners: Set = new Set(); private stateChangeListeners: Set<() => void> = new Set(); // For useSyncExternalStore - private autoSyncTimer: ReturnType | null = null; private masterPassword: string | null = null; // In memory only! private syncSecurityGeneration = 0; private hasStorageListener = false; diff --git a/infrastructure/services/cloudSync/autoSyncTimer.test.ts b/infrastructure/services/cloudSync/autoSyncTimer.test.ts new file mode 100644 index 000000000..7cfa9bea9 --- /dev/null +++ b/infrastructure/services/cloudSync/autoSyncTimer.test.ts @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + setAutoSyncImpl, + startAutoSyncImpl, + stopAutoSyncImpl, +} from "./syncAllStorageMethods"; + +test("CloudSyncManager autoSync preferences do not schedule a dead SYNC_STARTED interval", (t) => { + t.mock.timers.enable({ apis: ["setInterval"] }); + + let emitCalls = 0; + let stateNotifications = 0; + let saveCalls = 0; + let startCalls = 0; + let stopCalls = 0; + + const manager = { + state: { + securityState: "UNLOCKED", + autoSyncEnabled: false, + autoSyncInterval: 5, + }, + saveSyncConfig() { + saveCalls += 1; + }, + notifyStateChange() { + stateNotifications += 1; + }, + emit() { + emitCalls += 1; + }, + startAutoSync() { + startCalls += 1; + startAutoSyncImpl.call(this); + }, + stopAutoSync() { + stopCalls += 1; + stopAutoSyncImpl.call(this); + }, + }; + + try { + setAutoSyncImpl.call(manager, true, 1); + assert.equal(manager.state.autoSyncEnabled, true); + assert.equal(manager.state.autoSyncInterval, 1); + assert.equal(saveCalls, 1); + assert.equal(stateNotifications, 1); + assert.equal(startCalls, 1, "startAutoSync remains callable as a compatibility no-op"); + + // Advancing 10 minutes must not trigger any dead SYNC_STARTED emission or state churn + t.mock.timers.tick(10 * 60 * 1000); + assert.equal(emitCalls, 0); + assert.equal(stateNotifications, 1); + + setAutoSyncImpl.call(manager, false); + assert.equal(manager.state.autoSyncEnabled, false); + assert.equal(stopCalls, 1, "stopAutoSync remains callable as a compatibility no-op"); + } finally { + t.mock.timers.reset(); + } +}); diff --git a/infrastructure/services/cloudSync/syncAllStorageMethods.ts b/infrastructure/services/cloudSync/syncAllStorageMethods.ts index 4a23599fc..e63495c08 100644 --- a/infrastructure/services/cloudSync/syncAllStorageMethods.ts +++ b/infrastructure/services/cloudSync/syncAllStorageMethods.ts @@ -1029,26 +1029,18 @@ export function setAutoSyncImpl(this: any,enabled: boolean, intervalMinutes?: nu } } -export function startAutoSyncImpl(this: any): void { - if (this.autoSyncTimer) { - return; - } +/** + * No-op retained for compatibility with callers and test mocks. + * Real periodic auto-sync is driven by `useAutoSync` (`application/state/useAutoSync.ts`); + * `CloudSyncManager` only stores `autoSyncEnabled` / `autoSyncInterval` preferences. + */ +export function startAutoSyncImpl(): void { + // Intentionally empty: avoid scheduling a dead interval that emits unconsumed SYNC_STARTED events. +} - this.autoSyncTimer = setInterval( - () => { - // Auto-sync callback - caller should provide payload - this.emit({ type: 'SYNC_STARTED', provider: 'github' }); // Trigger UI to initiate sync - }, - this.state.autoSyncInterval * 60 * 1000 - ); - } - -export function stopAutoSyncImpl(this: any): void { - if (this.autoSyncTimer) { - clearInterval(this.autoSyncTimer); - this.autoSyncTimer = null; - } - } +export function stopAutoSyncImpl(): void { + // Intentionally empty: no manager-owned auto-sync interval exists. +} export function saveSyncConfigImpl( this: any,