Skip to content

Commit 260f9fe

Browse files
wesbillmanMeeseeks
andauthored
fix(desktop): quiesce renderer polling while hidden (block#3677) (block#5490)
Fixes block#3677. ## Problem The renderer never quiesces: recurring timers, query polling, and re-render tickers run at full rate whether the window is visible, hidden, or minimized. Measured on a live installed app: **27.5% mean renderer CPU visible vs 28.7% hidden** (60×1s `ps` samples of the WebContent process; `sample(1)` dominated by `WebCore::timerFired`/ThreadTimers, microtask checkpoints, JSON parsing, style matching). Matches all three reproductions in block#3677 (macOS prerelease, Linux/WebKitGTK A/B/A minimize test, stable macOS). Per-timer instrumentation (dev build, wrapped `setInterval`/`setTimeout`/rAF) attributed the recurring work: `useNow` 60 fires/min, 40 active TanStack refetch intervals, agent-turn pruning 12/min, auto-restart ticks, huddle/reminder polls — none visibility-gated. ## Fix (two-tier gating, standard mechanisms only) Two separate signals in `desktop/src/shared/lib/useDocumentVisible.ts`, because they mean different things and (see residuals) are delivered differently on macOS: - **`useDocumentVisible`** — true Page Visibility only (`document.visibilityState`). Gates local UI work that must keep running on a visible-but-unfocused window: `useNow` relative clocks, agent-turn pruning, huddle bar state/model-status polling, auto-restart tick. Hidden ⇒ paused; `useNow` snaps to fresh `Date.now()` on return. - **`useAppFocused`** — visible AND `document.hasFocus()`. Gates network refetch polling only (`useFocusedRefetchInterval`, ~15 query families: forum/home/agents/channels/templates/emoji/user-status/projects/workflows/persona-catalog/pulse/presence-list). TanStack's `focusManager` is wired to this signal (idempotent, single install) with `refetchOnWindowFocus: true`, so stale queries refresh promptly on return. Deliberate side effect, documented in code: query retries pause on blur; mutations and the presence heartbeat (`retry: 0`) are unaffected. - **Never gated:** reminder due-notification poll (fires while hidden/unfocused — extracted to `reminderNotificationPoll.ts` with regression test), huddle pipeline hot-start (`check_pipeline_hotstart` survives backgrounding for the duration of a huddle), relay stall watchdog, presence heartbeat. Live WebSocket delivery untouched throughout. - Huddle model-status indicator now clears only on huddle phase end, not on visibility/focus changes. ## Validation - Instrumented dev build, populated channel, fires/min: **visible+focused** unchanged (`useNow 60 / prune 12 / watchdog 6 / query 4 / auto-restart 4 / low-rate huddle/reminder/presence`); **visible+blurred**: query polls 0, UI clocks continue (`useNow 60 / prune 12`), reminders 2, presence live; **truly hidden**: only watchdog 6, reminders 2, presence ~2 — everything else 0. Return restored visible+focused, selection preserved, queries refreshed. - Hide-vs-blur decomposition (instrumented probe instance, AppleScript-driven): on macOS WKWebView, Cmd-H / minimize / full occlusion did **not** reliably produce `visibilityState === "hidden"` — they reliably produced focus loss. The CPU-dominant quiescence path on macOS is therefore the focus gate; the visibility gate is exercised fully on platforms that report hidden (e.g. WebKitGTK minimize per the Linux repro). - Gate-regression tests: signal separation, `useNow` hidden-pause + fresh-snap on return, focus-gated interval pause/resume-with-refresh, reminder delivery while hidden+unfocused (5 new, plus primitive wiring tests). - Push gate: desktop check, typecheck, full desktop suite **4549/4549** at `1237548d1`. ## Known residuals - **macOS hidden-signal limitation:** because WKWebView rarely reports `hidden` on app-hide/minimize, hidden-only consumers (`useNow`, prune, huddle UI polls) may keep ticking on macOS when the app is hidden. These are cheap local timers; the expensive network polling still quiesces via focus loss, which is what the measured 28% CPU was attributed to. If the residual local-timer cost proves measurable, the follow-up is bridging Tauri window hidden/minimized events into the visibility signal. - End-to-end CPU confirmation on a packaged build is the post-merge follow-up (against the 28% idle baseline). - Visible-state costs (skeleton animation pileups on stuck loading views, per-poll JSON payload churn) are intentionally out of scope — separate follow-up issue. --------- Signed-off-by: Wes <[email protected]> Co-authored-by: Meeseeks <2e96988f190ed1bd3c568760103aa4cadb2bc6195b832e252c984392c89039bd@buzz.block.builderlab.xyz>
1 parent 87cf3c9 commit 260f9fe

25 files changed

Lines changed: 545 additions & 90 deletions

‎desktop/src/features/agents/activeAgentTurnsStore.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ import {
66
compareObserverEvents,
77
} from "@/features/agents/observerRelayStore";
88
import { normalizePubkey } from "@/shared/lib/pubkey";
9+
import {
10+
isDocumentVisible,
11+
subscribeDocumentVisibility,
12+
} from "@/shared/lib/useDocumentVisible";
913
import type { ObserverEvent } from "./ui/agentSessionTypes";
1014

1115
/** Harness emits turn_liveness every ~10s (BUZZ_ACP_TURN_LIVENESS_SECS). */
@@ -134,6 +138,7 @@ function watermarkChannelKey(event: ObserverEvent): string {
134138
const terminalAtByAgent = new Map<string, Map<string, number>>();
135139

136140
let pruneInterval: ReturnType<typeof setInterval> | null = null;
141+
let unsubscribePruneVisibility: (() => void) | null = null;
137142

138143
function invalidateCache(agentKey: string) {
139144
cachedTurnSummaries.delete(agentKey);
@@ -440,16 +445,31 @@ function processEvent(agentPubkey: string, event: ObserverEvent) {
440445
}
441446
}
442447

443-
function ensurePruneInterval() {
444-
if (pruneInterval) return;
448+
function startPruneInterval() {
449+
if (pruneInterval || !isDocumentVisible()) return;
450+
pruneExpired();
445451
pruneInterval = setInterval(pruneExpired, PRUNE_INTERVAL_MS);
446452
}
447453

454+
function pausePruneInterval() {
455+
if (!pruneInterval) return;
456+
clearInterval(pruneInterval);
457+
pruneInterval = null;
458+
}
459+
460+
function ensurePruneInterval() {
461+
if (unsubscribePruneVisibility) return;
462+
startPruneInterval();
463+
unsubscribePruneVisibility = subscribeDocumentVisibility((visible) => {
464+
if (visible) startPruneInterval();
465+
else pausePruneInterval();
466+
});
467+
}
468+
448469
function stopPruneInterval() {
449-
if (pruneInterval) {
450-
clearInterval(pruneInterval);
451-
pruneInterval = null;
452-
}
470+
pausePruneInterval();
471+
unsubscribePruneVisibility?.();
472+
unsubscribePruneVisibility = null;
453473
}
454474

455475
export function subscribeActiveAgentTurns(listener: () => void) {

‎desktop/src/features/agents/hooks.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ import {
1818
} from "@/features/channels/hooks";
1919
import { updateCachedChannelMemberDisplayName } from "@/features/channels/channelMemberProfileCache";
2020
import { evictUsersBatchEntries } from "@/features/profile/hooks";
21+
import {
22+
useAppFocused,
23+
useFocusedRefetchInterval,
24+
} from "@/shared/lib/useDocumentVisible";
2125
import {
2226
createManagedAgent,
2327
deleteManagedAgent,
@@ -322,6 +326,7 @@ export function useManagedAgentPrereqsQuery(
322326
}
323327

324328
export function useRelayAgentsQuery(options?: { enabled?: boolean }) {
329+
const refetchInterval = useFocusedRefetchInterval(5 * 60_000);
325330
return useQuery({
326331
queryKey: relayAgentsQueryKey,
327332
queryFn: listRelayAgents,
@@ -334,19 +339,21 @@ export function useRelayAgentsQuery(options?: { enabled?: boolean }) {
334339
// the `agents-data-changed` event fires only for local persona/team/managed
335340
// reconcile (kinds PERSONA/TEAM/MANAGED_AGENT), never for kind:10100. So we
336341
// keep polling but at a relaxed cadence and pause it while backgrounded.
337-
refetchInterval: 5 * 60_000,
338-
refetchIntervalInBackground: false,
342+
refetchInterval,
343+
refetchOnWindowFocus: true,
339344
enabled: options?.enabled,
340345
});
341346
}
342347

343348
export function useManagedAgentsQuery(options?: { enabled?: boolean }) {
349+
const appFocused = useAppFocused();
344350
return useQuery({
345351
enabled: options?.enabled ?? true,
346352
queryKey: managedAgentsQueryKey,
347353
queryFn: listManagedAgents,
348354
staleTime: 5_000,
349355
refetchInterval: (query) => {
356+
if (!appFocused) return false;
350357
const agents = query.state.data as ManagedAgent[] | undefined;
351358
// Only local "running" agents need polling: process state can change
352359
// with no relay event to signal it, so this poll is the only liveness
@@ -357,6 +364,7 @@ export function useManagedAgentsQuery(options?: { enabled?: boolean }) {
357364
? 5_000
358365
: false;
359366
},
367+
refetchOnWindowFocus: true,
360368
});
361369
}
362370

@@ -895,26 +903,30 @@ export function useManagedAgentLogQuery(
895903
pubkey: string | null,
896904
lineCount = 120,
897905
) {
906+
const refetchInterval = useFocusedRefetchInterval(pubkey ? 30_000 : false);
898907
return useQuery({
899908
queryKey: ["managed-agent-log", pubkey, lineCount],
900909
queryFn: () => getManagedAgentLog(pubkey as string, lineCount),
901910
enabled: pubkey !== null,
902911
retry: false,
903912
staleTime: 3_000,
904-
refetchInterval: pubkey ? 30_000 : false,
913+
refetchInterval,
914+
refetchOnWindowFocus: true,
905915
});
906916
}
907917

908918
export const agentConfigSurfaceQueryKey = (pubkey: string) =>
909919
["agent-config-surface", pubkey] as const;
910920

911921
export function useAgentConfigSurface(pubkey: string | null) {
922+
const refetchInterval = useFocusedRefetchInterval(30_000);
912923
return useQuery({
913924
queryKey: agentConfigSurfaceQueryKey(pubkey ?? ""),
914925
queryFn: () => getAgentConfigSurface(pubkey ?? ""),
915926
enabled: !!pubkey,
916927
staleTime: 10_000,
917-
refetchInterval: 30_000,
928+
refetchInterval,
929+
refetchOnWindowFocus: true,
918930
});
919931
}
920932

‎desktop/src/features/agents/lib/useAutoRestartPolicy.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "@/shared/api/tauriManagedAgents";
1313
import { listManagedAgents } from "@/shared/api/tauri";
1414
import type { ManagedAgent } from "@/shared/api/types";
15+
import { useDocumentVisible } from "@/shared/lib/useDocumentVisible";
1516
import { getAgentObserverSnapshot } from "../observerRelayStore";
1617
import { getAgentWorkingState } from "../agentWorkingSignal";
1718
import {
@@ -40,13 +41,17 @@ export function useAutoRestartPolicy() {
4041
const edgesRef = React.useRef(new Map<string, AutoRestartEdgeState>());
4142
const inFlightRef = React.useRef(new Set<string>());
4243
const [, setTick] = React.useState(0);
44+
const documentVisible = useDocumentVisible();
4345

4446
// Re-evaluate on an interval so the quiescence clock advances even when
4547
// summaries and observer stores are quiet.
4648
React.useEffect(() => {
49+
if (!documentVisible) return;
50+
51+
setTick((t) => t + 1);
4752
const timer = setInterval(() => setTick((t) => t + 1), POLICY_TICK_MS);
4853
return () => clearInterval(timer);
49-
}, []);
54+
}, [documentVisible]);
5055

5156
// No dependency array by design: the tick pattern re-runs this effect
5257
// every render so it reads live store state; all mutation is ref-local.

‎desktop/src/features/agents/lib/usePersonaCatalogRelay.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from "@/features/agents/lib/personaCatalogRelay";
88
import { invalidatePersonaEditCaches } from "@/features/agents/lib/personaEditCaches";
99
import { relayClient } from "@/shared/api/relayClient";
10+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
1011
import {
1112
setPersonaShared,
1213
updatePersonaAndPublish,
@@ -19,12 +20,14 @@ export function personaCatalogQueryKey(communityId: string | null) {
1920
}
2021

2122
export function usePersonaCatalogQuery(communityId: string | null) {
23+
const refetchInterval = useFocusedRefetchInterval(120_000);
2224
return useQuery<PersonaCatalogPublication[]>({
2325
enabled: communityId !== null,
2426
queryKey: personaCatalogQueryKey(communityId),
2527
queryFn: fetchPersonaCatalogPublications,
2628
staleTime: 30_000,
27-
refetchInterval: 120_000,
29+
refetchInterval,
30+
refetchOnWindowFocus: true,
2831
});
2932
}
3033

‎desktop/src/features/channel-templates/hooks.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
22

3+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
4+
35
import {
46
createChannelTemplate,
57
deleteChannelTemplate,
@@ -16,11 +18,14 @@ import type {
1618
export const channelTemplatesQueryKey = ["channel-templates"] as const;
1719

1820
export function useChannelTemplatesQuery() {
21+
const refetchInterval = useFocusedRefetchInterval(30_000);
22+
1923
return useQuery({
2024
queryKey: channelTemplatesQueryKey,
2125
queryFn: listChannelTemplates,
2226
staleTime: 30_000,
23-
refetchInterval: 30_000,
27+
refetchInterval,
28+
refetchOnWindowFocus: true,
2429
});
2530
}
2631

‎desktop/src/features/channels/hooks.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import type {
3333
UpdateChannelInput,
3434
} from "@/shared/api/types";
3535
import { useIdentityQuery } from "@/shared/api/hooks";
36+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
3637
import { useCommunities } from "@/features/communities/useCommunities";
3738
import { canAddChannelMembers } from "@/features/channels/lib/channelMemberAdmission";
3839
import {
@@ -193,6 +194,7 @@ function setChannelArchivedState(
193194
export function useChannelsQuery(options?: { enabled?: boolean }) {
194195
const { activeCommunity } = useCommunities();
195196
const relayUrl = activeCommunity?.relayUrl ?? null;
197+
const refetchInterval = useFocusedRefetchInterval(60_000);
196198

197199
return useQuery({
198200
enabled: options?.enabled ?? true,
@@ -215,8 +217,8 @@ export function useChannelsQuery(options?: { enabled?: boolean }) {
215217
: undefined,
216218
initialDataUpdatedAt: 0,
217219
staleTime: 60_000,
218-
refetchInterval: 60_000,
219-
refetchIntervalInBackground: false,
220+
refetchInterval,
221+
refetchOnWindowFocus: true,
220222
});
221223
}
222224

‎desktop/src/features/custom-emoji/hooks.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
setCustomEmoji,
1111
} from "@/shared/api/customEmoji";
1212
import { relayClient } from "@/shared/api/relayClient";
13+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
1314
import type { CustomEmoji } from "@/shared/lib/remarkCustomEmoji";
1415

1516
/**
@@ -28,13 +29,16 @@ export const customEmojiQueryKey = ["custom-emoji"] as const;
2829
export const ownCustomEmojiQueryKey = ["custom-emoji-own"] as const;
2930

3031
export function useCustomEmojiQuery() {
32+
const refetchInterval = useFocusedRefetchInterval(120_000);
33+
3134
return useQuery<CustomEmoji[]>({
3235
queryKey: customEmojiQueryKey,
3336
queryFn: listCustomEmoji,
3437
// The palette changes rarely; avoid refetch storms while the picker is open,
3538
// but poll every 2 minutes as a backstop for any missed live event.
3639
staleTime: 60_000,
37-
refetchInterval: 120_000,
40+
refetchInterval,
41+
refetchOnWindowFocus: true,
3842
});
3943
}
4044

‎desktop/src/features/forum/hooks.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
22

33
import { getForumPosts, getForumThread } from "@/shared/api/forum";
4+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
45
import { useRelaySelfQuery } from "@/features/moderation/hooks";
56
import { deleteMessage, sendChannelMessage } from "@/shared/api/tauri";
67
import type {
@@ -19,6 +20,8 @@ export function forumThreadQueryKey(channelId: string, eventId: string) {
1920
}
2021

2122
export function useForumPostsQuery(channel: Channel | null) {
23+
const refetchInterval = useFocusedRefetchInterval(15_000);
24+
2225
const channelId = channel?.id ?? "";
2326
const enabled = channel !== null && channel.channelType === "forum";
2427
const relaySelfPubkey = useRelaySelfQuery(enabled).data;
@@ -28,14 +31,17 @@ export function useForumPostsQuery(channel: Channel | null) {
2831
queryKey: [...forumPostsQueryKey(channelId), relaySelfPubkey ?? null],
2932
queryFn: () => getForumPosts(channelId, 50, undefined, relaySelfPubkey),
3033
staleTime: 15_000,
31-
refetchInterval: 15_000,
34+
refetchInterval,
35+
refetchOnWindowFocus: true,
3236
});
3337
}
3438

3539
export function useForumThreadQuery(
3640
channelId: string | null,
3741
eventId: string | null,
3842
) {
43+
const refetchInterval = useFocusedRefetchInterval(10_000);
44+
3945
const enabled = channelId !== null && eventId !== null;
4046
const relaySelfPubkey = useRelaySelfQuery(enabled).data;
4147

@@ -54,7 +60,8 @@ export function useForumThreadQuery(
5460
relaySelfPubkey,
5561
),
5662
staleTime: 10_000,
57-
refetchInterval: 10_000,
63+
refetchInterval,
64+
refetchOnWindowFocus: true,
5865
});
5966
}
6067

‎desktop/src/features/home/hooks.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ import { useQuery } from "@tanstack/react-query";
22

33
import { getHomeFeed } from "@/shared/api/tauri";
44
import { useRelayConnection } from "@/shared/api/useRelayConnection";
5+
import { useFocusedRefetchInterval } from "@/shared/lib/useDocumentVisible";
56

67
export function useHomeFeedQuery() {
78
const connectionState = useRelayConnection();
89
const connected = connectionState === "connected";
10+
const refetchInterval = useFocusedRefetchInterval(connected ? 30_000 : false);
911

1012
return useQuery({
1113
queryKey: ["home-feed"],
@@ -19,6 +21,7 @@ export function useHomeFeedQuery() {
1921
// Pause background polling on degraded/stalled/disconnected connections.
2022
// The relay can't serve the request anyway, and the spurious failures
2123
// consume quota that the recovery path needs.
22-
refetchInterval: connected ? 30_000 : false,
24+
refetchInterval,
25+
refetchOnWindowFocus: true,
2326
});
2427
}

‎desktop/src/features/huddle/HuddleContext.tsx‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as React from "react";
44

55
import { setupAudioWorklet, type AudioWorkletHandle } from "./lib/audioWorklet";
66
import { type AudioInputDevice, useAudioDevices } from "./lib/useAudioDevices";
7+
import { usePipelineHotstart } from "./lib/usePipelineHotstart";
78
import { formatHuddleActionError } from "./lib/huddleError";
89
import {
910
type VoiceInputMode,
@@ -47,7 +48,6 @@ const HUDDLE_AUDIO_STATE_EVENT = "huddle-audio-state";
4748
const HUDDLE_AUDIO_LEVEL_EVENT = "huddle-audio-level";
4849

4950
const MIC_ANALYSER_UPDATE_INTERVAL_MS = 33;
50-
const PIPELINE_HOTSTART_INTERVAL_MS = 15_000;
5151
const MIC_INITIAL_NOISE_FLOOR = 0.01;
5252
const MIC_VOICE_GATE_ON_RMS = 0.018;
5353
const MIC_VOICE_GATE_OFF_RMS = 0.012;
@@ -778,16 +778,7 @@ export function HuddleProvider({
778778
selfPubkeyRef,
779779
);
780780

781-
// Pipeline hot-start — check if voice models finished downloading mid-huddle
782-
React.useEffect(() => {
783-
if (!ephemeralChannelId) return;
784-
const id = window.setInterval(() => {
785-
invoke("check_pipeline_hotstart").catch(() => {
786-
/* best-effort */
787-
});
788-
}, PIPELINE_HOTSTART_INTERVAL_MS);
789-
return () => window.clearInterval(id);
790-
}, [ephemeralChannelId]);
781+
usePipelineHotstart(ephemeralChannelId);
791782

792783
// Mic level analyser — drives the voice activity indicator
793784
React.useEffect(() => {

0 commit comments

Comments
 (0)