diff --git a/apps/server/src/automation/AutomationService.test.ts b/apps/server/src/automation/AutomationService.test.ts index 529b29e82d18b..346520ebdead5 100644 --- a/apps/server/src/automation/AutomationService.test.ts +++ b/apps/server/src/automation/AutomationService.test.ts @@ -1,6 +1,9 @@ import { type Automation, + AUTOMATION_MAX_RUNS, type AutomationConfig, + CommandId, + EventId, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -9,17 +12,25 @@ 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"; import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; 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"; @@ -29,6 +40,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"; @@ -61,9 +73,96 @@ const CONFIG: AutomationConfig = { runtimeMode: "full-access", workingCopy: "local", conversation: "fresh", + deleteThreadWhenDone: false, catchUpMinutes: 60, }; +const threadShell = ( + id: ThreadId, + latestTurn: OrchestrationLatestTurn["state"] | null, + overrides: Partial = {}, +): 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, + ...overrides, +}); + +const threadEventBase = (threadId: ThreadId) => ({ + sequence: 2, + eventId: EventId.make(`event-${threadId}`), + 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, + 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>; @@ -72,8 +171,15 @@ 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; + /** Completed once the service subscribes to `events`; earlier publishes are not seen. */ + readonly subscribed?: Deferred.Deferred; }) => AutomationService.layer.pipe( Layer.provide( @@ -84,10 +190,26 @@ const makeLayer = (input: { Effect.andThen(input.afterRecord?.(command) ?? Effect.void), Effect.as({ sequence: 1 }), ), + streamDomainEvents: input.events + ? Stream.unwrap( + PubSub.subscribe(input.events).pipe( + Effect.tap(() => + input.subscribed ? Deferred.succeed(input.subscribed, undefined) : Effect.void, + ), + Effect.map(Stream.fromSubscription), + ), + ) + : Stream.never, }), Layer.mock(ProjectionSnapshotQuery)({ getProjectShellById: () => Effect.succeed(Option.fromNullishOr(input.project)), - getThreadShellById: () => Effect.succeed(Option.none()), + getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }), + 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 +239,14 @@ const withService = ( ...environment }: Pick< Parameters[0], - "settings" | "providers" | "git" | "gitHubCli" | "afterRecord" + | "settings" + | "providers" + | "git" + | "gitHubCli" + | "afterRecord" + | "threads" + | "events" + | "subscribed" > & { /** Seeds `automations.json` before the service reads it. */ readonly automationsFile?: unknown; @@ -137,8 +266,10 @@ const withService = ( ); } const commands = yield* Ref.make>([]); - const service = yield* AutomationService.AutomationService.pipe( - Effect.provide(makeLayer({ stateDir, commands, project, ...environment })), + // Built in the test's scope, so the service's background work lives as long as the test. + const service = Context.get( + yield* Layer.build(makeLayer({ stateDir, commands, project, ...environment })), + AutomationService.AutomationService, ); return yield* body(service, { stateDir, commands }); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); @@ -384,6 +515,345 @@ describe("AutomationService", () => { ), ); + describe("deleting a run's thread when done", () => { + 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; + /** Runs as a run starts its turn, while the run is still being set up. */ + readonly onTurnStart?: (automation: { + readonly service: AutomationService.AutomationService["Service"]; + readonly automationId: string; + }) => Effect.Effect; + } = {}, + ) => + Effect.gen(function* () { + const threads = yield* Ref.make>( + new Map((options.threads ?? []).map((thread) => [thread.id, thread])), + ); + const events = yield* PubSub.unbounded(); + const subscribed = yield* Deferred.make(); + 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); + const automation = yield* Ref.make<{ + readonly service: AutomationService.AutomationService["Service"]; + readonly automationId: string; + } | null>(null); + return yield* withService( + PROJECT, + (service, { commands }) => + Effect.gen(function* () { + const automationId = + options.automationsFile === undefined + ? (yield* service.create({ ...CONFIG, deleteThreadWhenDone: true })).id + : "offline"; + yield* Ref.set(automation, { service, automationId }); + yield* service.start(); + yield* Deferred.await(subscribed); + 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] : [], + ), + ), + ), + waitDeleted: (threadId) => + service.changes.pipe( + Stream.filter((snapshot) => isDeleted(snapshot, threadId)), + Stream.runHead, + Effect.asVoid, + ), + }); + }), + { + threads, + events, + subscribed, + ...(options.automationsFile === undefined + ? {} + : { automationsFile: options.automationsFile }), + afterRecord: (command) => + command.type === "thread.create" + ? setThread(threadShell(command.threadId, null)) + : command.type === "thread.auto-delete" + ? (options.onDelete?.(command.threadId, { setThread, publish }) ?? Effect.void) + : command.type === "thread.turn.start" && options.onTurnStart + ? Ref.get(automation).pipe( + Effect.flatMap((current) => + current ? options.onTurnStart!(current) : 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("keeps a thread the user wrote in after the engine rejects a stale delete", () => + Effect.gen(function* () { + const rejected = yield* Ref.make>([]); + yield* withCleanup( + ({ service, automationId, setThread, publish, deletes, waitDeleted }) => + Effect.gen(function* () { + 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]); + }), + { + // 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, + 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("retries a rejected delete even when no watched event follows", () => + Effect.gen(function* () { + const rejected = yield* Ref.make(false); + yield* withCleanup( + ({ service, automationId, setThread, publish, deletes, waitDeleted }) => + Effect.gen(function* () { + const threadId = (yield* service.runNow(automationId)).threadId!; + yield* setThread(threadShell(threadId, "completed")); + yield* publish(sessionSettled(threadId)); + yield* waitDeleted(threadId); + assert.deepStrictEqual(yield* deletes, [threadId, threadId]); + }), + { + // Like a title or pull request update landing after the read: the engine rejects + // the delete, and the change emits nothing cleanup subscribes to. + onDelete: () => + Ref.getAndSet(rejected, true).pipe( + Effect.flatMap((already) => + already + ? Effect.void + : Effect.fail( + new OrchestrationCommandInvariantError({ + commandType: "thread.auto-delete", + detail: "thread changed before automatic deletion", + }), + ), + ), + ), + }, + ); + }), + ); + + it.effect("turning the setting off while a run starts spares that run's thread", () => + Effect.gen(function* () { + const disabled = yield* Ref.make(false); + yield* withCleanup( + ({ service, automationId, setThread, publish, deletes, waitDeleted }) => + Effect.gen(function* () { + const spared = (yield* service.runNow(automationId)).threadId!; + // Turned back on, it applies to the next run only. + yield* service.update(automationId, { ...CONFIG, deleteThreadWhenDone: true }); + const sentinel = (yield* service.runNow(automationId)).threadId!; + yield* setThread(threadShell(spared, "completed")); + yield* publish(sessionSettled(spared)); + yield* setThread(threadShell(sentinel, "completed")); + yield* publish(sessionSettled(sentinel)); + yield* waitDeleted(sentinel); + assert.deepStrictEqual(yield* deletes, [sentinel]); + }), + { + // Only the first run: the user saves the automation with the setting off meanwhile. + onTurnStart: ({ service, automationId }) => + Ref.getAndSet(disabled, true).pipe( + Effect.flatMap((already) => + already + ? Effect.void + : service.update(automationId, CONFIG).pipe(Effect.orDie, Effect.asVoid), + ), + ), + }, + ); + }), + ); + + 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( "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..5986d32c83d2c 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 */ @@ -21,6 +22,7 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, IsoDateTime, MessageId, + type OrchestrationThreadShell, ThreadId, } from "@t3tools/contracts"; import { @@ -35,6 +37,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,13 +63,21 @@ 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"; 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, /** @@ -76,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; @@ -123,10 +138,31 @@ 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; } +/** A continued conversation's thread outlives the run, so only fresh ones are deleted. */ +function deletesRunThreads(config: AutomationConfig): boolean { + return config.deleteThreadWhenDone && config.conversation === "fresh"; +} + +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), @@ -146,6 +182,47 @@ 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 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 || + 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 +309,100 @@ const make = Effect.gen(function* () { const failWith = (message: string) => Effect.fail(new AutomationError({ message })); + /** 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.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 thread once its turn completed. Safe to call at any time; one call at a + * 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 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* finishPendingThreadDelete(threadId, true); + } + const outcome = runThreadOutcome(thread, pending, yield* nowIso); + if (outcome === "wait") return; + 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), + Effect.catchTag("OrchestrationCommandInvariantError", () => Effect.succeed(false)), + ); + // The thread changed after the read, and not every change is an event cleanup watches, + // so check again against a fresh read. + if (!deleted) return yield* recheck(threadId); + yield* finishPendingThreadDelete(threadId, true); + }).pipe( + cleanupLock.withPermits(1), + Effect.catchCause((failure) => + Effect.logWarning("automation run thread cleanup failed", { + threadId, + cause: Cause.pretty(failure), + }), + ), + ); + + // Off the event stream, so a slow lookup or dispatch never holds up the engine's subscribers. + // 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); + }), + ); + // Annotated: the worker, `settleRunThread` and this refer to one another. A retry from inside + // `settleRunThread` only enqueues, so it cannot wait on the lock it holds. + const recheck = (threadId: ThreadId): Effect.Effect => + 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); + }), + ); + /** * 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 @@ -427,9 +598,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, @@ -437,6 +608,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 @@ -444,7 +616,7 @@ const make = Effect.gen(function* () { }), ), ), - Effect.flatMap(({ threadId, error }) => + Effect.flatMap(({ threadId, messageAt, error }) => Effect.gen(function* () { const run: AutomationRun = { id: yield* newId, @@ -456,7 +628,18 @@ const make = Effect.gen(function* () { yield* patchAutomation(automation.id, (stored) => ({ ...stored, runs: [run, ...stored.runs].slice(0, AUTOMATION_MAX_RUNS), + // The run's config made the thread and the stored one may have been edited while + // it started; both must still delete it. + pendingThreadDeletes: + threadId !== null && + messageAt !== null && + deletesRunThreads(automation) && + deletesRunThreads(stored) + ? [...stored.pendingThreadDeletes, { threadId, messageAt }] + : stored.pendingThreadDeletes, })).pipe(Effect.ignoreCause({ log: true })); + // The turn may have finished before its delete was recorded. + if (threadId !== null) yield* settleRunThread(threadId); return run; }), ), @@ -624,6 +807,30 @@ const make = Effect.gen(function* () { }); const start = Effect.fn("AutomationService.start")(function* () { + // Turns that finished while the server was down, checked once events are flowing. + const recheckAll = SubscriptionRef.get(state).pipe( + Effect.flatMap((file) => + Effect.forEach( + file.automations.flatMap((automation) => + automation.pendingThreadDeletes.map((entry) => entry.threadId), + ), + recheck, + { discard: true }, + ), + ), + ); + yield* forkParked( + 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( Effect.all([scheduleTick, githubTick], { discard: true }).pipe( Effect.catchCause((failure) => @@ -637,7 +844,10 @@ const make = Effect.gen(function* () { const buildStored = ( config: AutomationConfig, - base: Pick, + base: Pick< + StoredAutomation, + "id" | "createdAt" | "runs" | "githubCursor" | "pendingThreadDeletes" + >, now: string, ): StoredAutomation => ({ ...config, @@ -646,6 +856,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, @@ -660,7 +872,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 848719ac13f82..bb0f5ca21bdbc 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.threadDeleted ? ( + Thread deleted + ) : threadId ? ( diff --git a/docs/user/automations.md b/docs/user/automations.md index db41f7da80621..52071ca4e9198 100644 --- a/docs/user/automations.md +++ b/docs/user/automations.md @@ -44,5 +44,12 @@ 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, and so does a thread you send a +message in. It only applies to new threads for each run, and turning it off also spares runs that +are still going. 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..85918b2c4d0aa 100644 --- a/packages/contracts/src/automation.ts +++ b/packages/contracts/src/automation.ts @@ -82,6 +82,8 @@ export const AutomationRun = Schema.Struct({ cause: Schema.String, threadId: Schema.NullOr(ThreadId), error: Schema.NullOr(Schema.String), + /** Set once the run's thread was deleted, by `deleteThreadWhenDone` or by hand. */ + threadDeleted: Schema.optional(Schema.Boolean), }); export type AutomationRun = typeof AutomationRun.Type; @@ -102,6 +104,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, }); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 1ae704d3f6661..fcb7d4788b69c 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1165,6 +1165,18 @@ const ThreadAutoSettleCommand = Schema.Struct({ settledAt: IsoDateTime, }); +/** + * Deletes a finished automation run's thread. The engine rejects it when the thread has events + * after `snapshotSequence` or live background work, so it never stops a turn started after the + * caller decided the thread was done. + */ +const ThreadAutoDeleteCommand = Schema.Struct({ + type: Schema.Literal("thread.auto-delete"), + commandId: CommandId, + threadId: ThreadId, + snapshotSequence: NonNegativeInt, +}); + const ThreadUnsettleCommand = Schema.Struct({ type: Schema.Literal("thread.unsettle"), commandId: CommandId, @@ -1660,6 +1672,7 @@ const ThreadPullRequestLinkSyncCommand = Schema.Struct({ const InternalOrchestrationCommand = Schema.Union([ ThreadAutoSettleCommand, + ThreadAutoDeleteCommand, ThreadPullRequestSyncCommand, ThreadPullRequestLinkSyncCommand, ThreadSessionSetCommand,