Skip to content

Commit 1d1b732

Browse files
committed
feat(server): keep the host awake while agents work
- Add configurable host wake locks for active work or while T3 Code runs - Expose the setting in web and mobile settings, environment tools, and docs
1 parent e68e19d commit 1d1b732

14 files changed

Lines changed: 499 additions & 2 deletions

File tree

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/sess
55
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
66
import { AppText as Text } from "../../components/ui/AppText";
77
import {
8+
type KeepHostAwakeMode,
89
type ResponseStreamingMode,
910
type ServerSettings,
1011
type ServerSettingsPatch,
@@ -134,6 +135,28 @@ const STREAMING_CHOICES: ReadonlyArray<{
134135
},
135136
];
136137

138+
const KEEP_HOST_AWAKE_CHOICES: ReadonlyArray<{
139+
readonly mode: KeepHostAwakeMode;
140+
readonly label: string;
141+
readonly description: string;
142+
}> = [
143+
{
144+
mode: "off",
145+
label: "Off",
146+
description: "The host sleeps according to its own power settings.",
147+
},
148+
{
149+
mode: "whileWorking",
150+
label: "While agents work",
151+
description: "Prevent the host from sleeping while agents are working on it.",
152+
},
153+
{
154+
mode: "always",
155+
label: "Always",
156+
description: "Prevent the host from sleeping while T3 Code is running.",
157+
},
158+
];
159+
137160
// Only servers with thread auto-settlement store these, so other targets get the rest of a patch.
138161
const AUTO_SETTLE_SETTING_KEYS: ReadonlySet<string> = new Set([
139162
"sidebarAutoSettleOnMerge",
@@ -523,6 +546,29 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
523546
))}
524547
</SettingsSection>
525548
) : null}
549+
{!projectSelected ? (
550+
<SettingsSection
551+
title="Keep host awake"
552+
footer={managed("keepHostAwake")}
553+
trailing={
554+
pendingWrites === 0 && uniform("keepHostAwake") === null ? (
555+
<MixedValuesLabel projectSelected={projectSelected} />
556+
) : null
557+
}
558+
>
559+
{KEEP_HOST_AWAKE_CHOICES.map((choice, index) => (
560+
<SettingsChoiceRow
561+
key={choice.mode}
562+
label={choice.label}
563+
description={choice.description}
564+
selected={uniform("keepHostAwake") === choice.mode}
565+
separated={index > 0}
566+
disabled={disabledFor("keepHostAwake")}
567+
onPress={() => write({ keepHostAwake: choice.mode })}
568+
/>
569+
))}
570+
</SettingsSection>
571+
) : null}
526572
<SettingsSection title="Updates">
527573
<SettingsSwitchRow
528574
icon="arrow.clockwise"
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import type { KeepHostAwakeMode, OrchestrationV2DomainEvent } from "@t3tools/contracts";
2+
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
3+
import { describe, expect, it } from "@effect/vitest";
4+
import * as Effect from "effect/Effect";
5+
import * as Layer from "effect/Layer";
6+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
7+
import * as Queue from "effect/Queue";
8+
import * as Ref from "effect/Ref";
9+
import * as Sink from "effect/Sink";
10+
import * as Stream from "effect/Stream";
11+
12+
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
13+
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
14+
import * as ServerSettings from "../serverSettings.ts";
15+
import * as HostWakeLock from "./HostWakeLock.ts";
16+
17+
const runUpdated = { type: "run.updated" } as OrchestrationV2DomainEvent;
18+
const turnItemUpdated = { type: "turn-item.updated" } as OrchestrationV2DomainEvent;
19+
20+
const setup = Effect.fn("HostWakeLockTest.setup")(function* (input: {
21+
readonly mode: KeepHostAwakeMode;
22+
readonly working?: boolean;
23+
/** Helpers exit by themselves instead of holding until killed. */
24+
readonly exitsEarly?: boolean;
25+
}) {
26+
const mode = yield* Ref.make(input.mode);
27+
const working = yield* Ref.make(input.working ?? false);
28+
const workingReads = yield* Ref.make(0);
29+
const spawns = yield* Ref.make(0);
30+
const spawned = yield* Queue.unbounded<void>();
31+
const released = yield* Queue.unbounded<void>();
32+
const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
33+
const settingsChanges = yield* Queue.unbounded<KeepHostAwakeMode>();
34+
35+
const dependencies = Layer.mergeAll(
36+
Layer.mock(Orchestrator.OrchestratorV2)({ streamDomainEvents: Stream.fromQueue(events) }),
37+
Layer.mock(ProjectionStore.ProjectionStoreV2)({
38+
hasWorkingRuns: () =>
39+
Ref.update(workingReads, (reads) => reads + 1).pipe(Effect.andThen(Ref.get(working))),
40+
}),
41+
Layer.mock(ServerSettings.ServerSettingsService)({
42+
getSettings: Ref.get(mode).pipe(
43+
Effect.map((keepHostAwake) => ({ ...DEFAULT_SERVER_SETTINGS, keepHostAwake })),
44+
),
45+
subscribeChanges: Effect.succeed(
46+
Stream.fromQueue(settingsChanges).pipe(
47+
Stream.map((keepHostAwake) => ({ ...DEFAULT_SERVER_SETTINGS, keepHostAwake })),
48+
),
49+
),
50+
}),
51+
Layer.succeed(
52+
ChildProcessSpawner.ChildProcessSpawner,
53+
ChildProcessSpawner.make(() =>
54+
Effect.gen(function* () {
55+
yield* Ref.update(spawns, (count) => count + 1);
56+
yield* Effect.addFinalizer(() => Queue.offer(released, undefined));
57+
yield* Queue.offer(spawned, undefined);
58+
return ChildProcessSpawner.makeHandle({
59+
pid: ChildProcessSpawner.ProcessId(1),
60+
exitCode:
61+
input.exitsEarly === true
62+
? Effect.succeed(ChildProcessSpawner.ExitCode(1))
63+
: Effect.never,
64+
isRunning: Effect.succeed(true),
65+
kill: () => Effect.void,
66+
unref: Effect.succeed(Effect.void),
67+
stdin: Sink.drain,
68+
stdout: Stream.empty,
69+
stderr: Stream.empty,
70+
all: Stream.empty,
71+
getInputFd: () => Sink.drain,
72+
getOutputFd: () => Stream.empty,
73+
});
74+
}),
75+
),
76+
),
77+
);
78+
const service = yield* HostWakeLock.make.pipe(Effect.provide(dependencies));
79+
yield* service.start().pipe(Effect.provide(dependencies));
80+
81+
return {
82+
events,
83+
released,
84+
spawned,
85+
spawns,
86+
working,
87+
workingReads,
88+
setMode: (next: KeepHostAwakeMode) =>
89+
Ref.set(mode, next).pipe(Effect.andThen(Queue.offer(settingsChanges, next))),
90+
};
91+
});
92+
93+
describe("HostWakeLock", () => {
94+
it.effect("holds one lock while runs work and releases it when they stop", () =>
95+
Effect.scoped(
96+
Effect.gen(function* () {
97+
const host = yield* setup({ mode: "whileWorking" });
98+
99+
yield* Ref.set(host.working, true);
100+
yield* Queue.offer(host.events, runUpdated);
101+
yield* Queue.take(host.spawned);
102+
yield* Queue.offerAll(host.events, [runUpdated, runUpdated]);
103+
104+
yield* Ref.set(host.working, false);
105+
yield* Queue.offer(host.events, runUpdated);
106+
yield* Queue.take(host.released);
107+
expect(yield* Ref.get(host.spawns)).toBe(1);
108+
}),
109+
),
110+
);
111+
112+
it.effect("takes the lock at startup for runs that are already working", () =>
113+
Effect.scoped(
114+
Effect.gen(function* () {
115+
const host = yield* setup({ mode: "whileWorking", working: true });
116+
yield* Queue.take(host.spawned);
117+
}),
118+
),
119+
);
120+
121+
it.effect("follows the setting without reading runs outside while-working mode", () =>
122+
Effect.scoped(
123+
Effect.gen(function* () {
124+
const host = yield* setup({ mode: "off", working: true });
125+
yield* Queue.offer(host.events, runUpdated);
126+
127+
yield* host.setMode("always");
128+
yield* Queue.take(host.spawned);
129+
130+
yield* host.setMode("off");
131+
yield* Queue.take(host.released);
132+
expect(yield* Ref.get(host.workingReads)).toBe(0);
133+
expect(yield* Ref.get(host.spawns)).toBe(1);
134+
}),
135+
),
136+
);
137+
138+
it.effect("ignores events that cannot change whether a run is working", () =>
139+
Effect.scoped(
140+
Effect.gen(function* () {
141+
const host = yield* setup({ mode: "whileWorking" });
142+
yield* Ref.set(host.working, true);
143+
yield* Queue.offer(host.events, turnItemUpdated);
144+
145+
yield* Queue.offer(host.events, runUpdated);
146+
yield* Queue.take(host.spawned);
147+
// One read at startup, one for the run event.
148+
expect(yield* Ref.get(host.workingReads)).toBe(2);
149+
}),
150+
),
151+
);
152+
153+
it.effect("takes the lock again after the helper exits by itself", () =>
154+
Effect.scoped(
155+
Effect.gen(function* () {
156+
const host = yield* setup({ mode: "always", exitsEarly: true });
157+
yield* Queue.take(host.released);
158+
159+
yield* Queue.offer(host.events, runUpdated);
160+
yield* Queue.take(host.released);
161+
expect(yield* Ref.get(host.spawns)).toBe(2);
162+
}),
163+
),
164+
);
165+
166+
it.effect("releases the lock when the server shuts down", () =>
167+
Effect.gen(function* () {
168+
const released = yield* Effect.scoped(
169+
Effect.gen(function* () {
170+
const host = yield* setup({ mode: "always" });
171+
yield* Queue.take(host.spawned);
172+
return host.released;
173+
}),
174+
);
175+
yield* Queue.take(released);
176+
}),
177+
);
178+
});
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import * as HostProcess from "@t3tools/shared/HostProcess";
2+
import * as Effect from "effect/Effect";
3+
import * as FiberHandle from "effect/FiberHandle";
4+
import * as ChildProcess from "effect/process/ChildProcess";
5+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
6+
import * as Stream from "effect/Stream";
7+
8+
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
9+
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
10+
import { forkParked } from "../serverActivation.ts";
11+
import * as ServerSettings from "../serverSettings.ts";
12+
13+
const WINDOWS_ES_CONTINUOUS_SYSTEM_REQUIRED = 0x80000001;
14+
15+
/**
16+
* Each command holds a system sleep lock until it is killed. Each also watches the server's pid,
17+
* so a server that is killed outright cannot leave the host unable to sleep.
18+
*/
19+
function wakeLockCommand(platform: NodeJS.Platform, serverPid: number) {
20+
switch (platform) {
21+
case "darwin":
22+
return { command: "/usr/bin/caffeinate", args: ["-i", "-w", `${serverPid}`] };
23+
case "linux":
24+
return {
25+
command: "systemd-inhibit",
26+
args: [
27+
"--what=idle:sleep",
28+
"--who=T3 Code",
29+
"--why=Keeping this machine awake for coding agents",
30+
"--mode=block",
31+
"tail",
32+
`--pid=${serverPid}`,
33+
"-f",
34+
"/dev/null",
35+
],
36+
};
37+
case "win32":
38+
return {
39+
command: "powershell.exe",
40+
args: [
41+
"-NoProfile",
42+
"-NonInteractive",
43+
"-WindowStyle",
44+
"Hidden",
45+
"-Command",
46+
`$k = Add-Type -Name WakeLock -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint flags);'; [void]$k::SetThreadExecutionState(${WINDOWS_ES_CONTINUOUS_SYSTEM_REQUIRED}); Wait-Process -Id ${serverPid}`,
47+
],
48+
};
49+
default:
50+
return null;
51+
}
52+
}
53+
54+
/** Holds a host sleep lock according to the `keepHostAwake` setting. */
55+
export const make = Effect.gen(function* () {
56+
const orchestrator = yield* Orchestrator.OrchestratorV2;
57+
const projections = yield* ProjectionStore.ProjectionStoreV2;
58+
const settings = yield* ServerSettings.ServerSettingsService;
59+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
60+
61+
const shouldHold = Effect.gen(function* () {
62+
const { keepHostAwake } = yield* settings.getSettings;
63+
return keepHostAwake === "whileWorking"
64+
? yield* projections.hasWorkingRuns()
65+
: keepHostAwake === "always";
66+
});
67+
68+
const start = Effect.fn("HostWakeLock.start")(function* () {
69+
const wakeLock = wakeLockCommand(yield* HostProcess.Platform, process.pid);
70+
if (wakeLock === null) return;
71+
72+
const hold = Effect.scoped(
73+
Effect.gen(function* () {
74+
const handle = yield* spawner.spawn(
75+
ChildProcess.make(wakeLock.command, wakeLock.args, {
76+
stdin: "ignore",
77+
stdout: "ignore",
78+
stderr: "ignore",
79+
forceKillAfter: "2 seconds",
80+
}),
81+
);
82+
const exitCode = yield* handle.exitCode;
83+
yield* Effect.logWarning("host wake lock exited early", { exitCode });
84+
}),
85+
).pipe(
86+
Effect.catch((cause) => Effect.logWarning("host wake lock unavailable", { cause })),
87+
// Node throws some spawn errors synchronously, which `catch` cannot see.
88+
Effect.catchDefect((cause) => Effect.logWarning("host wake lock unavailable", { cause })),
89+
);
90+
91+
const lock = yield* FiberHandle.make<void>();
92+
const reconcile = shouldHold.pipe(
93+
Effect.flatMap((held) =>
94+
held
95+
? FiberHandle.run(lock, hold, { onlyIfMissing: true }).pipe(Effect.asVoid)
96+
: FiberHandle.clear(lock),
97+
),
98+
Effect.catch((cause) => Effect.logWarning("host wake lock update failed", { cause })),
99+
);
100+
101+
const settingsChanges = yield* settings.subscribeChanges;
102+
yield* forkParked(
103+
Stream.succeed(undefined).pipe(
104+
Stream.merge(
105+
settingsChanges.pipe(
106+
Stream.map((current) => current.keepHostAwake),
107+
Stream.changes,
108+
),
109+
),
110+
Stream.merge(
111+
orchestrator.streamDomainEvents.pipe(
112+
Stream.filter((event) => event.type === "run.created" || event.type === "run.updated"),
113+
),
114+
),
115+
Stream.runForEach(() => reconcile),
116+
),
117+
);
118+
});
119+
120+
return { start };
121+
});

‎apps/server/src/mcp/toolkits/environment/handlers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export function preferences(settings: ServerSettings) {
1414
newWorktreesStartFromOrigin,
1515
enableProviderUpdateChecks,
1616
backgroundActivity,
17+
keepHostAwake,
1718
sourceControlWritingStyle,
1819
} = settings;
1920
const characters = Array.from(sourceControlWritingStyle.customInstructions);
@@ -22,6 +23,7 @@ export function preferences(settings: ServerSettings) {
2223
newWorktreesStartFromOrigin,
2324
enableProviderUpdateChecks,
2425
backgroundActivity: { profile: backgroundActivity.profile },
26+
keepHostAwake,
2527
sourceControlWritingStyle: {
2628
...sourceControlWritingStyle,
2729
customInstructions: characters.slice(0, 4000).join(""),

‎apps/server/src/mcp/toolkits/environment/tools.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const PreferenceFields = {
2020
newWorktreesStartFromOrigin: ServerSettings.fields.newWorktreesStartFromOrigin,
2121
enableProviderUpdateChecks: ServerSettings.fields.enableProviderUpdateChecks,
2222
backgroundActivity: Schema.Struct({ profile: BackgroundActivityProfileSelection }),
23+
keepHostAwake: ServerSettings.fields.keepHostAwake,
2324
sourceControlWritingStyle: Schema.Struct({
2425
mode: Schema.String,
2526
followChangeRequestTemplates: Schema.Boolean,
@@ -63,6 +64,7 @@ const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update"
6364
newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin,
6465
enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks,
6566
backgroundActivity: Schema.optionalKey(Schema.Struct({ profile: BackgroundActivityProfile })),
67+
keepHostAwake: ServerSettingsPatch.fields.keepHostAwake,
6668
sourceControlWritingStyle: ServerSettingsPatch.fields.sourceControlWritingStyle,
6769
}),
6870
success: Schema.Struct(PreferenceFields),

0 commit comments

Comments
 (0)