Skip to content

Commit e48ab96

Browse files
MikaMcFlurryclaude
andcommitted
fix(server): pick an account with usage for scheduled task runs
Scheduled runs launched threads and queued bound sends without the account choice a user's send gets, so with fallbackToAvailableAccounts on they started on an exhausted account, failed with usage_limit and were only moved by the recovery worker later. New-thread runs now go through the same selection as launchThread, and bound runs through the one dispatchCommand applies (including the return after a limit switch). Agent-created tasks keep their model; nothing changes with the setting off. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0a25b23 commit e48ab96

3 files changed

Lines changed: 267 additions & 63 deletions

File tree

‎apps/server/src/orchestration-v2/ThreadMessageIntake.ts‎

Lines changed: 64 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,39 @@ const readAccountChoice = Effect.fn("ThreadMessageIntake.readAccountChoice")(fun
125125
return Object.assign(choose, { providers, now, settings });
126126
});
127127

128+
type MessageDispatchCommand = Extract<
129+
OrchestrationV2Command,
130+
{ readonly type: "message.dispatch" }
131+
>;
132+
133+
/**
134+
* The account a new turn on an existing thread starts on, or undefined to keep the one it
135+
* names (or the thread's). Null-safe when the setting is off or the thread cannot be read.
136+
*/
137+
const availableThreadAccount = Effect.fn("ThreadMessageIntake.availableThreadAccount")(function* (
138+
input: Pick<MessageDispatchCommand, "threadId" | "modelSelection" | "deliveryIntent">,
139+
sameModelOnly = false,
140+
) {
141+
const choose = yield* readAccountChoice();
142+
if (choose === null) return undefined;
143+
const threads = yield* ThreadManagement.ThreadManagementService;
144+
const window = yield* threads
145+
.getThreadSnapshotWindow(input.threadId, { rowLimit: 1 })
146+
.pipe(Effect.orElseSucceed(() => null));
147+
if (window === null) return undefined;
148+
const { thread } = window.projection;
149+
const selection = input.modelSelection ?? thread.modelSelection;
150+
const returned = yield* returnAfterLimitSwitch(input, selection, thread.projectId, choose);
151+
const next = choose(
152+
returned ?? selection,
153+
thread.projectId,
154+
sameModelOnly || thread.createdBy === "agent",
155+
);
156+
return next === selection ? undefined : next;
157+
});
158+
128159
const withAvailableAccount = Effect.fn("ThreadMessageIntake.withAvailableAccount")(function* (
129-
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
160+
command: MessageDispatchCommand,
130161
) {
131162
// Steering stays on the active run's account; server continuations validate their own.
132163
if (
@@ -137,26 +168,45 @@ const withAvailableAccount = Effect.fn("ThreadMessageIntake.withAvailableAccount
137168
) {
138169
return command;
139170
}
171+
const next = yield* availableThreadAccount(command);
172+
return next === undefined ? command : { ...command, modelSelection: next };
173+
});
174+
175+
/**
176+
* A queued send that bypasses dispatchCommand, such as a scheduled run on its bound thread,
177+
* starts on the account dispatchCommand would pick. An agent's send keeps its model.
178+
*/
179+
export const withAvailableSendAccount = Effect.fn("ThreadMessageIntake.withAvailableSendAccount")(
180+
function* (input: ThreadManagement.ThreadManagementSendInput) {
181+
// Other modes may steer the active run, which stays on its account.
182+
if (input.mode !== "queue") return input;
183+
const next = yield* availableThreadAccount(
184+
{
185+
threadId: input.threadId,
186+
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
187+
},
188+
input.createdBy === "agent",
189+
);
190+
return next === undefined ? input : { ...input, modelSelection: next };
191+
},
192+
);
193+
194+
/** A new thread starts on an account with usage left; a model an agent picked stays. */
195+
export const withAvailableLaunchAccount = Effect.fn(
196+
"ThreadMessageIntake.withAvailableLaunchAccount",
197+
)(function* (input: ThreadLaunch.ThreadLaunchInput) {
140198
const choose = yield* readAccountChoice();
141-
if (choose === null) return command;
142-
const threads = yield* ThreadManagement.ThreadManagementService;
143-
const window = yield* threads
144-
.getThreadSnapshotWindow(command.threadId, { rowLimit: 1 })
145-
.pipe(Effect.orElseSucceed(() => null));
146-
if (window === null) return command;
147-
const { thread } = window.projection;
148-
const selection = command.modelSelection ?? thread.modelSelection;
149-
const returned = yield* returnAfterLimitSwitch(command, selection, thread.projectId, choose);
150-
const next = choose(returned ?? selection, thread.projectId, thread.createdBy === "agent");
151-
return next === selection ? command : { ...command, modelSelection: next };
199+
if (choose === null) return input;
200+
const modelSelection = choose(input.modelSelection, input.projectId, input.createdBy === "agent");
201+
return modelSelection === input.modelSelection ? input : { ...input, modelSelection };
152202
});
153203

154204
/**
155205
* The account a usage-limit switch moved this thread away from, once it has usage again. Only
156206
* for a turn that starts now: never while a run is active or queued, so no turn is cut off.
157207
*/
158208
const returnAfterLimitSwitch = Effect.fn("ThreadMessageIntake.returnAfterLimitSwitch")(function* (
159-
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
209+
command: Pick<MessageDispatchCommand, "threadId" | "deliveryIntent">,
160210
current: ModelSelection,
161211
projectId: ProjectId,
162212
choice: {
@@ -370,18 +420,7 @@ export const launchThread = Effect.fn("ThreadMessageIntake.launchThread")(functi
370420
requested: ThreadLaunch.ThreadLaunchInput,
371421
) {
372422
const launches = yield* ThreadLaunch.ThreadLaunchService;
373-
const choose = yield* readAccountChoice();
374-
const input =
375-
choose === null
376-
? requested
377-
: {
378-
...requested,
379-
modelSelection: choose(
380-
requested.modelSelection,
381-
requested.projectId,
382-
requested.createdBy === "agent",
383-
),
384-
};
423+
const input = yield* withAvailableLaunchAccount(requested);
385424
yield* AttachmentClaims.validateAttachmentLimits(input.initialMessage?.attachments ?? []);
386425
if (!input.initialMessage?.attachments.some(AttachmentClaims.attachmentIsPendingUpload)) {
387426
return yield* launches.launch(input);

‎apps/server/src/scheduledTasks/ScheduledTaskService.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ import { assert, it, vi } from "@effect/vitest";
66
import {
77
CommandId,
88
ProjectId,
9+
ProviderDriverKind,
910
ProviderInstanceId,
1011
ScheduledTaskError,
1112
ScheduledTaskId,
1213
type ScheduledTaskUpsertInput,
1314
SecretRef,
1415
ThreadId,
16+
type ModelSelection,
17+
type ServerProvider,
1518
} from "@t3tools/contracts";
1619
import * as DateTime from "effect/DateTime";
1720
import * as Effect from "effect/Effect";
@@ -36,6 +39,8 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
3639
import * as SqlitePersistence from "../persistence/Sqlite.ts";
3740
import * as ScheduledTaskService from "./ScheduledTaskService.ts";
3841
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
42+
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
43+
import * as ServerSettings from "../serverSettings.ts";
3944

4045
const isScheduledTaskError = Schema.is(ScheduledTaskError);
4146

@@ -1226,3 +1231,129 @@ it.effect("a run interrupted right after it reserves the task does not block the
12261231
}).pipe(Effect.provide(layer));
12271232
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
12281233
);
1234+
1235+
it.effect.each([true, false] as const)(
1236+
"a run starts on an account with usage left only when the setting allows it (%s)",
1237+
(fallbackToAvailableAccounts) =>
1238+
Effect.gen(function* () {
1239+
const claude = (id: string, usedPercent: number): ServerProvider => ({
1240+
instanceId: ProviderInstanceId.make(id),
1241+
driver: ProviderDriverKind.make("claudeAgent"),
1242+
enabled: true,
1243+
installed: true,
1244+
version: null,
1245+
status: "ready",
1246+
auth: { status: "authenticated" },
1247+
checkedAt: "2026-09-13T00:00:00.000Z",
1248+
models: [
1249+
{ slug: "claude-opus-5-5", name: "Opus 5.5", isCustom: false, capabilities: null },
1250+
],
1251+
slashCommands: [],
1252+
skills: [],
1253+
usageLimits: {
1254+
checkedAt: "2026-09-13T00:00:00.000Z",
1255+
windows: [
1256+
{
1257+
id: "five_hour",
1258+
kind: "session",
1259+
label: "Session",
1260+
usedPercent,
1261+
resetsAt: "2099-01-01T00:00:00.000Z",
1262+
},
1263+
],
1264+
},
1265+
});
1266+
const exhausted: ModelSelection = {
1267+
instanceId: ProviderInstanceId.make("claude_work"),
1268+
model: "claude-opus-5-5",
1269+
};
1270+
const projectId = ProjectId.make("project:test");
1271+
const boundThread = ThreadId.make("thread:bound-limited");
1272+
const launched = yield* Ref.make<Array<ModelSelection>>([]);
1273+
const sent = yield* Ref.make<Array<ModelSelection | undefined>>([]);
1274+
const layer = ScheduledTaskService.layer.pipe(
1275+
Layer.provide(
1276+
Layer.mergeAll(
1277+
ManagedPolicy.layerTest(),
1278+
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
1279+
launch: (input) =>
1280+
Ref.update(launched, (all) => [...all, input.modelSelection]).pipe(
1281+
Effect.as({ threadId: ThreadId.make("thread:new"), resumed: false } as never),
1282+
),
1283+
}),
1284+
Layer.mock(ThreadManagementService.ThreadManagementService)({
1285+
getThreadShell: () => Effect.succeed({ projectId, deletedAt: null } as never),
1286+
getThreadSnapshotWindow: () =>
1287+
Effect.succeed({
1288+
projection: {
1289+
thread: { projectId, modelSelection: exhausted, createdBy: "user" },
1290+
},
1291+
} as never),
1292+
getLatestLimitSwitch: () => Effect.succeed(null),
1293+
sendToThread: (input) =>
1294+
Ref.update(sent, (all) => [...all, input.modelSelection]).pipe(
1295+
Effect.as({} as never),
1296+
),
1297+
}),
1298+
Layer.mock(ProviderRegistry.ProviderRegistry)({
1299+
getProviders: Effect.succeed([
1300+
claude("claude_work", 100),
1301+
claude("claude_personal", 30),
1302+
]),
1303+
}),
1304+
ServerSettings.layerTest({
1305+
fallbackToAvailableAccounts,
1306+
providerInstances: Object.fromEntries(
1307+
["claude_work", "claude_personal"].map((id) => [
1308+
ProviderInstanceId.make(id),
1309+
{ driver: ProviderDriverKind.make("claudeAgent"), enabled: true },
1310+
]),
1311+
),
1312+
}),
1313+
Layer.mock(SecretRequests.SecretRequests)({}),
1314+
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1315+
namedProjectsRoot: "/projects",
1316+
isScratchProject: () => Effect.succeed(false),
1317+
}),
1318+
NodeCrypto.layer,
1319+
Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
1320+
),
1321+
),
1322+
);
1323+
yield* Effect.gen(function* () {
1324+
const service = yield* ScheduledTaskService.ScheduledTaskService;
1325+
const task = {
1326+
title: "Check in",
1327+
prompt: "Check progress",
1328+
enabled: true,
1329+
schedule: { type: "interval", everyMs: 60_000 },
1330+
projectId,
1331+
workspaceStrategy: { type: "root" },
1332+
modelSelection: exhausted,
1333+
runtimeMode: "full-access",
1334+
interactionMode: "default",
1335+
} as const;
1336+
yield* service.upsert({ ...task, id: ScheduledTaskId.make("task:new-thread") });
1337+
yield* service.upsert({
1338+
...task,
1339+
id: ScheduledTaskId.make("task:bound"),
1340+
threadId: boundThread,
1341+
});
1342+
1343+
yield* service.runNow({ id: ScheduledTaskId.make("task:new-thread") });
1344+
yield* service.runNow({ id: ScheduledTaskId.make("task:bound") });
1345+
1346+
const available = {
1347+
instanceId: ProviderInstanceId.make("claude_personal"),
1348+
model: "claude-opus-5-5",
1349+
};
1350+
assert.deepEqual(yield* Ref.get(launched), [
1351+
fallbackToAvailableAccounts ? available : exhausted,
1352+
]);
1353+
// A bound run names no account unless it moves off the exhausted one.
1354+
assert.deepEqual(yield* Ref.get(sent), [
1355+
fallbackToAvailableAccounts ? available : undefined,
1356+
]);
1357+
}).pipe(Effect.provide(layer));
1358+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
1359+
);

0 commit comments

Comments
 (0)