Skip to content

Commit bade0f1

Browse files
feat(server): keep the computer awake while agents work
Holds an OS sleep inhibitor (caffeinate / systemd-inhibit / SetThreadExecutionState) while any run is preparing, starting or running, and releases it 60s after the last one ends. On by default, with a toggle in Settings → Maintenance on web and mobile. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3a8c250 commit bade0f1

7 files changed

Lines changed: 245 additions & 0 deletions

File tree

‎apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,21 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
555555
onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}
556556
/>
557557
</View>
558+
<View className="border-t border-border-subtle">
559+
<SettingsSwitchRow
560+
icon="bolt.circle"
561+
label="Keep awake while agents work"
562+
subtitle={managedSubtitle(
563+
"keepAwakeWhileAgentsWork",
564+
projectSelected
565+
? "Environment-wide setting. Select All projects to change it."
566+
: "Stop the computer from sleeping while agents work. Closing a laptop lid still sleeps it.",
567+
)}
568+
value={uniform("keepAwakeWhileAgentsWork")}
569+
disabled={disabledFor("keepAwakeWhileAgentsWork")}
570+
onValueChange={(value) => write({ keepAwakeWhileAgentsWork: value })}
571+
/>
572+
</View>
558573
</SettingsSection>
559574
</>
560575
) : null}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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.asVoid);
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+
});
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
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 type * as Scope from "effect/Scope";
7+
import * as Stream from "effect/Stream";
8+
import * as SqlClient from "effect/sql/SqlClient";
9+
10+
import * as HostProcess from "@t3tools/shared/HostProcess";
11+
12+
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
13+
import { forkParked } from "../serverActivation.ts";
14+
import * as Settings from "../serverSettings.ts";
15+
16+
// Bridges gaps between back-to-back runs, so a long-idle machine does not sleep mid-queue.
17+
const RELEASE_GRACE = Duration.seconds(60);
18+
19+
/** Each command holds its inhibitor until it exits, and exits on its own if the server dies. */
20+
function inhibitorCommand(
21+
platform: NodeJS.Platform,
22+
serverPid: number,
23+
): { readonly command: string; readonly args: ReadonlyArray<string> } | undefined {
24+
switch (platform) {
25+
case "darwin":
26+
return { command: "caffeinate", args: ["-i", "-w", String(serverPid)] };
27+
case "linux":
28+
return {
29+
command: "systemd-inhibit",
30+
args: [
31+
"--what=idle:sleep",
32+
"--who=T3 Code",
33+
"--why=Agents are working",
34+
"--mode=block",
35+
"tail",
36+
`--pid=${serverPid}`,
37+
"-f",
38+
"/dev/null",
39+
],
40+
};
41+
case "win32":
42+
return {
43+
command: "powershell.exe",
44+
args: [
45+
"-NoProfile",
46+
"-NonInteractive",
47+
"-Command",
48+
// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by this thread until Wait-Process returns.
49+
`$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}`,
50+
],
51+
};
52+
default:
53+
return undefined;
54+
}
55+
}
56+
57+
/** Holds while `wanted` is true and for `grace` after it turns false; a true inside the grace keeps the same hold. */
58+
export const holdWhileWanted = <E, R>(
59+
wanted: Stream.Stream<boolean, E, R>,
60+
hold: Effect.Effect<void, never, Scope.Scope>,
61+
grace: Duration.Input = RELEASE_GRACE,
62+
) =>
63+
wanted.pipe(
64+
Stream.changes,
65+
Stream.switchMap((on) =>
66+
on ? Stream.succeed(true) : Stream.fromEffect(Effect.as(Effect.sleep(grace), false)),
67+
),
68+
Stream.changes,
69+
Stream.switchMap((on) => (on ? Stream.unwrap(Effect.as(hold, Stream.never)) : Stream.empty)),
70+
Stream.runDrain,
71+
);
72+
73+
export const layer = Layer.effectDiscard(
74+
Effect.gen(function* () {
75+
const command = inhibitorCommand(yield* HostProcess.Platform, process.pid);
76+
if (command === undefined) return;
77+
const settings = yield* Settings.ServerSettingsService;
78+
const engine = yield* Orchestrator.OrchestratorV2;
79+
const sql = yield* SqlClient.SqlClient;
80+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
81+
82+
const hasActiveRun = sql<{ readonly active: number }>`
83+
SELECT EXISTS (
84+
SELECT 1 FROM orchestration_v2_projection_runs
85+
WHERE status IN ('preparing', 'starting', 'running')
86+
) AS active
87+
`.pipe(
88+
Effect.map((rows) => rows[0]?.active === 1),
89+
Effect.catchCause((cause) =>
90+
Effect.logWarning("keep-awake could not read active runs", { cause }).pipe(
91+
Effect.as(false),
92+
),
93+
),
94+
);
95+
const active = Stream.concat(
96+
Stream.fromEffect(hasActiveRun),
97+
engine.streamDomainEvents.pipe(
98+
Stream.filter((event) => event.type === "run.created" || event.type === "run.updated"),
99+
Stream.mapEffect(() => hasActiveRun),
100+
),
101+
);
102+
const enabled = Stream.unwrap(
103+
Effect.gen(function* () {
104+
const changes = yield* settings.subscribeChanges;
105+
const current = yield* settings.getSettings.pipe(
106+
Effect.map((value) => value.keepAwakeWhileAgentsWork),
107+
Effect.orElseSucceed(() => true),
108+
);
109+
return Stream.concat(
110+
Stream.succeed(current),
111+
Stream.map(changes, (value) => value.keepAwakeWhileAgentsWork),
112+
);
113+
}),
114+
);
115+
116+
const hold = spawner
117+
.spawn(
118+
ChildProcess.make(command.command, command.args, {
119+
detached: false,
120+
shell: false,
121+
stdin: "ignore",
122+
stdout: "ignore",
123+
stderr: "ignore",
124+
}),
125+
)
126+
.pipe(
127+
Effect.tap((child) =>
128+
Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }),
129+
),
130+
Effect.tap(() =>
131+
Effect.addFinalizer(() => Effect.logInfo("keep-awake released sleep inhibitor")),
132+
),
133+
Effect.asVoid,
134+
Effect.catchCause((cause) =>
135+
Effect.logWarning("keep-awake could not start the sleep inhibitor", {
136+
command: command.command,
137+
cause,
138+
}),
139+
),
140+
);
141+
142+
yield* forkParked(
143+
holdWhileWanted(
144+
Stream.zipLatestWith(enabled, active, (on, busy) => on && busy),
145+
hold,
146+
).pipe(Effect.catchCause((cause) => Effect.logWarning("keep-awake stopped", { cause }))),
147+
);
148+
}),
149+
);

‎apps/server/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
2828

2929
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
3030
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
31+
import * as KeepAwake from "./background/KeepAwake.ts";
3132
import * as ServerConfig from "./config.ts";
3233
import { withUntracedRequests } from "./http.ts";
3334
import * as ServerHttp from "./http.ts";
@@ -652,6 +653,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
652653
Layer.provide(layerServerRestart),
653654
),
654655
layerThreadPullRequestWorker,
656+
KeepAwake.layer,
655657
DelegatedTaskAnalytics.layer,
656658
Layer.effectDiscard(
657659
Effect.gen(function* () {

‎apps/web/src/components/settings/SettingsPanels.tsx‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,9 @@ export function useSettingsRestore(onRestored?: () => void) {
550550
? ["Continue threads after restarts"]
551551
: []),
552552
...(isBackgroundActivityDirty ? ["Background activity"] : []),
553+
...(settings.keepAwakeWhileAgentsWork !== DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork
554+
? ["Keep awake while agents work"]
555+
: []),
553556
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
554557
? ["New thread mode"]
555558
: []),
@@ -670,6 +673,7 @@ export function useSettingsRestore(onRestored?: () => void) {
670673
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
671674
continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,
672675
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
676+
keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork,
673677
backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
674678
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
675679
providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
@@ -2026,6 +2030,35 @@ export function MaintenanceSettingsPanel() {
20262030

20272031
<SettingsSection id="background" title="Background activity">
20282032
<BackgroundActivitySettingsRow />
2033+
<SettingsRow
2034+
serverScoped
2035+
settingKeys={["keepAwakeWhileAgentsWork"]}
2036+
{...searchableSetting("keep-awake-while-agents-work")}
2037+
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."
2038+
resetAction={
2039+
settings.keepAwakeWhileAgentsWork !==
2040+
DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork ? (
2041+
<SettingResetButton
2042+
label="keep awake while agents work"
2043+
onClick={() =>
2044+
updateSettings({
2045+
keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork,
2046+
})
2047+
}
2048+
/>
2049+
) : null
2050+
}
2051+
control={
2052+
<ScopedSwitch
2053+
settingKeys={["keepAwakeWhileAgentsWork"]}
2054+
checked={settings.keepAwakeWhileAgentsWork}
2055+
onCheckedChange={(checked) =>
2056+
updateSettings({ keepAwakeWhileAgentsWork: Boolean(checked) })
2057+
}
2058+
aria-label="Keep awake while agents work"
2059+
/>
2060+
}
2061+
/>
20292062
</SettingsSection>
20302063

20312064
<StorageCleanupSections />

‎apps/web/src/components/settings/settingsSearch.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,13 @@ export const SETTINGS_SEARCH_ITEMS = [
749749
"resume running active interrupted work restart reboot machine crash desktop update automatically",
750750
],
751751
},
752+
{
753+
id: "keep-awake-while-agents-work",
754+
title: "Keep awake while agents work",
755+
to: "/settings/maintenance",
756+
scope: "environment-defaults",
757+
searchTerms: ["caffeinate sleep prevent stay awake power laptop lid inhibit"],
758+
},
752759
{
753760
id: "background-activity",
754761
title: "Background activity",

‎packages/contracts/src/settings.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1355,6 +1355,8 @@ export const ServerSettings = Schema.Struct({
13551355
continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
13561356
Schema.withDecodingDefault(Effect.succeed(true)),
13571357
),
1358+
/** Holds an OS sleep inhibitor while any run is active; closing a laptop lid still sleeps it. */
1359+
keepAwakeWhileAgentsWork: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
13581360

13591361
enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
13601362
cloudSpeechCredentials: CloudSpeechCredentials.pipe(
@@ -1802,6 +1804,7 @@ export const ServerSettingsPatch = Schema.Struct({
18021804
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
18031805
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
18041806
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1807+
keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean),
18051808
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
18061809
cloudSpeechCredentials: Schema.optionalKey(
18071810
Schema.Struct({

0 commit comments

Comments
 (0)