@devries-cameron20 / t3code Mirror · read-only / commits / 587deab7d3
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 18:30 UTC

feat(server): keep the computer awake while agents work (#34128)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 12, 2026 at 16:19 UTC 587deab7d315612d88f9db5df26ec264a1047b76
7 files changed +287
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+15
@@ -582,6 +582,21 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
582 onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}
583 />
584 </View>
585 + <View className="border-t border-border-subtle">
586 + <SettingsSwitchRow
587 + icon="bolt.circle"
588 + label="Keep awake while agents work"
589 + subtitle={managedSubtitle(
590 + "keepAwakeWhileAgentsWork",
591 + projectSelected
592 + ? "Environment-wide setting. Select All projects to change it."
593 + : "Stop the computer from sleeping while agents work. Closing a laptop lid still sleeps it.",
594 + )}
595 + value={uniform("keepAwakeWhileAgentsWork")}
596 + disabled={disabledFor("keepAwakeWhileAgentsWork")}
597 + onValueChange={(value) => write({ keepAwakeWhileAgentsWork: value })}
598 + />
599 + </View>
600 </SettingsSection>
601 </>
602 ) : null}
apps/server/src/background/KeepAwake.test.ts new
+36
@@ -0,0 +1,36 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Queue from "effect/Queue";
4 +import * as Stream from "effect/Stream";
5 +import * as TestClock from "effect/testing/TestClock";
6 +
7 +import * as KeepAwake from "./KeepAwake.ts";
8 +
9 +describe("KeepAwake.holdWhileWanted", () => {
10 + it.effect("keeps one hold across a gap shorter than the grace and releases after it", () =>
11 + Effect.gen(function* () {
12 + const wanted = yield* Queue.unbounded<boolean>();
13 + const transitions = yield* Queue.unbounded<"held" | "released">();
14 + const hold = Effect.acquireRelease(Queue.offer(transitions, "held"), () =>
15 + Queue.offer(transitions, "released"),
16 + ).pipe(Effect.andThen(Effect.never), Effect.scoped);
17 + yield* KeepAwake.holdWhileWanted(Stream.fromQueue(wanted), hold, "60 seconds").pipe(
18 + Effect.forkScoped,
19 + );
20 +
21 + yield* Queue.offer(wanted, true);
22 + expect(yield* Queue.take(transitions)).toBe("held");
23 +
24 + yield* Queue.offer(wanted, false);
25 + yield* TestClock.adjust("30 seconds");
26 + yield* Queue.offer(wanted, true);
27 + yield* TestClock.adjust("120 seconds");
28 + expect(yield* Queue.size(transitions)).toBe(0);
29 +
30 + yield* Queue.offer(wanted, false);
31 + yield* TestClock.adjust("120 seconds");
32 + expect(yield* Queue.take(transitions)).toBe("released");
33 + expect(yield* Queue.size(transitions)).toBe(0);
34 + }),
35 + );
36 +});
apps/server/src/background/KeepAwake.ts new
+191
@@ -0,0 +1,191 @@
1 +import * as Duration from "effect/Duration";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as ChildProcess from "effect/process/ChildProcess";
5 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
6 +import * as Schedule from "effect/Schedule";
7 +import * as Schema from "effect/Schema";
8 +import * as Stream from "effect/Stream";
9 +import * as SqlClient from "effect/sql/SqlClient";
10 +
11 +import * as HostProcess from "@t3tools/shared/HostProcess";
12 +
13 +import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
14 +import { forkParked } from "../serverActivation.ts";
15 +import * as Settings from "../serverSettings.ts";
16 +
17 +// Bridges gaps between back-to-back runs, so a long-idle machine does not sleep mid-queue.
18 +const RELEASE_GRACE = Duration.seconds(60);
19 +
20 +/** Each command holds its inhibitor until it exits, and exits on its own if the server dies. */
21 +function inhibitorCommand(
22 + platform: NodeJS.Platform,
23 + serverPid: number,
24 +): { readonly command: string; readonly args: ReadonlyArray<string> } | undefined {
25 + switch (platform) {
26 + case "darwin":
27 + return { command: "caffeinate", args: ["-i", "-w", String(serverPid)] };
28 + case "linux":
29 + return {
30 + command: "systemd-inhibit",
31 + args: [
32 + "--what=idle:sleep",
33 + "--who=T3 Code",
34 + "--why=Agents are working",
35 + "--mode=block",
36 + "tail",
37 + `--pid=${serverPid}`,
38 + "-f",
39 + "/dev/null",
40 + ],
41 + };
42 + case "win32":
43 + return {
44 + command: "powershell.exe",
45 + args: [
46 + "-NoProfile",
47 + "-NonInteractive",
48 + "-Command",
49 + // ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by this thread until Wait-Process returns.
50 + `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649); Wait-Process -Id ${serverPid}`,
51 + ],
52 + };
53 + default:
54 + return undefined;
55 + }
56 +}
57 +
58 +/**
59 + * Runs `hold` while `wanted` is true and for `grace` after it turns false; a true inside the
60 + * grace keeps the same hold. `hold` runs until interrupted.
61 + */
62 +export const holdWhileWanted = <E, R>(
63 + wanted: Stream.Stream<boolean, E, R>,
64 + hold: Effect.Effect<void>,
65 + grace: Duration.Input = RELEASE_GRACE,
66 +) =>
67 + wanted.pipe(
68 + Stream.changes,
69 + Stream.switchMap((on) =>
70 + on ? Stream.succeed(true) : Stream.fromEffect(Effect.as(Effect.sleep(grace), false)),
71 + ),
72 + Stream.changes,
73 + Stream.switchMap((on) => (on ? Stream.fromEffect(hold) : Stream.empty)),
74 + Stream.runDrain,
75 + );
76 +
77 +// Reads, the event subscription and the inhibitor retry until they succeed; the cap keeps a
78 +// host without an inhibitor (e.g. no logind) from retrying and warning constantly.
79 +const backoff = Schedule.exponential("5 seconds").pipe(
80 + Schedule.modifyDelay(({ duration }) =>
81 + Effect.succeed(Duration.min(duration, Duration.minutes(10))),
82 + ),
83 +);
84 +const retryWithBackoff =
85 + (message: string) =>
86 + <A, E, R>(effect: Effect.Effect<A, E, R>) =>
87 + effect.pipe(
88 + Effect.tapCause((cause) => Effect.logWarning(message, { cause })),
89 + Effect.retry(backoff),
90 + );
91 +
92 +class KeepAwakeInhibitorExited extends Schema.TaggedError<KeepAwakeInhibitorExited>()(
93 + "KeepAwakeInhibitorExited",
94 + { exitCode: Schema.Number },
95 +) {}
96 +
97 +export const layer = Layer.effectDiscard(
98 + Effect.gen(function* () {
99 + const command = inhibitorCommand(yield* HostProcess.Platform, process.pid);
100 + if (command === undefined) return;
101 + const settings = yield* Settings.ServerSettingsService;
102 + const events = yield* OrchestrationEventStore.OrchestrationEventStore;
103 + const sql = yield* SqlClient.SqlClient;
104 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
105 +
106 + const hasActiveRun = sql<{ readonly active: number }>`
107 + SELECT EXISTS (
108 + SELECT 1 FROM orchestration_v2_projection_runs
109 + WHERE status IN ('preparing', 'starting', 'running')
110 + ) AS active
111 + `.pipe(
112 + Effect.map((rows) => rows[0]?.active === 1),
113 + retryWithBackoff("keep-awake could not read active runs"),
114 + );
115 + // Read the cursor before the snapshot so a run changing in between is replayed, not missed.
116 + const active = Stream.unwrap(
117 + events.latestApplicationSequence.pipe(
118 + retryWithBackoff("keep-awake could not read the event cursor"),
119 + Effect.map((afterSequence) =>
120 + Stream.concat(
121 + Stream.succeed(undefined),
122 + events
123 + .streamApplicationEvents({ afterSequence })
124 + .pipe(
125 + Stream.filter(
126 + (stored) =>
127 + "event" in stored &&
128 + (stored.event.type === "run.created" || stored.event.type === "run.updated"),
129 + ),
130 + ),
131 + ),
132 + ),
133 + ),
134 + ).pipe(
135 + Stream.mapEffect(() => hasActiveRun),
136 + // A failed subscription resubscribes, which re-reads the cursor and the snapshot.
137 + Stream.tapCause((cause) =>
138 + Effect.logWarning("keep-awake run event stream failed", { cause }),
139 + ),
140 + Stream.retry(backoff),
141 + );
142 + const enabled = Stream.unwrap(
143 + Effect.gen(function* () {
144 + const changes = yield* settings.subscribeChanges;
145 + const current = yield* settings.getSettings.pipe(
146 + Effect.map((value) => value.keepAwakeWhileAgentsWork),
147 + Effect.orElseSucceed(() => true),
148 + );
149 + return Stream.concat(
150 + Stream.succeed(current),
151 + Stream.map(changes, (value) => value.keepAwakeWhileAgentsWork),
152 + );
153 + }),
154 + );
155 +
156 + const holdOnce = spawner
157 + .spawn(
158 + ChildProcess.make(command.command, command.args, {
159 + detached: false,
160 + shell: false,
161 + stdin: "ignore",
162 + stdout: "ignore",
163 + stderr: "ignore",
164 + }),
165 + )
166 + .pipe(
167 + Effect.tap((child) =>
168 + Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }),
169 + ),
170 + Effect.tap(() =>
171 + Effect.addFinalizer(() => Effect.logInfo("keep-awake released sleep inhibitor")),
172 + ),
173 + Effect.flatMap((child) => child.exitCode),
174 + Effect.flatMap((exitCode) =>
175 + Effect.fail(new KeepAwakeInhibitorExited({ exitCode: Number(exitCode) })),
176 + ),
177 + Effect.scoped,
178 + );
179 + const hold = holdOnce.pipe(
180 + retryWithBackoff("keep-awake sleep inhibitor stopped"),
181 + Effect.ignore,
182 + );
183 +
184 + yield* forkParked(
185 + holdWhileWanted(
186 + Stream.zipLatestWith(enabled, active, (on, busy) => on && busy),
187 + hold,
188 + ).pipe(Effect.catchCause((cause) => Effect.logWarning("keep-awake stopped", { cause }))),
189 + );
190 + }),
191 +);
apps/server/src/server.ts
+2
@@ -29,6 +29,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
29
30 import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
31 import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
32 +import * as KeepAwake from "./background/KeepAwake.ts";
33 import * as ServerConfig from "./config.ts";
34 import { withUntracedRequests } from "./http.ts";
35 import * as ServerHttp from "./http.ts";
@@ -660,6 +661,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
661 Layer.provide(layerServerRestart),
662 ),
663 layerThreadPullRequestWorker,
664 + KeepAwake.layer,
665 DelegatedTaskAnalytics.layer,
666 Layer.effectDiscard(
667 Effect.gen(function* () {
apps/web/src/components/settings/SettingsPanels.tsx
+33
@@ -555,6 +555,9 @@ export function useSettingsRestore(onRestored?: () => void) {
555 ? ["Continue threads after restarts"]
556 : []),
557 ...(isBackgroundActivityDirty ? ["Background activity"] : []),
558 + ...(settings.keepAwakeWhileAgentsWork !== DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork
559 + ? ["Keep awake while agents work"]
560 + : []),
561 ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
562 ? ["New thread mode"]
563 : []),
@@ -678,6 +681,7 @@ export function useSettingsRestore(onRestored?: () => void) {
681 enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
682 continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,
683 backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
684 + keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork,
685 backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
686 automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
687 providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
@@ -2206,6 +2210,35 @@ export function MaintenanceSettingsPanel() {
2210
2211 <SettingsSection id="background" title="Background activity">
2212 <BackgroundActivitySettingsRow />
2213 + <SettingsRow
2214 + serverScoped
2215 + settingKeys={["keepAwakeWhileAgentsWork"]}
2216 + {...searchableSetting("keep-awake-while-agents-work")}
2217 + description="Stop the computer from going to sleep while agents are working, and let it sleep once they finish. Closing a laptop lid still puts it to sleep."
2218 + resetAction={
2219 + settings.keepAwakeWhileAgentsWork !==
2220 + DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork ? (
2221 + <SettingResetButton
2222 + label="keep awake while agents work"
2223 + onClick={() =>
2224 + updateSettings({
2225 + keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork,
2226 + })
2227 + }
2228 + />
2229 + ) : null
2230 + }
2231 + control={
2232 + <ScopedSwitch
2233 + settingKeys={["keepAwakeWhileAgentsWork"]}
2234 + checked={settings.keepAwakeWhileAgentsWork}
2235 + onCheckedChange={(checked) =>
2236 + updateSettings({ keepAwakeWhileAgentsWork: Boolean(checked) })
2237 + }
2238 + aria-label="Keep awake while agents work"
2239 + />
2240 + }
2241 + />
2242 </SettingsSection>
2243
2244 <StorageCleanupSections />
apps/web/src/components/settings/settingsSearch.ts
+7
@@ -777,6 +777,13 @@ export const SETTINGS_SEARCH_ITEMS = [
777 "resume running active interrupted work restart reboot machine crash desktop update automatically",
778 ],
779 },
780 + {
781 + id: "keep-awake-while-agents-work",
782 + title: "Keep awake while agents work",
783 + to: "/settings/maintenance",
784 + scope: "environment-defaults",
785 + searchTerms: ["caffeinate sleep prevent stay awake power laptop lid inhibit"],
786 + },
787 {
788 id: "background-activity",
789 title: "Background activity",
packages/contracts/src/settings.ts
+3
@@ -1375,6 +1375,8 @@ export const ServerSettings = Schema.Struct({
1375 continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
1376 Schema.withDecodingDefault(Effect.succeed(true)),
1377 ),
1378 + /** Holds an OS sleep inhibitor while any run is active; closing a laptop lid still sleeps it. */
1379 + keepAwakeWhileAgentsWork: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1380
1381 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1382 cloudSpeechCredentials: CloudSpeechCredentials.pipe(
@@ -1826,6 +1828,7 @@ export const ServerSettingsPatch = Schema.Struct({
1828 responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
1829 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1830 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1831 + keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean),
1832 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1833 cloudSpeechCredentials: Schema.optionalKey(
1834 Schema.Struct({