Skip to content

Commit 587deab

Browse files
feat(server): keep the computer awake while agents work (#34128)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 5959787 commit 587deab

7 files changed

Lines changed: 287 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
@@ -582,6 +582,21 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
582582
onValueChange={(value) => write({ continueThreadsAfterServerUpdate: value })}
583583
/>
584584
</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>
585600
</SettingsSection>
586601
</>
587602
) : 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.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+
});
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

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

3030
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
3131
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
32+
import * as KeepAwake from "./background/KeepAwake.ts";
3233
import * as ServerConfig from "./config.ts";
3334
import { withUntracedRequests } from "./http.ts";
3435
import * as ServerHttp from "./http.ts";
@@ -660,6 +661,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
660661
Layer.provide(layerServerRestart),
661662
),
662663
layerThreadPullRequestWorker,
664+
KeepAwake.layer,
663665
DelegatedTaskAnalytics.layer,
664666
Layer.effectDiscard(
665667
Effect.gen(function* () {

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,9 @@ export function useSettingsRestore(onRestored?: () => void) {
555555
? ["Continue threads after restarts"]
556556
: []),
557557
...(isBackgroundActivityDirty ? ["Background activity"] : []),
558+
...(settings.keepAwakeWhileAgentsWork !== DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork
559+
? ["Keep awake while agents work"]
560+
: []),
558561
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
559562
? ["New thread mode"]
560563
: []),
@@ -678,6 +681,7 @@ export function useSettingsRestore(onRestored?: () => void) {
678681
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
679682
continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,
680683
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
684+
keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork,
681685
backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
682686
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
683687
providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
@@ -2206,6 +2210,35 @@ export function MaintenanceSettingsPanel() {
22062210

22072211
<SettingsSection id="background" title="Background activity">
22082212
<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+
/>
22092242
</SettingsSection>
22102243

22112244
<StorageCleanupSections />

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,13 @@ export const SETTINGS_SEARCH_ITEMS = [
777777
"resume running active interrupted work restart reboot machine crash desktop update automatically",
778778
],
779779
},
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+
},
780787
{
781788
id: "background-activity",
782789
title: "Background activity",

‎packages/contracts/src/settings.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1375,6 +1375,8 @@ export const ServerSettings = Schema.Struct({
13751375
continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
13761376
Schema.withDecodingDefault(Effect.succeed(true)),
13771377
),
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))),
13781380

13791381
enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
13801382
cloudSpeechCredentials: CloudSpeechCredentials.pipe(
@@ -1826,6 +1828,7 @@ export const ServerSettingsPatch = Schema.Struct({
18261828
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
18271829
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
18281830
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1831+
keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean),
18291832
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
18301833
cloudSpeechCredentials: Schema.optionalKey(
18311834
Schema.Struct({

0 commit comments

Comments
 (0)