feat(desktop): add hot view retain/release lifecycle and process metrics
Replace single-shot acquireHotView with retainHotView/releaseHotView plus a minute-level reaper that closes views idle beyond 5 minutes and never evicts a view while it still has live retainers. Wrap adapter calls in try/finally so a failing publish/query still releases the view. Sample process metrics every minute and expose hot-view policy and process snapshot via the runtime snapshot for diagnostics. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import type {
|
|||||||
import type { DesktopAccountInfo, DesktopRuntimeSessionSyncRequest } from "@geo/shared-types";
|
import type { DesktopAccountInfo, DesktopRuntimeSessionSyncRequest } from "@geo/shared-types";
|
||||||
|
|
||||||
import { bindPublishAccount, openPublishAccountConsole } from "./account-binder";
|
import { bindPublishAccount, openPublishAccountConsole } from "./account-binder";
|
||||||
|
import { initProcessMetricsSampler } from "./process-metrics";
|
||||||
import { registerRendererDevtoolsProxyTarget } from "./renderer-devtools-proxy";
|
import { registerRendererDevtoolsProxyTarget } from "./renderer-devtools-proxy";
|
||||||
import {
|
import {
|
||||||
refreshRuntimeAccounts,
|
refreshRuntimeAccounts,
|
||||||
@@ -22,6 +23,7 @@ import { initSingleInstance } from "./single-instance";
|
|||||||
import { initTransport, listDesktopPublishTasks, retryDesktopPublishTask } from "./transport/api-client";
|
import { initTransport, listDesktopPublishTasks, retryDesktopPublishTask } from "./transport/api-client";
|
||||||
import { initTray } from "./tray";
|
import { initTray } from "./tray";
|
||||||
import { STANDARD_USER_AGENT } from "./user-agent";
|
import { STANDARD_USER_AGENT } from "./user-agent";
|
||||||
|
import { startHotViewReaper } from "./view-pool";
|
||||||
|
|
||||||
app.commandLine.appendSwitch(
|
app.commandLine.appendSwitch(
|
||||||
"disable-features",
|
"disable-features",
|
||||||
@@ -183,6 +185,8 @@ app.whenReady().then(async () => {
|
|||||||
await initSessionRegistry();
|
await initSessionRegistry();
|
||||||
initTransport();
|
initTransport();
|
||||||
initScheduler();
|
initScheduler();
|
||||||
|
initProcessMetricsSampler();
|
||||||
|
startHotViewReaper();
|
||||||
mainWindow = await createMainWindow();
|
mainWindow = await createMainWindow();
|
||||||
initTray(() => {
|
initTray(() => {
|
||||||
if (!mainWindow) {
|
if (!mainWindow) {
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { app } from "electron/main";
|
||||||
|
import type { ProcessMemoryInfo, ProcessMetric } from "electron/main";
|
||||||
|
|
||||||
|
const PROCESS_METRICS_INTERVAL_MS = 60_000;
|
||||||
|
const PROCESS_METRICS_MAX_SAMPLES = 12;
|
||||||
|
const PROCESS_METRICS_RECENT_WINDOW = 5;
|
||||||
|
|
||||||
|
interface SampledProcessMetric {
|
||||||
|
pid: number;
|
||||||
|
creationTime: number;
|
||||||
|
type: ProcessMetric["type"];
|
||||||
|
name: string | null;
|
||||||
|
serviceName: string | null;
|
||||||
|
workingSetSize: number;
|
||||||
|
peakWorkingSetSize: number;
|
||||||
|
privateBytes: number | null;
|
||||||
|
percentCPUUsage: number;
|
||||||
|
sandboxed: boolean | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProcessMetricsSample {
|
||||||
|
capturedAt: number;
|
||||||
|
mainProcess: {
|
||||||
|
pid: number;
|
||||||
|
memory: ProcessMemoryInfo | null;
|
||||||
|
};
|
||||||
|
totals: {
|
||||||
|
processCount: number;
|
||||||
|
workingSetSize: number;
|
||||||
|
privateBytes: number;
|
||||||
|
};
|
||||||
|
processes: SampledProcessMetric[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const samples: ProcessMetricsSample[] = [];
|
||||||
|
let samplerHandle: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
function normalizeProcessMetric(metric: ProcessMetric): SampledProcessMetric {
|
||||||
|
return {
|
||||||
|
pid: metric.pid,
|
||||||
|
creationTime: metric.creationTime,
|
||||||
|
type: metric.type,
|
||||||
|
name: metric.name ?? null,
|
||||||
|
serviceName: metric.serviceName ?? null,
|
||||||
|
workingSetSize: metric.memory.workingSetSize,
|
||||||
|
peakWorkingSetSize: metric.memory.peakWorkingSetSize,
|
||||||
|
privateBytes: metric.memory.privateBytes ?? null,
|
||||||
|
percentCPUUsage: Number(metric.cpu.percentCPUUsage.toFixed(2)),
|
||||||
|
sandboxed: metric.sandboxed ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function captureMainProcessMemory(): Promise<ProcessMemoryInfo | null> {
|
||||||
|
try {
|
||||||
|
return await process.getProcessMemoryInfo();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[desktop-metrics] process.getProcessMemoryInfo failed", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function sampleProcessMetrics(): Promise<void> {
|
||||||
|
const [mainProcessMemory, processMetrics] = await Promise.all([
|
||||||
|
captureMainProcessMemory(),
|
||||||
|
Promise.resolve(app.getAppMetrics()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const processes = processMetrics.map(normalizeProcessMetric);
|
||||||
|
const sample: ProcessMetricsSample = {
|
||||||
|
capturedAt: Date.now(),
|
||||||
|
mainProcess: {
|
||||||
|
pid: process.pid,
|
||||||
|
memory: mainProcessMemory,
|
||||||
|
},
|
||||||
|
totals: {
|
||||||
|
processCount: processes.length,
|
||||||
|
workingSetSize: processes.reduce((total, item) => total + item.workingSetSize, 0),
|
||||||
|
privateBytes: processes.reduce((total, item) => total + (item.privateBytes ?? 0), 0),
|
||||||
|
},
|
||||||
|
processes,
|
||||||
|
};
|
||||||
|
|
||||||
|
samples.push(sample);
|
||||||
|
if (samples.length > PROCESS_METRICS_MAX_SAMPLES) {
|
||||||
|
samples.splice(0, samples.length - PROCESS_METRICS_MAX_SAMPLES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initProcessMetricsSampler(): void {
|
||||||
|
if (samplerHandle) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void sampleProcessMetrics();
|
||||||
|
samplerHandle = setInterval(() => {
|
||||||
|
void sampleProcessMetrics();
|
||||||
|
}, PROCESS_METRICS_INTERVAL_MS);
|
||||||
|
samplerHandle.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getProcessMetricsSnapshot() {
|
||||||
|
const latestSample = samples.at(-1) ?? null;
|
||||||
|
return {
|
||||||
|
intervalMs: PROCESS_METRICS_INTERVAL_MS,
|
||||||
|
sampleCount: samples.length,
|
||||||
|
latestCapturedAt: latestSample?.capturedAt ?? null,
|
||||||
|
latestSample,
|
||||||
|
recentSamples: samples.slice(-PROCESS_METRICS_RECENT_WINDOW),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ import {
|
|||||||
normalizeAccountPlatformUid,
|
normalizeAccountPlatformUid,
|
||||||
sameAccountPlatformUid,
|
sameAccountPlatformUid,
|
||||||
} from "../shared/account-identity";
|
} from "../shared/account-identity";
|
||||||
import { acquireHotView } from "./view-pool";
|
import { releaseHotView, retainHotView } from "./view-pool";
|
||||||
import { getLeaseManagerSnapshot, noteLeaseExtended, noteLeaseReleased, setActiveLease } from "./lease-manager";
|
import { getLeaseManagerSnapshot, noteLeaseExtended, noteLeaseReleased, setActiveLease } from "./lease-manager";
|
||||||
import {
|
import {
|
||||||
initScheduler,
|
initScheduler,
|
||||||
@@ -939,25 +939,29 @@ async function executeTaskAdapter(
|
|||||||
const viewHandle =
|
const viewHandle =
|
||||||
adapter.executionMode === "session" || adapter.executionMode === "playwright"
|
adapter.executionMode === "session" || adapter.executionMode === "playwright"
|
||||||
? null
|
? null
|
||||||
: acquireHotView(task.accountId || task.id);
|
: retainHotView(task.accountId || task.id);
|
||||||
|
|
||||||
const result = await adapter.publish(
|
try {
|
||||||
{
|
return await adapter.publish(
|
||||||
taskId: task.id,
|
{
|
||||||
accountId: task.accountId || task.id,
|
taskId: task.id,
|
||||||
session: sessionHandle.session,
|
accountId: task.accountId || task.id,
|
||||||
view: viewHandle?.view ?? null,
|
session: sessionHandle.session,
|
||||||
signal,
|
view: viewHandle?.view ?? null,
|
||||||
phase: "initial",
|
signal,
|
||||||
article: await loadPublishArticle(task),
|
phase: "initial",
|
||||||
reportProgress(stage: string) {
|
article: await loadPublishArticle(task),
|
||||||
updateTaskProgress(task.id, `publish adapter progress: ${stage}`);
|
reportProgress(stage: string) {
|
||||||
|
updateTaskProgress(task.id, `publish adapter progress: ${stage}`);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
payload,
|
||||||
payload,
|
);
|
||||||
);
|
} finally {
|
||||||
|
if (viewHandle) {
|
||||||
return result;
|
releaseHotView(viewHandle.accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const adapter = selectMonitorAdapter(task.platform);
|
const adapter = selectMonitorAdapter(task.platform);
|
||||||
@@ -968,24 +972,28 @@ async function executeTaskAdapter(
|
|||||||
const viewHandle =
|
const viewHandle =
|
||||||
adapter.executionMode === "session" || adapter.executionMode === "playwright"
|
adapter.executionMode === "session" || adapter.executionMode === "playwright"
|
||||||
? null
|
? null
|
||||||
: acquireHotView(task.accountId || task.id);
|
: retainHotView(task.accountId || task.id);
|
||||||
|
|
||||||
const result = await adapter.query(
|
try {
|
||||||
{
|
return await adapter.query(
|
||||||
taskId: task.id,
|
{
|
||||||
accountId: task.accountId || task.id,
|
taskId: task.id,
|
||||||
session: sessionHandle.session,
|
accountId: task.accountId || task.id,
|
||||||
view: viewHandle?.view ?? null,
|
session: sessionHandle.session,
|
||||||
signal,
|
view: viewHandle?.view ?? null,
|
||||||
phase: "initial",
|
signal,
|
||||||
reportProgress(stage: string) {
|
phase: "initial",
|
||||||
updateTaskProgress(task.id, `monitor adapter progress: ${stage}`);
|
reportProgress(stage: string) {
|
||||||
|
updateTaskProgress(task.id, `monitor adapter progress: ${stage}`);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
payload,
|
||||||
payload,
|
);
|
||||||
);
|
} finally {
|
||||||
|
if (viewHandle) {
|
||||||
return result;
|
releaseHotView(viewHandle.accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildScaffoldResult(
|
function buildScaffoldResult(
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { app } from "electron/main";
|
import { app } from "electron/main";
|
||||||
|
|
||||||
|
import { getProcessMetricsSnapshot } from "./process-metrics";
|
||||||
import { getCircuitBreakerState } from "./circuit-breaker";
|
import { getCircuitBreakerState } from "./circuit-breaker";
|
||||||
import { collectRecoverySnapshot } from "./crash-recovery";
|
import { collectRecoverySnapshot } from "./crash-recovery";
|
||||||
import { getKeepAlivePlan } from "./keep-alive";
|
import { getKeepAlivePlan } from "./keep-alive";
|
||||||
@@ -10,7 +11,7 @@ import { getSchedulerState } from "./scheduler";
|
|||||||
import { getSessionHandle, listSessionHandleSnapshots } from "./session-registry";
|
import { getSessionHandle, listSessionHandleSnapshots } from "./session-registry";
|
||||||
import { getTransportSnapshot } from "./transport/api-client";
|
import { getTransportSnapshot } from "./transport/api-client";
|
||||||
import { describeVaultBackend } from "./vault";
|
import { describeVaultBackend } from "./vault";
|
||||||
import { listHotViews } from "./view-pool";
|
import { getHotViewPoolPolicy, listHotViews } from "./view-pool";
|
||||||
import { normalizeAccountPlatformUid } from "../shared/account-identity";
|
import { normalizeAccountPlatformUid } from "../shared/account-identity";
|
||||||
|
|
||||||
function minutesAhead(now: number, minutes: number): number {
|
function minutesAhead(now: number, minutes: number): number {
|
||||||
@@ -151,6 +152,8 @@ function createLiveRuntimeSnapshot(controller: ReturnType<typeof getRuntimeContr
|
|||||||
scheduler,
|
scheduler,
|
||||||
sessions,
|
sessions,
|
||||||
hotViews,
|
hotViews,
|
||||||
|
hotViewPool: getHotViewPoolPolicy(),
|
||||||
|
processMetrics: getProcessMetricsSnapshot(),
|
||||||
vault: describeVaultBackend(),
|
vault: describeVaultBackend(),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,15 +5,54 @@ export interface HotViewHandle {
|
|||||||
accountId: string;
|
accountId: string;
|
||||||
view: ElectronWebContentsView;
|
view: ElectronWebContentsView;
|
||||||
activatedAt: number;
|
activatedAt: number;
|
||||||
|
lastReleasedAt: number | null;
|
||||||
|
retainCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hotViews = new Map<string, HotViewHandle>();
|
const hotViews = new Map<string, HotViewHandle>();
|
||||||
|
const HOT_VIEW_IDLE_TTL_MS = 5 * 60_000;
|
||||||
|
const HOT_VIEW_REAPER_INTERVAL_MS = 60_000;
|
||||||
|
let reaperHandle: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
function closeView(handle: HotViewHandle): void {
|
||||||
|
if (!handle.view.webContents.isDestroyed()) {
|
||||||
|
handle.view.webContents.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function touchHandle(handle: HotViewHandle): HotViewHandle {
|
||||||
|
handle.activatedAt = Date.now();
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
function demoteViewInternal(accountId: string): boolean {
|
||||||
|
const handle = hotViews.get(accountId);
|
||||||
|
if (!handle) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
closeView(handle);
|
||||||
|
hotViews.delete(accountId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startHotViewReaper(): void {
|
||||||
|
if (reaperHandle) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
reaperHandle = setInterval(() => {
|
||||||
|
reapIdleHotViews();
|
||||||
|
}, HOT_VIEW_REAPER_INTERVAL_MS);
|
||||||
|
reaperHandle.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
export function acquireHotView(accountId: string): HotViewHandle {
|
export function acquireHotView(accountId: string): HotViewHandle {
|
||||||
|
startHotViewReaper();
|
||||||
|
|
||||||
const existing = hotViews.get(accountId);
|
const existing = hotViews.get(accountId);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
existing.activatedAt = Date.now();
|
return touchHandle(existing);
|
||||||
return existing;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handle: HotViewHandle = {
|
const handle: HotViewHandle = {
|
||||||
@@ -26,26 +65,80 @@ export function acquireHotView(accountId: string): HotViewHandle {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
activatedAt: Date.now(),
|
activatedAt: Date.now(),
|
||||||
|
lastReleasedAt: Date.now(),
|
||||||
|
retainCount: 0,
|
||||||
};
|
};
|
||||||
hotViews.set(accountId, handle);
|
hotViews.set(accountId, handle);
|
||||||
return handle;
|
return handle;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function demoteView(accountId: string): void {
|
export function retainHotView(accountId: string): HotViewHandle {
|
||||||
|
const handle = touchHandle(acquireHotView(accountId));
|
||||||
|
handle.retainCount += 1;
|
||||||
|
handle.lastReleasedAt = null;
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function releaseHotView(accountId: string): void {
|
||||||
const handle = hotViews.get(accountId);
|
const handle = hotViews.get(accountId);
|
||||||
if (!handle) {
|
if (!handle) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!handle.view.webContents.isDestroyed()) {
|
if (handle.retainCount > 0) {
|
||||||
handle.view.webContents.close();
|
handle.retainCount -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (handle.retainCount === 0) {
|
||||||
|
handle.lastReleasedAt = Date.now();
|
||||||
}
|
}
|
||||||
hotViews.delete(accountId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listHotViews(): Array<Pick<HotViewHandle, "accountId" | "activatedAt">> {
|
export function demoteView(accountId: string): boolean {
|
||||||
return [...hotViews.values()].map(({ accountId, activatedAt }) => ({
|
const handle = hotViews.get(accountId);
|
||||||
|
if (!handle || handle.retainCount > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return demoteViewInternal(accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reapIdleHotViews(
|
||||||
|
now = Date.now(),
|
||||||
|
idleTTLms = HOT_VIEW_IDLE_TTL_MS,
|
||||||
|
): string[] {
|
||||||
|
const reclaimed: string[] = [];
|
||||||
|
|
||||||
|
for (const [accountId, handle] of hotViews.entries()) {
|
||||||
|
if (handle.retainCount > 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const idleSince = handle.lastReleasedAt ?? handle.activatedAt;
|
||||||
|
if (now - idleSince < idleTTLms) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (demoteViewInternal(accountId)) {
|
||||||
|
reclaimed.push(accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return reclaimed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listHotViews(): Array<Pick<HotViewHandle, "accountId" | "activatedAt" | "lastReleasedAt" | "retainCount">> {
|
||||||
|
return [...hotViews.values()].map(({ accountId, activatedAt, lastReleasedAt, retainCount }) => ({
|
||||||
accountId,
|
accountId,
|
||||||
activatedAt,
|
activatedAt,
|
||||||
|
lastReleasedAt,
|
||||||
|
retainCount,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getHotViewPoolPolicy() {
|
||||||
|
return {
|
||||||
|
idleTTLms: HOT_VIEW_IDLE_TTL_MS,
|
||||||
|
reapIntervalMs: HOT_VIEW_REAPER_INTERVAL_MS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user