Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

desktopCaffeinate.ts

167 lines5.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import { Atom } from "effect/unstable/reactivity";
4import { useEffect, useRef, useState } from "react";
5​
6import { environmentCatalog } from "../connection/catalog";
7import { isDesktopHostedConnectionTarget } from "../connection/desktopLocal";
8import { useClientSettings } from "../hooks/useSettings";
9import { environmentThreadShells } from "./threads";
10​
11/**
12 * Discharging below this level releases the keep-awake assertion so the
13 * feature cannot drain an already-low battery; charging or recovering above
14 * it re-acquires automatically.
15 */
16export const KEEP_AWAKE_BATTERY_MIN_LEVEL = 0.1;
17​
18export interface BatteryState {
19 readonly charging: boolean;
20 /** 0..1, per the Battery Status API. */
21 readonly level: number;
23​
24/**
25 * A thread shell counts as working while its session is busy the way the
26 * server defines busy: "starting" (prompt submitted, worktree/provider still
27 * spinning up, and the gap between queued turns) or "running" with an active
28 * turn. Turns parked on approvals or user input stay "running" on purpose:
29 * the desktop hosts the server, so it must stay awake for a remote approval
30 * to be able to arrive at all.
31 */
32export function isThreadShellWorking(shell: Pick<EnvironmentThreadShell, "session">): boolean {
33 const session = shell.session;
34 if (session == null) {
35 return false;
36 }
37 return (
38 session.status === "starting" || (session.status === "running" && session.activeTurnId != null)
39 );
41​
42export function computeKeepAwake(input: {
43 readonly enabled: boolean;
44 readonly anyLocalAgentWorking: boolean;
45 /** `null` means the Battery Status API is unavailable; treated as OK. */
46 readonly battery: BatteryState | null;
47}): boolean {
48 if (!input.enabled || !input.anyLocalAgentWorking) {
49 return false;
50 }
51 return (
52 input.battery === null ||
53 input.battery.charging ||
54 input.battery.level >= KEEP_AWAKE_BATTERY_MIN_LEVEL
55 );
57​
58export const anyLocalAgentWorkingAtom = Atom.make((get) => {
59 const entries = get(environmentCatalog.catalogValueAtom).entries;
60 return get(environmentThreadShells.threadShellsAtom).some((shell) => {
61 const entry = entries.get(shell.environmentId);
62 return (
63 entry !== undefined &&
64 isDesktopHostedConnectionTarget(entry.target) &&
65 isThreadShellWorking(shell)
66 );
67 });
68}).pipe(Atom.withLabel("desktop:any-local-agent-working"));
69​
70interface BatteryManagerLike extends EventTarget {
71 readonly charging: boolean;
72 readonly level: number;
74​
75type NavigatorWithBattery = Navigator & {
76 getBattery?: () => Promise<BatteryManagerLike>;
77};
78​
79function useBatteryState(): BatteryState | null {
80 const [battery, setBattery] = useState<BatteryState | null>(null);
81​
82 useEffect(() => {
83 const getBattery = (navigator as NavigatorWithBattery).getBattery;
84 if (typeof getBattery !== "function") {
85 return;
86 }
87 let cancelled = false;
88 let unsubscribe: (() => void) | undefined;
89 getBattery
90 .call(navigator)
91 .then((manager) => {
92 if (cancelled) {
93 return;
94 }
95 const update = () => {
96 setBattery((previous) =>
97 previous !== null &&
98 previous.charging === manager.charging &&
99 previous.level === manager.level
100 ? previous
101 : { charging: manager.charging, level: manager.level },
102 );
103 };
104 update();
105 manager.addEventListener("chargingchange", update);
106 manager.addEventListener("levelchange", update);
107 unsubscribe = () => {
108 manager.removeEventListener("chargingchange", update);
109 manager.removeEventListener("levelchange", update);
110 };
111 })
112 .catch(() => {
113 // Battery state stays unknown, which computeKeepAwake treats as OK.
114 });
115 return () => {
116 cancelled = true;
117 unsubscribe?.();
118 };
119 }, []);
120​
121 return battery;
123​
124/**
125 * Drives the desktop shell's keep-awake assertion from the renderer, the only
126 * layer that sees every environment. Each state is sent over IPC at most once
127 * per flip; the initial send also resets main-process state after a renderer
128 * reload. The assertion is released on unmount and on `pagehide`, because
129 * React cleanups do not run when the renderer reloads.
130 */
131export function useDesktopCaffeination(): void {
132 const enabled = useClientSettings((settings) => settings.caffeinateWhileAgentsRunning);
133 const anyLocalAgentWorking = useAtomValue(anyLocalAgentWorkingAtom);
134 const battery = useBatteryState();
135 const keepAwake = computeKeepAwake({ enabled, anyLocalAgentWorking, battery });
136 const lastSentRef = useRef<boolean | null>(null);
137​
138 useEffect(() => {
139 const setKeepAwake = window.desktopBridge?.setKeepAwake;
140 if (typeof setKeepAwake !== "function") {
141 return;
142 }
143 const send = (value: boolean) => {
144 if (lastSentRef.current === value) {
145 return;
146 }
147 lastSentRef.current = value;
148 void setKeepAwake(value).catch(() => {
149 // Forget the failed send so the next evaluation resends; the
150 // main-process handler is idempotent, so an extra send is harmless.
151 lastSentRef.current = null;
152 });
153 };
154 send(keepAwake);
155 if (!keepAwake) {
156 return;
157 }
158 const release = () => {
159 send(false);
160 };
161 window.addEventListener("pagehide", release);
162 return () => {
163 window.removeEventListener("pagehide", release);
164 release();
165 };
166 }, [keepAwake]);