Files
Netcatty/application/state/useMonitorRuntime.ts
T
陈大猫andClaude Opus 5.5 fa554888a6 perf(terminal): stop per-second churn while connecting and while idle (#4118)
* perf(terminal): stop per-second churn while connecting and while idle

- Connecting sessions: the 200 ms progress animation and 1 s countdown were
  Terminal state threaded into the TerminalView ctx, so every connecting
  session (hidden tabs and startup restores included) re-rendered Terminal +
  TerminalView up to six times a second. Terminal now only publishes the
  timeout deadline and real progress events; the connection dialog animates
  and counts down locally (connectionTicker.ts). HostConnectionTestDialog
  keeps passing progress/timeLeft as before.
- Monitor runtime: polled every second unconditionally and woke every
  subscriber each time because takenAt always changes. It now polls at 1 s
  only while something is monitored (here or in another window), 10 s
  otherwise, and skips notifying for unchanged idle replies.
- Auto-reconnect progress log: capped at the newest 300 lines (it grew by a
  few lines every 5 s retry for as long as an outage lasted).
- App Lock: report activity at most once a second instead of an IPC per
  keystroke / wheel tick / pointer event.
- Tray/Dock: the renderer resends hosts only when the host list changed, and
  the main process rebuilds the macOS Dock menu (sort + one native item per
  host) only then, not on every session status change.

Real app, profiling build, main -> this change:
  3 SSH sessions connecting (3 s)   14 commits / 35.3 ms -> 8 / 1.7 ms
  idle (10 s)                       13 commits / 3.1 ms  -> 2 / 0.1 ms

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(terminal): update observe-popup reconnect deps assertion for capped progress logs

CI failed because #4118 wrapped setProgressLogs in useCallback to apply
capConnectionProgressLogs and added it to scheduleAutoReconnect deps.
The observe-popup source assertion still expected the old deps list.

The attachExistingSession early-return behavior is unchanged; only the
stale dependency regex needed updating.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 01:11:25 -08:00

211 lines
7.0 KiB
TypeScript

import { hostRestrictsExtraSshChannels } from "../../domain/host";
import { useEffect, useRef, useState } from "react";
import { buildHostConnectionTestPlan } from "../../domain/hostConnectionTest";
import { resolveEffectiveTerminalHost } from "../../domain/terminalHostResolution";
import { getEffectiveKnownHosts } from "../../infrastructure/syncHelpers";
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
import {
useAppLockChrome,
useAppSettingsRuntime,
useAppVaultRuntime,
} from "./appRuntimeBridge";
import { useMonitorPanels } from "./monitorPanelsStorage";
import {
monitorActions,
getMonitorHistoryCursor,
isIdleMonitorSnapshot,
publishMonitorSnapshot,
publishMonitorUnavailable,
} from "./monitorRuntimeStore";
import type { MonitorPanelDemand } from "../../domain/monitorRuntime";
/** Root lifetime, independent of Vault navigation. No runtime state is persisted. */
export function useMonitorRuntime() {
const panels = useMonitorPanels();
const {
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts,
isInitialized,
} = useAppVaultRuntime();
const { terminalSettings } = useAppSettingsRuntime();
const { locked } = useAppLockChrome();
const [running, setRunning] = useState(() => new Map<string, string>());
const [retryVersion, setRetryVersion] = useState(0);
const epoch = useRef<number | null>(null);
const runtimeId = useRef<string | null>(null);
const credentials = useRef(
new Map<string, { username: string; password: string }>(),
);
useEffect(() => {
monitorActions.start = (id) =>
setRunning((prev) => new Map(prev).set(id, crypto.randomUUID()));
monitorActions.stop = (id) =>
setRunning((prev) => {
const next = new Map(prev);
next.delete(id);
return next;
});
monitorActions.stopAll = () => {
credentials.current.clear();
setRunning(new Map());
void netcattyBridge.get()?.monitorStopAll?.();
};
monitorActions.retry = (id, override) => {
if (override) credentials.current.set(id, override);
void netcattyBridge
.get()
?.monitorRetry?.(id)
.then(() => setRetryVersion((v) => v + 1));
};
const offline = () => monitorActions.stopAll();
window.addEventListener("offline", offline);
return () => {
window.removeEventListener("offline", offline);
void netcattyBridge.get()?.monitorUpdate?.([]);
};
}, []);
useEffect(() => {
if (locked || !isInitialized) {
credentials.current.clear();
setRunning(new Map());
}
}, [locked, isInitialized]);
useEffect(() => {
const bridge = netcattyBridge.get();
if (!bridge?.monitorUpdate) {
publishMonitorUnavailable();
return;
}
const demand: MonitorPanelDemand[] =
locked || !isInitialized
? []
: panels
.filter((p) => running.has(p.id))
.map((panel) => ({
id: panel.id,
runId: running.get(panel.id)!,
interval: panel.interval,
hosts: panel.hostIds.map((id) => {
const host = hosts.find((h) => h.id === id);
if (
!host ||
(host.protocol && host.protocol !== "ssh") ||
hostRestrictsExtraSshChannels(host)
)
return { id };
const effective = resolveEffectiveTerminalHost({
host,
groupConfigs,
proxyProfiles,
});
const plan = buildHostConnectionTestPlan({
host,
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts: getEffectiveKnownHosts(knownHosts) ?? [],
terminalSettings,
sessionId: `monitor-${id}`,
bootEpoch: 0,
authOverride: credentials.current.has(id)
? { ...credentials.current.get(id), authMethod: "password" }
: null,
});
if (!plan.ok) return { id, status: "error" as const };
if (plan.needsCredentialReentry)
return { id, status: "login" as const };
return {
id,
options: {
...plan.options,
singleChannelSsh: hostRestrictsExtraSshChannels(effective),
sshAuthReadyTimeoutMs: 120000,
agentForwarding: effective.agentForwarding,
},
};
}),
}));
const activeHostIds = new Set(
demand.flatMap((p) => p.hosts.map((h) => h.id)),
);
for (const id of credentials.current.keys())
if (!activeHostIds.has(id)) credentials.current.delete(id);
void bridge
.monitorUpdate(demand)
.then(publishMonitorSnapshot)
.catch(() => {
credentials.current.clear();
setRunning((prev) => (prev.size ? new Map() : prev));
publishMonitorUnavailable();
});
}, [
panels,
running,
hosts,
keys,
identities,
groupConfigs,
proxyProfiles,
knownHosts,
terminalSettings,
locked,
isInitialized,
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.
const hasRunningPanels = running.size > 0;
useEffect(() => {
const bridge = netcattyBridge.get();
let disposed = false;
let pending = false;
let remoteRunning = false;
let timer: ReturnType<typeof setTimeout> | null = null;
const poll = async () => {
if (pending || !bridge?.monitorSnapshot) return;
pending = true;
try {
const snapshot = await bridge.monitorSnapshot(getMonitorHistoryCursor());
if (disposed) return;
remoteRunning = !isIdleMonitorSnapshot(snapshot);
if (
(epoch.current !== null && epoch.current !== snapshot.epoch) ||
(runtimeId.current !== null &&
runtimeId.current !== snapshot.runtimeId)
) {
credentials.current.clear();
setRunning(new Map());
}
epoch.current = snapshot.epoch;
runtimeId.current = snapshot.runtimeId;
publishMonitorSnapshot(snapshot);
} catch {
credentials.current.clear();
setRunning((prev) => (prev.size ? new Map() : prev));
publishMonitorUnavailable();
} finally {
pending = false;
}
};
const schedule = () => {
if (disposed) return;
timer = setTimeout(() => {
void poll().finally(schedule);
}, hasRunningPanels || remoteRunning ? 1000 : 10_000);
};
void poll().finally(schedule);
return () => {
disposed = true;
if (timer) clearTimeout(timer);
};
}, [hasRunningPanels]);
}