Skip to content

Commit 12c8580

Browse files
nullStack65claude
andcommitted
fix(placement): fail closed on unknown presence; keep work on its own machine
From review: logind errors no longer read as headless, a machine without agent scopes reports no agent count, default placement needs the caller's clientRequestId so a retry finds the chosen machine, and work started on someone's computer stays there when nothing else has room. Model: claude-opus-5-5 Task: fix Agent: Builder Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 926b6a9 commit 12c8580

10 files changed

Lines changed: 126 additions & 76 deletions

File tree

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,11 @@ const launchPlacedThere = Effect.fn("mcp.launchPlacedThere")(function* (
134134
},
135135
) {
136136
// A fresh worktree from origin needs nothing of this checkout, so the fleet places it
137-
// by default; anything else, or an explicit 'here', stays unless it asks.
137+
// by default; anything else, or an explicit 'here', stays unless it asks. Only with the
138+
// caller's key: a retry after a lost answer must reach the machine first chosen.
138139
const byDefault =
139140
input.placement === undefined &&
141+
input.clientRequestId !== undefined &&
140142
input.environmentId === undefined &&
141143
local.strategy?.type === "worktree" &&
142144
local.strategy.startFromOrigin === true &&
@@ -151,7 +153,6 @@ const launchPlacedThere = Effect.fn("mcp.launchPlacedThere")(function* (
151153
input = {
152154
...input,
153155
placement: "auto",
154-
clientRequestId: input.clientRequestId ?? local.threadId,
155156
modelSelection: input.modelSelection ?? local.callerModelSelection,
156157
};
157158
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
164164
placement: Schema.optional(
165165
Schema.Literals(["auto", "here"]).annotate({
166166
description:
167-
"'auto', without `environmentId`: here or on a linked environment with spare capacity, this repository's project and your exact `modelSelection`; there, in that project's checkout. Needs `modelSelection` and `clientRequestId`; a retry keeps the environment chosen. Attachments, scratch and worktrees not started from origin stay here. Omitted: a worktree started from origin is placed the same way, with your model, when this machine places by default. 'here' keeps it here.",
167+
"'auto', without `environmentId`: here or on a linked environment with spare capacity, this repository's project and your exact `modelSelection`; there, in that project's checkout. Needs `modelSelection` and `clientRequestId`; a retry keeps the environment chosen. Attachments, scratch and worktrees not started from origin stay here. Omitted with a `clientRequestId`: a worktree started from origin is placed the same way, with your model, when this machine places by default. 'here' keeps it here.",
168168
}),
169169
),
170170
/** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */

‎apps/server/src/peer/RemoteDelegation.test.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1658,17 +1658,27 @@ it.effect("a fresh worktree from origin is placed without asking, unless kept he
16581658
});
16591659
yield* linkTo(a.links, b, "full-access");
16601660
const fresh = { type: "worktree", baseRef: "main", startFromOrigin: true };
1661-
const placed = yield* launchUnplaced(a, { workspaceStrategy: fresh });
1661+
// Without a key nothing could find the machine again after a lost answer: it stays here.
1662+
yield* launchUnplaced(a, { workspaceStrategy: fresh });
1663+
expect(yield* Ref.get(localLaunches)).toBe(1);
1664+
const placed = yield* launchUnplaced(a, {
1665+
clientRequestId: "fresh",
1666+
workspaceStrategy: fresh,
1667+
});
16621668
expect(placed.isError, JSON.stringify(placed.content)).toBe(false);
16631669
expect(placed.structuredContent).toMatchObject({ environmentId: box.environmentId });
1664-
expect(yield* Ref.get(localLaunches)).toBe(0);
1670+
expect(yield* Ref.get(localLaunches)).toBe(1);
16651671

16661672
// 'here', or the fleet default turned off, keeps it on this machine.
1667-
yield* launchPlaced(a, { placement: "here", workspaceStrategy: fresh });
1668-
expect(yield* Ref.get(localLaunches)).toBe(1);
1669-
yield* a.settings.updateSettings({ automaticPlacementByDefault: false });
1670-
yield* launchUnplaced(a, { workspaceStrategy: fresh });
1673+
yield* launchPlaced(a, {
1674+
placement: "here",
1675+
clientRequestId: "kept",
1676+
workspaceStrategy: fresh,
1677+
});
16711678
expect(yield* Ref.get(localLaunches)).toBe(2);
1679+
yield* a.settings.updateSettings({ automaticPlacementByDefault: false });
1680+
yield* launchUnplaced(a, { clientRequestId: "off", workspaceStrategy: fresh });
1681+
expect(yield* Ref.get(localLaunches)).toBe(3);
16721682
}),
16731683
).pipe(Effect.provide(NodeHttpServer.layerTest)),
16741684
);
@@ -1689,7 +1699,7 @@ it.effect("placement nobody asked for runs here when no machine has room", () =>
16891699
});
16901700
yield* linkTo(a.links, b, "full-access");
16911701
const fresh = { type: "worktree", baseRef: "main", startFromOrigin: true };
1692-
yield* launchUnplaced(a, { workspaceStrategy: fresh });
1702+
yield* launchUnplaced(a, { clientRequestId: "room", workspaceStrategy: fresh });
16931703
expect(yield* Ref.get(localLaunches)).toBe(1);
16941704
expect(yield* Ref.get(thread.launched)).toBeNull();
16951705
// Asked for, it still fails loudly instead.

‎apps/server/src/resourceTelemetry/HostResources.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ const make = Effect.fn("makeHostResources")(function* () {
100100
cgroupPath === undefined ? undefined : /^(.*\/user@\d+\.service)\//.exec(cgroupPath)?.[1];
101101
if (manager === undefined) return undefined;
102102
const root = `/sys/fs/cgroup${manager}/${AGENTS_SLICE_PATH}`;
103+
// No agents slice means agent scopes are off here, so neither the count nor caps exist.
103104
const slices = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => null));
104-
if (slices === null) return 0;
105+
if (slices === null) return undefined;
105106
let running = 0;
106107
for (const slice of slices.filter((name) => name.endsWith(".slice"))) {
107108
const scopes = yield* fs

‎apps/server/src/resourceTelemetry/MachinePresence.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ const linux = (input: {
1818
readonly display: string;
1919
readonly session?: string;
2020
readonly calls?: Array<string>;
21+
/** logind refusing `show-user`, with this stderr. */
22+
readonly userError?: string;
2123
}) =>
2224
MachinePresenceLive.layer.pipe(
2325
Layer.provide(
@@ -29,10 +31,11 @@ const linux = (input: {
2931
run: ({ args }) =>
3032
Effect.sync(() => {
3133
input.calls?.push(args[0] ?? "");
34+
const refused = args[0] === "show-user" && input.userError !== undefined;
3235
return {
3336
stdout: args[0] === "show-user" ? input.display : (input.session ?? ""),
34-
stderr: "",
35-
code: ChildProcessSpawner.ExitCode(0),
37+
stderr: refused ? (input.userError ?? "") : "",
38+
code: ChildProcessSpawner.ExitCode(refused ? 1 : 0),
3639
timedOut: false,
3740
stdoutTruncated: false,
3841
stderrTruncated: false,
@@ -70,6 +73,21 @@ describe("MachinePresence", () => {
7073
}),
7174
);
7275

76+
it.effect("counts a machine logind cannot describe as someone's, in use", () =>
77+
Effect.gen(function* () {
78+
const unknown = yield* read.pipe(
79+
Effect.provide(linux({ role: "auto", display: "", userError: "Failed to connect to bus" })),
80+
);
81+
assert.deepStrictEqual(unknown, { placementRole: "interactive", humanActive: true });
82+
const loggedOut = yield* read.pipe(
83+
Effect.provide(
84+
linux({ role: "auto", display: "", userError: "User 1000 is not logged in." }),
85+
),
86+
);
87+
assert.deepStrictEqual(loggedOut, { placementRole: "headless" });
88+
}),
89+
);
90+
7391
it.effect("protects a graphical login unless its person is idle, locked or away", () =>
7492
Effect.gen(function* () {
7593
const inUse = yield* read.pipe(

‎apps/server/src/resourceTelemetry/MachinePresence.ts‎

Lines changed: 40 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ import * as ProcessRunner from "../processRunner.ts";
1111
import * as ServerSettings from "../serverSettings.ts";
1212
import { MachinePresence } from "./HostResources.ts";
1313

14-
/** A person who has not touched a Mac's keyboard or pointer for this long is away. */
15-
const DARWIN_IDLE_NANOS = 10 * 60 * 1e9;
16-
1714
function parseKeyValues(text: string): Map<string, string> {
1815
const values = new Map<string, string>();
1916
for (const line of text.split("\n")) {
@@ -40,84 +37,72 @@ export function isLocalGraphicalSession(shown: string): boolean {
4037
return (type === "x11" || type === "wayland" || type === "mir") && values.get("Remote") !== "yes";
4138
}
4239

43-
/** HIDIdleTime from `ioreg -c IOHIDSystem`; undefined when it cannot be read. */
44-
export function darwinIdleNanos(output: string): number | undefined {
45-
const value = /"HIDIdleTime"\s*=\s*(\d+)/.exec(output)?.[1];
46-
return value === undefined ? undefined : Number(value);
47-
}
40+
/**
41+
* What logind says about this user's local graphical login: none, one (with its state), or
42+
* unknown when logind could not be asked. Unknown never means nobody is there.
43+
*/
44+
type GraphicalLogin =
45+
| { readonly kind: "none" }
46+
| { readonly kind: "session"; readonly shown: string }
47+
| { readonly kind: "unknown" };
4848

4949
export const make = Effect.gen(function* () {
5050
const platform = yield* HostProcess.Platform;
5151
const runner = yield* ProcessRunner.ProcessRunner;
5252
const settingsService = yield* ServerSettings.ServerSettingsService;
5353
const { mode } = yield* ServerConfig.ServerConfig;
5454

55-
const run = (command: string, args: ReadonlyArray<string>) =>
56-
runner.run({ command, args, timeout: "2 seconds" }).pipe(
57-
Effect.map((result) => (result.code === 0 ? result.stdout : undefined)),
58-
Effect.orElseSucceed(() => undefined),
59-
);
55+
const run = (args: ReadonlyArray<string>) =>
56+
runner.run({ command: "loginctl", args, timeout: "2 seconds" }).pipe(Effect.option);
6057

61-
// The logind state of this user's local graphical login, or undefined when there is none.
6258
// Display can name a remote or text session, such as an SSH login, which nobody sits at.
63-
const graphicalSession = Effect.gen(function* () {
59+
const graphicalLogin: Effect.Effect<GraphicalLogin> = Effect.gen(function* () {
6460
const uid = NodeProcess.getuid?.();
65-
if (uid === undefined) return undefined;
66-
const display = (yield* run("loginctl", [
67-
"show-user",
68-
String(uid),
69-
"-p",
70-
"Display",
71-
"--value",
72-
]))?.trim();
73-
if (display === undefined || display.length === 0) return undefined;
74-
const shown = yield* run("loginctl", [
61+
if (uid === undefined) return { kind: "unknown" } as const;
62+
const user = yield* run(["show-user", String(uid), "-p", "Display", "--value"]);
63+
if (user._tag === "None") return { kind: "unknown" } as const;
64+
if (user.value.code !== 0)
65+
// Without a session or lingering manager logind knows no such user: nobody is logged in.
66+
return /not logged in/i.test(user.value.stderr)
67+
? ({ kind: "none" } as const)
68+
: ({ kind: "unknown" } as const);
69+
const display = user.value.stdout.trim();
70+
if (display.length === 0) return { kind: "none" } as const;
71+
const session = yield* run([
7572
"show-session",
7673
display,
7774
...["Type", "Remote", "Active", "LockedHint", "IdleHint"].flatMap((key) => ["-p", key]),
7875
]);
79-
// A session logind names but cannot describe is treated as someone's.
80-
if (shown === undefined) return "";
81-
return isLocalGraphicalSession(shown) ? shown : undefined;
76+
if (session._tag === "None" || session.value.code !== 0) return { kind: "unknown" } as const;
77+
return isLocalGraphicalSession(session.value.stdout)
78+
? ({ kind: "session", shown: session.value.stdout } as const)
79+
: ({ kind: "none" } as const);
8280
});
8381

84-
const resolveRole = Effect.fn("MachinePresence.resolveRole")(function* (
85-
setting: MachinePlacementRole,
86-
) {
82+
const role = Effect.gen(function* () {
83+
const settings = yield* settingsService.getSettings.pipe(Effect.option);
84+
const setting: MachinePlacementRole =
85+
settings._tag === "Some" ? settings.value.machinePlacementRole : "auto";
8786
if (setting !== "auto") return setting;
8887
if (mode === "desktop" || platform !== "linux") return "interactive" as const;
89-
return (yield* graphicalSession) === undefined
88+
return (yield* graphicalLogin).kind === "none"
9089
? ("headless" as const)
9190
: ("interactive" as const);
9291
});
9392

94-
const humanActive = Effect.gen(function* () {
95-
if (platform === "darwin") {
96-
const idle = darwinIdleNanos(
97-
(yield* run("/usr/sbin/ioreg", ["-c", "IOHIDSystem", "-d", "4", "-k", "HIDIdleTime"])) ??
98-
"",
99-
);
100-
return idle === undefined || idle < DARWIN_IDLE_NANOS;
101-
}
102-
if (platform !== "linux") return true;
103-
const session = yield* graphicalSession;
104-
return session !== undefined && linuxSessionInUse(session);
105-
});
106-
107-
const role = Effect.gen(function* () {
108-
const settings = yield* settingsService.getSettings.pipe(Effect.option);
109-
return yield* resolveRole(
110-
settings._tag === "Some" ? settings.value.machinePlacementRole : "auto",
111-
);
112-
});
113-
11493
return MachinePresence.of({
11594
role,
11695
read: Effect.gen(function* () {
11796
const placementRole = yield* role;
118-
return placementRole === "headless"
119-
? { placementRole }
120-
: { placementRole, humanActive: yield* humanActive };
97+
if (placementRole === "headless") return { placementRole };
98+
// Only Linux can tell, and only Linux caps agents there; elsewhere assume someone is.
99+
if (platform !== "linux") return { placementRole, humanActive: true };
100+
const login = yield* graphicalLogin;
101+
return {
102+
placementRole,
103+
humanActive:
104+
login.kind === "unknown" || (login.kind === "session" && linuxSessionInUse(login.shown)),
105+
};
121106
}),
122107
});
123108
});

‎docs/user/remote-access.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -401,16 +401,18 @@ fails with that reason.
401401

402402
Agents can let T3 Code pick the machine for independent work: a task with
403403
`placement: "auto"`, or a new thread in a worktree started from origin. In
404-
Closura builds the second needs no request. Turn **Place new agent threads
404+
Closura builds the second needs no request when the agent passes a
405+
`clientRequestId`. Turn **Place new agent threads
405406
automatically** off in **Settings → Labs** to keep those threads on this machine.
406407

407408
T3 Code picks the machine with the most room, judged by CPU use, load per core,
408409
free memory and how many agents already run there. Headless machines are used
409-
first. A machine marked as someone's computer gets work only when every
410+
first. A Linux machine marked as someone's computer gets work only when every
410411
headless machine is full and nobody is using it. Agents there are capped at half
411412
its cores and get low CPU and disk priority, and more of its memory is kept free,
412-
so it stays responsive. If no machine has room, work the agent did not
413-
explicitly place starts here.
413+
so it stays responsive. A Mac or Windows machine, or one on an older release,
414+
never takes placed work from another machine. If no machine has room, work that
415+
started here stays here.
414416

415417
Each machine decides its own role in **Settings → Labs → Load balancing**. The
416418
**Detect** setting treats the desktop app, a Mac, Windows, or a Linux graphical

‎packages/shared/src/loadBalancing.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ function headroom(resources: HostResourcesSnapshot, tier: keyof typeof LIMITS):
1515
const limits = LIMITS[tier];
1616
const { cpuUtilization, cpuCount, totalMemoryBytes, availableMemoryBytes } = resources;
1717
if (cpuUtilization === null || totalMemoryBytes <= 0 || cpuCount <= 0) return null;
18-
// An older server sends no load or agent count; only a headless one is trusted without them.
18+
// A headless machine that cannot report load (Windows) or agents (no systemd) is judged
19+
// without them; someone's computer never is.
1920
const loadPerCpu = resources.loadPerCpu ?? (tier === "headless" ? 0 : null);
2021
const agents = resources.runningAgents ?? (tier === "headless" ? 0 : null);
2122
if (loadPerCpu === null || agents === null) return null;
@@ -36,7 +37,12 @@ function headroom(resources: HostResourcesSnapshot, tier: keyof typeof LIMITS):
3637
/**
3738
* Callers supply only connected machines hosting the project and selected provider. Headless
3839
* machines take work first; an interactive machine is chosen only when no headless one has room,
39-
* its person is not using it, and it stays well clear of its limits.
40+
* its person is not using it, and it stays well clear of its limits. A machine that does not
41+
* report its role, such as one on an older release, counts as someone's computer in use.
42+
*
43+
* `originEnvironmentId` is where the work starts. When nothing has room it keeps the work if it
44+
* has room by headless limits, as before placement could pick: work started on someone's
45+
* computer is theirs to run there.
4046
*/
4147
export function chooseLoadBalancedEnvironment(
4248
candidates: ReadonlyArray<{
@@ -47,11 +53,13 @@ export function chooseLoadBalancedEnvironment(
4753
weight: number;
4854
}>,
4955
now: number,
56+
originEnvironmentId?: string,
5057
): string | null {
5158
const best = {
5259
headless: { id: null as string | null, score: 0 },
5360
interactive: { id: null as string | null, score: 0 },
5461
};
62+
let origin: string | null = null;
5563
for (const { environmentId, resources, receivedAt, weight } of candidates) {
5664
const sampledAt = receivedAt ?? resources?.sampledAt ?? 0;
5765
if (
@@ -63,6 +71,8 @@ export function chooseLoadBalancedEnvironment(
6371
) {
6472
continue;
6573
}
74+
if (environmentId === originEnvironmentId && headroom(resources, "headless") !== null)
75+
origin = environmentId;
6676
// A machine that does not say is someone's until it says otherwise, and in use if unsure.
6777
const tier = resources.placementRole === "headless" ? "headless" : "interactive";
6878
if (tier === "interactive" && resources.humanActive !== false) continue;
@@ -71,5 +81,5 @@ export function chooseLoadBalancedEnvironment(
7181
const score = weight * room;
7282
if (score > best[tier].score) best[tier] = { id: environmentId, score };
7383
}
74-
return best.headless.id ?? best.interactive.id;
84+
return best.headless.id ?? best.interactive.id ?? origin;
7585
}

‎packages/shared/src/threadPlacement.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,29 @@ describe("chooseThreadPlacement", () => {
151151
}
152152
});
153153

154+
it("keeps work on the person's own machine when nothing else has room", () => {
155+
const desk = host("here", 0.3, {
156+
resources: {
157+
...host("here", 0.3).resources!,
158+
placementRole: "interactive",
159+
humanActive: true,
160+
},
161+
});
162+
expect(chooseThreadPlacement(origin, [desk, host("r720", 0.97)], now)).toEqual({
163+
accepted: true,
164+
environmentId: "here",
165+
reason: "capacity",
166+
});
167+
// A headless machine with room still wins, and a full origin is not kept.
168+
expect(chooseThreadPlacement(origin, [desk, host("r720", 0.5)], now)).toMatchObject({
169+
environmentId: "r720",
170+
});
171+
expect(chooseThreadPlacement(origin, [host("here", 0.97), host("r720", 0.97)], now)).toEqual({
172+
accepted: false,
173+
reason: "no-eligible-environment",
174+
});
175+
});
176+
154177
it("refuses evidence that names one environment twice", () => {
155178
expect(chooseThreadPlacement(origin, [host("a", 0.1), host("a", 0.2)], now)).toEqual({
156179
accepted: false,

‎packages/shared/src/threadPlacement.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export function chooseThreadPlacement(
6262
.sort((a, b) =>
6363
a.environmentId < b.environmentId ? -1 : a.environmentId > b.environmentId ? 1 : 0,
6464
);
65-
const environmentId = chooseLoadBalancedEnvironment(eligible, now);
65+
const environmentId = chooseLoadBalancedEnvironment(eligible, now, request.originEnvironmentId);
6666
return environmentId === null
6767
? { accepted: false, reason: "no-eligible-environment" }
6868
: { accepted: true, environmentId, reason: "capacity" };

0 commit comments

Comments
 (0)