+
+
+ }
+ >
+
+
+ updateSettings({ automaticPlacementByDefault: Boolean(checked) })
+ }
+ aria-label="Place new agent threads automatically"
+ />
+ }
+ />
+
+
+ );
+}
+
function PromptSuggestionsRow() {
const settings = useScopedSettings();
const updateSettings = useUpdateScopedSettings();
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 01c86ed15480..d7e327f080b6 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -517,6 +517,20 @@ export const SETTINGS_SEARCH_ITEMS = [
scope: "environment",
searchTerms: ["beta link another machine vps peer agents work there delegate"],
},
+ {
+ id: "machine-placement-role",
+ title: "Load balancing",
+ to: "/settings/labs",
+ scope: "environment",
+ searchTerms: ["placement load balance headless gui laptop desktop busy machine spread agents"],
+ },
+ {
+ id: "automatic-placement-default",
+ title: "Place new agent threads automatically",
+ to: "/settings/labs",
+ scope: "environment",
+ searchTerms: ["placement auto default load balance worktree origin other machine"],
+ },
{
id: "prompt-suggestions-beta",
title: "Suggest next prompt",
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index c963e22b8d6a..e13ea4351abb 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -397,6 +397,29 @@ ends, as for any delegated task. It keeps following the task across restarts.
If the other machine revokes the link, or the link is removed here, the task
fails with that reason.
+### Spread agent work across linked machines
+
+Agents can let T3 Code pick the machine for independent work: a task with
+`placement: "auto"`, or a new thread in a worktree started from origin. In
+Closura builds the second needs no request when the agent passes a
+`clientRequestId`. Turn **Place new agent threads
+automatically** off in **Settings → Labs** to keep those threads on this machine.
+
+T3 Code picks the machine with the most room, judged by CPU use, load per core,
+free memory and how many agents already run there. Headless machines are used
+first. A Linux machine marked as someone's computer gets work only when every
+headless machine is full and nobody is using it. Agents there are capped at half
+its cores and get low CPU and disk priority, and more of its memory is kept free,
+so it stays responsive. A Mac or Windows machine, or one on an older release,
+never takes placed work from another machine. If no machine has room, work that
+started here stays here.
+
+Each machine decides its own role in **Settings → Labs → Load balancing**. The
+**Detect** setting treats the desktop app, a Mac, Windows, or a Linux graphical
+login as someone's computer. Set a headless machine that also runs a desktop,
+such as a computer-use host, to **Headless** by hand. A linked machine is used
+only if its link allows launching threads, not with read-only access.
+
## Manage or revoke access
On the host, **Settings → Sharing & access** lets authorized administrators create
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 4f454f9ad758..47de5847567f 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -184,7 +184,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
placement: Schema.optional(
Schema.Literals(["auto"]).annotate({
description:
- "'auto': for work that needs none of your checkout's changes. Runs here or on a linked environment with spare capacity, this repository's project and your exact provider and model; there, in that project's checkout. Ignored with target.environmentId or isolation. Reuse clientRequestId on retry to keep the environment chosen.",
+ "'auto': use for any work that needs none of your checkout's changes. Runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; there, in that project's checkout. Ignored with target.environmentId or isolation. Reuse clientRequestId on retry to keep the environment chosen.",
}),
),
mode: Schema.optional(
diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts
index e827ee1a1235..493dac10ce02 100644
--- a/packages/contracts/src/resourceTelemetry.ts
+++ b/packages/contracts/src/resourceTelemetry.ts
@@ -12,6 +12,15 @@ export const HostResourcesSnapshot = Schema.Struct({
cpuCount: NonNegativeInt,
availableMemoryBytes: NonNegativeInt,
totalMemoryBytes: NonNegativeInt,
+ // Optional so older servers still decode; placement treats a missing value conservatively.
+ /** One-minute load average per host CPU; work queued past 1 means the machine is saturated. */
+ loadPerCpu: Schema.optional(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0))),
+ /** Agent processes running on this host, across every T3 server there. */
+ runningAgents: Schema.optional(NonNegativeInt),
+ /** Interactive machines belong to a person; placement uses them last and only while idle. */
+ placementRole: Schema.optional(Schema.Literals(["headless", "interactive"])),
+ /** Someone is using this interactive machine now, or it cannot tell. */
+ humanActive: Schema.optional(Schema.Boolean),
});
export type HostResourcesSnapshot = typeof HostResourcesSnapshot.Type;
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 5e6917eb2819..77e69196e90e 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1375,6 +1375,9 @@ export const CloudSpeechCredentials = Schema.Struct({
assemblyai: CloudSpeechCredential,
});
+export const MachinePlacementRole = Schema.Literals(["auto", "headless", "interactive"]);
+export type MachinePlacementRole = typeof MachinePlacementRole.Type;
+
export const ServerSettings = Schema.Struct({
// Null means unmigrated; empty is authoritative and must not resurrect cleared preferences.
favorites: Schema.NullOr(ModelFavorites).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
@@ -1507,6 +1510,22 @@ export const ServerSettings = Schema.Struct({
automaticPlacementExcludedEnvironmentIds: Schema.Array(EnvironmentId).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
+ /**
+ * Whether this machine belongs to a person at its keyboard. Automatic placement fills headless
+ * machines first, uses an interactive one only while its person is idle and every headless one
+ * is full, and runs agents there under tighter limits. Auto: a desktop app, macOS, Windows or a
+ * Linux graphical login is interactive; anything else is headless.
+ */
+ machinePlacementRole: MachinePlacementRole.pipe(
+ Schema.withDecodingDefault(Effect.succeed("auto" as const)),
+ ),
+ /**
+ * Closura: agent-launched threads that need nothing of the caller's checkout are placed
+ * automatically unless they name an environment. Off launches them here unless they ask.
+ */
+ automaticPlacementByDefault: Schema.Boolean.pipe(
+ Schema.withDecodingDefault(Effect.succeed(true)),
+ ),
/** Beta: Claude and Codex predict the next prompt after completed turns. Codex follows a change at once; open Claude threads after they restart. */
promptSuggestionsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
@@ -1940,6 +1959,8 @@ export const ServerSettingsPatch = Schema.Struct({
guestSharingEnabled: Schema.optionalKey(Schema.Boolean),
linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean),
automaticPlacementExcludedEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)),
+ machinePlacementRole: Schema.optionalKey(MachinePlacementRole),
+ automaticPlacementByDefault: Schema.optionalKey(Schema.Boolean),
promptSuggestionsEnabled: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey(
Schema.Struct({
diff --git a/packages/shared/src/loadBalancing.ts b/packages/shared/src/loadBalancing.ts
index 0b938c6c090e..1969020c9cb3 100644
--- a/packages/shared/src/loadBalancing.ts
+++ b/packages/shared/src/loadBalancing.ts
@@ -1,6 +1,49 @@
import type { HostResourcesSnapshot } from "@t3tools/contracts";
-/** Callers supply only connected machines hosting the project and selected provider. */
+const GiB = 1024 ** 3;
+
+/**
+ * Headroom a machine must keep after placement. A headless machine is full near its limits;
+ * an interactive one, a person's computer, is full long before it would feel slow to them.
+ */
+const LIMITS = {
+ headless: { cpu: 0.95, loadPerCpu: 1, memoryShare: 0.05, memoryBytes: 1.5 * GiB, agents: null },
+ interactive: { cpu: 0.5, loadPerCpu: 0.5, memoryShare: 0.4, memoryBytes: 3 * GiB, agents: 2 },
+} as const;
+
+function headroom(resources: HostResourcesSnapshot, tier: keyof typeof LIMITS): number | null {
+ const limits = LIMITS[tier];
+ const { cpuUtilization, cpuCount, totalMemoryBytes, availableMemoryBytes } = resources;
+ if (cpuUtilization === null || totalMemoryBytes <= 0 || cpuCount <= 0) return null;
+ // A headless machine that cannot report load (Windows) or agents (no systemd) is judged
+ // without them; someone's computer never is.
+ const loadPerCpu = resources.loadPerCpu ?? (tier === "headless" ? 0 : null);
+ const agents = resources.runningAgents ?? (tier === "headless" ? 0 : null);
+ if (loadPerCpu === null || agents === null) return null;
+ const memoryAvailable = availableMemoryBytes / totalMemoryBytes;
+ if (
+ cpuUtilization >= limits.cpu ||
+ loadPerCpu >= limits.loadPerCpu ||
+ memoryAvailable <= limits.memoryShare ||
+ availableMemoryBytes < limits.memoryBytes ||
+ (limits.agents !== null && agents >= limits.agents)
+ )
+ return null;
+ // Run queues past the core count show saturation that a short CPU sample can miss.
+ const busy = Math.max(cpuUtilization, Math.min(1, loadPerCpu));
+ return (cpuCount * (1 - busy) * memoryAvailable) / (1 + agents);
+}
+
+/**
+ * Callers supply only connected machines hosting the project and selected provider. Headless
+ * machines take work first; an interactive machine is chosen only when no headless one has room,
+ * its person is not using it, and it stays well clear of its limits. A machine that does not
+ * report its role, such as one on an older release, counts as someone's computer in use.
+ *
+ * `originEnvironmentId` is where the work starts. When nothing has room it keeps the work if it
+ * has room by headless limits, as before placement could pick: work started on someone's
+ * computer is theirs to run there.
+ */
export function chooseLoadBalancedEnvironment(
candidates: ReadonlyArray<{
environmentId: string;
@@ -10,9 +53,13 @@ export function chooseLoadBalancedEnvironment(
weight: number;
}>,
now: number,
+ originEnvironmentId?: string,
): string | null {
- let selected: string | null = null;
- let bestScore = 0;
+ const best = {
+ headless: { id: null as string | null, score: 0 },
+ interactive: { id: null as string | null, score: 0 },
+ };
+ let origin: string | null = null;
for (const { environmentId, resources, receivedAt, weight } of candidates) {
const sampledAt = receivedAt ?? resources?.sampledAt ?? 0;
if (
@@ -20,21 +67,19 @@ export function chooseLoadBalancedEnvironment(
!Number.isFinite(weight) ||
weight <= 0 ||
now - sampledAt > 15_000 ||
- sampledAt > now + 5_000 ||
- resources.cpuUtilization === null ||
- resources.cpuUtilization >= 0.95 ||
- resources.totalMemoryBytes <= 0 ||
- resources.cpuCount <= 0
+ sampledAt > now + 5_000
) {
continue;
}
- const memoryAvailable = resources.availableMemoryBytes / resources.totalMemoryBytes;
- if (memoryAvailable <= 0.05) continue;
- const score = weight * resources.cpuCount * (1 - resources.cpuUtilization) * memoryAvailable;
- if (score > bestScore) {
- selected = environmentId;
- bestScore = score;
- }
+ if (environmentId === originEnvironmentId && headroom(resources, "headless") !== null)
+ origin = environmentId;
+ // A machine that does not say is someone's until it says otherwise, and in use if unsure.
+ const tier = resources.placementRole === "headless" ? "headless" : "interactive";
+ if (tier === "interactive" && resources.humanActive !== false) continue;
+ const room = headroom(resources, tier);
+ if (room === null) continue;
+ const score = weight * room;
+ if (score > best[tier].score) best[tier] = { id: environmentId, score };
}
- return selected;
+ return best.headless.id ?? best.interactive.id ?? origin;
}
diff --git a/packages/shared/src/threadPlacement.test.ts b/packages/shared/src/threadPlacement.test.ts
index b2218c21bae8..e27aa87a3c03 100644
--- a/packages/shared/src/threadPlacement.test.ts
+++ b/packages/shared/src/threadPlacement.test.ts
@@ -15,6 +15,9 @@ const host = (
cpuCount: 8,
availableMemoryBytes: 8 * GiB,
totalMemoryBytes: 16 * GiB,
+ loadPerCpu: 0,
+ runningAgents: 0,
+ placementRole: "headless",
},
receivedAt: now,
weight: 50,
@@ -79,8 +82,10 @@ describe("chooseThreadPlacement", () => {
cpuCount: 8,
availableMemoryBytes: 0.05 * 16 * GiB,
totalMemoryBytes: 16 * GiB,
+ placementRole: "headless",
},
}),
+ host("queued", 0.1, { resources: { ...host("q", 0.1).resources!, loadPerCpu: 1 } }),
host("absent", 0.1, { resources: null }),
];
expect(chooseThreadPlacement(origin, candidates, now)).toEqual({
@@ -93,6 +98,82 @@ describe("chooseThreadPlacement", () => {
});
});
+ it("fills headless machines first, by run queue and running agents as well as CPU", () => {
+ const busy = (id: string, extra: object) =>
+ host(id, 0.2, { resources: { ...host(id, 0.2).resources!, ...extra } });
+ // A short CPU sample can look idle while 8 runnable tasks per core wait (load 64 on 8 cores).
+ expect(
+ chooseThreadPlacement(origin, [busy("asus", { loadPerCpu: 8 }), host("r720", 0.6)], now),
+ ).toMatchObject({ environmentId: "r720" });
+ // Equal machines split by how many agents each already runs.
+ expect(
+ chooseThreadPlacement(
+ origin,
+ [busy("three", { runningAgents: 3 }), busy("one", { runningAgents: 1 })],
+ now,
+ ),
+ ).toMatchObject({ environmentId: "one" });
+ });
+
+ it("uses a person's computer only when every headless machine is full and they are away", () => {
+ const laptop = (extra: object) =>
+ host("laptop", 0.05, {
+ resources: {
+ ...host("laptop", 0.05).resources!,
+ placementRole: "interactive",
+ humanActive: false,
+ ...extra,
+ },
+ });
+ const full = host("r720", 0.96);
+ expect(chooseThreadPlacement(origin, [laptop({}), host("r720", 0.8)], now)).toMatchObject({
+ environmentId: "r720",
+ });
+ expect(chooseThreadPlacement(origin, [laptop({}), full], now)).toMatchObject({
+ environmentId: "laptop",
+ });
+ // Present, unsure, an older server that cannot say, or near the person's own headroom: never.
+ for (const extra of [
+ { humanActive: true },
+ { humanActive: undefined },
+ { placementRole: undefined, humanActive: undefined },
+ { loadPerCpu: undefined },
+ { cpuUtilization: 0.5 },
+ { loadPerCpu: 0.5 },
+ { runningAgents: 2 },
+ { availableMemoryBytes: 6 * GiB },
+ { availableMemoryBytes: 2.9 * GiB, totalMemoryBytes: 4 * GiB },
+ ]) {
+ expect(chooseThreadPlacement(origin, [laptop(extra), full], now)).toEqual({
+ accepted: false,
+ reason: "no-eligible-environment",
+ });
+ }
+ });
+
+ it("keeps work on the person's own machine when nothing else has room", () => {
+ const desk = host("here", 0.3, {
+ resources: {
+ ...host("here", 0.3).resources!,
+ placementRole: "interactive",
+ humanActive: true,
+ },
+ });
+ expect(chooseThreadPlacement(origin, [desk, host("r720", 0.97)], now)).toEqual({
+ accepted: true,
+ environmentId: "here",
+ reason: "capacity",
+ });
+ // A headless machine with room still wins, and a full origin is not kept.
+ expect(chooseThreadPlacement(origin, [desk, host("r720", 0.5)], now)).toMatchObject({
+ environmentId: "r720",
+ });
+ expect(chooseThreadPlacement(origin, [host("here", 0.97), host("r720", 0.97)], now)).toEqual({
+ accepted: false,
+ reason: "no-eligible-environment",
+ });
+ });
+
it("refuses evidence that names one environment twice", () => {
expect(chooseThreadPlacement(origin, [host("a", 0.1), host("a", 0.2)], now)).toEqual({
accepted: false,
diff --git a/packages/shared/src/threadPlacement.ts b/packages/shared/src/threadPlacement.ts
index 6f1c33108ef6..f52a64f7dc43 100644
--- a/packages/shared/src/threadPlacement.ts
+++ b/packages/shared/src/threadPlacement.ts
@@ -62,7 +62,7 @@ export function chooseThreadPlacement(
.sort((a, b) =>
a.environmentId < b.environmentId ? -1 : a.environmentId > b.environmentId ? 1 : 0,
);
- const environmentId = chooseLoadBalancedEnvironment(eligible, now);
+ const environmentId = chooseLoadBalancedEnvironment(eligible, now, request.originEnvironmentId);
return environmentId === null
? { accepted: false, reason: "no-eligible-environment" }
: { accepted: true, environmentId, reason: "capacity" };