import { serializeAssistantCitation, expandAssistantCitationsForProvider, } from "@t3tools/shared/assistantCitations"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; import { CheckpointScopeId, CommandId, ContextHandoffId, ContextTransferId, GitCommandError, MessageId, NodeId, ProviderSessionId, ProviderThreadId, ProviderTurnId, ProviderDriverKind, ProviderInstanceId, ProviderSetupError, RunAttemptId, RunId, ScheduledTaskId, ThreadId, TurnItemId, ProjectId, EnvironmentId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, type OrchestrationV2Checkpoint, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, OrchestrationV2DomainEvent, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts"; import * as CheckpointService from "./CheckpointService.ts"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import { withCheckpointRestoreReservation, withWorkspaceLease, } from "../workspace/workspaceLease.ts"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import { layerThreadWorktreeRestore, ThreadWorktreeRestore, } from "../workspace/restoreMissingWorktree.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { layerNoTaskFolders, layerRealGit } from "./ProviderTurnStartService.testkit.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ContextHandoffService from "./ContextHandoffService.ts"; import { withInlineContext } from "./ContextHandoffDelivery.ts"; import * as EventSink from "./EventSink.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; import * as ProviderTurnControlService from "./ProviderTurnControlService.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationService.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionMaintenance from "./ProjectionMaintenance.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderTurnStart from "./ProviderTurnStartService.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); const managedWorktreesDir = "/tmp/provider-turn-start-worktrees"; // fs.realpath applies `..` and `.` before following symlinks. const normalize = (target: string) => { const parts: Array = []; for (const part of target.split("/")) { if (part === "..") parts.pop(); else if (part !== "" && part !== ".") parts.push(part); } return `/${parts.join("/")}`; }; const layerWorktreeLocation = (worktreesDir = managedWorktreesDir) => Layer.mergeAll( Path.layer, NodeCrypto.layer, Layer.mock(ServerConfig.ServerConfig)({ worktreesDir, stateDir: "/tmp/provider-turn-start-state", } as ServerConfig.ServerConfig["Service"]), ServerSettings.layerTest(), ); function startWithMissingWorktree( worktreePath: string, realPaths: Record = { [managedWorktreesDir]: managedWorktreesDir, [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`, }, ) { const threadId = ThreadId.make("thread_provider_turn_start_projection_failure"); const runId = RunId.make("run_provider_turn_start_projection_failure"); const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure"); const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure"); const providerThreadId = ProviderThreadId.make( "provider_thread_provider_turn_start_projection_failure", ); const providerSessionId = ProviderSessionId.make( "provider_session_provider_turn_start_projection_failure", ); const messageId = MessageId.make("message_provider_turn_start_projection_failure"); const checkpointScopeId = CheckpointScopeId.make( "checkpoint_scope_provider_turn_start_projection_failure", ); const projection = { thread: { id: threadId, projectId: ProjectId.make("project_provider_turn_start_projection_failure"), branch: "feature/restore", worktreePath, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, }, runs: [ { id: runId, status: "starting", rootNodeId, activeAttemptId: attemptId, providerThreadId, userMessageId: messageId, ordinal: 2, }, ], nodes: [{ id: rootNodeId, checkpointScopeId }], attempts: [{ id: attemptId }], providerThreads: [{ id: providerThreadId, providerSessionId }], messages: [{ id: messageId, text: "Continue", attachments: [] }], checkpointScopes: [{ id: checkpointScopeId }], contextHandoffs: [], contextTransfers: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; let projectionReadCount = 0; const writeIfRunCurrent = vi.fn(() => Effect.succeed({ committed: true, storedEvents: [] } as never), ); const startRootRun = vi.fn(() => Effect.void); const pruneWorktrees = vi.fn(() => Effect.void); let worktreeExists = false; const createWorktree = vi.fn(() => Effect.sync(() => { worktreeExists = true; return {} as never; }), ); const listLocalBranchNames = vi.fn(() => Effect.succeed(["feature/restore"])); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread: () => Effect.succeed({ status: "no-script" }), }), Layer.mock(ThreadWorktreeRestore)({ takeRecreated: () => Effect.undefined }), Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(worktreeExists), realPath: (target: string) => normalize(target) in realPaths ? Effect.succeed(realPaths[normalize(target)]) : Effect.fail( PlatformError.systemError({ _tag: "NotFound", module: "FileSystem", method: "realPath", pathOrDescriptor: target, }), ), } as never), layerWorktreeLocation(), layerNoTaskFolders, Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree, listLocalBranchNames, }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getForkSourceRunIds: () => Effect.succeed(projection.runs.map((run) => run.id)), getThreadRecords: () => { projectionReadCount += 1; return Effect.succeed(projection); }, getTurnStartContext: () => { projectionReadCount += 1; return Effect.succeed({ ...projection, hasConversation: projection.messages.some( (m) => m.role === "user" && (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), ), }); }, getRuntimeRecoveryProjection: () => { projectionReadCount += 1; return Effect.fail( new ProjectionStore.ProjectionStoreReadError({ threadId, cause: "simulated inherited-background projection failure", }), ); }, }), Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand: () => Effect.succeed(false), }), Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({}), ), ), ); const start = Effect.gen(function* () { return yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2) .start({ threadId, runId, willRetry: true }) .pipe(Effect.flip); }).pipe(Effect.provide(layer), Effect.runPromise); return { start, pruneWorktrees, createWorktree, writeIfRunCurrent, startRootRun, projectionReads: () => projectionReadCount, }; } it.each([ { label: "//", worktreePath: `${managedWorktreesDir}/project/feature-restore`, recreated: true, }, { label: "the real path of a symlinked managed folder", worktreePath: "/real-worktrees/project/feature-restore", realPaths: { [managedWorktreesDir]: "/real-worktrees", "/real-worktrees": "/real-worktrees" }, recreated: true, }, { label: "a path outside the managed folder", worktreePath: "/tmp/provider-turn-start-project/.git/hooks", recreated: false, }, { label: "a symlink inside the managed folder that leads out", worktreePath: `${managedWorktreesDir}/project/hooks`, realPaths: { [managedWorktreesDir]: managedWorktreesDir, [`${managedWorktreesDir}/project`]: "/tmp/provider-turn-start-project/.git", }, recreated: false, }, { label: "a folder nested below a worktree", worktreePath: `${managedWorktreesDir}/project/feature-restore/link/hooks`, recreated: false, }, { label: "'..' out of the managed folder", worktreePath: `${managedWorktreesDir}/project/../../outside`, recreated: false, }, { // Left raw on purpose: git follows `link` before applying `..`. label: "'..' after a symlink inside the managed folder", worktreePath: `${managedWorktreesDir}/project/x/link/../../hooks`, realPaths: { [managedWorktreesDir]: managedWorktreesDir, [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`, [`${managedWorktreesDir}/project/x`]: `${managedWorktreesDir}/project/x`, [`${managedWorktreesDir}/project/x/link`]: "/tmp/provider-turn-start-project/.git/refs/heads", }, recreated: false, }, { label: "a relative path", worktreePath: "project/feature-restore", recreated: false }, ])("recreates a missing worktree only at the managed location: $label", async (input) => { const harness = startWithMissingWorktree(input.worktreePath, input.realPaths); await harness.start; expect(harness.createWorktree).toHaveBeenCalledTimes(input.recreated ? 1 : 0); }); const restoreLeaseExists = vi.fn(() => Effect.succeed(false)); const restoreLeaseCreateWorktree = vi.fn(() => Effect.succeed({} as never)); const restoreLeaseFiles = new Set(); // Each build is a server start over the same disk. const layerRestoreLeaseTest = () => layerThreadWorktreeRestore.pipe( Layer.provide( Layer.mergeAll( layerNoTaskFolders, Layer.succeed(FileSystem.FileSystem, { exists: (target: string) => restoreLeaseFiles.has(target) ? Effect.succeed(true) : restoreLeaseExists(), realPath: (target: string) => Effect.succeed(normalize(target)), makeDirectory: () => Effect.void, writeFileString: (target: string) => Effect.sync(() => restoreLeaseFiles.add(target)), remove: (target: string) => restoreLeaseFiles.delete(target) ? Effect.void : Effect.fail( PlatformError.systemError({ _tag: "NotFound", module: "FileSystem", method: "remove", pathOrDescriptor: target, }), ), } as never), layerWorktreeLocation(), Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees: () => Effect.void, createWorktree: restoreLeaseCreateWorktree, listLocalBranchNames: () => Effect.succeed(["feature/restore"]), }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), }), ), ), ); effectIt.effect("restores a missing worktree before a send only under the workspace lease", () => Effect.gen(function* () { const worktreePath = `${managedWorktreesDir}/project/feature-restore`; const projectId = ProjectId.make("project_send_restore_lease"); const { restore } = yield* ThreadWorktreeRestore; yield* withWorkspaceLease( worktreePath, Effect.gen(function* () { const restoring = yield* restore({ id: ThreadId.make("thread_send_restore_lease"), projectId, worktreePath, branch: "feature/restore", }).pipe(Effect.forkChild({ startImmediately: true })); expect(restoreLeaseExists).not.toHaveBeenCalled(); return restoring; }), ).pipe(Effect.flatMap(Fiber.join)); expect(restoreLeaseCreateWorktree).toHaveBeenCalledTimes(1); // Turn start finds the checkout present, so it runs setup from this hand-over, once, even // after a restart and for a fork sharing the checkout. const { takeRecreated } = yield* ThreadWorktreeRestore.pipe( Effect.provide(layerRestoreLeaseTest()), ); expect(yield* takeRecreated({ projectId, worktreePath })).toMatchObject({ worktreePath }); expect(yield* takeRecreated({ projectId, worktreePath })).toBeUndefined(); }).pipe(Effect.provide(layerRestoreLeaseTest())), ); effectIt.effect("a cancelled restore still hands its recreated worktree to setup", () => Effect.gen(function* () { const worktreePath = `${managedWorktreesDir}/project/feature-restore`; const projectId = ProjectId.make("project_cancelled_restore"); const created = yield* Deferred.make(); const release = yield* Deferred.make(); restoreLeaseCreateWorktree.mockImplementationOnce(() => Deferred.succeed(created, undefined).pipe( Effect.andThen(Deferred.await(release)), Effect.as({} as never), ), ); const { restoreLeased, takeRecreated } = yield* ThreadWorktreeRestore; const restoring = yield* restoreLeased({ id: ThreadId.make("thread_cancelled_restore"), projectId, worktreePath, branch: "feature/restore", }).pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(created); const interrupting = yield* Fiber.interrupt(restoring).pipe( Effect.forkChild({ startImmediately: true }), ); yield* Deferred.succeed(release, undefined); yield* Fiber.join(interrupting); expect(yield* takeRecreated({ projectId, worktreePath })).toMatchObject({ worktreePath }); }).pipe(Effect.provide(layerRestoreLeaseTest())), ); effectIt.effect("restores into a leftover worktree folder that cannot itself be removed", () => { const worktreePath = `${managedWorktreesDir}/project/feature-restore`; // Windows refuses to remove a folder that is still some process's cwd. const remove = vi.fn((target: string) => target === worktreePath ? Effect.fail( PlatformError.systemError({ _tag: "Busy", module: "FileSystem", method: "remove", pathOrDescriptor: target, }), ) : Effect.void, ); const createWorktree = vi.fn(() => Effect.succeed({} as never)); return Effect.gen(function* () { const { restore } = yield* ThreadWorktreeRestore; yield* restore({ id: ThreadId.make("thread_leftover_restore"), projectId: ProjectId.make("project_leftover_restore"), worktreePath, branch: "feature/restore", }); expect(remove).toHaveBeenCalledWith(`${worktreePath}/node_modules`, { recursive: true }); expect(createWorktree).toHaveBeenCalledTimes(1); }).pipe( Effect.provide( layerThreadWorktreeRestore.pipe( Layer.provide( Layer.mergeAll( layerNoTaskFolders, Layer.succeed(FileSystem.FileSystem, { exists: (target: string) => Effect.succeed(!target.endsWith("/.git")), readDirectory: () => Effect.succeed(["node_modules"]), stat: () => Effect.succeed({ type: "Directory" }), realPath: (target: string) => Effect.succeed(normalize(target)), remove, makeDirectory: () => Effect.void, writeFileString: () => Effect.void, } as never), layerWorktreeLocation(), Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees: () => Effect.void, createWorktree, listLocalBranchNames: () => Effect.succeed(["feature/restore"]), }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), }), ), ), ), ), ); }); effectIt.effect("hands a checkout left by a failed recreate to the next restore for setup", () => { const worktreePath = `${managedWorktreesDir}/project/feature-restore`; let checkedOut = false; const createWorktree = vi.fn(() => { checkedOut = true; return Effect.fail( new GitCommandError({ operation: "GitVcsDriver.createWorktree", command: "git worktree add", cwd: "/tmp/provider-turn-start-project", detail: "git worktree add failed: the post-checkout hook failed", }), ); }); return Effect.gen(function* () { const { restore, takeRecreated } = yield* ThreadWorktreeRestore; const threadId = ThreadId.make("thread_failed_hook_restore"); const failed = yield* restore({ id: threadId, projectId: ProjectId.make("project_failed_hook_restore"), worktreePath, branch: "feature/restore", }).pipe(Effect.flip); expect(failed._tag).toBe("WorktreeRecreateError"); expect(yield* takeRecreated(threadId)).toBeUndefined(); const retry = { id: threadId, projectId: ProjectId.make("project_failed_hook_restore"), worktreePath, branch: "feature/restore", }; // The kept checkout is reused, never removed or created again. yield* restore(retry); expect(createWorktree).toHaveBeenCalledTimes(1); expect(yield* takeRecreated(threadId)).toMatchObject({ worktreePath }); yield* restore(retry); expect(yield* takeRecreated(threadId)).toBeUndefined(); }).pipe( Effect.provide( layerThreadWorktreeRestore.pipe( Layer.provide( Layer.mergeAll( layerNoTaskFolders, Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.sync(() => checkedOut), realPath: (target: string) => Effect.succeed(normalize(target)), } as never), layerWorktreeLocation(), Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees: () => Effect.void, createWorktree, listLocalBranchNames: () => Effect.succeed(["feature/restore"]), }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), }), ), ), ), ), ); }); it.each([ { label: "directly in the scratch root", folder: "/tmp/t3-home/scratch/notes", recreated: true }, { label: "below another folder", folder: "/tmp/t3-home/scratch/notes/deep", recreated: false }, { label: "in another project", folder: "/tmp/elsewhere/notes", workspaceRoot: "/tmp/elsewhere", recreated: false, }, ])("recreates a pruned No project folder only $label", async (input) => { const makeDirectory = vi.fn(() => Effect.void); await Effect.gen(function* () { const { restore } = yield* ThreadWorktreeRestore; yield* restore({ id: ThreadId.make("thread_scratch_restore"), projectId: ProjectId.make("project_scratch_restore"), worktreePath: input.folder, branch: null, }); }).pipe( Effect.provide( layerThreadWorktreeRestore.pipe( Layer.provide( Layer.mergeAll( layerNoTaskFolders, Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false), realPath: (target: string) => Effect.succeed(target), makeDirectory, } as never), Path.layer, NodeCrypto.layer, Layer.mock(ServerConfig.ServerConfig)({ baseDir: "/tmp/t3-home", worktreesDir: managedWorktreesDir, } as ServerConfig.ServerConfig["Service"]), ServerSettings.layerTest(), Layer.mock(GitWorkflow.GitWorkflowService)({}), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: input.workspaceRoot ?? "/tmp/t3-home/scratch", } as never), }), ), ), ), ), Effect.runPromise, ); expect(makeDirectory).toHaveBeenCalledTimes(input.recreated ? 1 : 0); }); function makeLocalCommandHarness(input: { readonly text: string; readonly manualContinuation?: boolean; readonly nativeResumeUnsupported?: boolean; readonly steeringRestart?: boolean; readonly nativeGoals?: boolean; readonly canForkWhileSourceRunning?: boolean; readonly exposesNativeTurnId?: boolean; readonly goalDriver?: "opencode" | "antigravity"; readonly worktreePath?: string; readonly worktreesDir?: string; readonly workspaceRoot?: string; readonly gitWorkflow?: GitWorkflow.GitWorkflowService["Service"]; readonly fileSystem?: FileSystem.FileSystem; readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]; readonly recreatedBeforeDispatch?: boolean; readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; readonly createdBy?: "agent" | "system"; readonly scheduledTaskId?: ScheduledTaskId; readonly logoutFailure?: string; readonly openFailure?: unknown; readonly ensureThreadFailure?: unknown; readonly historyReadFailureAfterFallback?: unknown; readonly resumeFailure?: ProviderAdapter.ProviderAdapterV2Error; readonly interruptOpen?: boolean; readonly interruptRunBeforeOpenFailure?: boolean; readonly writeFailure?: unknown; readonly failReadsAfterRunning?: boolean; readonly missingProviderSession?: boolean; readonly recoveryReadFailure?: string; readonly previousTurn?: { readonly runStatus: "failed" | "completed" | "interrupted"; readonly turnStatus: "running" | "completed" | "interrupted"; readonly differentThread?: boolean; readonly liveSession?: boolean; readonly interruptFailure?: boolean; readonly interruptCurrentRun?: boolean; /** Puts the running turn on an attempt a steering restart superseded. */ readonly supersededTurn?: boolean; }; /** * A side chat whose context targets this run, an earlier run that failed or was cancelled before * the provider, or an earlier run that delivered it. `nativeForkFrom` plans a native fork of the * parent. `switchedProvider` puts the earlier run and its context on another provider thread. */ readonly sideChat?: { readonly contextRun: "current" | "failed" | "cancelled" | "delivered"; readonly unsentResume?: boolean; readonly repeatedResume?: boolean; readonly acceptedResume?: boolean; readonly restartedResume?: boolean; readonly nativeForkFrom?: "idle" | "busy"; readonly sourceBoundary?: "native" | "synthetic"; readonly sourceRolledBack?: boolean; readonly switchedProvider?: boolean; readonly threadRuntimeMode?: OrchestrationV2ThreadProjection["thread"]["runtimeMode"]; }; }) { const settledRuns: Array = []; const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z"); const threadId = ThreadId.make("thread-native-account-command"); const runId = RunId.make("run-native-account-command"); const rootNodeId = NodeId.make("root-native-account-command"); const attemptId = RunAttemptId.make("attempt-native-account-command"); const providerThreadId = ProviderThreadId.make("new-provider-thread"); const providerSessionId = ProviderSessionId.make("new-provider-session"); const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread"); const oldInstanceId = ProviderInstanceId.make("antigravity-personal"); const newInstanceId = ProviderInstanceId.make("codex-personal"); const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command"); const messageId = MessageId.make("message-native-account-command"); const run: OrchestrationV2ThreadProjection["runs"][number] = { ...(input.manualContinuation ? { manualContinuationOfRunId: RunId.make("stopped-run") } : {}), id: runId, threadId, ordinal: 2, providerInstanceId: newInstanceId, modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" }, providerThreadId, userMessageId: messageId, rootNodeId, activeAttemptId: attemptId, status: "starting", requestedAt: now, startedAt: null, completedAt: null, checkpointId: null, contextHandoffId: null, }; const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = { id: providerThreadId, driver: ProviderDriverKind.make( input.nativeGoals === undefined ? "codex" : (input.goalDriver ?? "opencode"), ), providerInstanceId: newInstanceId, providerSessionId: input.missingProviderSession === true ? null : providerSessionId, appThreadId: threadId, ownerNodeId: null, nativeThreadRef: null, nativeConversationHeadRef: null, status: "not_loaded", firstRunOrdinal: 2, lastRunOrdinal: 2, handoffIds: [], forkedFrom: null, createdAt: now, updatedAt: now, }; const message: OrchestrationV2ThreadProjection["messages"][number] = { id: messageId, threadId, runId, nodeId: rootNodeId, role: "user", text: input.text, attachments: [], streaming: false, createdBy: input.createdBy ?? "user", creationSource: input.createdBy === undefined ? "web" : "mcp", ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), createdAt: now, updatedAt: now, }; let projection: OrchestrationV2ThreadProjection = { thread: { id: threadId, activeProviderThreadId: providerThreadId, projectId: ProjectId.make("project-native-account-command"), runtimeMode: "full-access", interactionMode: "default", branch: input.worktreePath === undefined ? null : "feature/restore", worktreePath: input.worktreePath ?? null, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, } as OrchestrationV2ThreadProjection["thread"], runs: [ ...(input.previousNativeSession ? [ { ...run, id: RunId.make("previous-native-run"), ordinal: 1, status: "completed" as const, providerInstanceId: oldInstanceId, providerThreadId: oldProviderThreadId, }, ] : []), run, ], attempts: [ { id: attemptId, runId, rootNodeId, attemptOrdinal: 1, providerInstanceId: newInstanceId, providerThreadId, providerTurnId: null, reason: input.steeringRestart ? "steering_restart" : "initial", status: "pending", startedAt: null, completedAt: null, }, ], nodes: [ { id: rootNodeId, threadId, runId, parentNodeId: null, rootNodeId, kind: "root_turn", status: "pending", countsForRun: true, providerThreadId, providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, checkpointScopeId, startedAt: null, completedAt: null, }, ], providerThreads: [ ...(input.previousNativeSession ? [ { ...providerThread, id: oldProviderThreadId, providerInstanceId: oldInstanceId, driver: ProviderDriverKind.make("antigravity"), lastRunOrdinal: 1, nativeThreadRef: { driver: ProviderDriverKind.make("antigravity"), nativeId: "existing-session", strength: "strong" as const, }, }, ] : []), providerThread, ], messages: [ ...(input.previousMessages ?? []).map((text, index) => ({ ...message, id: MessageId.make(`previous-message-${index}`), text, })), message, ], checkpointScopes: [ { id: checkpointScopeId, threadId, runId, nodeId: rootNodeId, parentScopeId: null, providerThreadId, kind: "root_run", ordinalWithinParent: 0, advancesAppRunCount: true, cwd: "/tmp/native-account-command", createdAt: now, }, ], providerSessions: [], providerTurns: [], contextHandoffs: [], contextTransfers: [], turnItems: [], visibleTurnItems: [], runtimeRequests: [], subagents: [], plans: [], checkpoints: [], updatedAt: now, }; const parentThreadId = ThreadId.make("side-chat-parent"); const parentRunId = RunId.make("side-chat-parent-run"); const parentProviderThread = { ...providerThread, id: ProviderThreadId.make("side-chat-parent-provider-thread"), appThreadId: parentThreadId, nativeThreadRef: { driver: providerThread.driver, nativeId: "side-chat-parent-native", strength: "strong" as const, }, }; const parentProviderTurn = (ordinal: number, attemptRunId: RunId) => ({ attempt: { ...projection.attempts[0]!, id: RunAttemptId.make(`side-chat-parent-attempt-${ordinal}`), runId: attemptRunId, providerThreadId: parentProviderThread.id, status: "completed" as const, }, turn: { id: ProviderTurnId.make(`side-chat-parent-turn-${ordinal}`), providerThreadId: parentProviderThread.id, nodeId: rootNodeId, runAttemptId: RunAttemptId.make(`side-chat-parent-attempt-${ordinal}`), nativeTurnRef: ordinal === 1 && input.sideChat?.sourceBoundary === "synthetic" ? null : { driver: providerThread.driver, nativeId: `side-chat-parent-native-turn-${ordinal}`, strength: "strong" as const, }, ordinal, status: "completed" as const, startedAt: now, completedAt: now, }, }); const parentRolledBackRunId = RunId.make("side-chat-parent-rolled-back-run"); const parentTurns = [ parentProviderTurn(1, parentRunId), parentProviderTurn(2, parentRolledBackRunId), ]; const parentRecords = { ...projection, thread: { ...projection.thread, id: parentThreadId }, runs: [ { ...run, id: parentRunId, threadId: parentThreadId, ordinal: 1, providerThreadId: parentProviderThread.id, activeAttemptId: parentTurns[0]!.attempt.id, status: input.sideChat?.sourceRolledBack === true ? ("rolled_back" as const) : ("completed" as const), completedAt: now, }, { ...run, id: parentRolledBackRunId, threadId: parentThreadId, ordinal: 2, providerThreadId: parentProviderThread.id, activeAttemptId: parentTurns[1]!.attempt.id, status: "rolled_back" as const, completedAt: now, }, ...(input.sideChat?.nativeForkFrom === "busy" ? [ { ...run, id: RunId.make("side-chat-parent-busy-run"), threadId: parentThreadId, ordinal: 3, providerThreadId: parentProviderThread.id, status: "running" as const, }, ] : []), ], providerThreads: [parentProviderThread], attempts: parentTurns.map(({ attempt }) => attempt), providerTurns: parentTurns.map(({ turn }) => turn), turnItems: [], }; if (input.sideChat !== undefined) { const earlierRunId = RunId.make("side-chat-earlier-run"); projection = { ...projection, thread: { ...projection.thread, runtimeMode: input.sideChat.threadRuntimeMode ?? "full-access", lineage: { parentThreadId, relationshipToParent: "fork", rootThreadId: parentThreadId, sideChat: true, }, }, runs: input.sideChat.contextRun === "current" ? projection.runs : [ { ...run, id: earlierRunId, ordinal: 1, userMessageId: MessageId.make("side-chat-earlier-message"), activeAttemptId: RunAttemptId.make("side-chat-earlier-attempt"), ...(input.sideChat.switchedProvider ? { providerThreadId: oldProviderThreadId } : {}), status: input.sideChat.contextRun === "delivered" ? "completed" : input.sideChat.contextRun, completedAt: now, }, run, ], contextTransfers: input.sideChat.nativeForkFrom === undefined ? [] : [ { id: ContextTransferId.make("side-chat-fork"), type: "fork", sourceThreadId: parentThreadId, targetThreadId: threadId, sourcePoint: { threadId: parentThreadId, runId: parentRunId }, basePoint: null, sourceProviderInstanceId: newInstanceId, targetProviderInstanceId: newInstanceId, targetRunId: runId, status: "pending", resolution: null, createdBy: "user", error: null, createdAt: now, updatedAt: now, consumedAt: null, }, ], contextHandoffs: [ { id: ContextHandoffId.make("side-chat-context"), transferId: ContextTransferId.make("side-chat-fork"), threadId, targetRunId: input.sideChat.contextRun === "current" ? runId : earlierRunId, fromProviderThreadIds: [], toProviderThreadId: input.sideChat.switchedProvider ? oldProviderThreadId : providerThreadId, coveredRunOrdinals: { from: 1, to: 1 }, strategy: "manual_context", status: "ready", summaryMessageId: null, summaryText: "SIDE_CHAT_CONTEXT", createdByProviderInstanceId: null, createdAt: now, updatedAt: now, ...(input.sideChat.contextRun === "delivered" ? { delivery: { nativeThreadId: "side-chat-native", status: "inline" as const, itemIds: [], }, } : {}), }, ], }; } if (input.sideChat?.unsentResume) { const originalMessageId = MessageId.make("original-unsent-message"); projection = { ...projection, runs: [ { ...run, id: RunId.make("stopped-run"), manualContinuationOfRunId: undefined, userMessageId: originalMessageId, status: "interrupted", ordinal: 1, }, ...projection.runs, ], messages: [ { ...message, id: originalMessageId, text: "Original request" }, ...projection.messages, ], }; } if (input.sideChat?.repeatedResume) { const retry = RunId.make("stopped-resume"); projection = { ...projection, runs: projection.runs .map((r) => (r.id === runId ? { ...r, manualContinuationOfRunId: retry } : r)) .concat({ ...run, id: retry, manualContinuationOfRunId: RunId.make("stopped-run"), status: "interrupted", }), }; } if (input.sideChat?.acceptedResume) { const acceptedId = RunAttemptId.make("accepted-original"); projection = { ...projection, attempts: [ ...projection.attempts, { ...projection.attempts[0]!, id: acceptedId, runId: RunId.make("stopped-run"), providerThreadId: oldProviderThreadId, status: "interrupted", }, ...(input.sideChat.restartedResume ? [ { ...projection.attempts[0]!, id: RunAttemptId.make("unaccepted-replacement"), runId: RunId.make("stopped-run"), attemptOrdinal: 2, reason: "steering_restart" as const, status: "interrupted" as const, }, ] : []), ], providerTurns: [ ...projection.providerTurns, { id: ProviderTurnId.make("accepted-original-turn"), runAttemptId: acceptedId, providerThreadId: oldProviderThreadId, nodeId: rootNodeId, ordinal: 1, nativeTurnRef: null, status: "interrupted", startedAt: now, completedAt: now, }, ], }; } if ("historyReadFailureAfterFallback" in input || "resumeFailure" in input) { const nativeThreadRef = { driver: providerThread.driver, nativeId: "native-resume-thread", strength: "strong" as const, }; projection = { ...projection, providerThreads: projection.providerThreads.map((candidate) => candidate.id === providerThreadId ? { ...candidate, nativeThreadRef } : candidate, ), }; } const previousTurnId = ProviderTurnId.make("previous-provider-turn"); if (input.previousTurn !== undefined) { const previousRunId = RunId.make("previous-failed-run"); const previousAttemptId = RunAttemptId.make("previous-failed-attempt"); const steeredAttemptId = RunAttemptId.make("previous-steered-attempt"); const previousProviderThreadId = input.previousTurn.differentThread ? oldProviderThreadId : providerThreadId; projection = { ...projection, attempts: [ { id: previousAttemptId, runId: previousRunId, attemptOrdinal: 1, rootNodeId: NodeId.make("previous-root"), providerInstanceId: newInstanceId, providerThreadId: previousProviderThreadId, providerTurnId: null, reason: "initial", status: input.previousTurn.supersededTurn === true ? "superseded" : "interrupted", startedAt: now, completedAt: now, }, ...(input.previousTurn.supersededTurn === true ? [ { id: steeredAttemptId, runId: previousRunId, attemptOrdinal: 2, rootNodeId: NodeId.make("previous-steered-root"), providerInstanceId: newInstanceId, providerThreadId: previousProviderThreadId, providerTurnId: null, reason: "steering_restart" as const, status: "interrupted" as const, startedAt: null, completedAt: now, }, ] : []), ...projection.attempts, ], runs: [ { ...run, id: previousRunId, ordinal: 1, status: input.previousTurn.runStatus, rootNodeId: input.previousTurn.supersededTurn === true ? NodeId.make("previous-steered-root") : NodeId.make("previous-root"), activeAttemptId: input.previousTurn.supersededTurn === true ? steeredAttemptId : previousAttemptId, providerThreadId: previousProviderThreadId, completedAt: now, }, run, ], providerThreads: [ { ...providerThread, nativeThreadRef: { driver: providerThread.driver, nativeId: "existing-native-conversation", strength: "strong", }, }, ], providerTurns: [ // The steered attempt reached the provider once; only the earlier attempt's // turn is still running when the run was interrupted. ...(input.previousTurn.supersededTurn === true ? [ { id: ProviderTurnId.make("previous-steered-turn"), providerThreadId: previousProviderThreadId, nodeId: NodeId.make("previous-steered-root"), runAttemptId: steeredAttemptId, ordinal: 0, nativeTurnRef: null, status: "interrupted" as const, startedAt: now, completedAt: now, }, ] : []), { id: previousTurnId, providerThreadId: previousProviderThreadId, nodeId: NodeId.make("previous-root"), runAttemptId: previousAttemptId, ordinal: 1, nativeTurnRef: null, status: input.previousTurn.turnStatus, startedAt: now, completedAt: input.previousTurn.turnStatus === "running" ? null : now, }, ], }; } let providerBusy = (input.previousTurn?.runStatus === "failed" || input.previousTurn?.runStatus === "interrupted") && input.previousTurn.turnStatus === "running" && !input.previousTurn.differentThread && input.previousTurn.liveSession !== false; const interruptTurn = vi.fn((request: ProviderAdapter.ProviderAdapterV2InterruptInput) => Effect.gen(function* () { expect(request.providerTurnId).toBe(previousTurnId); expect(request.providerThread.id).toBe(providerThreadId); if (input.previousTurn?.interruptFailure) { return yield* new ProviderAdapter.ProviderAdapterInterruptError({ driver: providerThread.driver, providerThreadId, providerTurnId: request.providerTurnId, cause: "provider interrupt failed", }); } providerBusy = false; if (input.previousTurn?.interruptCurrentRun) interruptRun(); }), ); const events: Array = []; const interruptRun = () => { projection = { ...projection, runs: projection.runs.map((candidate) => candidate.id === runId ? { ...candidate, status: "interrupted", completedAt: now } : candidate, ), }; }; const ensureThread = vi.fn(() => Effect.sync(() => { if (input.interruptRunBeforeOpenFailure === true) interruptRun(); }).pipe( Effect.andThen( Effect.fail( new ProviderAdapter.ProviderAdapterEventStreamError({ driver: providerThread.driver, providerSessionId, cause: input.ensureThreadFailure, }), ), ), ), ); const fallbackEnsureThread = vi.fn(() => Effect.succeed(providerThread)); const providerSession = { id: providerSessionId, driver: providerThread.driver, providerInstanceId: newInstanceId, status: "ready", cwd: "/tmp/native-account-command", model: null, capabilities: { ...CodexProviderCapabilitiesV2, threads: { ...CodexProviderCapabilitiesV2.threads, canForkWhileSourceRunning: input.canForkWhileSourceRunning ?? CodexProviderCapabilitiesV2.threads.canForkWhileSourceRunning, }, turns: { ...CodexProviderCapabilitiesV2.turns, exposesNativeTurnId: input.exposesNativeTurnId ?? CodexProviderCapabilitiesV2.turns.exposesNativeTurnId, ...(input.nativeGoals === undefined ? {} : { supportsNativeGoals: input.nativeGoals }), }, }, createdAt: now, updatedAt: now, lastError: null, }; const resumeFallbackSession = { driver: providerThread.driver, providerSession, resumeThread: () => Effect.fail( input.resumeFailure ?? new ProviderAdapter.ProviderAdapterEventStreamError({ driver: providerThread.driver, providerSessionId, cause: "native thread is gone", }), ), ensureThread: fallbackEnsureThread, }; const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void); const sideChatThread = { ...providerThread, nativeThreadRef: { driver: providerThread.driver, nativeId: "side-chat-native", strength: "strong" as const, }, }; const forkThread = vi.fn(() => Effect.succeed(sideChatThread), ); const sideChatSession = { driver: providerThread.driver, providerSession, ensureThread: () => Effect.succeed(sideChatThread), resumeThread: () => Effect.succeed(sideChatThread), forkThread, startTurn, resumeTurn: input.nativeResumeUnsupported ? undefined : (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => startTurn(ProviderAdapter.resumeTurnInput(input)), }; const open = vi.fn(() => input.sideChat !== undefined ? Effect.succeed(sideChatSession as never) : input.interruptOpen === true ? Effect.interrupt : "historyReadFailureAfterFallback" in input || "resumeFailure" in input ? Effect.succeed(resumeFallbackSession as never) : "ensureThreadFailure" in input ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never) : "openFailure" in input ? Effect.sync(() => { if (input.interruptRunBeforeOpenFailure === true) interruptRun(); }).pipe( Effect.andThen( Effect.fail( new ProviderSessionManager.ProviderSessionOpenError({ instanceId: newInstanceId, providerSessionId, cause: input.openFailure, }), ), ), ) : input.failReadsAfterRunning === true || input.previousTurn !== undefined ? Effect.succeed({ driver: providerThread.driver, providerSession, ensureThread: () => Effect.succeed(providerThread), resumeThread: () => Effect.succeed(projection.providerThreads[0]), } as never) : Effect.die("A local command must not open a native session."), ); const startRootRun = vi.fn< ( input: RunExecutionService.RunExecutionServiceV2StartRootRunInput, ) => Effect.Effect >((runInput) => input.sideChat !== undefined ? (runInput.resume ? runInput.session.resumeTurn!({ ...runInput, messageId: runInput.message.messageId, } as never) : runInput.session.startTurn(runInput as never) ).pipe(Effect.orDie) : input.failReadsAfterRunning === true || input.previousTurn !== undefined ? Effect.suspend(() => providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void, ) : Effect.die("A local command must not start a native turn."), ); const failReadIfRunning = Effect.suspend(() => input.failReadsAfterRunning === true && projection.runs.find((candidate) => candidate.id === runId)?.status === "running" ? Effect.fail( new ProjectionStore.ProjectionStoreReadError({ threadId, cause: "database unavailable" }), ) : Effect.void, ); const tryHandlePromptCommand = vi.fn(() => input.logoutFailure === undefined ? Effect.succeed(true) : Effect.fail( new ProviderSetupError({ instanceId: oldInstanceId, operation: "logout", detail: input.logoutFailure, }), ), ); const writeIfRunCurrent = vi.fn( ({ events: incoming, activeAttemptId, expectedStatus }) => "writeFailure" in input ? Effect.fail( new EventSink.EventSinkWriteError({ eventCount: incoming.length, cause: input.writeFailure, }), ) : Effect.sync(() => { const current = projection.runs.find((candidate) => candidate.id === runId); const committed = current !== undefined && current.activeAttemptId === activeAttemptId && current.status === expectedStatus; if (committed) { for (const event of incoming) { expect(isDomainEvent(event)).toBe(true); events.push(event); projection = ProjectionStore.applyToProjection(projection, event); } } return { committed, storedEvents: [] }; }), ); const resolveRuntimePolicy = vi.fn( ({ thread }: Parameters[0]) => Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command", runtimeMode: thread.runtimeMode, } as never), ); const updateWorktreeSubmodules = vi.fn< GitWorkflow.GitWorkflowService["Service"]["updateWorktreeSubmodules"] >(() => Effect.void); const createWorktree = vi.fn(() => Effect.succeed({} as never), ); const getThreadRecords = vi.fn((id) => Effect.succeed(id === parentThreadId ? parentRecords : projection), ); const prepareProviderHandoff = vi.fn< ContextHandoffService.ContextHandoffServiceV2["Service"]["prepareProviderHandoff"] >((handoff) => input.sideChat?.nativeForkFrom === undefined ? Effect.die("history read must fail first") : Effect.succeed({ ...handoff, id: ContextHandoffId.make("side-chat-fork-context"), createdByProviderInstanceId: handoff.toProviderInstanceId, status: "ready", summaryMessageId: null, summaryText: "PARENT_HISTORY", updatedAt: handoff.createdAt, }), ); const getTurnStartContext = vi.fn(() => Effect.succeed({ ...projection, hasConversation: projection.messages.some( (m) => m.role === "user" && (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), ), }), ); const getRuntimeRecoveryProjection = vi.fn< ProjectionStore.ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] >(() => input.recoveryReadFailure !== undefined ? Effect.fail( new ProjectionStore.ProjectionStoreReadError({ threadId, cause: input.recoveryReadFailure, }), ) : Effect.as(failReadIfRunning, { ...projection, hasConversation: projection.messages.some( (m) => m.role === "user" && (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), ), }), ); const getRun = vi.fn((_threadId, id) => Effect.as( failReadIfRunning, projection.runs.find((candidate) => candidate.id === id), ), ); const recreatedBeforeDispatch = { pending: input.recreatedBeforeDispatch === true }; const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ prepareProviderHandoff, }), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent, write: ({ events: incoming }) => Effect.sync(() => { for (const event of incoming) { events.push(event); projection = ProjectionStore.applyToProjection(projection, event); } return []; }), }), IdAllocator.layer, Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread: input.runSetup ?? (() => Effect.succeed({ status: "no-script" })), }), Layer.mock(ThreadWorktreeRestore)({ takeRecreated: () => Effect.sync(() => { if (!recreatedBeforeDispatch.pending || input.worktreePath === undefined) return; recreatedBeforeDispatch.pending = false; return { project: { workspaceRoot: input.workspaceRoot ?? "/tmp/native-account-project", } as never, worktreePath: input.worktreePath, }; }), }), layerWorktreeLocation(input.worktreesDir), layerNoTaskFolders, input.fileSystem === undefined ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) }) : Layer.succeed(FileSystem.FileSystem, input.fileSystem), input.gitWorkflow === undefined ? Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees: () => Effect.void, listLocalBranchNames: () => Effect.succeed(["feature/restore"]), createWorktree, updateWorktreeSubmodules, }) : Layer.succeed(GitWorkflow.GitWorkflowService, input.gitWorkflow), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: input.workspaceRoot ?? "/tmp/native-account-project", } as never), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getForkSourceRunIds: () => Effect.succeed(parentRecords.runs.map((run) => run.id)), getThreadRecords, getTurnStartContext, getTurnItem: () => Effect.succeed(null), getRuntimeRecoveryProjection, getRun, getTurnStartHistory: () => input.sideChat !== undefined || input.previousTurn !== undefined ? Effect.succeed([]) : Effect.fail( new ProjectionStore.ProjectionStoreReadError({ threadId, cause: input.historyReadFailureAfterFallback, }), ), }), Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open, get: () => Effect.succeed( input.previousTurn?.liveSession === false ? Option.none() : Option.some({ driver: providerThread.driver, providerSessionId, interruptTurn, } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime), ), }), Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }), Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun, forkBaseline: () => Effect.succeed(Effect.void), }), Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, { runStarted: () => Effect.void, turnCompleted: () => Effect.void, runSettled: (report) => Effect.sync(() => void settledRuns.push(report.status)), }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy, }), ), ), ); return { layer, interruptRun, settledRuns, getThreadRecords, getTurnStartContext, getRuntimeRecoveryProjection, getRun, setProjection: (next: OrchestrationV2ThreadProjection) => { projection = next; }, resolveRuntimePolicy, createWorktree, updateWorktreeSubmodules, open, fallbackEnsureThread, writeIfRunCurrent, startRootRun, startTurn, forkThread, prepareProviderHandoff, interruptTurn, tryHandlePromptCommand, events, oldInstanceId, newInstanceId, attemptId, projection: () => projection, start: Effect.gen(function* () { yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId }); }).pipe(Effect.provide(layer)), startWithRetry: Effect.gen(function* () { yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId, willRetry: true, }); }).pipe(Effect.provide(layer)), }; } function layerStartEffectWorker( harness: ReturnType, control: Partial = {}, ) { const executor = EffectWorker.layerExecutor.pipe( Layer.provide( Layer.mergeAll( harness.layer, Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), Layer.mock(ProviderTurnControlService.ProviderTurnControlServiceV2)(control), Layer.mock(RunFinalizationService.RunFinalizationService)({}), Layer.mock(CheckpointRollbackService.CheckpointRollbackServiceV2)({}), Layer.mock(RuntimeRequestService.RuntimeRequestServiceV2)({}), Layer.mock(ThreadTitleRegenerationService.ThreadTitleRegenerationService)({}), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(ProjectionStore.ProjectionStoreV2)({}), Layer.mock(ProjectionMaintenance.ProjectionMaintenanceV2)({}), ServerSettings.layerTest(), ), ), ); return EffectWorker.layerWithOptions({ maxAttempts: 2 }).pipe( Layer.provideMerge( Layer.merge(executor, EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))), ), ); } const enqueueStart = ( projection: OrchestrationV2ThreadProjection, request?: EffectOutbox.OrchestrationEffectRequestV2, ) => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; const run = projection.runs.at(-1)!; yield* outbox.enqueue([ { id: "effect:failed-start", commandId: CommandId.make("command:failed-start"), threadId: run.threadId, request: request ?? { type: "provider-turn.start", runId: run.id }, }, ]); return { storedEffect: outbox.get("effect:failed-start").pipe(Effect.map(Option.getOrThrow)) }; }); effectIt.effect( "settles an exhausted start effect without claiming an external turn stopped", () => { const harness = makeLocalCommandHarness({ text: "Continue", missingProviderSession: true }); const projection = harness.projection(); const previousAttempt = { ...projection.attempts[0]!, id: RunAttemptId.make("superseded-attempt"), rootNodeId: NodeId.make("superseded-root"), status: "superseded" as const, }; const externalTurn = { id: ProviderTurnId.make("still-running-provider-turn"), providerThreadId: projection.providerThreads[0]!.id, nodeId: previousAttempt.rootNodeId, runAttemptId: previousAttempt.id, nativeTurnRef: null, ordinal: 1, status: "running" as const, startedAt: projection.updatedAt, completedAt: null, }; harness.setProjection({ ...projection, attempts: [ previousAttempt, { ...projection.attempts[0]!, attemptOrdinal: 2, reason: "steering_restart" }, ], providerTurns: [externalTurn], }); return Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const { storedEffect } = yield* enqueueStart(harness.projection()); expect(yield* worker.drain()).toBe(1); expect(yield* storedEffect).toMatchObject({ status: "pending", attemptCount: 1 }); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.events).toEqual([]); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain()).toBe(1); expect(yield* storedEffect).toMatchObject({ status: "succeeded", attemptCount: 2 }); expect(harness.projection().runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); expect(harness.projection().attempts.at(-1)).toMatchObject({ status: "failed", startedAt: null, }); expect(harness.projection().nodes[0]).toMatchObject({ status: "failed", startedAt: null }); expect(harness.projection().turnItems).toMatchObject([ { type: "error", status: "failed", title: "Turn failed to start", failure: { class: "unknown", message: "T3 Code could not start this turn. Send the message again; if it keeps failing, check the server logs.", }, }, ]); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().providerTurns).toEqual([externalTurn]); }).pipe(Effect.provide(layerStartEffectWorker(harness))); }, ); effectIt.effect("retries a failed settlement past the start budget until it is persisted", () => { const harness = makeLocalCommandHarness({ text: "Continue", missingProviderSession: true }); harness.writeIfRunCurrent.mockImplementationOnce(({ events }) => Effect.fail( new EventSink.EventSinkWriteError({ eventCount: events.length, cause: "storage unavailable", }), ), ); return Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const { storedEffect } = yield* enqueueStart(harness.projection()); yield* worker.drain(); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain()).toBe(1); expect(yield* storedEffect).toMatchObject({ status: "pending", attemptCount: 2 }); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.events).toEqual([]); yield* TestClock.adjust("200 millis"); expect(yield* worker.drain()).toBe(1); expect(yield* storedEffect).toMatchObject({ status: "succeeded", attemptCount: 3 }); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); expect(harness.projection().turnItems).toHaveLength(1); }).pipe(Effect.provide(layerStartEffectWorker(harness))); }); effectIt.effect.each(["interrupt", "start"] as const)( "keeps a failed restart %s separate from starting-run settlement", (stage) => { const harness = makeLocalCommandHarness({ text: "Continue", missingProviderSession: true }); const projection = harness.projection(); const run = projection.runs.at(-1)!; const providerTurnId = ProviderTurnId.make("restart-interrupted-turn"); return Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const { storedEffect } = yield* enqueueStart(projection, { type: "provider-turn.restart", runId: run.id, providerSessionId: ProviderSessionId.make("restart-interrupted-session"), providerThreadId: projection.providerThreads[0]!.id, providerTurnId, interruptedAttemptId: RunAttemptId.make("restart-interrupted-attempt"), }); yield* worker.drain(); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain()).toBe(1); if (stage === "interrupt") { yield* TestClock.adjust("200 millis"); expect(yield* worker.drain()).toBe(1); expect(yield* storedEffect).toMatchObject({ status: "pending", attemptCount: 3 }); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.events).toEqual([]); expect(harness.writeIfRunCurrent).not.toHaveBeenCalled(); } else { expect(yield* storedEffect).toMatchObject({ status: "succeeded", attemptCount: 2 }); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); expect(harness.projection().turnItems).toMatchObject([ { type: "error", title: "Turn failed to start" }, ]); } }).pipe( Effect.provide( layerStartEffectWorker(harness, { interruptAndAwaitTerminal: () => stage === "interrupt" ? Effect.fail( new ProviderTurnControlService.ProviderTurnControlError({ threadId: run.threadId, operation: "restart", providerTurnId, cause: "provider interrupt failed", }), ) : Effect.void, }), ), ); }, ); effectIt.effect.each(["Stop", "a replacement attempt"] as const)( "does not overwrite %s committed during the final start failure write", (change) => { const harness = makeLocalCommandHarness({ text: "Continue", missingProviderSession: true }); const write = harness.writeIfRunCurrent.getMockImplementation()!; let protectedProjection = harness.projection(); harness.writeIfRunCurrent.mockImplementationOnce((input) => Effect.suspend(() => { const projection = harness.projection(); if (change === "Stop") harness.interruptRun(); else { harness.setProjection({ ...projection, runs: projection.runs.map((run) => ({ ...run, activeAttemptId: RunAttemptId.make("replacement-attempt"), rootNodeId: NodeId.make("replacement-root"), })), }); } protectedProjection = harness.projection(); return write(input); }), ); return Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const { storedEffect } = yield* enqueueStart(harness.projection()); yield* worker.drain(); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain()).toBe(1); expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce(); expect(harness.projection()).toEqual(protectedProjection); expect(harness.events).toEqual([]); expect(yield* storedEffect).toMatchObject({ status: "succeeded" }); }).pipe(Effect.provide(layerStartEffectWorker(harness))); }, ); effectIt.effect("preserves a replacement committed after the final pre-running start read", () => { const harness = makeLocalCommandHarness({ text: "Continue", missingProviderSession: true }); const read = harness.getTurnStartContext.getMockImplementation()!; let reads = 0; let replacement: OrchestrationV2ThreadProjection; harness.getTurnStartContext.mockImplementation(() => Effect.suspend(() => { const snapshot = read(); reads++; if (reads === 2) { const projection = harness.projection(); const attemptId = RunAttemptId.make("replacement-before-fallback"); const rootNodeId = NodeId.make("replacement-root-before-fallback"); replacement = { ...projection, runs: projection.runs.map((run) => ({ ...run, activeAttemptId: attemptId, rootNodeId })), attempts: [ ...projection.attempts, { ...projection.attempts[0]!, id: attemptId, rootNodeId }, ], nodes: [...projection.nodes, { ...projection.nodes[0]!, id: rootNodeId }], }; harness.setProjection(replacement); } return snapshot; }), ); return Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const { storedEffect } = yield* enqueueStart(harness.projection()); yield* worker.drain(); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain()).toBe(1); expect(harness.projection()).toEqual(replacement!); expect(harness.events).toEqual([]); expect(yield* storedEffect).toMatchObject({ status: "succeeded", attemptCount: 2 }); }).pipe(Effect.provide(layerStartEffectWorker(harness))); }); effectIt.effect("preserves a replacement committed before exhausted start settlement reads", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true }); harness.getRuntimeRecoveryProjection.mockImplementation(() => Effect.succeed(harness.projection()), ); harness.getRun.mockImplementation((_threadId, id) => Effect.succeed(harness.projection().runs.find((candidate) => candidate.id === id)), ); const projection = harness.projection(); const run = projection.runs[0]!; const replacementAttemptId = RunAttemptId.make("replacement-before-settlement"); const replacementRootId = NodeId.make("replacement-root-before-settlement"); const providerTurn = { id: ProviderTurnId.make("old-start-provider-turn"), providerThreadId: run.providerThreadId!, nodeId: run.rootNodeId!, runAttemptId: run.activeAttemptId!, nativeTurnRef: null, ordinal: 1, status: "running" as const, startedAt: projection.updatedAt, completedAt: null, }; const turnIngested = yield* Deferred.make(); const storageFailure = new EventSink.EventSinkWriteError({ eventCount: 5, cause: "terminal-write ownership query unavailable", }); const write = harness.writeIfRunCurrent.getMockImplementation()!; harness.writeIfRunCurrent.mockImplementation((input) => input.expectedStatus === "running" ? Effect.fail(storageFailure) : write(input), ); harness.open.mockImplementationOnce(() => Effect.fail( new ProviderSessionManager.ProviderSessionOpenError({ instanceId: harness.newInstanceId, providerSessionId: projection.providerThreads[0]!.providerSessionId!, cause: "transient session failure", }), ), ); const executionLayer = RunExecutionService.layer.pipe( Layer.provide( Layer.mergeAll( McpAppModelContext.layerEmpty, PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.mock(EventSink.EventSinkV2)({ consumeProviderEvents: (source, process, after) => source.pipe( Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))), Stream.takeUntil(Boolean), Stream.runDrain, ), writeIfRunCurrent: harness.writeIfRunCurrent, }), IdAllocator.layer, ThreadCommandExecutor.layer, Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ ingestNormalized: () => Effect.sync(() => { harness.setProjection({ ...harness.projection(), providerTurns: [providerTurn] }); }).pipe(Effect.andThen(Deferred.succeed(turnIngested, undefined)), Effect.as([])), }), ServerSettings.layerTest(), ), ), ); let protectedProjection = projection; let escapedStartError: RunExecutionService.RunExecutionServiceV2Error | undefined; return yield* Effect.gen(function* () { const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const outbox = yield* EffectOutbox.EffectOutboxV2; harness.startRootRun.mockImplementation((input) => Effect.gen(function* () { const execution = yield* RunExecutionService.RunExecutionServiceV2; yield* execution.startRootRun({ ...input, session: { ...input.session, events: Stream.concat( Stream.succeed({ type: "provider_turn.updated" as const, driver: input.providerThread.driver, threadId: run.threadId, providerTurn, }), Stream.never, ), startTurn: () => Effect.gen(function* () { yield* Deferred.await(turnIngested); const current = harness.projection(); expect(current.runs[0]?.status).toBe("running"); // Steering commits a new attempt while the original start still owns the lane. harness.setProjection({ ...current, runs: [ { ...current.runs[0]!, status: "starting", activeAttemptId: replacementAttemptId, rootNodeId: replacementRootId, }, ], attempts: [ { ...current.attempts[0]!, status: "superseded", completedAt: current.updatedAt, }, { ...projection.attempts[0]!, id: replacementAttemptId, rootNodeId: replacementRootId, attemptOrdinal: 2, reason: "steering_restart", }, ], nodes: [ { ...current.nodes[0]!, status: "interrupted", completedAt: current.updatedAt, }, { ...projection.nodes[0]!, id: replacementRootId, rootNodeId: replacementRootId, }, ], }); protectedProjection = harness.projection(); yield* outbox .enqueue([ { id: "effect:replacement-restart", commandId: CommandId.make("command:replacement-restart"), threadId: run.threadId, request: { type: "provider-turn.restart", runId: run.id, providerSessionId: input.providerSessionId, providerThreadId: run.providerThreadId!, providerTurnId: providerTurn.id, interruptedAttemptId: input.attemptId, }, }, ]) .pipe(Effect.orDie); return yield* new ProviderAdapter.ProviderAdapterTurnStartError({ driver: input.session.driver, threadId: run.threadId, providerThreadId: run.providerThreadId!, runId: run.id, cause: "provider start failed after publishing its turn", }); }), }, }); }).pipe( Effect.tapError((error) => Effect.sync(() => { escapedStartError = error; }), ), Effect.provide(executionLayer.pipe(Layer.orDie)), ), ); const { storedEffect } = yield* enqueueStart(projection); expect(yield* worker.drain()).toBe(1); yield* TestClock.adjust("100 millis"); expect(yield* worker.drain(1)).toBe(1); expect(escapedStartError).toMatchObject({ cause: { write: storageFailure } }); expect(yield* outbox.get("effect:replacement-restart")).toMatchObject({ value: { status: "pending", attemptCount: 0 }, }); expect(yield* storedEffect).toMatchObject({ status: "succeeded", attemptCount: 2 }); expect(harness.projection()).toEqual(protectedProjection); }).pipe(Effect.provide(layerStartEffectWorker(harness))); }), ); effectIt.effect( "recovers the local or pushed thread tip, else the current branch, remote default, or detached HEAD", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const gitWorkflow = yield* GitWorkflow.GitWorkflowService; const driver = yield* GitVcsDriver.GitVcsDriver; const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-repo-" }); const workspaceRoot = path.join(root, "project"); const originRoot = path.join(root, "origin.git"); const worktreesDir = path.join(root, "worktrees"); const worktreePath = path.join(worktreesDir, "project", "restore"); yield* fileSystem.makeDirectory(workspaceRoot); const git = (cwd: string, args: ReadonlyArray) => driver .execute({ operation: "test.worktreeRecovery", cwd, args }) .pipe(Effect.map((result) => result.stdout.trim())); const branchConfig = (key: string) => git(workspaceRoot, ["config", "--get", `branch.feature/restore.${key}`]).pipe( Effect.orElseSucceed(() => ""), ); yield* git(root, ["init", "--bare", "-b", "main", originRoot]); yield* git(workspaceRoot, ["init", "-b", "main"]); yield* git(workspaceRoot, ["config", "user.name", "Test"]); yield* git(workspaceRoot, ["config", "user.email", "test@example.com"]); yield* git(workspaceRoot, ["commit", "--allow-empty", "-m", "base"]); const baseTip = yield* git(workspaceRoot, ["rev-parse", "HEAD"]); yield* git(workspaceRoot, ["remote", "add", "origin", originRoot]); yield* git(workspaceRoot, ["push", "origin", "main"]); yield* git(workspaceRoot, ["remote", "set-head", "origin", "main"]); yield* git(workspaceRoot, ["worktree", "add", "-b", "feature/restore", worktreePath]); yield* fileSystem.writeFileString(path.join(worktreePath, "thread.txt"), "thread work"); yield* git(worktreePath, ["add", "."]); yield* git(worktreePath, ["commit", "-m", "thread tip"]); const threadTip = yield* git(worktreePath, ["rev-parse", "HEAD"]); yield* git(workspaceRoot, ["switch", "-c", "project-current"]); yield* fileSystem.writeFileString( path.join(workspaceRoot, "project.txt"), "new project code", ); yield* git(workspaceRoot, ["add", "."]); yield* git(workspaceRoot, ["commit", "-m", "project tip"]); const projectTip = yield* git(workspaceRoot, ["rev-parse", "HEAD"]); expect(projectTip).not.toBe(threadTip); // Tags must neither hide the thread branch nor select a different recovery tip. yield* git(workspaceRoot, ["tag", "feature/restore", projectTip]); yield* git(workspaceRoot, ["tag", "project-current", threadTip]); yield* git(workspaceRoot, ["tag", "origin/feature/restore", threadTip]); const expectedTips = { retained: { tip: threadTip, file: "thread.txt", upstream: null, base: "" }, // A failed removal can leave the folder behind with only dependencies inside. leftover: { tip: threadTip, file: "thread.txt", upstream: null, base: "" }, deleted: { tip: projectTip, file: "project.txt", upstream: null, base: "project-current" }, pushed: { tip: threadTip, file: "thread.txt", upstream: "refs/remotes/origin/feature/restore", base: "", }, "pushed-detached": { tip: threadTip, file: "thread.txt", upstream: "refs/remotes/origin/feature/restore", base: "", }, "pushed-sole-remote": { tip: threadTip, file: "thread.txt", upstream: "refs/remotes/upstream/feature/restore", base: "", }, detached: { tip: baseTip, file: null, upstream: null, base: "main" }, "detached-no-remote": { tip: projectTip, file: "project.txt", upstream: null, base: "" }, } as const; // Reuse the workflow across turns so recovery cannot select a cached project branch. for (const scenario of Object.keys(expectedTips) as Array) { const expected = expectedTips[scenario]; if (scenario === "pushed") { yield* git(workspaceRoot, ["push", "origin", `${threadTip}:refs/heads/feature/restore`]); yield* git(workspaceRoot, ["fetch", "origin"]); } if (scenario === "pushed-detached") { yield* git(workspaceRoot, ["switch", "--detach"]); expect(yield* git(workspaceRoot, ["branch", "--show-current"])).toBe(""); } if (scenario === "pushed-sole-remote") { yield* git(workspaceRoot, ["remote", "rename", "origin", "upstream"]); } if (scenario === "detached") { yield* git(workspaceRoot, ["remote", "rename", "upstream", "origin"]); yield* git(workspaceRoot, ["push", "origin", "--delete", "feature/restore"]); } if (scenario === "detached-no-remote") { yield* git(workspaceRoot, ["remote", "remove", "origin"]); } yield* fileSystem.remove(worktreePath, { recursive: true }); if (scenario === "leftover") { yield* fileSystem.makeDirectory(path.join(worktreePath, "node_modules"), { recursive: true, }); } if (scenario !== "retained" && scenario !== "leftover") { yield* git(workspaceRoot, ["worktree", "prune"]); yield* git(workspaceRoot, ["branch", "-D", "feature/restore"]); } const harness = makeLocalCommandHarness({ text: "Continue", workspaceRoot, worktreePath, worktreesDir, fileSystem, gitWorkflow, failReadsAfterRunning: true, }); const open = harness.open.getMockImplementation()!; harness.open.mockImplementation(() => Effect.gen(function* () { expect(yield* git(worktreePath, ["branch", "--show-current"])).toBe("feature/restore"); expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe(expected.tip); for (const file of ["thread.txt", "project.txt"]) { expect(yield* fileSystem.exists(path.join(worktreePath, file))).toBe( file === expected.file, ); } expect(yield* branchConfig("merge")).toBe( expected.upstream === null ? "" : "refs/heads/feature/restore", ); if (expected.upstream !== null) { expect( yield* git(worktreePath, ["rev-parse", "--symbolic-full-name", "@{upstream}"]), ).toBe(expected.upstream); } expect(yield* branchConfig("t3-merge-base")).toBe(expected.base); return yield* open(); }).pipe(Effect.orDie), ); yield* harness.start; expect(harness.open).toHaveBeenCalledOnce(); expect(harness.startRootRun).toHaveBeenCalledWith( expect.objectContaining({ runtimePolicy: expect.objectContaining({ cwd: worktreePath }), }), ); expect(harness.projection().runs.at(-1)?.status).toBe("running"); } }).pipe(Effect.scoped, Effect.provide(layerRealGit)), ); effectIt.effect("leaves a managed worktree folder without .git that holds user files", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-leftover-" }); const worktreePath = path.join(worktreesDir, "project", "restore"); yield* fileSystem.makeDirectory(path.join(worktreePath, "node_modules"), { recursive: true }); yield* fileSystem.writeFileString(path.join(worktreePath, "notes.md"), "keep me"); const harness = makeLocalCommandHarness({ text: "Continue", worktreePath, worktreesDir, fileSystem, failReadsAfterRunning: true, }); yield* harness.start; expect(harness.createWorktree).not.toHaveBeenCalled(); expect(yield* fileSystem.readFileString(path.join(worktreePath, "notes.md"))).toBe("keep me"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); effectIt.effect.each([ { async: false, exitCode: 0 }, { async: false, exitCode: 1 }, { async: true, exitCode: 0 }, ])("restored setup respects async=$async and exitCode=$exitCode", (input) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-setup-" }); const worktreePath = path.join(worktreesDir, "project", "restore"); const setupStarted = yield* Deferred.make(); const setupDone = yield* Deferred.make(); const completionObserved = yield* Deferred.make(); const harness = makeLocalCommandHarness({ text: "Continue", worktreesDir, worktreePath, fileSystem, failReadsAfterRunning: true, runSetup: () => withWorkspaceLease(worktreePath, Deferred.succeed(setupStarted, undefined)).pipe( Effect.as({ status: "started", scriptId: "setup", scriptName: "Setup", scriptCommand: "setup", terminalId: "setup-test", cwd: worktreePath, async: input.async, completion: Deferred.await(setupDone).pipe( Effect.tap(() => Deferred.succeed(completionObserved, undefined)), ), }), ), }); harness.createWorktree.mockImplementation(() => fileSystem .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) .pipe(Effect.as({} as never), Effect.orDie), ); const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(setupStarted); if (input.async) yield* Fiber.join(startup); else expect(harness.open).not.toHaveBeenCalled(); yield* Deferred.succeed(setupDone, { exitCode: input.exitCode, durationMs: 0 }); yield* Deferred.await(completionObserved); yield* Fiber.join(startup); const failed = !input.async && input.exitCode !== 0; expect(harness.projection().runs.at(-1)?.status).toBe(failed ? "failed" : "running"); expect(harness.open).toHaveBeenCalledTimes(failed ? 0 : 1); if (failed) { expect(harness.projection().turnItems).toMatchObject([ { type: "error", title: "Couldn't set up restored workspace", failure: { message: `Setup script exited with ${input.exitCode} in '${worktreePath}'.`, }, }, ]); } }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect("runs setup for a worktree a send recreated before dispatch", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-sent-setup-" }); const worktreePath = path.join(worktreesDir, "project", "restore"); yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true }); const runSetup = vi.fn(() => Effect.succeed({ status: "no-script" as const })); const harness = makeLocalCommandHarness({ text: "Continue", worktreesDir, worktreePath, fileSystem, failReadsAfterRunning: true, recreatedBeforeDispatch: true, runSetup, }); yield* harness.start; expect(harness.createWorktree).not.toHaveBeenCalled(); expect(runSetup).toHaveBeenCalledWith(expect.objectContaining({ worktreePath })); expect(harness.open).toHaveBeenCalledTimes(1); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect( "preserves recreation interrupts and retries, then fails the final attempt before provider start", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-failure-", }); const worktreePath = path.join(worktreesDir, "project", "restore"); const harness = makeLocalCommandHarness({ text: "Continue", worktreesDir, worktreePath, fileSystem, failReadsAfterRunning: true, }); harness.createWorktree.mockImplementationOnce(() => Effect.interrupt); harness.createWorktree.mockImplementation(() => Effect.fail( new GitCommandError({ operation: "worktree-add", command: "git worktree add", cwd: "/tmp/native-account-project", detail: "fatal: private git diagnostic", }), ), ); const interrupted = yield* Effect.exit(harness.start); expect(interrupted._tag).toBe("Failure"); if (interrupted._tag === "Failure") expect(Cause.hasInterruptsOnly(interrupted.cause)).toBe(true); expect(harness.events).toEqual([]); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); const retry = yield* Effect.result(harness.startWithRetry); expect(retry).toMatchObject({ _tag: "Failure", failure: { _tag: "ProviderTurnStartError" } }); expect(harness.events).toEqual([]); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); yield* harness.start; expect(harness.createWorktree).toHaveBeenCalledTimes(3); expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce(); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.turnItems).toMatchObject([ { type: "error", failure: { message: `Could not recreate the worktree for branch 'feature/restore' at ${worktreePath}.`, }, }, ]); expect(JSON.stringify(harness.events)).not.toContain("private git diagnostic"); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect("finishes the submodules of a recreation a stopped turn left unfinished", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-stop-" }); const worktreePath = path.join(worktreesDir, "project", "restore"); const adminDir = path.join(worktreesDir, "admin"); const runSetup = vi.fn(() => Effect.succeed({ status: "no-script" as const })); const harness = makeLocalCommandHarness({ text: "Continue", worktreesDir, worktreePath, fileSystem, failReadsAfterRunning: true, runSetup, }); // Stopped after the checkout exists, while Git still initializes its submodules. harness.createWorktree.mockImplementationOnce((_input, options) => Effect.gen(function* () { yield* fileSystem.makeDirectory(adminDir, { recursive: true }); yield* fileSystem.makeDirectory(worktreePath, { recursive: true }); yield* fileSystem.writeFileString(path.join(worktreePath, ".git"), `gitdir: ${adminDir}\n`); yield* options?.progress?.onWorktreeClaimed?.(worktreePath) ?? Effect.void; return yield* Effect.interrupt; }).pipe(Effect.orDie), ); harness.updateWorktreeSubmodules.mockImplementationOnce(() => Effect.fail( new GitCommandError({ operation: "submodule-update", command: "git submodule update", cwd: worktreePath, detail: "fatal: could not lock config file", }), ), ); const stopped = yield* Effect.exit(harness.start); expect(stopped._tag === "Failure" && Cause.hasInterruptsOnly(stopped.cause)).toBe(true); expect(yield* fileSystem.readDirectory(adminDir)).toHaveLength(1); const failed = yield* Effect.result(harness.startWithRetry); expect(failed._tag).toBe("Failure"); expect(yield* fileSystem.readDirectory(adminDir)).toHaveLength(1); expect(runSetup).not.toHaveBeenCalled(); yield* harness.start; expect(harness.updateWorktreeSubmodules).toHaveBeenCalledTimes(2); expect(harness.updateWorktreeSubmodules).toHaveBeenLastCalledWith({ cwd: "/tmp/native-account-project", worktreePath, }); expect(harness.createWorktree).toHaveBeenCalledOnce(); expect(yield* fileSystem.readDirectory(adminDir)).toEqual([]); expect(runSetup).toHaveBeenCalledWith(expect.objectContaining({ worktreePath })); expect(harness.open).toHaveBeenCalledTimes(1); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); effectIt.effect("recovers an abandoned failed turn before continuing its native conversation", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "failed", turnStatus: "running" }, }); yield* harness.start; expect(harness.interruptTurn).toHaveBeenCalledOnce(); expect(harness.projection().runs.at(-1)?.status).toBe("running"); expect(harness.projection().providerTurns[0]).toMatchObject({ status: "interrupted", completedAt: expect.anything(), }); expect(harness.startRootRun).toHaveBeenCalledOnce(); expect(harness.startRootRun.mock.calls[0]?.[0].providerThread.nativeThreadRef?.nativeId).toBe( "existing-native-conversation", ); }), ); effectIt.effect( "recovers a running turn its interrupted run left behind on a superseded attempt", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "interrupted", turnStatus: "running", supersededTurn: true }, }); yield* harness.start; expect(harness.interruptTurn).toHaveBeenCalledOnce(); // The steered attempt's turn was already interrupted in the fixture; the // repair this asserts is the running turn left on the superseded attempt. const abandoned = harness .projection() .providerTurns.find((turn) => turn.id === ProviderTurnId.make("previous-provider-turn")); expect(abandoned).toMatchObject({ status: "interrupted", completedAt: expect.anything(), }); expect(harness.projection().runs.at(-1)?.status).toBe("running"); expect(harness.startRootRun).toHaveBeenCalledOnce(); }), ); it("finds abandoned turns in a long history reading each record a bounded number of times", () => { let reads = 0; const counted = (record: T): T => new Proxy(record, { get: (target, key, receiver) => { reads += 1; return Reflect.get(target, key, receiver); }, }); const providerThreadId = ProviderThreadId.make("provider-thread-long-history"); const endings = ["failed", "interrupted", "cancelled"] as const; const runs = []; const attempts = []; const providerTurns = []; for (let index = 0; index < 2_000; index += 1) { // Every tenth run ended without completing, after a steering restart. const status = index % 10 === 0 ? endings[(index / 10) % endings.length]! : "completed"; const attemptIds = status === "completed" ? [`a${index}`] : [`a${index}-steered`, `a${index}`]; runs.push({ id: `r${index}`, ordinal: index + 1, status, providerThreadId, activeAttemptId: attemptIds.at(-1), }); for (const attemptId of attemptIds) { attempts.push({ id: attemptId, runId: `r${index}` }); const running = attemptId === "a10-steered" || attemptId === "a20" || attemptId === "a21"; providerTurns.push({ id: `t-${attemptId}`, providerThreadId, runAttemptId: attemptId, status: running ? "running" : "completed", }); } } const projection = { runs: runs.map(counted), attempts: attempts.map(counted), providerTurns: providerTurns.map(counted), } as unknown as Parameters[0]; const abandoned = ProviderTurnStart.abandonedProviderTurns( projection, { ordinal: 2_001 }, providerThreadId, ); expect(abandoned.map(({ turn, run }) => [turn.id, run.id])).toEqual([ ["t-a10-steered", "r10"], ["t-a20", "r20"], ]); const records = runs.length + attempts.length + providerTurns.length; expect(reads).toBeLessThanOrEqual(4 * records); }); const ran = { status: "completed", checkpoint: "ready" }; const removed = { status: "cancelled", checkpoint: null }; // A queued message whose prompt now belongs to the run at `ordinal`. const steeredInto = (ordinal: number) => ({ ...removed, steeredInto: `run-${ordinal}` }); effectIt.effect.each([ { label: "a queued message steered into it", runs: [ran, steeredInto(1)], source: 1 }, { label: "several steered into it", runs: [ran, steeredInto(1), steeredInto(1)], source: 1 }, { label: "a removed queued message", runs: [ran, removed], source: undefined }, { label: "a queued message that ran", runs: [ran, ran], source: undefined }, { label: "a message steered into the starting run", runs: [ran, steeredInto(3)], source: undefined, }, { label: "a turn whose checkpoint was not captured", runs: [{ ...ran, checkpoint: "error" }, steeredInto(1)], source: undefined, }, { label: "a failed run", runs: [{ ...ran, status: "failed" }, steeredInto(1)], source: undefined, }, { label: "a missing row", runs: [ran, null, steeredInto(1)], source: undefined }, ])("starts a turn from the last turn's checkpoint after $label", (input) => Effect.gen(function* () { const ordinal = input.runs.length + 1; const runs = [ ...input.runs.flatMap((run, index) => run === null ? [] : [ { ...run, id: `run-${index + 1}`, userMessageId: `message-${index + 1}`, ordinal: index + 1, checkpointId: run.checkpoint === null ? null : `checkpoint-${index + 1}`, }, ], ), { id: `run-${ordinal}`, userMessageId: "message-starting", ordinal, status: "starting", checkpoint: null, checkpointId: null, }, ]; const source = yield* ProviderTurnStart.findBaselineSourceOrdinal( runs as unknown as Parameters[0], { ordinal }, (messageId) => { const queued = runs.find((run) => run.userMessageId === messageId); return Effect.succeed( queued !== undefined && "steeredInto" in queued ? ({ type: "user_message", inputIntent: "promoted_queued_to_steer", runId: queued.steeredInto, } as OrchestrationV2TurnItem) : null, ); }, (checkpointId) => { const owner = runs.find((run) => run.checkpointId === checkpointId); return Effect.succeed({ checkpoints: owner === undefined ? [] : [ { id: checkpointId, runId: owner.id, appRunOrdinal: owner.ordinal, status: owner.checkpoint, } as OrchestrationV2Checkpoint, ], }); }, ); expect(source).toBe(input.source); }), ); effectIt.effect("sends new steering text when restarting a manual continuation", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "New steering instruction", manualContinuation: true, steeringRestart: true, nativeResumeUnsupported: true, sideChat: { contextRun: "delivered" }, }); yield* harness.start; expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("New steering instruction"); expect(harness.startRootRun.mock.calls[0]?.[0].resume).toBe(false); }), ); effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", manualContinuation: true, nativeResumeUnsupported: true, sideChat: { contextRun: "delivered" }, }); yield* harness.start; expect(harness.startTurn).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.settledRuns).toEqual(["failed"]); expect(harness.projection().turnItems).toEqual( expect.arrayContaining([ expect.objectContaining({ type: "error", failure: expect.objectContaining({ message: "This provider cannot resume without a new message. Send a message to continue.", }), }), ]), ); }), ); effectIt.effect.each([ { contextRun: "current" }, { contextRun: "failed", switchedProvider: true }, ] as const)( "a resume that carries pending context asks a provider without native resume to continue: %j", (sideChat) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", manualContinuation: true, nativeResumeUnsupported: true, sideChat, }); yield* harness.start; expect(harness.settledRuns).toEqual([]); expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), ]); }), ); effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "cancelled", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", switchedProvider: true, runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT", }, { contextRun: "delivered", runtimeMode: "full-access", context: "" }, { contextRun: "delivered", runtimeMode: "full-access", context: "", unsentResume: true }, { contextRun: "delivered", runtimeMode: "full-access", context: "", unsentResume: true, repeatedResume: true, }, { contextRun: "delivered", runtimeMode: "full-access", context: "", unsentResume: true, acceptedResume: true, }, { contextRun: "delivered", runtimeMode: "full-access", context: "", unsentResume: true, acceptedResume: true, restartedResume: true, }, { contextRun: "current", threadRuntimeMode: "approval-required", runtimeMode: "approval-required", context: "SIDE_CHAT_CONTEXT", }, ] as const)( "sends side chat context inline once, for the first turn that reaches the provider: %j", ({ runtimeMode, context, ...sideChat }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", manualContinuation: true, sideChat, }); yield* harness.start; expect(harness.open).toHaveBeenCalledWith( expect.objectContaining({ runtimePolicy: expect.objectContaining({ runtimeMode }) }), ); const resendsOriginal = "unsentResume" in sideChat && (!("acceptedResume" in sideChat) || "restartedResume" in sideChat); const texts = harness.startTurn.mock.calls.map(([turn]) => turn.message.text); expect(texts).toHaveLength(1); if (resendsOriginal || context === "") { expect(texts[0]).toBe( withInlineContext(context, resendsOriginal ? "Original request" : ""), ); } else { // A resume that has to carry context still tells the agent to continue. const contextPrefix = withInlineContext(context, ""); expect(texts[0]?.startsWith(contextPrefix)).toBe(true); expect(texts[0]?.slice(contextPrefix.length).trim()).not.toBe(""); } expect(harness.startTurn.mock.calls[0]?.[0].resume === true).toBe( context === "" && !resendsOriginal, ); expect(harness.projection().contextHandoffs).toMatchObject([ { id: "side-chat-context", toProviderThreadId: "new-provider-thread", delivery: { nativeThreadId: "side-chat-native", status: "inline" }, }, ]); }), ); effectIt.effect.each([ { scheduled: false, status: "superseded" }, { scheduled: true, status: "ready" }, ] as const)( "a fresh run starts without failed runs' side chat notes; an unscheduled one retires them: %j", ({ scheduled, status }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Start over", sideChat: { contextRun: "failed" }, }); const projection = harness.projection(); const current = projection.runs.at(-1)!; const [note] = projection.contextHandoffs; harness.setProjection({ ...projection, runs: projection.runs.map((run) => run.id === current.id ? { ...run, freshContext: true } : run, ), // Each send that fails before the side chat's fork resolves leaves its own note. contextHandoffs: [ ...projection.contextHandoffs, { ...note!, id: ContextHandoffId.make("side-chat-context-retry") }, ], turnItems: scheduled ? [ ...projection.turnItems, { type: "user_message", id: TurnItemId.make("scheduled-fresh-message"), threadId: projection.thread.id, runId: current.id, nodeId: null, providerThreadId: current.providerThreadId, providerTurnId: null, nativeItemRef: null, parentItemId: null, ordinal: 0, status: "completed", title: null, startedAt: projection.updatedAt, completedAt: projection.updatedAt, updatedAt: projection.updatedAt, createdBy: "user", creationSource: "server", messageId: current.userMessageId, text: "Start over", inputIntent: "turn_start", attachments: [], scheduledTaskId: ScheduledTaskId.make("fresh-session-task"), }, ] : projection.turnItems, }); yield* harness.start; expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("Start over"); expect( harness.projection().contextHandoffs.map((handoff) => [handoff.status, handoff.delivery]), ).toEqual([ [status, undefined], [status, undefined], ]); }), ); effectIt.effect.each([ { nativeForkFrom: "idle", canForkWhileSourceRunning: false, sourceBoundary: "native", forks: true, transferStatus: "consumed", handoffIds: [], }, { nativeForkFrom: "busy", canForkWhileSourceRunning: true, sourceBoundary: "native", forks: true, transferStatus: "consumed", handoffIds: [], }, { nativeForkFrom: "busy", canForkWhileSourceRunning: false, sourceBoundary: "native", forks: false, transferStatus: "resolved_portable", handoffIds: ["side-chat-fork-context"], }, { nativeForkFrom: "busy", canForkWhileSourceRunning: true, sourceBoundary: "synthetic", forks: false, transferStatus: "resolved_portable", handoffIds: ["side-chat-fork-context"], }, { nativeForkFrom: "busy", canForkWhileSourceRunning: true, exposesNativeTurnId: false, sourceBoundary: "synthetic", forks: true, transferStatus: "consumed", handoffIds: [], }, ] as const)( "runs a planned native side chat fork when the parent is $nativeForkFrom with canForkWhileSourceRunning=$canForkWhileSourceRunning, sourceBoundary=$sourceBoundary and exposesNativeTurnId=$exposesNativeTurnId", ({ nativeForkFrom, sourceBoundary, forks, transferStatus, handoffIds, ...capability }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "What is the main thread doing?", sideChat: { contextRun: "current", nativeForkFrom, sourceBoundary }, ...capability, }); yield* harness.start; expect(harness.forkThread).toHaveBeenCalledTimes(forks ? 1 : 0); // The parent's rolled-back turn is gone from its native conversation. expect( harness.forkThread.mock.calls[0]?.[0].sourceProviderTurns?.map((turn) => turn.id), ).toEqual(forks ? ["side-chat-parent-turn-1"] : undefined); if (forks) { expect(harness.forkThread).toHaveBeenCalledWith( expect.objectContaining({ providerTurnId: "side-chat-parent-turn-1", message: expect.objectContaining({ text: "What is the main thread doing?" }), }), ); } expect(harness.projection().contextTransfers).toMatchObject([ { id: "side-chat-fork", status: transferStatus }, ]); expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("PARENT_HISTORY")).toBe( !forks, ); expect(harness.projection().providerThreads[0]?.handoffIds).toEqual(handoffIds); }), ); effectIt.effect.each( ( [ { goalDriver: "opencode", nativeGoals: false }, { goalDriver: "opencode", nativeGoals: true }, { goalDriver: "antigravity", nativeGoals: false }, { goalDriver: "antigravity", nativeGoals: true }, ] as const ).flatMap((choice) => [ { ...choice, resuming: false }, { ...choice, resuming: true }, ]), )( "$goalDriver goal prompts go verbatim whether or not goals are native: $nativeGoals, resuming: $resuming", ({ goalDriver, nativeGoals, resuming }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: resuming ? "" : "/goal all tests pass", manualContinuation: resuming, goalDriver, nativeGoals, sideChat: { contextRun: "failed", switchedProvider: true, unsentResume: resuming }, }); if (resuming) { const projection = harness.projection(); harness.setProjection({ ...projection, messages: projection.messages.map((message) => message.id === "original-unsent-message" ? { ...message, text: "/goal all tests pass" } : message, ), }); } harness.tryHandlePromptCommand.mockReturnValue(Effect.succeed(false)); yield* harness.start; expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("/goal all tests pass"); }), ); effectIt.effect.each(["before-start", "during-fork"] as const)( "recovers a planned native fork after the parent rolls back %s", (rollback) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue from the selected turn", sideChat: { contextRun: "current", nativeForkFrom: "idle", sourceRolledBack: rollback === "before-start", }, }); const parentThreadId = ThreadId.make("side-chat-parent"); let parent = { ...harness.projection(), ...(yield* harness.getThreadRecords(parentThreadId, [ "runs", "attempts", "providerThreads", "providerTurns", "turnItems", ])), }; const selectedRun = parent.runs[0]!; const earlierRun = { ...selectedRun, id: RunId.make("side-chat-kept-run"), ordinal: 1, activeAttemptId: null, status: "completed" as const, }; const items = [earlierRun, selectedRun].map((sourceRun, ordinal) => ({ type: "user_message" as const, id: TurnItemId.make(`parent-item-${ordinal}`), threadId: parentThreadId, runId: sourceRun.id, nodeId: null, providerThreadId: sourceRun.providerThreadId, providerTurnId: null, nativeItemRef: null, parentItemId: null, ordinal, status: "completed" as const, title: null, startedAt: parent.updatedAt, completedAt: parent.updatedAt, updatedAt: parent.updatedAt, createdBy: "user" as const, creationSource: "server" as const, messageId: MessageId.make(`parent-message-${ordinal}`), text: ordinal === 0 ? "KEPT_HISTORY" : "ROLLED_BACK_HISTORY", inputIntent: "turn_start" as const, attachments: [], })); parent = { ...parent, runs: [ earlierRun, ...parent.runs.map((sourceRun) => ({ ...sourceRun, ordinal: sourceRun.ordinal + 1 })), ], turnItems: items, }; harness.getThreadRecords.mockImplementation((id) => Effect.succeed(id === parentThreadId ? parent : harness.projection()), ); harness.forkThread.mockImplementation(() => Effect.sync(() => { parent = { ...parent, runs: parent.runs.map((sourceRun) => sourceRun.id === selectedRun.id ? { ...sourceRun, status: "rolled_back" } : sourceRun, ), }; }).pipe( Effect.andThen( Effect.fail( new ProviderAdapter.ProviderAdapterForkThreadError({ driver: ProviderDriverKind.make("codex"), providerThreadId: ProviderThreadId.make("side-chat-parent-provider-thread"), cause: "Selected native turn was removed by rollback", }), ), ), ), ); yield* harness.start; expect(harness.forkThread).toHaveBeenCalledTimes(rollback === "before-start" ? 0 : 1); expect(harness.projection().contextTransfers).toMatchObject([ { id: "side-chat-fork", status: "resolved_portable" }, ]); expect(harness.startTurn.mock.calls[0]?.[0].message.text).toContain("PARENT_HISTORY"); expect(harness.projection().providerThreads[0]?.handoffIds).toEqual([ "side-chat-fork-context", ]); expect(harness.settledRuns).toEqual([]); expect( harness.prepareProviderHandoff.mock.calls[0]?.[0].items.map((item) => item.id), ).toEqual([items[0]!.id]); }), ); effectIt.effect.each([ { runStatus: "failed", turnStatus: "completed" }, { runStatus: "completed", turnStatus: "completed" }, { runStatus: "failed", turnStatus: "running", differentThread: true }, { runStatus: "failed", turnStatus: "running", liveSession: false }, { runStatus: "failed", turnStatus: "interrupted", interruptFailure: true }, ] as const)("continues without interrupting when recovery does not apply: %j", (previousTurn) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn }); yield* harness.start; expect(harness.interruptTurn).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("running"); }), ); effectIt.effect("leaves delegated children to their own runs when the parent starts a turn", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "completed", turnStatus: "completed" }, }); const projection = harness.projection(); const completedChild = (origin: "provider_native" | "app_owned") => ({ id: NodeId.make(`node:${origin}`), threadId: projection.thread.id, runId: projection.runs[0]!.id, parentNodeId: NodeId.make(`node:${origin}:parent`), origin, createdBy: "agent" as const, driver: ProviderDriverKind.make("codex"), providerInstanceId: ProviderInstanceId.make("codex"), providerThreadId: ProviderThreadId.make(`provider-thread:${origin}`), childThreadId: ThreadId.make(`thread:${origin}`), nativeTaskRef: null, prompt: "work", title: null, model: null, status: "completed" as const, result: "done", startedAt: null, completedAt: null, updatedAt: projection.updatedAt, }); harness.setProjection({ ...projection, subagents: [completedChild("provider_native"), completedChild("app_owned")], }); yield* harness.start; // A delegated child thread has its own run on the shared session; a parent run that also // owns it ingests every one of the child's later items a second time. expect(harness.startRootRun.mock.calls[0]?.[0]).toMatchObject({ relatedThreadIds: [ThreadId.make("thread:provider_native")], relatedProviderThreadIds: [ProviderThreadId.make("provider-thread:provider_native")], }); }), ); effectIt.effect("does not start another turn when abandoned-turn cleanup fails", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true }, }); yield* harness.start; expect(harness.interruptTurn).toHaveBeenCalledOnce(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); }), ); effectIt.effect("retries abandoned-turn cleanup without failing the continuation early", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true }, }); const error = yield* harness.startWithRetry.pipe(Effect.flip); expect(error._tag).toBe("ProviderTurnStartError"); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.open).not.toHaveBeenCalled(); }), ); effectIt.effect("does not start the continuation if recording recovery fails", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "failed", turnStatus: "running" }, writeFailure: new Error("database unavailable"), }); const error = yield* harness.start.pipe(Effect.flip); expect(error._tag).toBe("ProviderTurnStartError"); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.projection().providerTurns[0]?.status).toBe("running"); expect(harness.open).not.toHaveBeenCalled(); }), ); effectIt.effect("does not resume a continuation stopped while recovery was in flight", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "failed", turnStatus: "running", interruptCurrentRun: true }, }); yield* harness.start; expect(harness.projection().runs.at(-1)?.status).toBe("interrupted"); expect(harness.open).not.toHaveBeenCalled(); }), ); effectIt.effect.each(["cleanup-first", "startup-first"])( "coordinates provider startup with %s", (order) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" }); const worktreePath = path.join(workspaceRoot, "project", "worktree"); yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true }); const release = yield* Deferred.make(); const openEntered = yield* Deferred.make(); const harness = makeLocalCommandHarness({ text: "Continue", worktreePath, worktreesDir: workspaceRoot, fileSystem, failReadsAfterRunning: true, }); harness.createWorktree.mockImplementation(() => fileSystem .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) .pipe(Effect.as({} as never), Effect.orDie), ); const open = harness.open.getMockImplementation()!; harness.open.mockImplementation(() => Effect.gen(function* () { expect(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)).toBe(true); yield* Deferred.succeed(openEntered, undefined); if (order === "startup-first") yield* Deferred.await(release); return yield* open(); }), ); let cleanupEntered = false; const cleanupEffect = withWorkspaceLease( worktreePath, Effect.gen(function* () { cleanupEntered = true; if (order === "cleanup-first") yield* Deferred.await(release); else { expect(harness.projection().providerSessions).toHaveLength(1); expect(harness.projection().runs.at(-1)?.status).toBe("running"); } yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); }), ); const cleanup = order === "cleanup-first" ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) : undefined; const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); if (order === "cleanup-first") expect(harness.open).not.toHaveBeenCalled(); if (order === "startup-first") yield* Deferred.await(openEntered); const laterCleanup = order === "startup-first" ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) : undefined; if (order === "startup-first") expect(cleanupEntered).toBe(false); yield* Deferred.succeed(release, undefined); if (cleanup !== undefined) yield* Fiber.join(cleanup); yield* Fiber.join(startup); if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup); if (order === "cleanup-first") { expect(harness.createWorktree).toHaveBeenCalledWith( { cwd: "/tmp/native-account-project", refName: "feature/restore", path: worktreePath }, expect.anything(), ); } expect(harness.resolveRuntimePolicy).toHaveBeenCalledWith( expect.objectContaining({ thread: expect.objectContaining({ worktreePath }), }), ); expect(harness.open).toHaveBeenCalledWith( expect.objectContaining({ runtimePolicy: expect.objectContaining({ cwd: worktreePath }), }), ); expect(harness.startRootRun).toHaveBeenCalledWith( expect.objectContaining({ appThread: expect.objectContaining({ worktreePath }), runtimePolicy: expect.objectContaining({ cwd: worktreePath }), }), ); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); // regression: #12341 a turn start overlapping a checkpoint restore wrote into the checkout // The filesystem is synchronous so the turn start either reaches the provider or parks on the // lease before the restore is released; realPath models the symlink alias and missing worktrees. effectIt.effect.each([ { overlap: "a project-root thread during a restore of the project checkout", restorePath: "/tmp/native-account-project", worktreePath: undefined, realPaths: {}, missing: [], }, { overlap: "a symlink alias of the restoring checkout", restorePath: "/tmp/restore-overlap/link", worktreePath: "/tmp/restore-overlap/checkout", realPaths: { "/tmp/restore-overlap/link": "/tmp/restore-overlap/checkout" }, missing: [], }, { overlap: "a directory inside the restoring checkout", restorePath: "/tmp/restore-overlap/checkout", worktreePath: "/tmp/restore-overlap/checkout/packages/app", realPaths: {}, missing: [], }, { overlap: "a not-yet-recreated worktree under a symlink alias of the restoring one", restorePath: "/tmp/restore-overlap/link/missing-child", worktreePath: "/tmp/restore-overlap/checkout/missing-child", realPaths: { "/tmp/restore-overlap/link": "/tmp/restore-overlap/checkout" }, missing: [ "/tmp/restore-overlap/link/missing-child", "/tmp/restore-overlap/checkout/missing-child", ], }, ] as const)( "does not start provider work in $overlap until the restore finishes", ({ restorePath, worktreePath, realPaths, missing }) => Effect.gen(function* () { const order: Array = []; const releaseRestore = yield* Deferred.make(); const restoreEntered = yield* Deferred.make(); const fileSystem = FileSystem.makeNoop({ exists: () => Effect.succeed(true), realPath: (candidate) => (missing as ReadonlyArray).includes(candidate) ? Effect.fail( PlatformError.systemError({ _tag: "NotFound", module: "FileSystem", method: "realPath", pathOrDescriptor: candidate, }), ) : Effect.succeed((realPaths as Record)[candidate] ?? candidate), }); const harness = makeLocalCommandHarness({ text: "Continue", ...(worktreePath === undefined ? {} : { worktreePath }), fileSystem, failReadsAfterRunning: true, }); const open = harness.open.getMockImplementation()!; harness.open.mockImplementation(() => Effect.sync(() => order.push("provider session opened")).pipe(Effect.andThen(open())), ); // The reservation CheckpointRollbackServiceV2.execute holds around its // isolation check, provider rollback, and git restore of `restorePath`. const restore = yield* withCheckpointRestoreReservation( fileSystem, yield* Path.Path, restorePath, Deferred.succeed(restoreEntered, undefined).pipe( Effect.andThen(Deferred.await(releaseRestore)), Effect.andThen(Effect.sync(() => order.push("checkpoint files restored"))), ), ).pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(restoreEntered); const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.succeed(releaseRestore, undefined); yield* Fiber.join(restore); yield* Fiber.join(startup); expect(order).toEqual(["checkpoint files restored", "provider session opened"]); }).pipe(Effect.provide(Path.layer)), ); effectIt.effect("reads current startup state after waiting for the workspace lease", () => Effect.gen(function* () { const worktreePath = "/tmp/provider-start-fresh-state"; const release = yield* Deferred.make(); const readEntered = yield* Deferred.make(); const harness = makeLocalCommandHarness({ text: "Continue", worktreePath, failReadsAfterRunning: true, }); harness.getThreadRecords.mockImplementationOnce(() => Deferred.succeed(readEntered, undefined).pipe(Effect.as(harness.projection())), ); const holder = yield* withWorkspaceLease(worktreePath, Deferred.await(release)).pipe( Effect.forkChild({ startImmediately: true }), ); const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(readEntered); expect(harness.getTurnStartContext).not.toHaveBeenCalled(); const projection = harness.projection(); harness.setProjection({ ...projection, runs: projection.runs.map((run) => ({ ...run, status: "running" })), }); yield* Deferred.succeed(release, undefined); yield* Fiber.join(holder); yield* Fiber.join(startup); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); }), ); // regression: #15784 superseded provider startups kept running effectIt.effect.each([ { boundary: "policy resolution", loss: "replaced" }, { boundary: "session opening", loss: "interrupted" }, ])("does not continue startup when $loss during $boundary", ({ boundary, loss }) => Effect.gen(function* () { const entered = yield* Deferred.make(); const release = yield* Deferred.make(); const gate = Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release))); const harness = makeLocalCommandHarness({ text: "Continue" }); const projection = harness.projection(); const providerThread = projection.providerThreads[0]!; const ensureThread = vi.fn(() => Effect.succeed(providerThread)); const resumeThread = vi.fn(() => Effect.succeed(providerThread)); const forkThread = vi.fn(() => Effect.succeed(providerThread)); harness.open.mockReturnValue( (boundary === "session opening" ? gate : Effect.void).pipe( Effect.as({ driver: providerThread.driver, ensureThread, resumeThread, forkThread, } as never), ), ); if (boundary === "policy resolution") { harness.resolveRuntimePolicy.mockReturnValue( gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)), ); } const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(entered); const current = harness.projection(); const replacementId = RunAttemptId.make("replacement-attempt"); const updated = { ...current, runs: current.runs.map((candidate) => loss === "replaced" ? { ...candidate, activeAttemptId: replacementId } : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt }, ), attempts: loss === "replaced" ? [...current.attempts, { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 }] : current.attempts, }; harness.setProjection(updated); yield* Deferred.succeed(release, undefined); yield* Fiber.join(startup); expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0); expect(ensureThread).not.toHaveBeenCalled(); expect(resumeThread).not.toHaveBeenCalled(); expect(forkThread).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.writeIfRunCurrent).not.toHaveBeenCalled(); expect(harness.events).toEqual([]); expect(harness.projection()).toEqual(updated); }), ); effectIt.effect("starts another provider in the same checkout while a turn is pending", () => Effect.gen(function* () { const worktreePath = "/tmp/provider-start-shared-checkout"; const turnEntered = yield* Deferred.make(); const releaseTurn = yield* Deferred.make(); const first = makeLocalCommandHarness({ text: "Continue", worktreePath, failReadsAfterRunning: true, }); const second = makeLocalCommandHarness({ text: "Continue", worktreePath, failReadsAfterRunning: true, }); first.startRootRun.mockImplementation(() => Deferred.succeed(turnEntered, undefined).pipe(Effect.andThen(Deferred.await(releaseTurn))), ); const pending = yield* first.start.pipe(Effect.forkChild({ startImmediately: true })); yield* Deferred.await(turnEntered); yield* second.start; expect(second.startRootRun).toHaveBeenCalledOnce(); expect(second.projection().runs.at(-1)?.status).toBe("running"); yield* Deferred.succeed(releaseTurn, undefined); yield* Fiber.join(pending); }), ); effectIt.effect("fails a starting run when its recovery state cannot be read", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", recoveryReadFailure: "stored turn item no longer decodes", }); yield* harness.start.pipe(Effect.ignore); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.turnItems).toMatchObject([{ type: "error", status: "failed" }]); }), ); effectIt.effect("terminalizes a starting run when its provider session cannot open", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", openFailure: new Error("DESCRIPTION is not valid ACP JSON"), }); yield* harness.start; expect(harness.open).toHaveBeenCalledOnce(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.writeIfRunCurrent).toHaveBeenCalledWith( expect.objectContaining({ activeAttemptId: harness.attemptId, expectedStatus: "starting", }), ); const projection = harness.projection(); expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); expect(harness.settledRuns).toEqual(["failed"]); expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.turnItems).toMatchObject([ { type: "error", status: "failed", failure: { class: "provider_error", message: "DESCRIPTION is not valid ACP JSON", }, }, ]); }), ); effectIt.effect("leaves the run starting when a session-open failure will be retried", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", openFailure: new Error("provider session rejected"), }); const error = yield* harness.startWithRetry.pipe(Effect.flip); expect(error._tag).toBe("ProviderTurnStartError"); expect(harness.writeIfRunCurrent).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); }), ); effectIt.effect("fails rather than retries a provider thread request with an unknown outcome", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", ensureThreadFailure: { _tag: "CodexAppServerUnresponsiveError", method: "thread/start" }, }); yield* harness.startWithRetry; expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); }), ); effectIt.effect("fails rather than starts a fresh thread when a resume outcome is unknown", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", resumeFailure: new ProviderAdapter.ProviderAdapterEventStreamError({ driver: ProviderDriverKind.make("codex"), providerSessionId: ProviderSessionId.make("resume-provider-session"), cause: { _tag: "CodexAppServerUnresponsiveError", method: "thread/resume" }, }), }); const exit = yield* Effect.exit(harness.startWithRetry); expect(exit._tag).toBe("Success"); expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); }), ); effectIt.effect("fails the run without a retry when the provider needs sign-in", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", openFailure: new ProviderAdapter.ProviderAdapterOpenSessionError({ driver: ProviderDriverKind.make("antigravity"), providerSessionId: ProviderSessionId.make("new-provider-session"), requiresSignIn: true, }), }); yield* harness.startWithRetry; expect(harness.open).toHaveBeenCalledOnce(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); expect(harness.projection().turnItems).toMatchObject([ { type: "error", status: "failed", failure: { class: "provider_error", message: "Failed to open antigravity provider session new-provider-session.", }, }, ]); }), ); effectIt.effect("does not terminalize a provider-session open interruption", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true }); const exit = yield* Effect.exit(harness.start); expect(exit._tag).toBe("Failure"); if (exit._tag === "Failure") { expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true); } expect(harness.writeIfRunCurrent).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("starting"); expect(harness.events).toEqual([]); }), ); effectIt.effect("does not overwrite a run interrupted while its provider session opens", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", openFailure: new Error("provider session rejected"), interruptRunBeforeOpenFailure: true, }); yield* harness.start; expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce(); expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.runs.at(-1)?.status).toBe("interrupted"); expect(harness.settledRuns).toEqual([]); expect(projection.attempts[0]?.status).toBe("pending"); expect(projection.nodes[0]?.status).toBe("pending"); expect(projection.turnItems).toEqual([]); expect(harness.events).toEqual([]); }), ); effectIt.effect("checks the run's status without loading the thread's history", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", previousTurn: { runStatus: "completed", turnStatus: "completed" }, }); yield* harness.start; const controls = harness.startRootRun.mock.calls[0]?.[0]; expect(controls).toBeDefined(); if (controls === undefined) return; expect(yield* controls.shouldStartProviderTurn!()).toBe(true); expect(yield* controls.shouldFinalizeRun!()).toBe(true); // Each check needs one run row; the recovery projection reads every run and open turn item. // The one read left is the start's inherited background items snapshot, not a status check. expect( harness.getRuntimeRecoveryProjection.mock.calls.length, "recovery projection reads beyond the inherited background items snapshot", ).toBe(1); }), ); effectIt.effect("fails the run instead of replacing a native thread another client holds", () => Effect.gen(function* () { const detail = "This conversation is open in another Codex client."; const harness = makeLocalCommandHarness({ text: "Continue", resumeFailure: new ProviderAdapter.ProviderAdapterThreadInUseError({ driver: ProviderDriverKind.make("codex"), providerThreadId: ProviderThreadId.make("new-provider-thread"), detail, cause: new Error("thread native-resume-thread already has an active writer"), }), }); const exit = yield* Effect.exit(harness.start); expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); expect(exit._tag).toBe("Success"); expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.providerThreads.at(-1)?.nativeThreadRef?.nativeId).toBe( "native-resume-thread", ); expect(projection.contextHandoffs).toEqual([]); expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); expect(projection.turnItems).toMatchObject([ { type: "error", title: "Provider turn failed to start", failure: { class: "provider_error", message: detail }, }, ]); }), ); effectIt.effect("does not mistake a failed state read for a superseded run", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true }); yield* harness.start; expect(harness.projection().runs.at(-1)?.status).toBe("running"); const controls = harness.startRootRun.mock.calls[0]?.[0]; expect(controls).toBeDefined(); if (controls === undefined) return; const startCheck = yield* Effect.flip(controls.shouldStartProviderTurn!()); const finalizeCheck = yield* Effect.flip(controls.shouldFinalizeRun!()); expect(startCheck._tag).toBe("ProjectionStoreReadError"); expect(finalizeCheck._tag).toBe("ProjectionStoreReadError"); }), ); effectIt.effect.each(["not_loaded", "error"] as const)( "signs out the existing native provider before opening the newly selected provider with status %s", (providerThreadStatus) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true }); const initial = harness.projection(); harness.setProjection({ ...initial, providerThreads: initial.providerThreads.map((thread) => thread.id === "new-provider-thread" ? { ...thread, status: providerThreadStatus } : thread, ), }); yield* harness.start; yield* harness.start; expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({ instanceId: harness.oldInstanceId, text: "/logout", hasAttachments: false, sentByPerson: true, }); expect(harness.open).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.runs.at(-1)?.status).toBe("completed"); expect(projection.attempts[0]?.status).toBe("completed"); expect(projection.nodes[0]?.status).toBe("completed"); expect(projection.turnItems).toMatchObject([ { type: "command_execution", title: "Provider signed out", output: "Provider signed out", status: "completed", }, ]); expect(projection.providerTurns).toEqual([]); expect(projection.checkpoints).toEqual([]); expect( projection.providerThreads.find((thread) => thread.id === "new-provider-thread")?.status, ).toBe(providerThreadStatus); }), ); effectIt.effect.each([ { name: "an agent", createdBy: "agent" as const }, // A scheduled delivery keeps its task author's createdBy. { name: "a scheduled task", scheduledTaskId: ScheduledTaskId.make("task") }, ])("does not let $name sign a provider out", ({ name: _name, ...sender }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "/logout", ...sender, previousNativeSession: true, }); yield* harness.start; expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ sentByPerson: false }), ); }), ); for (const previousMessages of [[], ["/compact", " /COMPACT "]]) { effectIt.effect( `rejects compaction without conversation context after ${previousMessages.length} prior compactions`, () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "/compact", previousMessages }); yield* harness.start; expect(harness.open).not.toHaveBeenCalled(); expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled(); expect(harness.startRootRun).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); expect(harness.projection().turnItems).toMatchObject([ { type: "error", failure: { class: "validation_error", message: "Start a conversation before compacting this thread.", }, }, ]); }), ); } effectIt.effect("rejects citation expansion before opening a provider session", () => Effect.gen(function* () { const marker = serializeAssistantCitation({ version: 1, environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread"), messageId: MessageId.make("assistant"), text: "\u0001".repeat(8_000), start: 0, end: 8_000, prefix: "", suffix: "", }); const text = "x".repeat(80_000) + marker; expect(text.length).toBeLessThan(PROVIDER_SEND_TURN_MAX_INPUT_CHARS); expect(expandAssistantCitationsForProvider(text).length).toBeGreaterThan( PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ); const harness = makeLocalCommandHarness({ text }); yield* harness.start; expect(harness.open).not.toHaveBeenCalled(); expect(harness.startTurn).not.toHaveBeenCalled(); expect(harness.projection().runs.at(-1)?.status).toBe("failed"); expect(harness.projection().turnItems).toMatchObject([ { type: "error", failure: { class: "validation_error", message: expect.stringContaining("120,000") }, }, ]); expect(harness.projection().messages[0]?.text).toBe(text); }), );