Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettin
"enableAgentBrowserAccess",
"sidebarAutoSettleOnMerge",
"sidebarAutoSettleAfterDays",
"autoResumeLimitedThreads",
],
"source-control": ["defaultAutoPull", "removeAgentCreditsOnMerge"],
worktrees: [
Expand Down
50 changes: 26 additions & 24 deletions apps/mobile/src/features/settings/ThreadSettingsSections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,30 +135,32 @@ export function AutoSettleSettingsRows(props: {

return (
<View className="gap-6">
{!projectSelected ? (
<SettingsSection title={gt("Usage limits")}>
<SettingsSwitchRow
icon="clock"
label={gt("Resume after usage limits")}
subtitle={gt(
"Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.",
)}
value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")}
disabled={disabledFor("autoResumeLimitedThreads")}
onValueChange={(value) => writeToAll({ autoResumeLimitedThreads: value })}
/>
<SettingsSwitchRow
icon="clock"
label={gt("Snooze until limits reset")}
subtitle={gt(
"Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.",
)}
value={uniformMobileSetting(displayTargets, "snoozeLimitedThreads")}
disabled={disabledFor("snoozeLimitedThreads")}
onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })}
/>
</SettingsSection>
) : null}
<SettingsSection title={gt("Usage limits")}>
<SettingsSwitchRow
icon="clock"
label={gt("Resume after usage limits")}
subtitle={gt(
"Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.",
)}
value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")}
disabled={disabledFor("autoResumeLimitedThreads")}
onValueChange={(value) => writeToAll({ autoResumeLimitedThreads: value })}
/>
<SettingsSwitchRow
icon="clock"
label={gt("Snooze until limits reset")}
subtitle={
projectSelected
? gt("Environment-wide setting. Select All projects to change it.")
: gt(
"Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.",
)
}
value={uniformMobileSetting(displayTargets, "snoozeLimitedThreads")}
disabled={disabledFor("snoozeLimitedThreads") || projectSelected}
onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })}
/>
</SettingsSection>
<SettingsSection title={gt("Auto-settle")}>
<SettingsSwitchRow
icon="arrow.triangle.branch"
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8955,6 +8955,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
if (lastErrorClass === "usage_limit") {
assert.deepEqual(candidate, {
id: sqlShell.id,
projectId: sqlShell.projectId,
status: sqlShell.status,
lastErrorClass: sqlShell.lastErrorClass,
usageLimitResetAt: sqlShell.usageLimitResetAt,
Expand Down
11 changes: 10 additions & 1 deletion apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export type ProjectionRecoveryKind =
export type ProjectionLimitRecoveryCandidate = Pick<
OrchestrationV2ThreadShell,
| "id"
| "projectId"
| "status"
| "lastErrorClass"
| "latestRunId"
Expand Down Expand Up @@ -673,7 +674,10 @@ export interface ProjectionStoreV2Shape {
) => Effect.Effect<OrchestrationV2AppThread | null, ProjectionStoreV2Error>;
readonly getLimitRecoveryCandidates: (options: {
readonly now: DateTime.Utc;
/** Arms unarmed candidates by default; the project lists flip it, and the worker still decides per candidate. */
readonly autoResume: boolean;
readonly autoResumeEnabledProjectIds?: ReadonlyArray<ProjectId>;
readonly autoResumeDisabledProjectIds?: ReadonlyArray<ProjectId>;
readonly snooze: boolean;
}) => Effect.Effect<ReadonlyArray<ProjectionLimitRecoveryCandidate>, ProjectionStoreV2Error>;
/** Epoch ms of the next armed reset or snooze end after `now`, when a waiting thread becomes a candidate. */
Expand Down Expand Up @@ -5052,7 +5056,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
OR json_extract(t.payload_json, '$.limitRecovery.resetAt') IS NOT json_extract(item.payload_json, '$.failure.resetAt')
)
AND (
${booleanInt(options.autoResume)}
CASE
WHEN t.project_id IN (SELECT value FROM json_each(${encodeIdList(options.autoResumeDisabledProjectIds ?? [])})) THEN 0
WHEN t.project_id IN (SELECT value FROM json_each(${encodeIdList(options.autoResumeEnabledProjectIds ?? [])})) THEN 1
ELSE ${booleanInt(options.autoResume)}
END
OR (${booleanInt(options.snooze)} AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(${DateTime.formatIso(options.now)}))
)
-- A subagent of a settled, archived or deleted parent is abandoned work.
Expand Down Expand Up @@ -5085,6 +5093,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
if (summary.lastErrorClass !== "usage_limit") continue;
candidates.push({
id: thread.id,
projectId: thread.projectId,
status: "failed",
lastErrorClass: summary.lastErrorClass,
usageLimitResetAt: summary.usageLimitResetAt,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { RunId, ThreadId, type OrchestrationV2DomainEvent } from "@t3tools/contracts";
import { ProjectId, RunId, ThreadId, type OrchestrationV2DomainEvent } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
Expand Down Expand Up @@ -46,6 +46,7 @@ it.effect("idle sweeps skip SQL until the next wake time or a relevant event", (
getSettings: Effect.succeed({
autoResumeLimitedThreads: true,
snoozeLimitedThreads: false,
projectSettingsOverrides: {},
} as never),
streamChanges: Stream.never,
}),
Expand Down Expand Up @@ -77,6 +78,7 @@ const failedThread = (failedAgoMs: number, resetAgoMs: number) => {
const failedAt = DateTime.makeUnsafe(nowMs - failedAgoMs);
const candidate: ProjectionStore.ProjectionLimitRecoveryCandidate = {
id: ThreadId.make("thread:limited"),
projectId: ProjectId.make("project:limited"),
status: "failed",
lastErrorClass: "usage_limit",
usageLimitResetAt: DateTime.formatIso(DateTime.makeUnsafe(nowMs - resetAgoMs)),
Expand Down
49 changes: 39 additions & 10 deletions apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { CommandId, MessageId, type OrchestrationV2Command } from "@t3tools/contracts";
import {
CommandId,
MessageId,
type OrchestrationV2Command,
type OrchestrationV2DomainEvent,
ProjectId,
type ServerSettings as ServerSettingsValue,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { OrchestrationV2DomainEvent } from "@t3tools/contracts";
import * as DueHint from "../scheduling/DueHint.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import { forkParked } from "../serverActivation.ts";
Expand All @@ -14,6 +21,32 @@ import * as ThreadManagement from "./ThreadManagementService.ts";

export const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000;

function resolveLimitRecoveryPolicy(
settings: ServerSettingsValue,
thread: Pick<ProjectionStore.ProjectionLimitRecoveryCandidate, "projectId">,
): { readonly autoResume: boolean; readonly snooze: boolean } {
return {
autoResume: resolveProjectSettings(settings, thread.projectId).settings
.autoResumeLimitedThreads,
snooze: settings.snoozeLimitedThreads,
};
}

/** Narrows the sweep's query to candidates whose project could auto-arm. */
function limitAutoResumeScope(settings: ServerSettingsValue) {
const enabled: Array<ProjectId> = [];
const disabled: Array<ProjectId> = [];
for (const [projectId, overrides] of Object.entries(settings.projectSettingsOverrides)) {
if (overrides.autoResumeLimitedThreads === true) enabled.push(ProjectId.make(projectId));
if (overrides.autoResumeLimitedThreads === false) disabled.push(ProjectId.make(projectId));
}
return {
autoResume: settings.autoResumeLimitedThreads,
autoResumeEnabledProjectIds: enabled,
autoResumeDisabledProjectIds: disabled,
};
}

export function limitRecoveryCommand(
thread: ProjectionStore.ProjectionLimitRecoveryCandidate,
autoResume: boolean,
Expand Down Expand Up @@ -87,7 +120,7 @@ const affectsLimitRecovery = (event: OrchestrationV2DomainEvent) =>
event.type.startsWith("provider-session.") ||
(event.type === "turn-item.updated" && event.payload.type === "error");

const makeSweep = Effect.gen(function* () {
export const makeSweep = Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threads = yield* ThreadManagement.ThreadManagementService;
const orchestrator = yield* Orchestrator.OrchestratorV2;
Expand All @@ -107,17 +140,13 @@ const makeSweep = Effect.gen(function* () {
const preferences = yield* settings.getSettings;
const candidates = yield* projections.getLimitRecoveryCandidates({
now,
autoResume: preferences.autoResumeLimitedThreads,
...limitAutoResumeScope(preferences),
snooze: preferences.snoozeLimitedThreads,
});
let acted = false;
for (const thread of candidates) {
const command = limitRecoveryCommand(
thread,
preferences.autoResumeLimitedThreads,
nowMs,
preferences.snoozeLimitedThreads,
);
const policy = resolveLimitRecoveryPolicy(preferences, thread);
const command = limitRecoveryCommand(thread, policy.autoResume, nowMs, policy.snooze);
if (command === null) continue;
acted = true;
yield* Effect.gen(function* () {
Expand Down
Loading
Loading