diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
index 7d22b2e27eac8..ac890178d035c 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
@@ -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();
@@ -231,7 +231,7 @@ describe("SettingsServerControlsRouteScreen", () => {
act(() => root.render());
const autoSettle = [...container.querySelectorAll('[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);
});
diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
index 41600619b3a47..a17682631efd5 100644
--- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
+++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
@@ -148,7 +148,7 @@ export function AutoSettleSettingsRows(props: {
writeToAll({ sidebarAutoSettleOnMerge: value })}
diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
index 201fc78234f5a..f89aa0d861d0e 100644
--- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
+++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
@@ -30,7 +30,6 @@ export function UsageLimitRecoveryCard({
const [error, setError] = useState(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));
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index 65e7ce0690a24..de00c4a500d82 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -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");
@@ -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",
);
@@ -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");
}),
);
});
diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
index d79d1a2d9ca97..33f7611f5a364 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
@@ -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",
@@ -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",
@@ -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);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 42b4c83ca75e4..8664b2fdc51c4 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -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
@@ -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,
},
},
@@ -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);
@@ -3815,32 +3832,6 @@ 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 =
@@ -3848,7 +3839,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
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);
@@ -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 ||
@@ -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,
@@ -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 &&
@@ -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 = {
@@ -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 } : {}),
},
@@ -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 &&
@@ -10445,8 +10428,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const dispatchQueuedRunCancel = Effect.fn("Orchestrator.dispatchQueuedRunCancel")(function* (
command: Extract,
events: Ref.Ref>,
- // 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,
@@ -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 });
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 557160816bbb1..30670a021fd3b 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -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}`;
}
@@ -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;
@@ -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.
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index e0f6ba249f293..a6a026b12debf 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -4134,7 +4134,6 @@ export const layer: Layer.Layer =
AND json_extract(failure.payload_json, '$.failure.class') = 'usage_limit'
)
AND json_extract(t.payload_json, '$.archivedAt') IS NULL
- AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled'
AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit'
AND json_extract(item.payload_json, '$.failure.resetAt') IS NOT NULL
AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(COALESCE(r.completed_at, json_extract(t.payload_json, '$.updatedAt')))
@@ -4158,14 +4157,13 @@ export const layer: Layer.Layer =
${booleanInt(options.autoResume)}
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.
+ -- A subagent of an archived or deleted parent is abandoned work.
AND NOT EXISTS (
SELECT 1 FROM orchestration_v2_projection_threads parent
WHERE json_extract(t.payload_json, '$.lineage.relationshipToParent') = 'subagent'
AND parent.thread_id = json_extract(t.payload_json, '$.lineage.parentThreadId')
AND (
- json_extract(parent.payload_json, '$.settledOverride') = 'settled'
- OR json_extract(parent.payload_json, '$.archivedAt') IS NOT NULL
+ json_extract(parent.payload_json, '$.archivedAt') IS NOT NULL
OR parent.deleted_at IS NOT NULL
)
)
diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
index 6eca0cb39aa24..f5e4336fec045 100644
--- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
@@ -100,14 +100,7 @@ interface ReadPlan {
const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
-type WatchEndReason =
- | "merged"
- | "closed"
- | "unreadable"
- | "comment-limit"
- | "settled"
- | "subagent"
- | "stopped";
+type WatchEndReason = "merged" | "closed" | "unreadable" | "comment-limit" | "subagent" | "stopped";
interface WatchLife {
readonly threadId: string;
@@ -423,11 +416,9 @@ export const make = Effect.gen(function* () {
const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
link.snapshot?.state === "merged"
? "merged"
- : thread.settledOverride === "settled" || thread.settledAt !== null
- ? "settled"
- : thread.lineage.relationshipToParent === "subagent"
- ? "subagent"
- : undefined;
+ : thread.lineage.relationshipToParent === "subagent"
+ ? "subagent"
+ : undefined;
const eachTarget = (
group: WatchGroup,
diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts
index d2f21a772ac99..299e3e43b5b3f 100644
--- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts
+++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts
@@ -1211,19 +1211,20 @@ it.effect.each([
}),
);
-it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
+it.effect("does not wake a snoozed thread, but continues a settled one or an elapsed snooze", () =>
Effect.gen(function* () {
const live = makeProjection();
- for (const held of [
- { snoozedUntil: DateTime.add(now, { days: 1 }) },
+ const snoozed = { ...live.thread, snoozedUntil: DateTime.add(now, { days: 1 }) };
+ assert.isUndefined(restartContinuationRun({ ...live, thread: snoozed }, now));
+ assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread: snoozed }), []);
+ // Settling only parks the thread in the sidebar; its cut turn still continues.
+ for (const awake of [
{ settledOverride: "settled" as const },
+ { snoozedUntil: DateTime.subtract(now, { minutes: 1 }) },
]) {
- const thread = { ...live.thread, ...held };
- assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
- assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
+ const thread = { ...live.thread, ...awake };
+ assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
}
- const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
- assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
}),
);
diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts
index 20d110d335aa2..f8724d0fbf025 100644
--- a/apps/server/src/orchestration-v2/RestartContinuation.ts
+++ b/apps/server/src/orchestration-v2/RestartContinuation.ts
@@ -49,7 +49,6 @@ function restartContinuationBlocked(
if (
thread.archivedAt !== null ||
thread.deletedAt !== null ||
- thread.settledOverride === "settled" ||
(thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now))
)
return true;
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
index f3c83eca70646..30b8cdc4c6fb1 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
@@ -369,14 +369,15 @@ describe("resolveAutoSettlementAt", () => {
pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
}),
).toBeNull();
+ const closed = {
+ ...input,
+ thread: shell(),
+ pullRequest: { state: "closed" as const, closedAt: DateTime.formatIso(at(-1)) },
+ };
+ expect(ThreadSettlementService.resolveAutoSettlementAt(closed)).toEqual(shell().createdAt);
expect(
- ThreadSettlementService.resolveAutoSettlementAt({
- ...input,
- thread: shell(),
- pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
- autoSettleOnMerge: false,
- }),
- ).toEqual(shell().createdAt);
+ ThreadSettlementService.resolveAutoSettlementAt({ ...closed, autoSettleOnMerge: false }),
+ ).toBeNull();
});
it("settles on merge after agent-started runs, but not after the user writes again", () => {
@@ -562,16 +563,25 @@ interface HarnessOptions {
input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
) => Effect.Effect;
readonly onCloseIdle?: () => Effect.Effect;
- readonly currentThreads?: ReadonlyArray;
+ readonly currentThreads?: ReadonlyArray<
+ OrchestrationV2AppThread & Partial>
+ >;
}
+// Auto-settlement is off by default; these tests exercise the rules with both turned on.
+const ENABLED_SETTINGS: ContractServerSettings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ sidebarAutoSettleOnMerge: true,
+ sidebarAutoSettleAfterDays: 7,
+};
+
const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
const activation = yield* Deferred.make();
const snapshots = yield* Ref.make(options.snapshot);
const snapshotReadCount = yield* Ref.make(0);
const snapshotReads = yield* Queue.unbounded();
const candidateReads = yield* Ref.make>([]);
- const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
+ const settings = yield* Ref.make(options.settings ?? ENABLED_SETTINGS);
const settingsReadCount = yield* Ref.make(0);
const settingsChanges = yield* PubSub.unbounded();
const mergedPullRequests = yield* PubSub.unbounded();
@@ -670,10 +680,16 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
: snapshot.threads.filter((thread) => thread.id === threadId),
),
),
- getThread: (threadId) => {
+ getThreadShell: (threadId) => {
const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
return thread
- ? Effect.succeed(thread)
+ ? Effect.succeed({
+ status: "idle",
+ activeRunId: null,
+ activityRunStatus: null,
+ pendingBackgroundTasks: [],
+ ...thread,
+ } as unknown as OrchestrationV2ThreadShell)
: Effect.die(new Error(`Unexpected thread read: ${threadId}`));
},
}),
@@ -774,7 +790,7 @@ describe("ThreadSettlementServiceV2 worker", () => {
);
const fixture = yield* makeHarness({
snapshot: makeSnapshot(threads),
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
+ settings: { ...ENABLED_SETTINGS, sidebarAutoSettleAfterDays: 3 },
});
yield* Effect.gen(function* () {
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
@@ -822,7 +838,7 @@ describe("ThreadSettlementServiceV2 worker", () => {
});
const fixture = yield* makeHarness({
snapshot: makeSnapshot([thread]),
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
+ settings: { ...ENABLED_SETTINGS, sidebarAutoSettleAfterDays: null },
});
yield* Effect.gen(function* () {
@@ -898,7 +914,7 @@ describe("ThreadSettlementServiceV2 worker", () => {
let disable: Effect.Effect = Effect.void;
const fixture = yield* makeHarness({
snapshot: makeSnapshot(threads),
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
+ settings: { ...ENABLED_SETTINGS, sidebarAutoSettleAfterDays: 3 },
onDispatch: () => disable,
});
disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
@@ -1456,21 +1472,28 @@ describe("ThreadSettlementServiceV2 terminals", () => {
payload: thread,
});
- it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
+ it.effect("keeps the terminals of a thread re-engaged or busy before the event ran", () =>
Effect.scoped(
Effect.gen(function* () {
const settled = appThread("reengaged-thread", "settled");
const reengaged = appThread("reengaged-thread", "active");
+ // Still settled, but its agent already started a turn, e.g. for a background result.
+ const busy = appThread("busy-thread", "settled");
const marker = appThread("marker-thread", "settled");
const fixture = yield* makeHarness({
snapshot: makeSnapshot([]),
- currentThreads: [reengaged, marker],
+ currentThreads: [
+ reengaged,
+ { ...busy, status: "running", activeRunId: RunId.make("busy-run") },
+ marker,
+ ],
});
yield* Effect.gen(function* () {
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
yield* startHarness(service, fixture.activation, fixture.snapshotReads);
yield* fixture.publishEvent(settledEvent(settled));
+ yield* fixture.publishEvent(settledEvent(busy));
yield* fixture.publishEvent(settledEvent(marker));
assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
}).pipe(Effect.provide(fixture.layer));
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts
index 8c852426da323..e24b860f05ff1 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts
@@ -44,6 +44,13 @@ export interface SettlementPullRequest {
}
const DAY_MS = 24 * 60 * 60 * 1_000;
+const BUSY_SHELL_STATUSES: ReadonlySet = new Set([
+ "queued",
+ "preparing",
+ "starting",
+ "running",
+ "waiting",
+]);
const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
function toMillis(value: DateTime.Utc | null | undefined): number | null {
@@ -129,9 +136,7 @@ function pullRequestSettles(
pullRequest: SettlementPullRequest,
autoSettleOnMerge: boolean,
): boolean {
- if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
- return false;
- }
+ if (pullRequest.state === "open" || !autoSettleOnMerge) return false;
const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
if (terminalAt == null) return false;
const userAnchorMs = latestMillis([
@@ -596,17 +601,31 @@ export const make = Effect.gen(function* () {
return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
});
+ // An agent can start a turn just as its thread settles (a background task's result), so
+ // settle actions run only on a thread that is still settled and has no run or queued work.
+ const settledAndIdle = Effect.fnUntraced(function* (threadId: ThreadId) {
+ const thread = yield* projections.getThreadShell(threadId);
+ return thread !== null &&
+ thread.settledOverride === "settled" &&
+ thread.activeRunId === null &&
+ (thread.activityRunStatus ?? null) === null &&
+ !BUSY_SHELL_STATUSES.has(thread.status) &&
+ !backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
+ ? thread
+ : null;
+ });
+
// Skip settle scripts in shared checkouts where other threads may still work.
const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
function* (threadId: ThreadId) {
- const settled = yield* projections.getThread(threadId);
- if (settled.settledOverride !== "settled") return;
+ const settled = yield* settledAndIdle(threadId);
+ if (settled === null) return;
yield* terminals.closeOnSettle({ threadId });
const worktreePath = settled.worktreePath;
if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
// Recheck after closing and worktree I/O; re-engaged threads must not be cleaned up.
- const thread = yield* projections.getThread(threadId);
- if (thread.settledOverride !== "settled") return;
+ const thread = yield* settledAndIdle(threadId);
+ if (thread === null) return;
const settledAtMs = toMillis(thread.settledAt);
if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
const run = yield* projectScripts.runForThread({
diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
index 985815bd73eb4..062f748deb038 100644
--- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
+++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
@@ -26,7 +26,6 @@ export function limitRecoveryCommand(
!thread.latestRunId ||
!thread.usageLimitResetAt ||
thread.archivedAt !== null ||
- thread.settledOverride === "settled" ||
thread.pendingRuntimeRequest !== null
)
return null;
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index a31a96cf5b463..d32800e34268b 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -1896,7 +1896,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
}),
);
- it.effect("dismisses message-capable questions directly and while settling", () =>
+ it.effect("dismisses message-capable questions directly but keeps them while settling", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const eventSink = yield* EventSink.EventSinkV2;
@@ -2024,18 +2024,10 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
commandId: CommandId.make("runtime-settle-question-command"),
threadId: settled.threadId,
});
+ // Settling only parks the thread, so the agent's question stays open.
const settledProjection = yield* orchestrator.getThreadProjection(settled.threadId);
assert.equal(settledProjection.thread.settledOverride, "settled");
- assert.equal(settledProjection.runtimeRequests[0]?.status, "resolved");
- assert.equal(settledProjection.runtimeRequests[0]?.decision, "cancel");
- assert.equal(
- settledProjection.nodes.find((node) => node.id === settled.nodeId)?.status,
- "cancelled",
- );
- assert.equal(
- settledProjection.turnItems.find((item) => item.id === settled.itemId)?.status,
- "cancelled",
- );
+ assert.equal(settledProjection.runtimeRequests[0]?.status, "pending");
}),
);
@@ -3120,109 +3112,146 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- it.effect.each(["manual", "automatic"])("settling ends every pull request watch: %s", (mode) =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const maintenance = yield* ProjectionReplay.ProjectionReplay;
- const threadId = ThreadId.make(`pr-watch-settle-${mode}`);
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`pr-watch-settle-create-${mode}`),
- threadId,
- projectId: ProjectId.make("pr-watch-settle-project"),
- title: "Settle watched PRs",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- });
- const key = { host: "github.com", repository: "pingdotgg/t3code" };
- for (const number of [7, 8]) {
+ it.effect.each(["manual", "automatic"])(
+ "settling keeps the agent session and pull request watches: %s",
+ (mode) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const maintenance = yield* ProjectionReplay.ProjectionReplay;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const threadId = ThreadId.make(`pr-watch-settle-${mode}`);
+ yield* seedProject({
+ projectId: ProjectId.make(`pr-watch-settle-project-${mode}`),
+ title: "Settle watched PRs",
+ workspaceRoot: process.cwd(),
+ defaultModelSelection: modelSelection,
+ createdAt: DateTime.formatIso(yield* DateTime.now),
+ });
yield* orchestrator.dispatch({
- type: "thread.pull-request.watch",
- commandId: CommandId.make(`pr-watch-settle-start-${mode}-${number}`),
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`pr-watch-settle-create-${mode}`),
threadId,
- ...key,
- number,
- watching: true,
- link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
+ projectId: ProjectId.make(`pr-watch-settle-project-${mode}`),
+ title: "Settle watched PRs",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
});
- }
- const before = yield* orchestrator.getThreadShell(threadId);
- const started = before?.pullRequests?.[0]?.watch;
- assert.isDefined(started);
- if (started === undefined || before === null) return;
- yield* orchestrator.dispatch({
- ...(mode === "manual"
- ? { type: "thread.settle" as const }
- : { type: "thread.auto-settle" as const, snapshotAt: before.updatedAt }),
- commandId: CommandId.make(`pr-watch-settle-${mode}`),
- threadId,
- });
- const expected = before.pullRequests?.map(({ watch, ...link }) => ({
- ...link,
- endedWatch: watch,
- }));
- assert.deepEqual((yield* orchestrator.getThreadShell(threadId))?.pullRequests, expected);
- assert.isTrue((yield* maintenance.rebuild).valid);
- assert.deepEqual((yield* orchestrator.getThreadShell(threadId))?.pullRequests, expected);
+ const key = { host: "github.com", repository: "pingdotgg/t3code" };
+ for (const number of [7, 8]) {
+ yield* orchestrator.dispatch({
+ type: "thread.pull-request.watch",
+ commandId: CommandId.make(`pr-watch-settle-start-${mode}-${number}`),
+ threadId,
+ ...key,
+ number,
+ watching: true,
+ link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
+ });
+ }
+ // An agent between turns, such as Claude about to deliver a background task's result.
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ commandId: CommandId.make(`pr-watch-settle-attach-${mode}`),
+ events: [
+ {
+ id: EventId.make(`pr-watch-settle-attach-${mode}`),
+ type: "provider-session.attached",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: ProviderSessionId.make(`pr-watch-settle-session-${mode}`),
+ driver,
+ providerInstanceId: modelSelection.instanceId,
+ status: "ready",
+ cwd: process.cwd(),
+ model: modelSelection.model,
+ capabilities: CodexProviderCapabilitiesV2,
+ createdAt: now,
+ updatedAt: now,
+ lastError: null,
+ },
+ },
+ ],
+ });
+ const before = yield* orchestrator.getThreadShell(threadId);
+ const started = before?.pullRequests?.[0]?.watch;
+ assert.isDefined(started);
+ if (started === undefined || before === null) return;
+ const settleCommandId = CommandId.make(`pr-watch-settle-${mode}`);
+ yield* orchestrator.dispatch({
+ ...(mode === "manual"
+ ? { type: "thread.settle" as const }
+ : { type: "thread.auto-settle" as const, snapshotAt: before.updatedAt }),
+ commandId: settleCommandId,
+ threadId,
+ });
+ assert.deepEqual(
+ (yield* outbox.listByCommandId(settleCommandId)).filter(
+ (effect) => effect.request.type === "provider-session.detach",
+ ),
+ [],
+ );
+ const settled = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(settled.thread.settledOverride, "settled");
+ assert.deepEqual(
+ settled.providerSessions.map((session) => session.status),
+ ["ready"],
+ );
+ assert.deepEqual(
+ (yield* orchestrator.getThreadShell(threadId))?.pullRequests,
+ before.pullRequests,
+ );
+ assert.isTrue((yield* maintenance.rebuild).valid);
+ assert.deepEqual(
+ (yield* orchestrator.getThreadShell(threadId))?.pullRequests,
+ before.pullRequests,
+ );
- for (const wake of [
- undefined,
- {
- messageId: MessageId.make(`pr-watch-settle-late-wake-${mode}`),
- text: "Update",
- notification: {
- source: { kind: "monitor" as const },
- outcome: "updated" as const,
- summary: "#7",
- },
- },
- ]) {
- const late = yield* orchestrator
+ const blocked = yield* orchestrator
.dispatch({
- type: "thread.pull-request-watch.sync",
- commandId: CommandId.make(`pr-watch-settle-late-${mode}-${wake !== undefined}`),
+ type: "thread.pull-request.watch",
+ commandId: CommandId.make(`pr-watch-settle-blocked-${mode}`),
threadId,
...key,
- number: 7,
- startedAt: started.startedAt,
- watch: { ...started, headSha: "late", wakes: 1 },
- ...(wake === undefined ? {} : { wake }),
+ number: 9,
+ watching: true,
})
.pipe(Effect.flip);
- assert.equal(late._tag, "OrchestratorDispatchError");
- }
- const restart = {
- type: "thread.pull-request.watch" as const,
- threadId,
- ...key,
- number: 7,
- watching: true,
- };
- const blocked = yield* orchestrator
- .dispatch({
- ...restart,
- commandId: CommandId.make(`pr-watch-settle-blocked-${mode}`),
- })
- .pipe(Effect.flip);
- assert.equal(blocked._tag, "OrchestratorDispatchError");
- assert.deepEqual((yield* orchestrator.getThreadRecords(threadId, ["messages"])).messages, []);
- yield* orchestrator.dispatch({
- type: "thread.unsettle",
- commandId: CommandId.make(`pr-watch-settle-unsettle-${mode}`),
- threadId,
- reason: "user",
- });
- yield* orchestrator.dispatch({
- ...restart,
- commandId: CommandId.make(`pr-watch-settle-restart-${mode}`),
- });
- assert.isDefined((yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch);
- }),
+ assert.equal(blocked._tag, "OrchestratorDispatchError");
+
+ const wakeMessageId = MessageId.make(`pr-watch-settle-wake-${mode}`);
+ yield* orchestrator.dispatch({
+ type: "thread.pull-request-watch.sync",
+ commandId: CommandId.make(`pr-watch-settle-wake-${mode}`),
+ threadId,
+ ...key,
+ number: 7,
+ startedAt: started.startedAt,
+ watch: { ...started, headSha: "late", wakes: 1 },
+ wake: {
+ messageId: wakeMessageId,
+ text: "Update",
+ notification: {
+ source: { kind: "monitor" as const },
+ outcome: "updated" as const,
+ summary: "#7",
+ },
+ },
+ });
+ const woken = yield* orchestrator.getThreadRecords(threadId, ["messages"]);
+ assert.deepEqual(
+ woken.messages.map((message) => message.id),
+ [wakeMessageId],
+ );
+ assert.isNull(woken.thread.settledOverride);
+ assert.isNull(woken.thread.settledAt);
+ }),
);
it.effect("archiving ends watches, and an archived thread cannot start one", () =>
@@ -4939,7 +4968,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- it.effect("settles past held automatic runs but not held user messages", () =>
+ it.effect("settles past held automatic runs, keeping them, but not held user messages", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const eventSink = yield* EventSink.EventSinkV2;
@@ -5047,7 +5076,24 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
});
const settled = yield* orchestrator.getThreadProjection(threadId);
assert.isNotNull(settled.thread.settledAt);
- assert.isTrue(settled.runs.every((run) => run.status === "cancelled"));
+ // Settling keeps the background wake; starting it brings the thread back to active.
+ assert.deepEqual(
+ settled.runs.map((run) => run.status),
+ ["cancelled", "queued"],
+ );
+ yield* orchestrator.dispatch({
+ type: "queue.resume",
+ commandId: CommandId.make("settle-automatic-resume"),
+ threadId,
+ });
+ const resumed = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(
+ resumed.runs.map((run) => run.status),
+ ["cancelled", "starting"],
+ );
+ assert.isNull(resumed.thread.settledOverride);
+ assert.isNull(resumed.thread.settledAt);
+ yield* holdQueueAfterRestart("settle-automatic-restart-resumed");
yield* orchestrator.dispatch({
type: "thread.unsettle",
@@ -8862,6 +8908,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
"rearm",
"snooze-race",
"archive",
+ "settle",
"replacement",
"manual-snooze",
"invalid-snooze",
@@ -9271,6 +9318,12 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
commandId: CommandId.make(`recovery:archive:${scenario}`),
threadId,
});
+ if (scenario === "settle")
+ yield* orchestrator.dispatch({
+ type: "thread.settle",
+ commandId: CommandId.make(`recovery:settle:${scenario}`),
+ threadId,
+ });
if (scenario === "stop") {
yield* orchestrator.dispatch({
type: "thread.stop",
@@ -9427,6 +9480,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
(scenario === "resume" ||
scenario === "resume-started" ||
scenario === "resume-untagged" ||
+ scenario === "settle" ||
stopBeforeArm ||
scenario === "queued-resume" ||
scenario === "independent-patches" ||
@@ -9440,6 +9494,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
(scenario === "resume" ||
scenario === "resume-started" ||
scenario === "resume-untagged" ||
+ scenario === "settle" ||
stopBeforeArm ||
scenario === "queued-resume" ||
scenario === "independent-patches" ||
@@ -9447,6 +9502,12 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
? 1
: 0),
);
+ if (scenario === "settle") {
+ // Settling only parks the thread; the resumed run brings it back to active.
+ assert.equal(after.runs.at(-1)?.status, "starting");
+ assert.isNull(after.thread.settledOverride);
+ assert.isNull(after.thread.settledAt);
+ }
if (scenario === "stop") {
assert.deepInclude(after.thread.limitRecovery, { runId: run.id, autoResume: false });
const projections = yield* ProjectionStore.ProjectionStoreV2;
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
index 4eb466200bc90..806708b9ba194 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
@@ -61,7 +61,7 @@ const makeHarness = Effect.fn(function* (options: {
return () => listeners.delete(listener);
}),
write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
- closeIdle: () => Effect.void,
+ closeIdle: () => Effect.succeed(true),
closeOnSettle: () => Effect.void,
});
const runner = yield* ProjectSetupScriptRunner.make.pipe(
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts
index 8e7c3105b36bc..eed0296842b3a 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts
@@ -544,7 +544,7 @@ export const make = Effect.gen(function* () {
const completion = observed?.completion.pipe(
Effect.tap(({ exitCode }) =>
exitCode === 0
- ? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
+ ? terminalManager.closeIdle({ threadId: input.threadId, terminalId }).pipe(Effect.asVoid)
: Effect.void,
),
);
diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts
index de1ccfefcf64f..6f6fc6f31cc1c 100644
--- a/apps/server/src/storageCleanup.test.ts
+++ b/apps/server/src/storageCleanup.test.ts
@@ -195,7 +195,7 @@ describe("V2 storage cleanup eligibility", () => {
autoResume: true,
settled: true,
resetIn: -1_000,
- idle: true,
+ idle: false,
},
{ name: "not yet armed by the recovery worker", armed: false, resetIn: DAY_MS, idle: false },
{
@@ -354,6 +354,7 @@ const cleanupFixture = (
let gitInspections = 0;
let snapshotReads = 0;
let terminalListener: ((event: TerminalMetadataStreamEvent) => Effect.Effect) | undefined;
+ const closedIdleTerminals: Array<{ threadId: string; terminalId?: string }> = [];
let events: Stream.Stream = Stream.empty;
const activated = yield* Deferred.make();
const context = yield* Layer.build(StorageCleanup.layer).pipe(
@@ -473,6 +474,11 @@ const cleanupFixture = (
terminalListener = listener;
return () => {};
}),
+ closeIdle: (input: { threadId: string; terminalId?: string }) =>
+ Effect.suspend(() => {
+ closedIdleTerminals.push(input);
+ return terminalListener?.({ type: "remove", ...input } as never) ?? Effect.void;
+ }).pipe(Effect.as(true)),
} as unknown as TerminalManager.TerminalManager["Service"]),
Effect.provideService(ServerActivation, Deferred.await(activated)),
);
@@ -541,7 +547,11 @@ const cleanupFixture = (
setOpenSessionCwd: (cwd: string | null) => {
openSessionCwd = cwd;
},
- openTerminal: (paths: { cwd: string; worktreePath: string | null }) =>
+ closedIdleTerminals: () => closedIdleTerminals,
+ openTerminal: (
+ paths: { cwd: string; worktreePath: string | null },
+ hasRunningSubprocess = true,
+ ) =>
terminalListener?.({
type: "upsert",
terminal: {
@@ -551,7 +561,7 @@ const cleanupFixture = (
pid: 1,
exitCode: null,
exitSignal: null,
- hasRunningSubprocess: false,
+ hasRunningSubprocess,
label: "Terminal",
updatedAt: "2026-06-10T12:00:00.000Z",
...paths,
@@ -1346,7 +1356,7 @@ describe("deleted thread worktrees", () => {
pid: 1,
exitCode: null,
exitSignal: null,
- hasRunningSubprocess: false,
+ hasRunningSubprocess: true,
label: "Terminal",
updatedAt: DateTime.formatIso(at(0)),
},
@@ -1951,6 +1961,20 @@ describe("orphan worktree reports", () => {
),
);
+ it.live("closes a shell idle at its prompt when it removes the worktree", () =>
+ runCleanupTest(
+ Effect.gen(function* () {
+ const fixture = yield* cleanupFixture();
+ yield* fixture.openTerminal({ cwd: fixture.worktree, worktreePath: null }, false);
+ const report = yield* fixture.service.runNow;
+ expect(report.entries[0]).toMatchObject({ outcome: "removed" });
+ expect(fixture.closedIdleTerminals()).toEqual([
+ { threadId: "thread-1", terminalId: "terminal-1" },
+ ]);
+ }),
+ ),
+ );
+
it.live.each(["win32", "linux"] as const)(
"matches a provider session at the worktree root with host casing rules (%s)",
(platform) =>
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index a5f9cd7eefa12..55e76f15a2443 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -169,8 +169,7 @@ function heldForLimitRecovery(
thread.status !== "failed" ||
thread.lastErrorClass !== "usage_limit" ||
!thread.usageLimitResetAt ||
- thread.archivedAt !== null ||
- thread.settledOverride === "settled"
+ thread.archivedAt !== null
)
return false;
const resetMs = Date.parse(thread.usageLimitResetAt);
@@ -328,10 +327,10 @@ const make = Effect.gen(function* () {
!path.isAbsolute(relative)
);
};
- const hasTerminal = (worktreePath: string) =>
+ const terminalsAt = (worktreePath: string) =>
[...liveTerminals.values()]
.flatMap((entries) => [...entries.values()])
- .some((terminal) => {
+ .filter((terminal) => {
if (terminal.status !== "starting" && terminal.status !== "running") return false;
const cwd = path.resolve(terminal.cwd);
return (
@@ -341,6 +340,15 @@ const make = Effect.gen(function* () {
inside(worktreePath, cwd)
);
});
+ // A shell waiting at its prompt does not hold the worktree; removal closes it first.
+ const hasTerminal = (worktreePath: string) =>
+ terminalsAt(worktreePath).some(
+ (terminal) => terminal.status === "starting" || terminal.hasRunningSubprocess,
+ );
+ const closeIdleTerminals = (worktreePath: string) =>
+ Effect.forEach(terminalsAt(worktreePath), (terminal) =>
+ terminals.closeIdle({ threadId: terminal.threadId, terminalId: terminal.terminalId }),
+ ).pipe(Effect.map((closed) => closed.every(Boolean)));
// pnpm imports packages by clone or reflink when its store shares a device
// with the worktree. Those files have one link but share blocks with the
@@ -1206,6 +1214,8 @@ const make = Effect.gen(function* () {
)
)
return keep("settings changed since check");
+ if (!(yield* closeIdleTerminals(worktreePath)))
+ return keep(waitForStop("open terminal"));
// Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check.
if (settings.worktreeKeepWhen === "tracked-changes")
yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean");
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index ed4645b18becf..98c48f93699e6 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -740,52 +740,56 @@ it.layer(
}),
);
- it.effect(
- "closes idle shells and opted-in actions on settlement without stopping other commands",
- () =>
- Effect.gen(function* () {
- const { manager, ptyAdapter } = yield* createManager(5, {
- processTable: Effect.succeed([
- { pid: 9000, ppid: 1, name: "zsh" },
- { pid: 100, ppid: 9000, name: "zsh" },
- { pid: 9001, ppid: 1, name: "zsh" },
- { pid: 200, ppid: 9001, name: "node" },
- { pid: 9002, ppid: 1, name: "zsh" },
- { pid: 300, ppid: 9002, name: "zsh" },
- { pid: 301, ppid: 300, name: "sleep" },
- { pid: 9003, ppid: 1, name: "zsh" },
- { pid: 9004, ppid: 1, name: "zsh" },
- { pid: 400, ppid: 9004, name: "node" },
- ]),
- }).pipe(Effect.provide(layerWithHostPlatform("linux")));
- yield* manager.open(openInput({ terminalId: "idle" }));
- yield* manager.open(openInput({ terminalId: "dev-server" }));
- yield* manager.open(openInput({ terminalId: "subshell" }));
- yield* manager.open(openInput({ threadId: "thread-2", stopOnSettle: true }));
- yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
-
- yield* manager.closeIdle({ threadId: "thread-1" });
-
- expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
- true,
- false,
- false,
- false,
- false,
- ]);
- yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: false }));
- yield* manager.closeOnSettle({ threadId: "thread-1" });
- expect(ptyAdapter.processes[4]?.killed).toBe(false);
- yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
- yield* manager.closeOnSettle({ threadId: "thread-1" });
- expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
- true,
- false,
- false,
- false,
- true,
- ]);
- }),
+ it.effect("settlement closes only opted-in actions, and closeIdle spares running commands", () =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager(5, {
+ processTable: Effect.succeed([
+ { pid: 9000, ppid: 1, name: "zsh" },
+ { pid: 100, ppid: 9000, name: "zsh" },
+ { pid: 9001, ppid: 1, name: "zsh" },
+ { pid: 200, ppid: 9001, name: "node" },
+ { pid: 9002, ppid: 1, name: "zsh" },
+ { pid: 300, ppid: 9002, name: "zsh" },
+ { pid: 301, ppid: 300, name: "sleep" },
+ { pid: 9003, ppid: 1, name: "zsh" },
+ { pid: 9004, ppid: 1, name: "zsh" },
+ { pid: 400, ppid: 9004, name: "node" },
+ ]),
+ }).pipe(Effect.provide(layerWithHostPlatform("linux")));
+ yield* manager.open(openInput({ terminalId: "idle" }));
+ yield* manager.open(openInput({ terminalId: "dev-server" }));
+ yield* manager.open(openInput({ terminalId: "subshell" }));
+ yield* manager.open(openInput({ threadId: "thread-2", stopOnSettle: true }));
+ yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
+
+ yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: false }));
+ yield* manager.closeOnSettle({ threadId: "thread-1" });
+ expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ false,
+ ]);
+ yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
+ yield* manager.closeOnSettle({ threadId: "thread-1" });
+ expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ true,
+ ]);
+
+ yield* manager.closeIdle({ threadId: "thread-1" });
+ expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
+ true,
+ false,
+ false,
+ false,
+ true,
+ ]);
+ }),
);
it.effect("labels a running command by its whole process name, spaces included", () =>
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index e2061df592d00..40398d750afa6 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -221,10 +221,11 @@ export class TerminalManager extends Context.Service<
readonly closeOnSettle: (input: { readonly threadId: string }) => Effect.Effect;
+ /** Succeeds with whether every matching running terminal was idle and closed. */
readonly closeIdle: (input: {
readonly threadId: string;
readonly terminalId?: string;
- }) => Effect.Effect;
+ }) => Effect.Effect;
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect,
@@ -3430,7 +3431,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
Number.isInteger(session.pid) &&
(input.terminalId === undefined || session.terminalId === input.terminalId),
);
- if (running.length === 0) return;
+ if (running.length === 0) return true;
const marks = new Map(
running.map((session) => [session.terminalId, terminalActivityMark(session)]),
);
@@ -3439,26 +3440,24 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix,
);
const inspector = yield* Effect.fromResult(inspectorResult);
- yield* Effect.forEach(
- running,
- (session) =>
- inspector(session.pid).pipe(
- Effect.flatMap((result) =>
- result.hasRunningSubprocess ||
- terminalActivityMark(session) !== marks.get(session.terminalId)
- ? Effect.void
- : closeSession(input.threadId, session.terminalId, false),
- ),
+ const closed = yield* Effect.forEach(running, (session) =>
+ inspector(session.pid).pipe(
+ Effect.flatMap((result) =>
+ result.hasRunningSubprocess ||
+ terminalActivityMark(session) !== marks.get(session.terminalId)
+ ? Effect.succeed(false)
+ : closeSession(input.threadId, session.terminalId, false).pipe(Effect.as(true)),
),
- { discard: true },
+ ),
);
+ return closed.every(Boolean);
}),
).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to close idle terminals", {
threadId: input.threadId,
error: error.message,
- }),
+ }).pipe(Effect.as(false)),
),
);
@@ -3476,7 +3475,6 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
);
}),
);
- yield* closeIdle(input);
});
return TerminalManager.of({
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 055e1a23f6354..d54d6d78c9a19 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -2517,7 +2517,6 @@ export default function ChatView(props: ChatViewProps) {
errorCode: serverRuntime?.lastErrorCode ?? null,
resetAt: serverRuntime?.usageLimitResetAt ?? null,
stoppedAt: limitRecoveryRun.completedAt ?? activeThreadShell.updatedAt,
- settled: activeThreadShell.settledOverride === "settled",
requestPending: pendingApprovals.length > 0 || pendingUserInputs.length > 0,
recovery: activeThreadShell.limitRecovery ?? null,
snoozedUntil: activeThreadShell.snoozedUntil,
diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx
index 84b71be9b62d9..87ae945caffdd 100644
--- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx
+++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx
@@ -12,7 +12,6 @@ function bannerDescription(resetAt: Date, timestampFormat: TimestampFormat) {
errorCode: null,
resetAt: resetAt.toISOString(),
stoppedAt: stoppedAt.toISOString(),
- settled: false,
requestPending: false,
snoozedUntil: null,
recovery: null,
diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
index 744db5ea3a1e9..7e8028dd3d98a 100644
--- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
+++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx
@@ -26,7 +26,6 @@ type RecoveryProps = {
errorCode: string | null;
resetAt: string | null;
stoppedAt: string;
- settled: boolean;
requestPending: boolean;
snoozedUntil: string | null;
recovery: OrchestrationV2LimitRecovery | null;
@@ -40,7 +39,6 @@ export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBann
errorCode,
resetAt,
stoppedAt,
- settled,
requestPending,
recovery,
snoozedUntil,
@@ -48,7 +46,7 @@ export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBann
} = props;
// The server refuses recovery changes while a request is pending.
const canSchedule =
- !settled && !requestPending && resetAt !== null && Date.parse(resetAt) > Date.parse(stoppedAt);
+ !requestPending && resetAt !== null && Date.parse(resetAt) > Date.parse(stoppedAt);
const resumes =
canSchedule && recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;
const workspaceLimit = errorCode === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index dcaca88e6c7f7..6123b47332e3e 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -501,7 +501,7 @@ export function useSettingsRestore(onRestored?: () => void) {
? ["Keep threads with a PR"]
: []),
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge
- ? ["Auto-settle merged threads"]
+ ? ["Auto-settle when a pull request merges or closes"]
: []),
...(settings.autoResumeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads
? ["Resume after usage limits"]
@@ -1756,7 +1756,7 @@ export function ThreadsSettingsPanel() {
serverScoped
settingKeys={["sidebarAutoSettleOnMerge"]}
{...searchableSetting("auto-settle-merged-threads")}
- description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."
+ description="Settle a thread when its pull request merges or closes."
resetAction={
settings.sidebarAutoSettleOnMerge !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? (
@@ -1777,7 +1777,7 @@ export function ThreadsSettingsPanel() {
onCheckedChange={(checked) =>
updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })
}
- aria-label="Auto-settle merged threads"
+ aria-label="Auto-settle when a pull request merges or closes"
/>
}
/>
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 4f61ba41c0d86..54925f9ea1f54 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -642,9 +642,9 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "auto-settle-merged-threads",
- title: "Auto-settle merged threads",
+ title: "Auto-settle when a pull request merges or closes",
to: "/settings/threads",
- searchTerms: ["pull request merge closed automatically sidebar"],
+ searchTerms: ["pull request merged merges closed closes automatically sidebar"],
requiresThreadAutoSettlement: true,
scope: "project-defaults",
},
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index 8880dcb3e64ca..0cad979ea0d6e 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -230,7 +230,8 @@ merging, or when they have no commits beyond the default branch. Set settled ret
to remove a worktree at the next cleanup after settlement. In repositories without remotes,
unchanged-worktree cleanup compares against the branch checked out in the project workspace;
if that checkout has a detached HEAD, the worktree is kept. Only T3-managed worktrees are eligible.
-Active sessions and shared worktrees prevent removal. **Keep worktrees with local changes** defaults
+Active sessions, terminals running a command, and shared worktrees prevent removal. A terminal
+waiting at an idle prompt there is closed when the worktree is removed. **Keep worktrees with local changes** defaults
to **Uncommitted changes**, which protects tracked edits and untracked files but deletes ignored
files such as `.env` and build output. **Any local files** also protects ignored files other than
`node_modules`. **Edited tracked files** protects only tracked edits and allows untracked and
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index 8bbeb7e988cbe..62ef90b1dfe32 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -320,7 +320,7 @@ Linking and unlinking are available in the web and desktop clients.
The **Linked pull requests** panel lists every review and groups stacks. Unlink a review from its
row menu. An unlinked stack layer stays out of later syncs. Open linked reviews refresh on the server;
closed reviews refresh periodically so reopening one on the host is detected. Merged reviews refresh
-when requested. A settled thread's reviews stop refreshing until you unsettle it. With **Auto-settle merged threads** enabled, a thread can settle after every linked
+when requested. A settled thread's reviews stop refreshing until you unsettle it. With **Auto-settle when a pull request merges or closes** enabled, a thread can settle after every linked
review is terminal. An open or unsynced link keeps it active.
Ask the agent to watch, monitor, or babysit a pull request and it calls `watch_pull_request`. While
@@ -331,8 +331,8 @@ first asks whether anything changed and reads the pull request only when it did,
watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends
when the pull request merges or closes, after 10 wakes in a row that bring only comments, after 8
failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching.
-Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new
-watch. Watching a pull request again does not repeat check or conflict news its last
+Archiving a thread also ends all its watches. Settling keeps them, and a wake moves the thread back to
+active work. Unsettle the thread before starting a new watch. Watching a pull request again does not repeat check or conflict news its last
watch already reported; unlinking the pull request clears that. Subagents cannot watch pull requests; the thread that delegated to them does. To start or stop
it yourself, use the row menu in the **Linked pull requests** panel. In the thread details card, a
watched pull request shows an eye; click it to stop watching.
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 09ce63e2a3e65..1f7e7bb532091 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -164,10 +164,10 @@ section is off. Each device keeps its own choice.
Choose **Settle thread** from its menu to move finished work out of the active list
without deleting the conversation. **Un-settle thread** restores it to active work
and prevents automatic settlement until new activity resumes the usual rules.
-Manually settling an idle thread dismisses unanswered async questions without
-sending an answer or restarting the agent. Settling also closes the thread's
-terminals that wait at an idle prompt, and keeps their output. A terminal that
-runs a command, such as a dev server, stays open unless its action has **Stop this action
+Settling only changes where the thread is listed. It does not stop the agent,
+answer its questions, or drop background results, pull request watches, or usage-limit
+resumes it is waiting on. When one of those starts a turn, the thread moves back to
+active work. Terminals stay open unless their action has **Stop this action
when the thread settles** enabled in Settings > Projects > Actions. You can also set
`"stopOnSettle": true` on a `t3.json` action and import it there. Start the command through
that action so T3 can stop its terminal and child processes. Commands started through an
@@ -177,7 +177,9 @@ To reclaim disk space from settled work, turn on **Run in the thread's worktree
thread settles** for one of the project's actions, or set `"runOnSettle": true` on a
`t3.json` script, for example `cargo clean`. It runs each time a thread in its own
worktree settles, manually or automatically, even if a terminal there still runs a
-command such as a dev server. Threads in the project's main checkout skip it. Its terminal
+command such as a dev server. Settle actions, including **Stop this action when the thread
+settles**, run only while the thread is settled and idle: if the agent is already starting a
+turn when the thread settles, they are skipped for that settlement. Threads in the project's main checkout skip it. Its terminal
closes when the command succeeds and stays open when it fails.
On web and desktop, press a thread's **Settle** button and drag up or down to
@@ -185,9 +187,11 @@ settle every thread in that section between it and the one you release on.
The **Un-settle** and **Wake** buttons work the same way in their sections.
Press `Escape` while dragging to cancel.
-By default, environments settle inactive threads after seven days and settle
-threads whose pull request merged. A closed pull request can also settle an idle
-thread. An empty thread's inactivity counts from when it was created.
+Automatic settlement is off by default, including on environments where you never changed
+these settings; earlier versions settled inactive threads after seven days and threads whose
+pull request merged or closed. In **Settings → Threads**, you can turn on settling threads
+after a number of inactive days, or when their pull request merges or closes.
+An empty thread's inactivity counts from when it was created.
Work in progress, pending questions or approvals, and background work the agent
is waiting on prevent automatic settlement. An open pull request does not prevent inactivity
settlement unless you turn on **Keep threads with a PR** in **Settings → Threads**,
@@ -259,7 +263,8 @@ continuation. You can cancel it from the thread. Enable **Resume after
usage limits** in **Settings → Threads** to schedule limit stops by default.
The environment must be running when the reset arrives; it resumes overdue
continuations after a restart. Stopping the thread, sending a new message,
-archiving, or settling it prevents a pending continuation from starting.
+or archiving it prevents a pending continuation from starting. A settled thread still
+resumes and moves back to active work.
Choose **Snooze until reset** to hide the thread until its allowance returns.
Snooze and auto-resume are independent: snooze alone wakes the thread without
diff --git a/docs/user/updating.md b/docs/user/updating.md
index 123306077f8f5..470625814f6b1 100644
--- a/docs/user/updating.md
+++ b/docs/user/updating.md
@@ -77,7 +77,7 @@ command or monitor the agent said it was waiting on is woken and told that this
stopped. Other background shells and monitors, such as a dev server and its
watchdog, do not wake it; the thread learns about them with your next message.
A thread is not resumed while it waits for your approval, answer, or secret, or
-while it is archived, snoozed, or settled. After three automatic resumes in a row,
+while it is archived or snoozed. A settled thread is resumed like any other. After three automatic resumes in a row,
the thread waits for your next message.
Updates from the previous orchestration system preserve conversation transcripts but cannot carry
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 346213992e4b2..405626dbaf8c7 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -94,7 +94,6 @@ export const SidebarAutoSettleAfterDays = Schema.Number.check(
}),
);
export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
-const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 7;
export const MAX_SNOOZE_PRESET_MINUTES = 30 * 24 * 60;
export const MAX_SNOOZE_PRESETS = 8;
@@ -1420,7 +1419,7 @@ export const ServerSettings = Schema.Struct({
/** Alpha: Simlock device hosts. Off, the server ignores `simlockDeviceHosts`. */
simlockDeviceHostsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
- Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
+ Schema.withDecodingDefault(Effect.succeed(null)),
),
compactIdleThreads: LegacyCompactIdleThreads.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
@@ -1455,7 +1454,7 @@ export const ServerSettings = Schema.Struct({
sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
),
- sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
backgroundActivity: BackgroundActivitySettings,
automaticGitFetchInterval: Schema.DurationFromMillis.pipe(