diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index cc570a9ef113d..ce3d5afb47999 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -14,8 +14,11 @@ import { ProviderDriverKind, ProviderInstanceId, ProviderThreadId, + ProviderTurnId, + RunAttemptId, RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -1172,6 +1175,281 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { }), ); + // Stop recorded on a waiting run: `turn` is the provider turn it was sent to, with when its attempt + // ended relative to the request; none means it reached no provider turn. + const captureWithStopRequest = (name: string, turn?: { readonly endedAfterStop: boolean }) => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const sideChatThreadId = ThreadId.make(`thread:checkpoint-capture-stop-request-${name}`); + const sideChatRunId = RunId.make(`run:checkpoint-capture-stop-request-${name}`); + const sideChatScopeId = CheckpointScopeId.make( + `scope:checkpoint-capture-stop-request-${name}`, + ); + const sideChatRootNodeId = NodeId.make(`node:checkpoint-capture-stop-request-${name}-root`); + const sideChatProviderThreadId = ProviderThreadId.make( + `provider-thread:checkpoint-capture-stop-request-${name}`, + ); + const stoppedAt = DateTime.add(now, { seconds: 1 }); + const attemptId = RunAttemptId.make(`attempt:checkpoint-capture-stop-request-${name}`); + const providerTurnId = ProviderTurnId.make( + `provider-turn:checkpoint-capture-stop-request-${name}`, + ); + const event = { threadId: sideChatThreadId, occurredAt: now }; + const events: ReadonlyArray = [ + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:thread`), + type: "thread.created", + payload: { + createdBy: "user", + creationSource: "web", + id: sideChatThreadId, + projectId, + title: "Side chat", + providerInstanceId, + modelSelection, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: "/repo", + activeProviderThreadId: null, + lineage: { + parentThreadId: threadId, + relationshipToParent: "fork", + rootThreadId: threadId, + sideChat: true, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }, + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:provider-thread`), + type: "provider-thread.updated", + driver, + providerInstanceId, + payload: { + id: sideChatProviderThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: sideChatThreadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }, + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:run`), + type: "run.updated", + runId: sideChatRunId, + payload: { + id: sideChatRunId, + threadId: sideChatThreadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: sideChatProviderThreadId, + userMessageId: MessageId.make(`message:checkpoint-capture-stop-request-${name}`), + rootNodeId: sideChatRootNodeId, + activeAttemptId: turn === undefined ? null : attemptId, + status: "waiting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }, + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:node`), + type: "node.updated", + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + payload: { + id: sideChatRootNodeId, + threadId: sideChatThreadId, + runId: sideChatRunId, + parentNodeId: null, + rootNodeId: sideChatRootNodeId, + kind: "root_turn", + status: "waiting", + countsForRun: true, + providerThreadId: sideChatProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: sideChatScopeId, + startedAt: now, + completedAt: null, + }, + }, + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:scope`), + type: "checkpoint-scope.created", + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + payload: { + id: sideChatScopeId, + threadId: sideChatThreadId, + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + parentScopeId: null, + providerThreadId: sideChatProviderThreadId, + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo", + createdAt: now, + }, + }, + ...(turn === undefined + ? [] + : [ + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:attempt`), + type: "run-attempt.updated" as const, + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + providerInstanceId, + payload: { + id: attemptId, + runId: sideChatRunId, + attemptOrdinal: 1, + rootNodeId: sideChatRootNodeId, + providerInstanceId, + providerThreadId: sideChatProviderThreadId, + providerTurnId, + reason: "initial" as const, + status: "completed" as const, + startedAt: now, + completedAt: turn.endedAfterStop ? DateTime.add(stoppedAt, { seconds: 1 }) : now, + }, + }, + ]), + // Stop committed its request while the provider's completed terminal was finalizing. + { + ...event, + id: EventId.make(`event:checkpoint-capture-stop-request-${name}:interrupt-request`), + type: "turn-item.updated", + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + providerInstanceId, + payload: { + id: TurnItemId.make( + `turn-item:checkpoint-capture-stop-request-${name}:interrupt-request`, + ), + type: "run_interrupt_request", + threadId: sideChatThreadId, + runId: sideChatRunId, + nodeId: sideChatRootNodeId, + providerThreadId: sideChatProviderThreadId, + providerTurnId: turn === undefined ? null : providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: "Interrupt requested", + startedAt: stoppedAt, + completedAt: stoppedAt, + updatedAt: stoppedAt, + message: "Stopped by user", + }, + }, + ]; + yield* Effect.forEach(events, (candidate) => projectionStore.apply(candidate)); + const gitUnavailable = () => Effect.die("side chats must not snapshot the shared worktree"); + const layerCapture = CheckpointCaptureService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + NodeCrypto.layer, + layerNoTrackedFolders, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: gitUnavailable, + captureCheckpoint: gitUnavailable, + hasCheckpointRef: gitUnavailable, + }), + ), + ), + ), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Effect.forEach(input.events, (committed) => projectionStore.apply(committed)).pipe( + Effect.as({ committed: true } as never), + Effect.orDie, + ), + }), + ), + ), + ); + + yield* CheckpointCaptureService.CheckpointCaptureServiceV2.use((service) => + service.execute({ + threadId: sideChatThreadId, + runId: sideChatRunId, + scopeId: sideChatScopeId, + }), + ).pipe(Effect.provide(layerCapture)); + + const { checkpoints, runs, turnItems } = yield* projectionStore.getThreadRecords( + sideChatThreadId, + ["runs", "checkpoints", "turnItems"], + ); + assert.notEqual( + checkpoints.find((candidate) => candidate.id === runs[0]?.checkpointId), + undefined, + ); + return { + status: runs[0]?.status, + answered: turnItems.some((item) => item.type === "run_interrupt_result"), + }; + }); + + it.effect("does not complete a waiting run whose Stop request has no result yet", () => + Effect.gen(function* () { + const outcome = yield* captureWithStopRequest("unreached"); + assert.deepEqual(outcome, { status: "interrupted", answered: true }); + }), + ); + + it.effect("ends interrupted a run whose turn completed after Stop reached it", () => + Effect.gen(function* () { + const outcome = yield* captureWithStopRequest("live", { endedAfterStop: true }); + assert.deepEqual(outcome, { status: "interrupted", answered: true }); + }), + ); + + it.effect("completes a run whose turn ended before Stop was sent to its background work", () => + Effect.gen(function* () { + const outcome = yield* captureWithStopRequest("background", { endedAfterStop: false }); + assert.deepEqual(outcome, { status: "completed", answered: false }); + }), + ); + // A thread on real Git checkouts: `folders` is what the project tracks, read at each turn. const withTrackedRepositories = ( name: string, diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index dd7f27079a4e5..29d722602f6aa 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -21,6 +21,7 @@ import * as CheckpointService from "./CheckpointService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as RunExecutionService from "./RunExecutionService.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; // Git processes are already capped server-wide; this keeps one thread from taking every slot. @@ -259,6 +260,26 @@ export const layer: Layer.Layer< if (currentRun.status !== "waiting" && !stoppedNow) { return; } + // An unanswered Stop ends the run stopped when it reached no provider turn, or reached the + // turn before it ended. One sent after the turn ended only stops its background work. + const { turnItems: stopItems, attempts } = stoppedNow + ? { turnItems: [], attempts: [] } + : yield* projections.getThreadRecords(input.threadId, ["turnItems", "attempts"], { + turnItemTypes: ["run_interrupt_request", "run_interrupt_result"], + turnItemRunIds: [run.id], + attemptIds: currentRun.activeAttemptId === null ? [] : [currentRun.activeAttemptId], + }); + const stopRequest = stopItems.some((item) => item.type === "run_interrupt_result") + ? undefined + : stopItems.find((item) => item.type === "run_interrupt_request"); + const attemptEndedAt = attempts[0]?.completedAt ?? null; + const stopRequested = + stopRequest?.type === "run_interrupt_request" && + (stopRequest.providerTurnId === null || + (attemptEndedAt !== null && + stopRequest.startedAt !== null && + DateTime.isLessThan(stopRequest.startedAt, attemptEndedAt))); + const finalStatus = stopRequested ? ("interrupted" as const) : ("completed" as const); // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = currentRun; @@ -328,6 +349,27 @@ export const layer: Layer.Layer< completedAt: capturedAt, }), }, + ...(stopRequested + ? [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "turn-item.updated" as const, + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: RunExecutionService.makeInterruptResultTurnItem({ + idAllocator: ids, + run, + rootNode, + providerThread, + reason: stopRequest.message, + completedAt: capturedAt, + }), + }, + ] + : []), { id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), type: "run.updated", @@ -340,7 +382,7 @@ export const layer: Layer.Layer< ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id } : { ...runWithoutDelegatedCompletion, - status: "completed", + status: finalStatus, completedAt: capturedAt, checkpointId: checkpoint.id, }, @@ -358,7 +400,7 @@ export const layer: Layer.Layer< occurredAt: capturedAt, payload: { ...rootNode, - status: "completed" as const, + status: finalStatus, completedAt: capturedAt, checkpointScopeId: scope.id, },