From 8ed0ec83067595bdf6c6094b7c7c6cacbbac84ff Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 08:05:37 -0300 Subject: [PATCH 1/3] feat(automation): delete finished run threads - Add an option to delete successful fresh-run threads when their turn completes - Keep failed or stopped threads and show deleted status in run history - Cover pending cleanup, including turns completed while the server was down --- .../src/automation/AutomationService.test.ts | 204 +++++++++++++++++- .../src/automation/AutomationService.ts | 130 ++++++++++- .../automations/AutomationsPage.tsx | 24 ++- docs/user/automations.md | 6 + packages/contracts/src/automation.ts | 10 + 5 files changed, 370 insertions(+), 4 deletions(-) diff --git a/apps/server/src/automation/AutomationService.test.ts b/apps/server/src/automation/AutomationService.test.ts index 529b29e82d18b..ded1dd81d637b 100644 --- a/apps/server/src/automation/AutomationService.test.ts +++ b/apps/server/src/automation/AutomationService.test.ts @@ -1,6 +1,8 @@ import { type Automation, type AutomationConfig, + CommandId, + EventId, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -9,7 +11,12 @@ import { type ServerSettings, type VcsCreateWorktreeInput, type OrchestrationCommand, + type OrchestrationEvent, + type OrchestrationLatestTurn, type OrchestrationProjectShell, + type OrchestrationThreadShell, + ThreadId, + TurnId, } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -20,6 +27,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; @@ -61,9 +69,72 @@ const CONFIG: AutomationConfig = { runtimeMode: "full-access", workingCopy: "local", conversation: "fresh", + deleteThreadWhenDone: false, catchUpMinutes: 60, }; +const threadShell = ( + id: ThreadId, + latestTurn: OrchestrationLatestTurn["state"] | null, +): OrchestrationThreadShell => ({ + id, + projectId: PROJECT_ID, + title: "Nightly review", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + pullRequests: [], + branch: null, + worktreePath: null, + latestTurn: + latestTurn === null + ? null + : { + turnId: TurnId.make("turn-1"), + state: latestTurn, + requestedAt: "2026-09-01T00:00:00.000Z", + startedAt: "2026-09-01T00:00:00.000Z", + completedAt: latestTurn === "running" ? null : "2026-09-01T00:01:00.000Z", + assistantMessageId: null, + }, + createdAt: "2026-09-01T00:00:00.000Z", + updatedAt: "2026-09-01T00:00:00.000Z", + archivedAt: null, + settledOverride: null, + settledAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, +}); + +/** The session settling, which is what tells cleanup to look at the thread again. */ +const sessionSettled = (threadId: ThreadId): OrchestrationEvent => ({ + sequence: 2, + eventId: EventId.make(`event-${threadId}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: "2026-09-01T00:01:00.000Z", + commandId: CommandId.make(`command-${threadId}`), + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.session-set", + payload: { + threadId, + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: "2026-09-01T00:01:00.000Z", + }, + }, +}); + const makeLayer = (input: { readonly stateDir: string; readonly commands: Ref.Ref>; @@ -74,6 +145,9 @@ const makeLayer = (input: { readonly gitHubCli?: Partial; /** Runs after a command is recorded, e.g. to hold one up. */ readonly afterRecord?: (command: OrchestrationCommand) => Effect.Effect; + /** Thread shells the projection returns; missing ids read as deleted. */ + readonly threads?: Ref.Ref>; + readonly events?: PubSub.PubSub; }) => AutomationService.layer.pipe( Layer.provide( @@ -84,10 +158,16 @@ const makeLayer = (input: { Effect.andThen(input.afterRecord?.(command) ?? Effect.void), Effect.as({ sequence: 1 }), ), + streamDomainEvents: input.events ? Stream.fromPubSub(input.events) : Stream.never, }), Layer.mock(ProjectionSnapshotQuery)({ getProjectShellById: () => Effect.succeed(Option.fromNullishOr(input.project)), - getThreadShellById: () => Effect.succeed(Option.none()), + getThreadShellById: (threadId) => + input.threads + ? Ref.get(input.threads).pipe( + Effect.map((threads) => Option.fromNullishOr(threads.get(threadId))), + ) + : Effect.succeedNone, }), Layer.mock(ThreadDeletionReactor)({ drainThrough: () => Effect.void }), Layer.mock(GitWorkflowService)(input.git ?? {}), @@ -117,7 +197,7 @@ const withService = ( ...environment }: Pick< Parameters[0], - "settings" | "providers" | "git" | "gitHubCli" | "afterRecord" + "settings" | "providers" | "git" | "gitHubCli" | "afterRecord" | "threads" | "events" > & { /** Seeds `automations.json` before the service reads it. */ readonly automationsFile?: unknown; @@ -384,6 +464,126 @@ describe("AutomationService", () => { ), ); + describe("deleting a run's thread when done", () => { + const cleanupOf = (snapshot: { automations: ReadonlyArray }, threadId: ThreadId) => + snapshot.automations[0]?.runs.find((run) => run.threadId === threadId)?.threadCleanup; + + it.effect("deletes the thread once its turn completes and keeps one that errored", () => + Effect.gen(function* () { + const threads = yield* Ref.make>(new Map()); + const events = yield* PubSub.unbounded(); + yield* withService( + PROJECT, + (service, { commands }) => + Effect.gen(function* () { + const created = yield* service.create({ ...CONFIG, deleteThreadWhenDone: true }); + yield* service.start(); + const deletes = Ref.get(commands).pipe( + Effect.map((all) => + all.flatMap((command) => + command.type === "thread.delete" ? [command.threadId] : [], + ), + ), + ); + const settle = (threadId: ThreadId, state: OrchestrationLatestTurn["state"]) => + Ref.update(threads, (current) => + new Map(current).set(threadId, threadShell(threadId, state)), + ).pipe(Effect.andThen(PubSub.publish(events, sessionSettled(threadId)))); + + // Still running when recorded, so the run waits for its turn. + const finished = yield* service.runNow(created.id); + assert.strictEqual(finished.threadCleanup, "pending"); + const finishedThread = finished.threadId!; + yield* settle(finishedThread, "completed"); + yield* service.changes.pipe( + Stream.filter((snapshot) => cleanupOf(snapshot, finishedThread) === "deleted"), + Stream.runHead, + ); + assert.deepStrictEqual(yield* deletes, [finishedThread]); + + const failed = yield* service.runNow(created.id); + const failedThread = failed.threadId!; + yield* settle(failedThread, "error"); + yield* service.changes.pipe( + Stream.filter( + (snapshot) => + snapshot.automations[0]?.runs.some( + (run) => run.threadId === failedThread && run.threadCleanup === undefined, + ) ?? false, + ), + Stream.runHead, + ); + assert.deepStrictEqual(yield* deletes, [finishedThread]); + }), + { + threads, + events, + // A new thread exists with no turn yet, like right after `thread.create`. + afterRecord: (command) => + command.type === "thread.create" + ? Ref.update(threads, (current) => + new Map(current).set(command.threadId, threadShell(command.threadId, null)), + ) + : Effect.void, + }, + ); + }), + ); + + it.effect("finishes cleanup for turns that completed while the server was down", () => + Effect.gen(function* () { + const threadId = ThreadId.make("finished-offline"); + const threads = yield* Ref.make>( + new Map([[threadId, threadShell(threadId, "completed")]]), + ); + const events = yield* PubSub.unbounded(); + yield* withService( + PROJECT, + (service, { commands }) => + Effect.gen(function* () { + yield* service.start(); + yield* service.changes.pipe( + Stream.filter((snapshot) => cleanupOf(snapshot, threadId) === "deleted"), + Stream.runHead, + ); + const dispatched = yield* Ref.get(commands); + assert.deepStrictEqual( + dispatched.map((command) => command.type), + ["thread.delete"], + ); + }), + { + threads, + events, + automationsFile: { + automations: [ + { + ...CONFIG, + deleteThreadWhenDone: true, + id: "offline", + createdAt: "2026-09-01T00:00:00.000Z", + updatedAt: "2026-09-01T00:00:00.000Z", + scheduleCursor: "2026-09-01T00:00:00.000Z", + githubCursor: null, + runs: [ + { + id: "run-1", + startedAt: "2026-09-01T00:00:00.000Z", + cause: "Manual run", + threadId, + error: null, + threadCleanup: "pending", + }, + ], + }, + ], + }, + }, + ); + }), + ); + }); + it.effect( "an automation on a profiled project runs inside the profile, not on the environment default", () => { diff --git a/apps/server/src/automation/AutomationService.ts b/apps/server/src/automation/AutomationService.ts index ad74b201daf04..3c2061e0a8ff9 100644 --- a/apps/server/src/automation/AutomationService.ts +++ b/apps/server/src/automation/AutomationService.ts @@ -3,7 +3,8 @@ * * The records live in `automations.json` in the state directory. A run creates a thread in the * automation's project (in a fresh worktree or the project checkout) and starts a turn with the - * automation's instructions, the same way a user sending a first message would. + * automation's instructions, the same way a user sending a first message would. With + * `deleteThreadWhenDone`, the run's thread is deleted once that turn completes. * * @module AutomationService */ @@ -16,11 +17,13 @@ import { type AutomationConfig, type AutomationGitHubEvent, type AutomationRun, + type AutomationRunThreadCleanup, type AutomationsSnapshot, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, IsoDateTime, MessageId, + type OrchestrationThreadShell, ThreadId, } from "@t3tools/contracts"; import { @@ -35,6 +38,7 @@ import { resolveProviderProfile, resolveProviderProfileFallbackModelSelection, } from "@t3tools/shared/projectSettings"; +import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -60,6 +64,7 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ThreadDeletionReactor } from "../orchestration/Services/ThreadDeletionReactor.ts"; +import { threadHasQueuedTurnStart } from "../orchestration/ThreadSettlementPolicy.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts"; import { forkParked } from "../serverActivation.ts"; @@ -146,6 +151,38 @@ function githubItemMatches(event: AutomationGitHubEvent, item: GitHubItem): bool } } +/** + * What to do with a run's thread marked for deletion: delete it once its turn completed, keep it + * when the turn errored or was stopped so the user can see why, and wait while work remains. + */ +function runThreadOutcome( + thread: OrchestrationThreadShell, + now: string, +): "delete" | "keep" | "wait" { + if ( + thread.hasPendingApprovals || + thread.hasPendingUserInput || + thread.session?.status === "starting" || + thread.session?.status === "running" || + thread.backgroundLiveness != null || + threadHasQueuedTurnStart(thread, now) + ) { + return "wait"; + } + switch (thread.latestTurn?.state) { + case "completed": + return "delete"; + case "error": + case "interrupted": + return "keep"; + case "running": + return "wait"; + default: + // No turn yet: waiting on it, unless the session failed before it could start. + return thread.session?.status === "error" ? "keep" : "wait"; + } +} + const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fs = yield* FileSystem.FileSystem; @@ -232,6 +269,62 @@ const make = Effect.gen(function* () { const failWith = (message: string) => Effect.fail(new AutomationError({ message })); + /** Sets or clears the cleanup mark on the pending runs of `threadId`. */ + const markRunThread = (threadId: ThreadId, cleanup: AutomationRunThreadCleanup | undefined) => + modify((file) => + Effect.succeed([ + undefined, + { + automations: file.automations.map((automation) => ({ + ...automation, + runs: automation.runs.map((run) => { + if (run.threadId !== threadId || run.threadCleanup !== "pending") return run; + const { threadCleanup: _threadCleanup, ...rest } = run; + return cleanup === undefined ? rest : { ...rest, threadCleanup: cleanup }; + }), + })), + }, + ] as const), + ); + + const cleanupLock = yield* Semaphore.make(1); + /** + * Deletes a pending run's thread once its turn completed. Safe to call at any time; one call at + * a time, so two events for the same finished turn cannot delete its thread twice. + */ + const settleRunThread = (threadId: ThreadId) => + Effect.gen(function* () { + const file = yield* SubscriptionRef.get(state); + const pending = file.automations.some((automation) => + automation.runs.some((run) => run.threadId === threadId && run.threadCleanup === "pending"), + ); + if (!pending) return; + const thread = yield* snapshotQuery + .getThreadShellById(threadId) + .pipe(Effect.map(Option.getOrUndefined)); + if (thread === undefined) { + // Deleted some other way, e.g. by the user. + return yield* markRunThread(threadId, "deleted"); + } + const outcome = runThreadOutcome(thread, yield* nowIso); + if (outcome === "wait") return; + if (outcome === "keep") return yield* markRunThread(threadId, undefined); + yield* engine.dispatch({ + type: "thread.delete", + commandId: CommandId.make(`server:automation-thread-delete:${yield* newId}`), + threadId, + }); + yield* markRunThread(threadId, "deleted"); + }).pipe( + cleanupLock.withPermits(1), + Effect.catchCause((failure) => + Effect.logWarning("automation run thread cleanup failed", { + threadId, + cause: Cause.pretty(failure), + }), + ), + ); + /** * Checks a pull request out detached in a fresh worktree. The PR's branch is usually still * checked out by the thread that wrote it, and git allows a branch in only one worktree, so a @@ -446,17 +539,25 @@ const make = Effect.gen(function* () { ), Effect.flatMap(({ threadId, error }) => Effect.gen(function* () { + // A continued conversation's thread outlives the run, so only fresh ones are deleted. + const cleanUp = + threadId !== null && + automation.deleteThreadWhenDone && + automation.conversation === "fresh"; const run: AutomationRun = { id: yield* newId, startedAt: yield* nowIso, cause, threadId, error, + ...(cleanUp ? { threadCleanup: "pending" as const } : {}), }; yield* patchAutomation(automation.id, (stored) => ({ ...stored, runs: [run, ...stored.runs].slice(0, AUTOMATION_MAX_RUNS), })).pipe(Effect.ignoreCause({ log: true })); + // The turn may have finished before the run was recorded as pending. + if (cleanUp) yield* settleRunThread(threadId); return run; }), ), @@ -624,6 +725,33 @@ const make = Effect.gen(function* () { }); const start = Effect.fn("AutomationService.start")(function* () { + // Off the event stream, so a slow lookup or dispatch never holds up the engine's subscribers. + const cleanup = yield* makeDrainableWorker(settleRunThread); + // Turns that finished while the server was down, checked once events are flowing. + const enqueuePendingRuns = SubscriptionRef.get(state).pipe( + Effect.flatMap((file) => + Effect.forEach( + file.automations.flatMap((automation) => + automation.runs.flatMap((run) => + run.threadId !== null && run.threadCleanup === "pending" ? [run.threadId] : [], + ), + ), + cleanup.enqueue, + { discard: true }, + ), + ), + ); + yield* forkParked( + Stream.runForEach( + engine.streamDomainEvents.pipe(Stream.onStart(enqueuePendingRuns)), + (event) => + event.type === "thread.session-set" || + event.type === "thread.turn-diff-completed" || + event.type === "thread.deleted" + ? cleanup.enqueue(event.payload.threadId) + : Effect.void, + ), + ); yield* forkParked( Effect.all([scheduleTick, githubTick], { discard: true }).pipe( Effect.catchCause((failure) => diff --git a/apps/web/src/components/automations/AutomationsPage.tsx b/apps/web/src/components/automations/AutomationsPage.tsx index 848719ac13f82..40067710b564b 100644 --- a/apps/web/src/components/automations/AutomationsPage.tsx +++ b/apps/web/src/components/automations/AutomationsPage.tsx @@ -124,6 +124,7 @@ interface AutomationDraft { readonly runtimeMode: RuntimeMode; readonly workingCopy: AutomationWorkingCopy; readonly conversation: AutomationConversation; + readonly deleteThreadWhenDone: boolean; readonly catchUpMinutes: number; } @@ -138,6 +139,7 @@ const EMPTY_DRAFT: AutomationDraft = { runtimeMode: DEFAULT_RUNTIME_MODE, workingCopy: "worktree", conversation: "fresh", + deleteThreadWhenDone: false, catchUpMinutes: DEFAULT_AUTOMATION_CATCH_UP_MINUTES, }; @@ -153,6 +155,7 @@ function draftFromAutomation(automation: EnvironmentAutomation): AutomationDraft runtimeMode: automation.runtimeMode, workingCopy: automation.workingCopy, conversation: automation.conversation, + deleteThreadWhenDone: automation.deleteThreadWhenDone, catchUpMinutes: automation.catchUpMinutes, }; } @@ -187,6 +190,7 @@ function configFromDraft( runtimeMode: draft.runtimeMode, workingCopy: draft.workingCopy, conversation: draft.conversation, + deleteThreadWhenDone: draft.deleteThreadWhenDone, catchUpMinutes: draft.catchUpMinutes, }, }; @@ -809,6 +813,22 @@ function AutomationEditor({ onChange={(conversation) => patch({ conversation })} /> + + patch({ deleteThreadWhenDone })} + /> + {formatRelativeTimeLabel(run.startedAt)} - {threadId ? ( + {run.threadCleanup === "deleted" ? ( + Thread deleted + ) : threadId ? ( diff --git a/docs/user/automations.md b/docs/user/automations.md index db41f7da80621..6523352d7b04c 100644 --- a/docs/user/automations.md +++ b/docs/user/automations.md @@ -44,5 +44,11 @@ linked to the pull request. To review newer commits, ask the agent to run **Conversation** chooses between a new thread for each run and continuing the previous run's thread. +**Delete thread when done** deletes each run's thread once the agent finishes, for automations +whose results live elsewhere, such as a pushed branch or a pull request comment. A run that fails +or that you stop keeps its thread so you can see what happened. It only applies to new threads for +each run. The run's worktree is removed too when **Delete worktrees with deleted threads** is on +in **Settings → Storage**. + **Permissions** work like [permission modes](./permission-modes.md). Runs start with nobody watching, so a mode that asks before acting waits until you answer in the thread. diff --git a/packages/contracts/src/automation.ts b/packages/contracts/src/automation.ts index 9815cc45050ae..d0561d1c0900a 100644 --- a/packages/contracts/src/automation.ts +++ b/packages/contracts/src/automation.ts @@ -75,6 +75,13 @@ export type AutomationWorkingCopy = typeof AutomationWorkingCopy.Type; export const AutomationConversation = Schema.Literals(["fresh", "continue"]); export type AutomationConversation = typeof AutomationConversation.Type; +/** + * A run whose thread is deleted once its turn completes: `pending` until then, `deleted` after. + * A turn that errors or is stopped keeps its thread and drops the mark. + */ +export const AutomationRunThreadCleanup = Schema.Literals(["pending", "deleted"]); +export type AutomationRunThreadCleanup = typeof AutomationRunThreadCleanup.Type; + export const AutomationRun = Schema.Struct({ id: TrimmedNonEmptyString, startedAt: IsoDateTime, @@ -82,6 +89,7 @@ export const AutomationRun = Schema.Struct({ cause: Schema.String, threadId: Schema.NullOr(ThreadId), error: Schema.NullOr(Schema.String), + threadCleanup: Schema.optional(AutomationRunThreadCleanup), }); export type AutomationRun = typeof AutomationRun.Type; @@ -102,6 +110,8 @@ export const AutomationConfig = Schema.Struct({ runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))), workingCopy: AutomationWorkingCopy, conversation: AutomationConversation, + /** Delete each run's thread once its turn completes. Only applies to fresh conversations. */ + deleteThreadWhenDone: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), /** How late a missed scheduled run may still start, e.g. after the machine slept. */ catchUpMinutes: NonNegativeInt, }); From d1f9f4b87686ea6a42fb7ef2f1c85912a31de188 Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Wed, 30 Sep 2026 08:40:58 -0300 Subject: [PATCH 2/3] feat(automation): delete finished run threads - Track pending deletions beyond capped run history - Recheck after user activity and background task completion - Guard automatic deletes against stale or active threads --- .../src/automation/AutomationService.test.ts | 351 +++++++++++++----- .../src/automation/AutomationService.ts | 190 +++++++--- .../Layers/OrchestrationEngine.test.ts | 81 ++++ .../Layers/OrchestrationEngine.ts | 12 +- apps/server/src/orchestration/decider.ts | 3 +- .../automations/AutomationsPage.tsx | 2 +- docs/user/automations.md | 5 +- packages/contracts/src/automation.ts | 10 +- packages/contracts/src/orchestration.ts | 13 + 9 files changed, 505 insertions(+), 162 deletions(-) diff --git a/apps/server/src/automation/AutomationService.test.ts b/apps/server/src/automation/AutomationService.test.ts index ded1dd81d637b..2d0183c1db922 100644 --- a/apps/server/src/automation/AutomationService.test.ts +++ b/apps/server/src/automation/AutomationService.test.ts @@ -1,5 +1,6 @@ import { type Automation, + AUTOMATION_MAX_RUNS, type AutomationConfig, CommandId, EventId, @@ -21,6 +22,7 @@ import { import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -37,6 +39,7 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import { ServerConfig } from "../config.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; +import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ThreadDeletionReactor } from "../orchestration/Services/ThreadDeletionReactor.ts"; @@ -76,6 +79,7 @@ const CONFIG: AutomationConfig = { const threadShell = ( id: ThreadId, latestTurn: OrchestrationLatestTurn["state"] | null, + overrides: Partial = {}, ): OrchestrationThreadShell => ({ id, projectId: PROJECT_ID, @@ -107,19 +111,42 @@ const threadShell = ( hasPendingApprovals: false, hasPendingUserInput: false, hasActionableProposedPlan: false, + ...overrides, }); -/** The session settling, which is what tells cleanup to look at the thread again. */ -const sessionSettled = (threadId: ThreadId): OrchestrationEvent => ({ +const threadEventBase = (threadId: ThreadId) => ({ sequence: 2, eventId: EventId.make(`event-${threadId}`), - aggregateKind: "thread", + aggregateKind: "thread" as const, aggregateId: threadId, occurredAt: "2026-09-01T00:01:00.000Z", commandId: CommandId.make(`command-${threadId}`), causationEventId: null, correlationId: null, metadata: {}, +}); + +/** A background task finishing, which can come after the turn and its checkpoint. */ +const taskCompleted = (threadId: ThreadId): OrchestrationEvent => ({ + ...threadEventBase(threadId), + type: "thread.activity-appended", + payload: { + threadId, + activity: { + id: EventId.make(`task-${threadId}`), + tone: "info", + kind: "task.completed", + summary: "Task completed", + payload: {}, + turnId: null, + createdAt: "2026-09-01T00:02:00.000Z", + }, + }, +}); + +/** The session settling, which is what tells cleanup to look at the thread again. */ +const sessionSettled = (threadId: ThreadId): OrchestrationEvent => ({ + ...threadEventBase(threadId), type: "thread.session-set", payload: { threadId, @@ -143,8 +170,10 @@ const makeLayer = (input: { readonly providers?: ReadonlyArray; readonly git?: Partial; readonly gitHubCli?: Partial; - /** Runs after a command is recorded, e.g. to hold one up. */ - readonly afterRecord?: (command: OrchestrationCommand) => Effect.Effect; + /** Runs after a command is recorded, e.g. to hold one up or reject it. */ + readonly afterRecord?: ( + command: OrchestrationCommand, + ) => Effect.Effect; /** Thread shells the projection returns; missing ids read as deleted. */ readonly threads?: Ref.Ref>; readonly events?: PubSub.PubSub; @@ -162,6 +191,7 @@ const makeLayer = (input: { }), Layer.mock(ProjectionSnapshotQuery)({ getProjectShellById: () => Effect.succeed(Option.fromNullishOr(input.project)), + getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }), getThreadShellById: (threadId) => input.threads ? Ref.get(input.threads).pipe( @@ -465,123 +495,258 @@ describe("AutomationService", () => { ); describe("deleting a run's thread when done", () => { - const cleanupOf = (snapshot: { automations: ReadonlyArray }, threadId: ThreadId) => - snapshot.automations[0]?.runs.find((run) => run.threadId === threadId)?.threadCleanup; - - it.effect("deletes the thread once its turn completes and keeps one that errored", () => + const isDeleted = (snapshot: { automations: ReadonlyArray }, threadId: ThreadId) => + snapshot.automations[0]?.runs.some((run) => run.threadId === threadId && run.threadDeleted) ?? + false; + + /** + * A service with cleanup started, whose projection starts each new thread without a turn. + * The cleanup worker checks threads in order, so once a later thread is deleted every + * earlier check has been decided. + */ + const withCleanup = ( + body: (context: { + readonly service: AutomationService.AutomationService["Service"]; + readonly automationId: string; + readonly setThread: (thread: OrchestrationThreadShell) => Effect.Effect; + readonly publish: (event: OrchestrationEvent) => Effect.Effect; + readonly deletes: Effect.Effect>; + readonly waitDeleted: (threadId: ThreadId) => Effect.Effect; + }) => Effect.Effect, + options: { + readonly threads?: ReadonlyArray; + readonly automationsFile?: unknown; + /** Runs when a delete is dispatched; fail to reject it like the engine guard would. */ + readonly onDelete?: ( + threadId: ThreadId, + projection: { + readonly setThread: (thread: OrchestrationThreadShell) => Effect.Effect; + readonly publish: (event: OrchestrationEvent) => Effect.Effect; + }, + ) => Effect.Effect; + } = {}, + ) => Effect.gen(function* () { - const threads = yield* Ref.make>(new Map()); + const threads = yield* Ref.make>( + new Map((options.threads ?? []).map((thread) => [thread.id, thread])), + ); const events = yield* PubSub.unbounded(); - yield* withService( + const setThread = (thread: OrchestrationThreadShell) => + Ref.update(threads, (current) => new Map(current).set(thread.id, thread)); + const publish = (event: OrchestrationEvent) => + PubSub.publish(events, event).pipe(Effect.asVoid); + return yield* withService( PROJECT, (service, { commands }) => Effect.gen(function* () { - const created = yield* service.create({ ...CONFIG, deleteThreadWhenDone: true }); + const automationId = + options.automationsFile === undefined + ? (yield* service.create({ ...CONFIG, deleteThreadWhenDone: true })).id + : "offline"; yield* service.start(); - const deletes = Ref.get(commands).pipe( - Effect.map((all) => - all.flatMap((command) => - command.type === "thread.delete" ? [command.threadId] : [], + return yield* body({ + service, + automationId, + setThread, + publish, + deletes: Ref.get(commands).pipe( + Effect.map((all) => + all.flatMap((command) => + command.type === "thread.auto-delete" ? [command.threadId] : [], + ), ), ), - ); - const settle = (threadId: ThreadId, state: OrchestrationLatestTurn["state"]) => - Ref.update(threads, (current) => - new Map(current).set(threadId, threadShell(threadId, state)), - ).pipe(Effect.andThen(PubSub.publish(events, sessionSettled(threadId)))); - - // Still running when recorded, so the run waits for its turn. - const finished = yield* service.runNow(created.id); - assert.strictEqual(finished.threadCleanup, "pending"); - const finishedThread = finished.threadId!; - yield* settle(finishedThread, "completed"); - yield* service.changes.pipe( - Stream.filter((snapshot) => cleanupOf(snapshot, finishedThread) === "deleted"), - Stream.runHead, - ); - assert.deepStrictEqual(yield* deletes, [finishedThread]); - - const failed = yield* service.runNow(created.id); - const failedThread = failed.threadId!; - yield* settle(failedThread, "error"); - yield* service.changes.pipe( - Stream.filter( - (snapshot) => - snapshot.automations[0]?.runs.some( - (run) => run.threadId === failedThread && run.threadCleanup === undefined, - ) ?? false, - ), - Stream.runHead, - ); - assert.deepStrictEqual(yield* deletes, [finishedThread]); + waitDeleted: (threadId) => + service.changes.pipe( + Stream.filter((snapshot) => isDeleted(snapshot, threadId)), + Stream.runHead, + Effect.asVoid, + ), + }); }), { threads, events, - // A new thread exists with no turn yet, like right after `thread.create`. + ...(options.automationsFile === undefined + ? {} + : { automationsFile: options.automationsFile }), afterRecord: (command) => command.type === "thread.create" - ? Ref.update(threads, (current) => - new Map(current).set(command.threadId, threadShell(command.threadId, null)), - ) - : Effect.void, + ? setThread(threadShell(command.threadId, null)) + : command.type === "thread.auto-delete" + ? (options.onDelete?.(command.threadId, { setThread, publish }) ?? Effect.void) + : Effect.void, }, ); - }), + }); + + it.effect("deletes the thread once its turn completes and keeps one that errored", () => + withCleanup(({ service, automationId, setThread, publish, deletes, waitDeleted }) => + Effect.gen(function* () { + const failed = (yield* service.runNow(automationId)).threadId!; + const finished = (yield* service.runNow(automationId)).threadId!; + yield* setThread(threadShell(failed, "error")); + yield* publish(sessionSettled(failed)); + yield* setThread(threadShell(finished, "completed")); + yield* publish(sessionSettled(finished)); + yield* waitDeleted(finished); + assert.deepStrictEqual(yield* deletes, [finished]); + + // The errored thread was let go, so a later completion does not delete it either. + const sentinel = (yield* service.runNow(automationId)).threadId!; + yield* setThread(threadShell(failed, "completed")); + yield* publish(sessionSettled(failed)); + yield* setThread(threadShell(sentinel, "completed")); + yield* publish(sessionSettled(sentinel)); + yield* waitDeleted(sentinel); + assert.deepStrictEqual(yield* deletes, [finished, sentinel]); + }), + ), ); - it.effect("finishes cleanup for turns that completed while the server was down", () => + it.effect("keeps a thread the user wrote in after the engine rejects a stale delete", () => Effect.gen(function* () { - const threadId = ThreadId.make("finished-offline"); - const threads = yield* Ref.make>( - new Map([[threadId, threadShell(threadId, "completed")]]), - ); - const events = yield* PubSub.unbounded(); - yield* withService( - PROJECT, - (service, { commands }) => + const rejected = yield* Ref.make>([]); + yield* withCleanup( + ({ service, automationId, setThread, publish, deletes, waitDeleted }) => Effect.gen(function* () { - yield* service.start(); - yield* service.changes.pipe( - Stream.filter((snapshot) => cleanupOf(snapshot, threadId) === "deleted"), - Stream.runHead, - ); - const dispatched = yield* Ref.get(commands); - assert.deepStrictEqual( - dispatched.map((command) => command.type), - ["thread.delete"], + const adopted = (yield* service.runNow(automationId)).threadId!; + const sentinel = (yield* service.runNow(automationId)).threadId!; + yield* setThread(threadShell(adopted, "completed")); + yield* publish(sessionSettled(adopted)); + yield* setThread(threadShell(sentinel, "completed")); + yield* publish(sessionSettled(sentinel)); + yield* waitDeleted(sentinel); + assert.deepStrictEqual(yield* Ref.get(rejected), [adopted]); + + // The user's turn finishing later still leaves the thread alone. + const laterSentinel = (yield* service.runNow(automationId)).threadId!; + yield* setThread( + threadShell(adopted, "completed", { + latestUserMessageAt: "2026-09-01T00:03:00.000Z", + }), ); + yield* publish(sessionSettled(adopted)); + yield* setThread(threadShell(laterSentinel, "completed")); + yield* publish(sessionSettled(laterSentinel)); + yield* waitDeleted(laterSentinel); + assert.deepStrictEqual(yield* deletes, [adopted, sentinel, laterSentinel]); }), { - threads, - events, - automationsFile: { - automations: [ - { - ...CONFIG, - deleteThreadWhenDone: true, - id: "offline", - createdAt: "2026-09-01T00:00:00.000Z", - updatedAt: "2026-09-01T00:00:00.000Z", - scheduleCursor: "2026-09-01T00:00:00.000Z", - githubCursor: null, - runs: [ - { - id: "run-1", - startedAt: "2026-09-01T00:00:00.000Z", - cause: "Manual run", + // The user's message lands after cleanup read the thread and before the engine + // decides the delete, so the engine rejects it and the message queues another check. + onDelete: (threadId, { setThread, publish }) => + Effect.gen(function* () { + if ((yield* Ref.get(rejected)).length > 0) return; + yield* Ref.set(rejected, [threadId]); + yield* setThread( + threadShell(threadId, "running", { + latestUserMessageAt: "2026-09-01T00:03:00.000Z", + session: { threadId, - error: null, - threadCleanup: "pending", + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.make("turn-2"), + lastError: null, + updatedAt: "2026-09-01T00:03:00.000Z", }, - ], - }, - ], - }, + }), + ); + yield* publish(sessionSettled(threadId)); + return yield* new OrchestrationCommandInvariantError({ + commandType: "thread.auto-delete", + detail: "thread changed before automatic deletion", + }); + }), }, ); }), ); + + it.effect("rechecks when a background task outlasting the turn finishes", () => + withCleanup(({ service, automationId, setThread, publish, deletes, waitDeleted }) => + Effect.gen(function* () { + const threadId = (yield* service.runNow(automationId)).threadId!; + const sentinel = (yield* service.runNow(automationId)).threadId!; + // The turn and its checkpoint are done, but a subagent is still working. + yield* setThread(threadShell(threadId, "completed", { backgroundLiveness: "working" })); + yield* publish(sessionSettled(threadId)); + yield* setThread(threadShell(sentinel, "completed")); + yield* publish(sessionSettled(sentinel)); + yield* waitDeleted(sentinel); + assert.deepStrictEqual(yield* deletes, [sentinel]); + + // Finishing the task emits only an activity, no session or checkpoint event. + yield* setThread(threadShell(threadId, "completed")); + yield* publish(taskCompleted(threadId)); + yield* waitDeleted(threadId); + assert.deepStrictEqual(yield* deletes, [sentinel, threadId]); + }), + ), + ); + + it.effect("still deletes a thread whose run fell out of the run history", () => + Effect.gen(function* () { + const deleted = yield* Deferred.make(); + yield* withCleanup( + ({ service, automationId, setThread, publish }) => + Effect.gen(function* () { + const oldest = (yield* service.runNow(automationId)).threadId!; + for (let index = 0; index < AUTOMATION_MAX_RUNS; index++) { + yield* service.runNow(automationId); + } + const snapshot = yield* service.changes.pipe(Stream.runHead); + assert.isFalse( + Option.getOrThrow(snapshot).automations[0]!.runs.some( + (run) => run.threadId === oldest, + ), + ); + yield* setThread(threadShell(oldest, "completed")); + yield* publish(sessionSettled(oldest)); + assert.strictEqual(yield* Deferred.await(deleted), oldest); + }), + { onDelete: (threadId) => Deferred.succeed(deleted, threadId).pipe(Effect.asVoid) }, + ); + }), + ); + + it.effect("finishes cleanup for turns that completed while the server was down", () => { + const threadId = ThreadId.make("finished-offline"); + return withCleanup( + ({ deletes, waitDeleted }) => + Effect.gen(function* () { + yield* waitDeleted(threadId); + assert.deepStrictEqual(yield* deletes, [threadId]); + }), + { + threads: [threadShell(threadId, "completed")], + automationsFile: { + automations: [ + { + ...CONFIG, + deleteThreadWhenDone: true, + id: "offline", + createdAt: "2026-09-01T00:00:00.000Z", + updatedAt: "2026-09-01T00:00:00.000Z", + scheduleCursor: "2026-09-01T00:00:00.000Z", + githubCursor: null, + pendingThreadDeletes: [{ threadId, messageAt: "2026-09-01T00:00:00.000Z" }], + runs: [ + { + id: "run-1", + startedAt: "2026-09-01T00:00:00.000Z", + cause: "Manual run", + threadId, + error: null, + }, + ], + }, + ], + }, + }, + ); + }); }); it.effect( diff --git a/apps/server/src/automation/AutomationService.ts b/apps/server/src/automation/AutomationService.ts index 3c2061e0a8ff9..9bf068912ed7c 100644 --- a/apps/server/src/automation/AutomationService.ts +++ b/apps/server/src/automation/AutomationService.ts @@ -17,7 +17,6 @@ import { type AutomationConfig, type AutomationGitHubEvent, type AutomationRun, - type AutomationRunThreadCleanup, type AutomationsSnapshot, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, @@ -71,7 +70,14 @@ import { forkParked } from "../serverActivation.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as GitHubCli from "../sourceControl/GitHubCli.ts"; -/** What the file keeps beyond the public record: how far each trigger source has been read. */ +/** A run thread to delete once its turn finishes; `messageAt` is when the run's message was sent. */ +const PendingThreadDelete = Schema.Struct({ threadId: ThreadId, messageAt: IsoDateTime }); +type PendingThreadDelete = typeof PendingThreadDelete.Type; + +/** + * What the file keeps beyond the public record: how far each trigger source has been read, and + * which run threads still need deleting. + */ const StoredAutomation = Schema.Struct({ ...Automation.fields, /** @@ -81,6 +87,10 @@ const StoredAutomation = Schema.Struct({ scheduleCursor: IsoDateTime, /** GitHub items created at or before this instant have been handled; null until first poll. */ githubCursor: Schema.NullOr(IsoDateTime), + /** Kept apart from the capped run history, so newer runs cannot drop an older run's cleanup. */ + pendingThreadDeletes: Schema.Array(PendingThreadDelete).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), }); type StoredAutomation = typeof StoredAutomation.Type; @@ -128,10 +138,26 @@ export class AutomationService extends Context.Service< >()("t3/automation/AutomationService") {} function toPublic(stored: StoredAutomation): Automation { - const { scheduleCursor: _scheduleCursor, githubCursor: _githubCursor, ...automation } = stored; + const { + scheduleCursor: _scheduleCursor, + githubCursor: _githubCursor, + pendingThreadDeletes: _pendingThreadDeletes, + ...automation + } = stored; return automation; } +function findPendingThreadDelete( + file: AutomationsFile, + threadId: ThreadId, +): PendingThreadDelete | undefined { + for (const automation of file.automations) { + const pending = automation.pendingThreadDeletes.find((entry) => entry.threadId === threadId); + if (pending) return pending; + } + return undefined; +} + function toSnapshot(file: AutomationsFile): AutomationsSnapshot { return { automations: file.automations.map(toPublic), @@ -153,12 +179,21 @@ function githubItemMatches(event: AutomationGitHubEvent, item: GitHubItem): bool /** * What to do with a run's thread marked for deletion: delete it once its turn completed, keep it - * when the turn errored or was stopped so the user can see why, and wait while work remains. + * when the turn errored or was stopped so the user can see why or when the user wrote in it, and + * wait while work remains. */ function runThreadOutcome( thread: OrchestrationThreadShell, + pending: PendingThreadDelete, now: string, ): "delete" | "keep" | "wait" { + // Server-stamped, so a later message is the user's, not the run's. + if ( + thread.latestUserMessageAt !== null && + Date.parse(thread.latestUserMessageAt) > Date.parse(pending.messageAt) + ) { + return "keep"; + } if ( thread.hasPendingApprovals || thread.hasPendingUserInput || @@ -269,52 +304,65 @@ const make = Effect.gen(function* () { const failWith = (message: string) => Effect.fail(new AutomationError({ message })); - /** Sets or clears the cleanup mark on the pending runs of `threadId`. */ - const markRunThread = (threadId: ThreadId, cleanup: AutomationRunThreadCleanup | undefined) => + /** Drops the pending delete for `threadId`, marking its run when the thread is gone. */ + const finishPendingThreadDelete = (threadId: ThreadId, deleted: boolean) => modify((file) => Effect.succeed([ undefined, { - automations: file.automations.map((automation) => ({ - ...automation, - runs: automation.runs.map((run) => { - if (run.threadId !== threadId || run.threadCleanup !== "pending") return run; - const { threadCleanup: _threadCleanup, ...rest } = run; - return cleanup === undefined ? rest : { ...rest, threadCleanup: cleanup }; - }), - })), + automations: file.automations.map((automation) => + automation.pendingThreadDeletes.some((entry) => entry.threadId === threadId) + ? { + ...automation, + pendingThreadDeletes: automation.pendingThreadDeletes.filter( + (entry) => entry.threadId !== threadId, + ), + runs: deleted + ? automation.runs.map((run) => + run.threadId === threadId ? { ...run, threadDeleted: true } : run, + ) + : automation.runs, + } + : automation, + ), }, ] as const), ); const cleanupLock = yield* Semaphore.make(1); /** - * Deletes a pending run's thread once its turn completed. Safe to call at any time; one call at - * a time, so two events for the same finished turn cannot delete its thread twice. + * Deletes a pending run thread once its turn completed. Safe to call at any time. The delete + * is guarded by the projection sequence read before the thread, so the engine rejects it if + * anything, such as a new user message, reached the thread after that read. */ const settleRunThread = (threadId: ThreadId) => Effect.gen(function* () { - const file = yield* SubscriptionRef.get(state); - const pending = file.automations.some((automation) => - automation.runs.some((run) => run.threadId === threadId && run.threadCleanup === "pending"), - ); - if (!pending) return; + const pending = findPendingThreadDelete(yield* SubscriptionRef.get(state), threadId); + if (pending === undefined) return; + const { snapshotSequence } = yield* snapshotQuery.getSnapshotSequence(); const thread = yield* snapshotQuery .getThreadShellById(threadId) .pipe(Effect.map(Option.getOrUndefined)); if (thread === undefined) { // Deleted some other way, e.g. by the user. - return yield* markRunThread(threadId, "deleted"); + return yield* finishPendingThreadDelete(threadId, true); } - const outcome = runThreadOutcome(thread, yield* nowIso); + const outcome = runThreadOutcome(thread, pending, yield* nowIso); if (outcome === "wait") return; - if (outcome === "keep") return yield* markRunThread(threadId, undefined); - yield* engine.dispatch({ - type: "thread.delete", - commandId: CommandId.make(`server:automation-thread-delete:${yield* newId}`), - threadId, - }); - yield* markRunThread(threadId, "deleted"); + if (outcome === "keep") return yield* finishPendingThreadDelete(threadId, false); + const deleted = yield* engine + .dispatch({ + type: "thread.auto-delete", + commandId: CommandId.make(`server:automation-thread-delete:${yield* newId}`), + threadId, + snapshotSequence, + }) + .pipe( + Effect.as(true), + // The thread changed after the read; whatever changed it queues another check. + Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.succeed(false)), + ); + if (deleted) yield* finishPendingThreadDelete(threadId, true); }).pipe( cleanupLock.withPermits(1), Effect.catchCause((failure) => @@ -520,9 +568,9 @@ const make = Effect.gen(function* () { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, createdAt, }); - return threadId; + return { threadId, messageAt: createdAt }; }).pipe( - Effect.map((threadId) => ({ threadId, error: null })), + Effect.map(({ threadId, messageAt }) => ({ threadId, messageAt, error: null })), Effect.catchCause((failure) => Effect.logWarning("automation run failed", { automationId: automation.id, @@ -530,6 +578,7 @@ const make = Effect.gen(function* () { }).pipe( Effect.as({ threadId: null, + messageAt: null, error: Cause.squash(failure) instanceof Error ? (Cause.squash(failure) as Error).message @@ -537,27 +586,32 @@ const make = Effect.gen(function* () { }), ), ), - Effect.flatMap(({ threadId, error }) => + Effect.flatMap(({ threadId, messageAt, error }) => Effect.gen(function* () { // A continued conversation's thread outlives the run, so only fresh ones are deleted. - const cleanUp = + const pendingDelete = threadId !== null && + messageAt !== null && automation.deleteThreadWhenDone && - automation.conversation === "fresh"; + automation.conversation === "fresh" + ? { threadId, messageAt } + : null; const run: AutomationRun = { id: yield* newId, startedAt: yield* nowIso, cause, threadId, error, - ...(cleanUp ? { threadCleanup: "pending" as const } : {}), }; yield* patchAutomation(automation.id, (stored) => ({ ...stored, runs: [run, ...stored.runs].slice(0, AUTOMATION_MAX_RUNS), + pendingThreadDeletes: pendingDelete + ? [...stored.pendingThreadDeletes, pendingDelete] + : stored.pendingThreadDeletes, })).pipe(Effect.ignoreCause({ log: true })); - // The turn may have finished before the run was recorded as pending. - if (cleanUp) yield* settleRunThread(threadId); + // The turn may have finished before its delete was recorded. + if (pendingDelete) yield* settleRunThread(pendingDelete.threadId); return run; }), ), @@ -726,30 +780,47 @@ const make = Effect.gen(function* () { const start = Effect.fn("AutomationService.start")(function* () { // Off the event stream, so a slow lookup or dispatch never holds up the engine's subscribers. - const cleanup = yield* makeDrainableWorker(settleRunThread); + // A thread already queued is not queued again; it is dequeued before it is read, so an event + // arriving during a check still queues the next one. + const queued = new Set(); + const cleanup = yield* makeDrainableWorker((threadId: ThreadId) => + Effect.suspend(() => { + queued.delete(threadId); + return settleRunThread(threadId); + }), + ); + const recheck = (threadId: ThreadId) => + SubscriptionRef.get(state).pipe( + Effect.flatMap((file) => { + if (queued.has(threadId) || findPendingThreadDelete(file, threadId) === undefined) { + return Effect.void; + } + queued.add(threadId); + return cleanup.enqueue(threadId); + }), + ); // Turns that finished while the server was down, checked once events are flowing. - const enqueuePendingRuns = SubscriptionRef.get(state).pipe( + const recheckAll = SubscriptionRef.get(state).pipe( Effect.flatMap((file) => Effect.forEach( file.automations.flatMap((automation) => - automation.runs.flatMap((run) => - run.threadId !== null && run.threadCleanup === "pending" ? [run.threadId] : [], - ), + automation.pendingThreadDeletes.map((entry) => entry.threadId), ), - cleanup.enqueue, + recheck, { discard: true }, ), ), ); yield* forkParked( - Stream.runForEach( - engine.streamDomainEvents.pipe(Stream.onStart(enqueuePendingRuns)), - (event) => - event.type === "thread.session-set" || - event.type === "thread.turn-diff-completed" || - event.type === "thread.deleted" - ? cleanup.enqueue(event.payload.threadId) - : Effect.void, + Stream.runForEach(engine.streamDomainEvents.pipe(Stream.onStart(recheckAll)), (event) => + // Session and checkpoint events end a turn; activities resolve requests and end + // background tasks, which can outlast both. + event.type === "thread.session-set" || + event.type === "thread.turn-diff-completed" || + event.type === "thread.activity-appended" || + event.type === "thread.deleted" + ? recheck(event.payload.threadId) + : Effect.void, ), ); yield* forkParked( @@ -765,7 +836,10 @@ const make = Effect.gen(function* () { const buildStored = ( config: AutomationConfig, - base: Pick, + base: Pick< + StoredAutomation, + "id" | "createdAt" | "runs" | "githubCursor" | "pendingThreadDeletes" + >, now: string, ): StoredAutomation => ({ ...config, @@ -774,6 +848,8 @@ const make = Effect.gen(function* () { createdAt: base.createdAt, runs: base.runs, githubCursor: base.githubCursor, + // Turning the setting off also spares threads of runs still going. + pendingThreadDeletes: config.deleteThreadWhenDone ? base.pendingThreadDeletes : [], updatedAt: now, // Editing restarts the schedule from now, so saving never replays a time that already passed. scheduleCursor: now, @@ -788,7 +864,13 @@ const make = Effect.gen(function* () { const now = yield* nowIso; const stored = buildStored( config, - { id: yield* newId, createdAt: now, runs: [], githubCursor: null }, + { + id: yield* newId, + createdAt: now, + runs: [], + githubCursor: null, + pendingThreadDeletes: [], + }, now, ); yield* modify((file) => diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index 9ccf78ca1744c..f2428e33cce95 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -701,6 +701,87 @@ describe("OrchestrationEngine", () => { }).pipe(Effect.provide(makeOrchestrationLayer())), ); + effectIt.effect( + "rejects an automatic delete after the thread changed or with live background work", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(now())); + const engine = yield* OrchestrationEngineService; + const snapshots = yield* ProjectionSnapshotQuery; + const backgroundLiveness = yield* ThreadBackgroundLiveness.ThreadBackgroundLivenessService; + const projectId = ProjectId.make("project-auto-delete-guard"); + const threadId = ThreadId.make("thread-auto-delete-guarded"); + + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.make("cmd-auto-delete-guard-project"), + projectId, + title: "Project", + workspaceRoot: "/tmp/project-auto-delete-guard", + createdAt: now(), + }); + yield* engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-auto-delete-guard-thread"), + threadId, + projectId, + title: "Thread", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt: now(), + }); + + // Any thread event after the caller's read, such as a new user message, rejects it. + const readSequence = yield* engine.latestSequence; + yield* engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.make("cmd-auto-delete-guard-meta"), + threadId, + title: "Changed", + }); + const stale = yield* engine + .dispatch({ + type: "thread.auto-delete", + commandId: CommandId.make("cmd-auto-delete-stale"), + threadId, + snapshotSequence: readSequence, + }) + .pipe(Effect.flip); + expect(stale._tag).toBe("OrchestrationCommandInvariantError"); + + const freshSequence = yield* engine.latestSequence; + backgroundLiveness.recordTaskLiveness({ + threadId, + taskId: "task-working", + taskType: "subagent", + status: undefined, + kind: "started", + }); + const live = yield* engine + .dispatch({ + type: "thread.auto-delete", + commandId: CommandId.make("cmd-auto-delete-live"), + threadId, + snapshotSequence: freshSequence, + }) + .pipe(Effect.flip); + expect(live._tag).toBe("OrchestrationCommandInvariantError"); + expect(yield* engine.latestSequence).toBe(freshSequence); + backgroundLiveness.clearThreadLiveness(threadId); + + yield* engine.dispatch({ + type: "thread.auto-delete", + commandId: CommandId.make("cmd-auto-delete-fresh"), + threadId, + snapshotSequence: freshSequence, + }); + expect(Option.isNone(yield* snapshots.getThreadShellById(threadId))).toBe(true); + }).pipe(Effect.provide(makeOrchestrationLayer())), + ); + it("persists deterministic read models for repeated snapshot reads", async () => { const createdAt = now(); const system = await createOrchestrationSystem(); diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 9136d080c1c37..6cfeb434d56e5 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -172,7 +172,8 @@ const makeOrchestrationEngine = Effect.gen(function* () { } if ( - envelope.command.type === "thread.auto-settle" && + (envelope.command.type === "thread.auto-settle" || + envelope.command.type === "thread.auto-delete") && (yield* eventStore.hasEventAfter({ aggregateKind: "thread", aggregateId: envelope.command.threadId, @@ -181,7 +182,11 @@ const makeOrchestrationEngine = Effect.gen(function* () { ) { return yield* new OrchestrationCommandInvariantError({ commandType: envelope.command.type, - detail: `thread ${envelope.command.threadId} changed before automatic settlement`, + detail: `thread ${envelope.command.threadId} changed before ${ + envelope.command.type === "thread.auto-settle" + ? "automatic settlement" + : "automatic deletion" + }`, }); } @@ -203,7 +208,8 @@ const makeOrchestrationEngine = Effect.gen(function* () { } if ( - envelope.command.type === "thread.auto-settle" && + (envelope.command.type === "thread.auto-settle" || + envelope.command.type === "thread.auto-delete") && threadBackgroundLiveness.getThreadBackgroundLiveness(envelope.command.threadId) !== null ) { return yield* new OrchestrationCommandInvariantError({ diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 21df39a162e6b..a6c795df2a5c1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -410,7 +410,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }; } - case "thread.delete": { + case "thread.delete": + case "thread.auto-delete": { yield* requireThread({ readModel, command, diff --git a/apps/web/src/components/automations/AutomationsPage.tsx b/apps/web/src/components/automations/AutomationsPage.tsx index 40067710b564b..bb0f5ca21bdbc 100644 --- a/apps/web/src/components/automations/AutomationsPage.tsx +++ b/apps/web/src/components/automations/AutomationsPage.tsx @@ -1457,7 +1457,7 @@ function RunHistory({ {formatRelativeTimeLabel(run.startedAt)} - {run.threadCleanup === "deleted" ? ( + {run.threadDeleted ? ( Thread deleted ) : threadId ? (