Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ describe("SettingsServerControlsRouteScreen", () => {
)!;

act(() => toggle("Agent browser access").click());
act(() => toggle("Auto-settle merged threads").click());
act(() => toggle("Auto-settle when a pull request merges or closes").click());

// Both rewrite the whole project override, so a second write planned now would drop the first.
expect(mocks.updateSettings).toHaveBeenCalledOnce();
Expand All @@ -231,7 +231,7 @@ describe("SettingsServerControlsRouteScreen", () => {
act(() => root.render(<SettingsThreadsRouteScreen />));

const autoSettle = [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find(
(button) => button.textContent === "Auto-settle merged threads",
(button) => button.textContent === "Auto-settle when a pull request merges or closes",
)!;
expect(autoSettle.disabled).toBe(true);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ export function AutoSettleSettingsRows(props: {
<SettingsSection title="Auto-settle">
<SettingsSwitchRow
icon="arrow.triangle.branch"
label="Auto-settle merged threads"
label="Auto-settle when a pull request merges or closes"
value={referenceSettings.sidebarAutoSettleOnMerge}
disabled={disabledFor("sidebarAutoSettleOnMerge")}
onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export function UsageLimitRecoveryCard({
const [error, setError] = useState<string | null>(null);
const resetAt = thread.runtime?.usageLimitResetAt ?? null;
const canSchedule =
thread.settledOverride !== "settled" &&
resetAt !== null &&
Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1887,7 +1887,7 @@ it.layer(layerContinuationWorkerTest)("interrupted completion wakes", (it) => {
}),
);

it.effect("settling with a queued completion wake disposes its running siblings", () =>
it.effect("settling with a queued completion wake keeps it and its running siblings", () =>
Effect.gen(function* () {
const { orchestrator, sink, now, threadId, originRunId, sibling, wake, completeSibling } =
yield* queueCompletionWakeBesideRunningSibling("sibling-settle");
Expand Down Expand Up @@ -1918,16 +1918,19 @@ it.layer(layerContinuationWorkerTest)("interrupted completion wakes", (it) => {
commandId: CommandId.make("sibling-settle-settle"),
threadId,
});
// Settling only parks the thread; the wake and its siblings keep their delivery.
assert.deepEqual(
settled.storedEvents.flatMap(({ event }) =>
event.type === "run.updated" && event.payload.id === wake.id
? [event.payload.status]
: [],
),
["cancelled"],
[],
);
const afterSettle = yield* orchestrator.getThreadProjection(threadId);
assert.equal(
assert.equal(afterSettle.thread.settledOverride, "settled");
assert.equal(afterSettle.runs.find((run) => run.id === wake.id)?.status, "queued");
assert.notEqual(
afterSettle.subagents.find((task) => task.id === sibling.id)?.completionDelivery?.state,
"disposed",
);
Expand All @@ -1944,20 +1947,15 @@ it.layer(layerContinuationWorkerTest)("interrupted completion wakes", (it) => {
Stream.runDrain,
);
const afterLateResult = yield* orchestrator.getThreadProjection(threadId);
assert.equal(
assert.notEqual(
afterLateResult.subagents.find((task) => task.id === sibling.id)?.completionDelivery?.state,
"disposed",
);
assert.deepEqual(
afterLateResult.runs.map((run) => run.id),
afterSettle.runs.map((run) => run.id),
);
assert.equal(
assert.notEqual(
afterLateResult.runs.find((run) => run.id === originRunId)?.delegatedCompletion
?.disposition,
"disposed",
);
assert.equal(afterLateResult.thread.settledOverride, "settled");
}),
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1663,6 +1663,7 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const events = yield* EventSink.EventSinkV2;
const outbox = yield* EffectOutbox.EffectOutboxV2;
const threadId = ThreadId.make("thread:settle-snoozed");
yield* orchestrator.dispatch({
type: "thread.create",
Expand All @@ -1681,6 +1682,25 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
const now = yield* DateTime.now;
const settledAt = DateTime.add(now, { seconds: 1 });
const snoozedUntil = DateTime.add(now, { hours: 1 });
// Settling must leave a live agent alone; it may be about to deliver background results.
yield* projections.apply({
id: EventId.make("attach-settle-snoozed"),
type: "provider-session.attached",
threadId,
occurredAt: now,
payload: {
id: ProviderSessionId.make("session:settle-snoozed"),
driver: adapter.driver,
providerInstanceId: instanceId,
status: "ready",
cwd: "/repo",
model: modelSelection.model,
capabilities: CodexProviderCapabilitiesV2,
createdAt: now,
updatedAt: now,
lastError: null,
},
});
for (const round of [1, 2]) {
yield* orchestrator.dispatch({
type: "thread.snooze",
Expand All @@ -1705,6 +1725,7 @@ it.effect("explicit settle clears snooze atomically and stays idempotent after r
const committed = yield* events.readByCommandId({ commandId }).pipe(Stream.runCollect);
assert.lengthOf(committed, 1);
assert.equal(committed[0]?.event.type, "thread.settled");
assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
assert.deepInclude(committed[0]?.event.payload, expected);
const settled = yield* projections.getThreadShell(threadId);
assert.deepInclude(settled, expected);
Expand Down
101 changes: 40 additions & 61 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2595,6 +2595,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const detachReason = freshContext
? FRESH_CONTEXT_DETACH_REASON
: "Provider or model selection changed.";
const selectedThread: OrchestrationV2AppThread = selectionChanged
? {
...projection.thread,
providerInstanceId: queuedRun.providerInstanceId,
modelSelection: queuedRun.modelSelection,
updatedAt: now,
}
: projection.thread;
yield* writeSystemEvents(
[
...(selectionChanged
Expand All @@ -2607,10 +2615,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
threadId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: selectedThread,
},
]
: []),
// Automatic runs can wait in a settled thread's queue; a running thread is not settled.
...(selectedThread.settledOverride === "settled"
? [
{
type: "thread.unsettled" as const,
threadId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: {
...projection.thread,
providerInstanceId: queuedRun.providerInstanceId,
modelSelection: queuedRun.modelSelection,
...selectedThread,
settledOverride: null,
settledAt: null,
unsettledAt: now,
updatedAt: now,
},
},
Expand Down Expand Up @@ -3403,16 +3424,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(candidate) =>
candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key),
);
const inactive =
thread.archivedAt !== null ||
thread.settledOverride === "settled" ||
thread.settledAt !== null ||
isProviderNativeSubagentThread(thread);
const inactive = thread.archivedAt !== null || isProviderNativeSubagentThread(thread);
if (link?.watch?.startedAt !== command.startedAt || (command.wake && inactive)) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: "The pull request watch ended or its thread settled while it was read.",
cause: "The pull request watch ended or its thread was archived while it was read.",
});
}
yield* dispatchThreadMutation(command, events, effects);
Expand Down Expand Up @@ -3815,40 +3832,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Thread ${command.threadId} ${blocker}`,
});
}

for (const request of pendingRequests) {
yield* dispatchRuntimeRequestRespond(
{
type: "runtime-request.respond",
commandId: command.commandId,
threadId: command.threadId,
requestId: request.id,
decision: "cancel",
},
events,
effects,
);
}
for (const run of automaticQueuedRuns) {
yield* dispatchQueuedRunCancel(
{
type: "queued-run.cancel",
commandId: command.commandId,
threadId: command.threadId,
runId: run.id,
},
events,
"cohort",
);
}
}

const needsProviderState =
command.type === "thread.runtime-mode.set" ||
command.type === "thread.model-selection.set" ||
command.type === "provider.switch" ||
command.type === "thread.archive" ||
command.type === "thread.settle" ||
(command.type === "thread.metadata.update" &&
command.worktreePath !== undefined &&
command.worktreePath !== thread.worktreePath);
Expand Down Expand Up @@ -3916,7 +3906,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (
!Number.isFinite(resetMs) ||
thread.archivedAt !== null ||
thread.settledOverride === "settled" ||
run?.id !== command.limitRecovery.runId ||
failure?.class !== "usage_limit" ||
failure.resetAt !== command.limitRecovery.resetAt ||
Expand Down Expand Up @@ -4021,7 +4010,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...thread,
settledOverride: "settled",
settledAt: alreadySettled ? thread.settledAt : (command.settledAt ?? now),
pullRequests: thread.pullRequests?.map((link) => withPullRequestWatch(link, undefined)),
unsettledAt: null,
pinnedAt: null,
pinOrderKey: null,
Expand Down Expand Up @@ -4647,10 +4635,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* closePendingLinkRequests({ command, events, threadId: command.threadId, now });
}

// Archive and settle stop idle background work; serialized commands prevent starts racing detach.
// Settlement rejects active or blocked runs.
// Archive stops idle background work; serialized commands prevent starts racing detach.
// Settling only parks the thread: its agent may still be delivering background results.
const detachSessionIds = new Set(
command.type === "thread.archive" || command.type === "thread.settle"
command.type === "thread.archive"
? (providerContext?.providerSessions ?? []).map((session) => session.id)
: command.type === "thread.metadata.update" &&
command.worktreePath !== undefined &&
Expand Down Expand Up @@ -4690,13 +4678,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
reason:
command.type === "thread.archive"
? "Thread archived."
: command.type === "thread.settle"
? "Thread settled."
: command.type === "thread.metadata.update"
? "Workspace changed."
: command.type === "thread.runtime-mode.set"
? "Runtime mode changed."
: "Provider or model selection changed.",
: command.type === "thread.metadata.update"
? "Workspace changed."
: command.type === "thread.runtime-mode.set"
? "Runtime mode changed."
: "Provider or model selection changed.",
},
});
const pendingEffect = {
Expand All @@ -4709,13 +4695,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
detail:
command.type === "thread.archive"
? "Thread archived."
: command.type === "thread.settle"
? "Thread settled."
: command.type === "thread.metadata.update"
? "Workspace changed."
: command.type === "thread.runtime-mode.set"
? "Runtime mode changed."
: "Provider or model selection changed.",
: command.type === "thread.metadata.update"
? "Workspace changed."
: command.type === "thread.runtime-mode.set"
? "Runtime mode changed."
: "Provider or model selection changed.",
// Terminal detaches revoke MCP credentials; reattachments need other detach reasons to preserve them.
...(command.type === "thread.archive" ? { revokeMcpCredential: true } : {}),
},
Expand Down Expand Up @@ -5984,7 +5968,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
projection.thread.archivedAt !== null ||
projection.thread.deletedAt !== null ||
projection.thread.settledOverride === "settled" ||
projection.thread.providerInstanceId !== run.providerInstanceId ||
projection.runtimeRequests.some((request) => request.status === "pending") ||
(projection.thread.snoozedUntil != null &&
Expand Down Expand Up @@ -10445,8 +10428,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const dispatchQueuedRunCancel = Effect.fn("Orchestrator.dispatchQueuedRunCancel")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "queued-run.cancel" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
// Settling disposes a cancelled wake's whole cohort, so a sibling's late result cannot unsettle it.
disposes: "wake" | "cohort" = "wake",
) {
const projection = yield* loadProjectionForCommand(
command,
Expand Down Expand Up @@ -10474,9 +10455,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
disposition: "disposed",
now,
cancelQueuedDelivery: false,
...(disposes === "wake"
? { interruptedWakeTaskIds: queuedMessage.delegatedCompletion.taskIds }
: {}),
interruptedWakeTaskIds: queuedMessage.delegatedCompletion.taskIds,
});
}
yield* emitQueuedRunCancellation({ command, events, projection, run: queuedRun, now });
Expand Down
27 changes: 15 additions & 12 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6299,18 +6299,20 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
const [originalRow] = yield* sql<{
payload_json: string;
}>`SELECT payload_json FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId}`;
for (const [field, value] of [
["archivedAt", DateTime.formatIso(now)],
["settledOverride", "settled"],
]) {
// Archiving puts the work away; settling only parks the thread, so it still recovers.
for (const [field, value, recovers] of [
["archivedAt", DateTime.formatIso(now), false],
["settledOverride", "settled", true],
] as const) {
yield* sql`UPDATE orchestration_v2_projection_threads
SET payload_json = json_set(payload_json, ${`$.${field}`}, ${value})
WHERE thread_id = ${threadId}`;
assert.isUndefined(
(yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).find(
(row) => row.id === threadId,
),
);
const candidate = (yield* store.getLimitRecoveryCandidates({
now,
autoResume: true,
snooze: false,
})).find((row) => row.id === threadId);
assert.equal(candidate !== undefined, recovers);
yield* sql`UPDATE orchestration_v2_projection_threads
SET payload_json = ${originalRow!.payload_json} WHERE thread_id = ${threadId}`;
}
Expand Down Expand Up @@ -6464,7 +6466,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
}),
);

it.effect("does not freshly arm limit recovery for a subagent of a put-away parent", () =>
it.effect("does not freshly arm limit recovery for a subagent of an archived parent", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
Expand Down Expand Up @@ -6607,10 +6609,11 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
)?.type === "thread.metadata.update",
)
.map((row) => row.id);
// Settling only parks the parent in the sidebar; it still waits on its subagent.
assert.deepEqual(
armed,
[activeParentChild],
`only the child of the open parent is armed (${JSON.stringify(options)})`,
[activeParentChild, settledParentChild],
`only children of live parents are armed (${JSON.stringify(options)})`,
);
}
// A recovery armed before the parent settled still resumes at its reset.
Expand Down
Loading
Loading