diff --git a/apps/mobile/src/features/threads/RestartCodexCard.tsx b/apps/mobile/src/features/threads/RestartCodexCard.tsx new file mode 100644 index 0000000000000..5f4a16b0ded14 --- /dev/null +++ b/apps/mobile/src/features/threads/RestartCodexCard.tsx @@ -0,0 +1,66 @@ +import { useAtomValue } from "@effect/atom-react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts"; +import { useState } from "react"; +import { Alert, Pressable, View } from "react-native"; +import { AppText as Text } from "../../components/AppText"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useAtomCommand } from "../../state/use-atom-command"; + +export function RestartCodexCard({ + environmentId, + threadId, + retryRunId, + continueWork = false, +}: { + environmentId: EnvironmentId; + threadId: ThreadId; + retryRunId: RunId; + continueWork?: boolean; +}) { + const restart = useAtomCommand(orchestrationEnvironment.restartCodex, { reportFailure: false }); + const allowed = useAtomValue(orchestrationEnvironment.restartCodex.permissionAtom(environmentId)); + const [pending, setPending] = useState(false); + const [message, setMessage] = useState(null); + return ( + + { + if (pending) return; + setPending(true); + setMessage(null); + try { + const result = await restart({ environmentId, input: { threadId, retryRunId } }); + if (result._tag === "Failure") throw squashAtomCommandFailure(result); + Alert.alert(continueWork ? "Conversation continued" : "Message resent"); + } catch (cause) { + setMessage( + cause instanceof Error ? cause.message : "Could not recover the conversation.", + ); + } finally { + setPending(false); + } + }} + > + + {pending + ? continueWork + ? "Continuing…" + : "Retrying message…" + : continueWork + ? "Continue" + : "Retry message"} + + + {message ? ( + + {message} + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index d9da5f506656c..db87730c74b63 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1,6 +1,8 @@ +import type { CodexRecoveryAction } from "@t3tools/client-runtime/state/thread-execution"; import * as Dialog from "../../components/ui/Dialog"; import { useAtomValue } from "@effect/atom-react"; import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities"; +import { RestartCodexCard } from "./RestartCodexCard"; import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard"; import { useNavigation } from "@react-navigation/native"; import type { WorktreeSetupCardProps } from "./worktree-setup-card"; @@ -154,6 +156,7 @@ import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow"; import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider"; export interface ThreadDetailScreenProps { + readonly codexRecovery: CodexRecoveryAction | null; readonly worktreeSetup?: WorktreeSetupCardProps | null; readonly setupWorkingStartedAt?: string | null; readonly canOperateThread: boolean; @@ -1201,6 +1204,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread /> ) : null} + {props.codexRecovery !== null ? ( + + ) : null} deriveCodexRecoveryAction(selectedThreadDetail), + [selectedThreadDetail], + ); const { selectedThreadCwd } = useSelectedThreadWorktree(); const composer = useThreadComposerState(); const gitState = useSelectedThreadGitState(); @@ -967,6 +972,7 @@ function ThreadRouteContent( { ), ); - it.effect("continues an interrupted native thread with empty input and reasoning summaries", () => - Effect.scoped( - Effect.gen(function* () { - const scenario = "codex-restart-promptless"; - const nativeThreadId = "native-restart-promptless"; - const nativeTurnId = "turn-restart-promptless"; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "unused", - }).slice(0, 5); - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...preamble, - { - type: "expect_outbound", - label: "resume", - frame: { - id: 3, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, + it.effect.each([false, true])( + "resumes native history with the right input for stream recovery (stream failure: %s)", + (streamFailure) => + Effect.scoped( + Effect.gen(function* () { + const scenario = "codex-restart-promptless"; + const nativeThreadId = "native-restart-promptless"; + const nativeTurnId = "turn-restart-promptless"; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "unused", + }).slice(0, 5); + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...preamble, + { + type: "expect_outbound", + label: "resume", + frame: { + id: 3, + method: "thread/resume", + params: { + threadId: nativeThreadId, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, }, }, - }, - { - type: "emit_inbound", - label: "resume", - frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - { - type: "expect_outbound", - label: "continue", - frame: { - id: 4, - method: "turn/start", - params: { - threadId: nativeThreadId, - input: [], - cwd: "/workspace", - model: "gpt-5.4", - approvalPolicy: "never", - approvalsReviewer: "user", - sandboxPolicy: { type: "dangerFullAccess" }, - summary: "detailed", + { + type: "emit_inbound", + label: "resume", + frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, + }, + { + type: "expect_outbound", + label: "continue", + frame: { + id: 4, + method: "turn/start", + params: { + threadId: nativeThreadId, + input: streamFailure ? [{ type: "text", text: "Continue" }] : [], + cwd: "/workspace", + model: "gpt-5.4", + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + summary: "detailed", + }, }, }, - }, - { - type: "emit_inbound", - label: "continue", - frame: { - id: 4, - result: { turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }) }, + { + type: "emit_inbound", + label: "continue", + frame: { + id: 4, + result: { turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }) }, + }, }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const resumed = yield* harness.runtime.resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - yield* harness.runtime.startTurn({ - ...makeCodexTestTurnInput({ + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + const turnInput = makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: resumed, now: yield* DateTime.now, attemptId: RunAttemptId.make("attempt-restart-promptless"), text: "Continue where you left off.", - }), - restartContinuationOfRunId: RunId.make("run-before-restart"), - }); - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + }); + yield* harness.runtime.startTurn({ + ...turnInput, + ...(streamFailure + ? { + appContext: [{ key: "previous-tool", text: "Do not repeat this context." }], + message: { + ...turnInput.message, + messageId: MessageId.make("message:codex-retry:failed-stream"), + text: "Continue", + }, + } + : {}), + restartContinuationOfRunId: RunId.make("run-before-restart"), + }); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), ), ), - ), ); it.effect("resolves retryable app-server errors on resumed provider activity", () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 19d1e7b7ffe29..e6f83def49085 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6614,11 +6614,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( : null; if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); return Effect.gen(function* () { + const streamRecovery = + turnInput.restartContinuationOfRunId !== undefined && + turnInput.message.messageId.startsWith("message:codex-retry:"); yield* startNativeTurn( - turnInput, + streamRecovery ? { ...turnInput, appContext: [] } : turnInput, turnInput.restartContinuationOfRunId === undefined ? yield* toCodexInput(turnInput) - : [], + : streamRecovery + ? [{ type: "text", text: "Continue" }] + : [], ); }).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index cb41dc7365123..a7c90aee01477 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -32,6 +32,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ Schema.Struct({ type: Schema.Literal("provider-runtime.continue"), sourceRunId: RunId, + reason: Schema.optional(Schema.Literal("event_stream_closed")), }), Schema.Struct({ type: Schema.Literal("provider-session.detach"), diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 6227e3a5df217..b91af6ffb8d2c 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -28,6 +28,7 @@ import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationServic import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { continueRestartedRun } from "./RestartContinuation.ts"; +import { continueProviderStream } from "./ProviderStreamContinuation.ts"; export class OrchestrationEffectExecutionError extends Schema.TaggedError()( "OrchestrationEffectExecutionError", @@ -103,7 +104,16 @@ export const layerExecutor: Layer.Layer< switch (effect.request.type) { case "provider-runtime.continue": { const sourceRunId = effect.request.sourceRunId; - return continueRestartedRun({ threadId: effect.threadId, sourceRunId }).pipe( + const continuation = + effect.request.reason === "event_stream_closed" + ? continueProviderStream + : continueRestartedRun; + return continuation({ threadId: effect.threadId, sourceRunId }).pipe( + Effect.andThen( + effect.request.reason === "event_stream_closed" + ? threads.recoverDelegatedTask(effect.threadId, sourceRunId) + : Effect.void, + ), Effect.provideService(ThreadManagementService.ThreadManagementService, threads), Effect.provideService(ServerSettings.ServerSettingsService, settings), Effect.tapError(() => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 491ddff3a720b..0712478823d2f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6,6 +6,8 @@ import type { import { latestExecutedRun, latestRootProviderFailure, + isProviderEventStreamFailure, + hasAcceptedProviderTurn, runRanAfter, usageLimitBlockedRun, } from "@t3tools/shared/orchestrationV2ThreadError"; @@ -4496,6 +4498,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) => Effect.gen(function* () { let projection = yield* getProjectionWithPendingEvents(command.threadId, events); + if (command.retryOfRunId !== undefined) { + const source = latestExecutedRun(projection.runs); + if ( + source?.id !== command.retryOfRunId || + source.status !== "failed" || + (hasAcceptedProviderTurn(source, projection.providerTurns) && + command.restartContinuationOfRunId !== source.id) || + command.dispatchMode.type !== "start_immediately" || + projection.thread.archivedAt !== null || + projection.thread.deletedAt !== null || + projection.runtimeRequests.some((request) => request.status === "pending") + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The failed run can no longer be retried.", + }); + } + } if (command.manualContinuationOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId); const limited = latestRootProviderFailure(source ?? null, projection.turnItems); @@ -4564,10 +4585,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId); if ( !source || - !isRestartContinuationSource(source, projection.providerTurns) || + !( + isRestartContinuationSource(source, projection.providerTurns) || + (command.retryOfRunId === source.id && + source.status === "failed" && + hasAcceptedProviderTurn(source, projection.providerTurns) && + isProviderEventStreamFailure(latestRootProviderFailure(source, projection.turnItems))) + ) || projection.thread.archivedAt !== null || projection.thread.deletedAt !== null || projection.thread.providerInstanceId !== source.providerInstanceId || + (command.modelSelection !== undefined && + command.modelSelection.instanceId !== source.providerInstanceId) || + (command.retryOfRunId !== undefined && + command.creationSource === "server" && + (projection.thread.settledOverride === "settled" || + (projection.thread.snoozedUntil != null && + DateTime.isGreaterThan(projection.thread.snoozedUntil, yield* DateTime.now)))) || projection.runs.some( (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source), ) || diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 56db053920a27..5dee7965c6f53 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -10,6 +10,7 @@ import { type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, + type OrchestrationV2Run, type Project, ProjectId, ProviderDriverKind, @@ -546,6 +547,7 @@ function layerTest(input: { layerTestStores, layerConfiguredEventSink, IdAllocator.layer, + ThreadCommandExecutor.layer, layerConfiguredMcpRegistry, McpProviderSessions.layer, ProviderSessionManager.layerWithOptions({ @@ -560,6 +562,7 @@ function layerTest(input: { ), layerConfiguredEventSink, IdAllocator.layer, + ThreadCommandExecutor.layer, layerProviderEventIngestorTest, layerConfiguredMcpRegistry, layerTestStores, @@ -2966,6 +2969,54 @@ it.effect("ProviderSessionManagerV2 keeps a provider update that lands while rel }), ); +it.effect( + "ProviderSessionManagerV2 refuses manual reset during background work and reopens after reset", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const pendingWork = yield* Ref.make(true); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("manual-codex-reset"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const input = { threadId, providerSessionId, modelSelection, runtimePolicy }; + const first = yield* manager.open(input); + const reset = manager.release({ + providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + }); + assert.equal((yield* reset.pipe(Effect.flip))._tag, "ProviderSessionBusyError"); + assert.equal((yield* Ref.get(state)).closeCount, 0); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* Ref.set(pendingWork, false); + yield* reset; + assert.isFalse(yield* manager.isLive(providerSessionId)); + assert.equal((yield* Ref.get(state)).closeCount, 1); + const replacement = yield* manager.open(input); + assert.notStrictEqual(replacement, first); + assert.equal((yield* Ref.get(state)).openCount, 2); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 60_000, + hasPendingBackgroundWork: Ref.get(pendingWork), + }), + ), + ); + }), +); + it.effect("ProviderSessionManagerV2 defers idle release while background work is pending", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); @@ -3411,6 +3462,11 @@ it.effect( runtimePolicy, }); + const resetFailure = yield* manager + .release({ providerSessionId, reason: "manual_shutdown", rejectIfBusy: true }) + .pipe(Effect.flip); + assert.equal(resetFailure._tag, "ProviderSessionBusyError"); + yield* TestClock.adjust("2 seconds"); yield* Effect.yieldNow; assert.equal((yield* Ref.get(state)).closeCount, 0); @@ -3589,6 +3645,16 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r modelSelection, runtimePolicy, }); + const reset = yield* manager + .release({ + providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + }) + .pipe(Effect.result); + assert.equal(reset._tag, "Failure"); + if (reset._tag === "Failure") assert.equal(reset.failure._tag, "ProviderSessionBusyError"); + assert.isTrue(yield* manager.isLive(providerSessionId)); yield* manager.release({ providerSessionId, reason: "runtime_error", @@ -4908,3 +4974,128 @@ it.effect( assert.isFalse(denied?.capabilities?.has("device")); }), ); + +it.effect( + "ProviderSessionManagerV2 refuses reset during sibling admission and until its run settles", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const admitting = yield* Deferred.make(); + const commitAdmission = yield* Deferred.make(); + const backgroundCheck = yield* Ref.make(Effect.succeed(false)); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const commands = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const now = yield* DateTime.now; + const threadId = ThreadId.make("manual-reset-owner"); + const siblingId = ThreadId.make("manual-reset-sibling"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: siblingId, now }), + ], + }); + const input = { providerSessionId, modelSelection, runtimePolicy }; + yield* manager.open({ ...input, threadId }); + yield* manager.open({ ...input, threadId: siblingId }); + const run: OrchestrationV2Run = { + id: idAllocator.derive.run({ threadId: siblingId, ordinal: 1 }), + threadId: siblingId, + ordinal: 1, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: null, + userMessageId: yield* idAllocator.allocate.message({ threadId: siblingId, ordinal: 1 }), + rootNodeId: null, + activeAttemptId: null, + status: "starting", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const persistRun = (payload: OrchestrationV2Run) => + Effect.gen(function* () { + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: siblingId }), + type: "run.updated", + threadId: siblingId, + runId: run.id, + occurredAt: now, + payload, + }, + ], + }); + }); + const admission = yield* commands + .withLock( + siblingId, + Deferred.succeed(admitting, undefined).pipe( + Effect.andThen(Deferred.await(commitAdmission)), + Effect.andThen(persistRun(run)), + ), + ) + .pipe(Effect.forkChild); + yield* Deferred.await(admitting); + const reset = commands + .withLock( + threadId, + manager.release({ + providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + alreadyLockedThreadId: threadId, + }), + ) + .pipe(Effect.result); + const assertBusy = (result: Effect.Success) => { + assert.equal(result._tag, "Failure"); + if (result._tag === "Failure") + assert.equal(result.failure._tag, "ProviderSessionBusyError"); + }; + // The sibling owns its command lock but has not committed its run yet. + assertBusy(yield* reset); + yield* Deferred.succeed(commitAdmission, undefined); + yield* Fiber.join(admission); + // Admission committed; startTurn has not marked the runtime busy yet. + assertBusy(yield* reset); + assert.isTrue(yield* manager.isLive(providerSessionId)); + assert.equal((yield* Ref.get(state)).closeCount, 0); + yield* commands.withLock( + siblingId, + persistRun({ ...run, status: "completed", completedAt: now }), + ); + // Exercise the original race: after reading idle projections, the + // guard must still exclude admission while probing background work. + yield* Ref.set( + backgroundCheck, + commands.withLockIfAvailable(siblingId, Effect.die("must not admit during reset")).pipe( + Effect.map((admitted) => { + assert.isTrue(Option.isNone(admitted)); + return false; + }), + ), + ); + assert.equal((yield* reset)._tag, "Success"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + assert.equal((yield* Ref.get(state)).closeCount, 1); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 60_000, + hasPendingBackgroundWork: Ref.get(backgroundCheck).pipe(Effect.flatten), + }), + ), + ); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index edcaecfa88489..aea6b766c658a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -52,6 +52,7 @@ import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; @@ -107,6 +108,11 @@ export class ProviderSessionCloseError extends Schema.TaggedError()( + "ProviderSessionBusyError", + { providerSessionId: ProviderSessionId }, +) {} + export class ProviderSessionReleaseError extends Schema.TaggedError()( "ProviderSessionReleaseError", { @@ -138,6 +144,7 @@ export const ProviderSessionManagerV2Error = Schema.Union([ ProviderSessionLookupError, ProviderSessionCloseError, ProviderSessionReleaseError, + ProviderSessionBusyError, ProviderSessionActivityError, ]); export type ProviderSessionManagerV2Error = typeof ProviderSessionManagerV2Error.Type; @@ -172,6 +179,9 @@ export interface ProviderSessionManagerV2Shape { readonly release: (input: { readonly providerSessionId: ProviderSessionId; readonly reason: ProviderSessionReleaseReason; + readonly rejectIfBusy?: boolean; + /** A thread command lock the caller already holds; other attached threads are guarded here. */ + readonly alreadyLockedThreadId?: ThreadId; readonly detail?: string; }) => Effect.Effect; readonly detach: (input: { @@ -307,6 +317,7 @@ export const layerWithOptions = ( | ProjectionStore.ProjectionStoreV2 | ProviderEventIngestor.ProviderEventIngestorV2 | ProviderAdapterRegistry.ProviderAdapterRegistryV2 + | ThreadCommandExecutor.ThreadCommandExecutor > => Layer.effect( ProviderSessionManagerV2, @@ -328,6 +339,7 @@ export const layerWithOptions = ( const idAllocator = yield* IdAllocator.IdAllocatorV2; const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const agentScope = yield* AgentScope; const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")( function* (threadId: ThreadId) { @@ -910,33 +922,96 @@ export const layerWithOptions = ( const removeLiveEntry = (input: { readonly providerSessionId: ProviderSessionId; readonly onlyIfIdleGeneration?: number; - }): Effect.Effect, DateTime.Utc]> => + readonly rejectIfBusy?: boolean; + readonly alreadyLockedThreadId?: ThreadId; + }): Effect.Effect< + readonly [Option.Option, DateTime.Utc], + ProviderSessionBusyError + > => Effect.gen(function* () { const key = sessionKey(input.providerSessionId); const candidate = (yield* Ref.get(sessions)).get(key); if (candidate === undefined) { return [Option.none(), yield* DateTime.now] as const; } - const removed = yield* Effect.zip( - Ref.modify(sessions, (current) => { - const existing = current.get(key); - if (existing !== candidate) { - return [existing === undefined ? "gone" : "changed", current] as const; - } - if ( - input.onlyIfIdleGeneration !== undefined && - (existing.busyTurns.size > 0 || - existing.idleGeneration !== input.onlyIfIdleGeneration) - ) { - return ["kept", current] as const; + let remove = Effect.gen(function* () { + if (input.rejectIfBusy) { + // Setup and native compaction can run before startTurn marks the + // session busy. Check every attached thread before removing it. + const busy = yield* Effect.gen(function* () { + for (const threadId of candidate.attachedThreadIds) { + const { runs, runtimeRequests } = yield* projectionStore.getThreadRecords( + threadId, + ["runs", "runtimeRequests"], + ); + if ( + runtimeRequests.some((request) => request.status === "pending") || + runs.some((run) => + ["preparing", "starting", "running", "waiting"].includes(run.status), + ) + ) { + return true; + } + } + return candidate.runtime.hasPendingBackgroundWork === undefined + ? false + : yield* candidate.runtime.hasPendingBackgroundWork; + }).pipe( + Effect.timeout("5 seconds"), + Effect.orElseSucceed(() => true), + ); + if (busy) { + return yield* new ProviderSessionBusyError({ + providerSessionId: input.providerSessionId, + }); } - const updated = new Map(current); - updated.delete(key); - return ["removed", updated] as const; - }), - DateTime.now, - ).pipe(candidate.requestEventPermit.withPermits(1)); + } + return yield* Effect.zip( + Ref.modify(sessions, (current) => { + const existing = current.get(key); + if (existing !== candidate) { + return [existing === undefined ? "gone" : "changed", current] as const; + } + if (input.rejectIfBusy && existing.busyTurns.size > 0) { + return ["busy", current] as const; + } + if ( + input.onlyIfIdleGeneration !== undefined && + (existing.busyTurns.size > 0 || + existing.idleGeneration !== input.onlyIfIdleGeneration) + ) { + return ["kept", current] as const; + } + const updated = new Map(current); + updated.delete(key); + return ["removed", updated] as const; + }), + DateTime.now, + ); + }).pipe(candidate.requestEventPermit.withPermits(1)); + if (input.rejectIfBusy) { + // Admission persists a run before startTurn marks the runtime busy. + // Hold its locks through the check and removal. Never wait for a + // sibling: the caller may already hold another thread's lock. + for (const threadId of candidate.attachedThreadIds) { + if (threadId === input.alreadyLockedThreadId) continue; + remove = threadCommands.withLockIfAvailable(threadId, remove).pipe( + Effect.flatMap( + Option.match({ + onSome: Effect.succeed, + onNone: () => + new ProviderSessionBusyError({ providerSessionId: input.providerSessionId }), + }), + ), + ); + } + } + const removed = yield* remove; const [outcome, releasedAt] = removed; + if (outcome === "busy") + return yield* new ProviderSessionBusyError({ + providerSessionId: input.providerSessionId, + }); if (outcome === "changed") return yield* removeLiveEntry(input); return [ outcome === "removed" ? Option.some(candidate) : Option.none(), @@ -984,6 +1059,8 @@ export const layerWithOptions = ( const releaseEntry = (input: { readonly providerSessionId: ProviderSessionId; readonly reason: ProviderSessionReleaseReason; + readonly rejectIfBusy?: boolean; + readonly alreadyLockedThreadId?: ThreadId; readonly detail?: string; readonly detachedThreadId?: ThreadId; readonly cancelIdleFiber?: boolean; @@ -1087,11 +1164,17 @@ export const layerWithOptions = ( ).pipe( Effect.catchCause((cause) => Effect.fail( - new ProviderSessionReleaseError({ - providerSessionId: input.providerSessionId, - reason: input.reason, - cause, - }), + Cause.findErrorOption(cause).pipe( + Option.filter(Schema.is(ProviderSessionBusyError)), + Option.getOrElse( + () => + new ProviderSessionReleaseError({ + providerSessionId: input.providerSessionId, + reason: input.reason, + cause, + }), + ), + ), ), ), ); diff --git a/apps/server/src/orchestration-v2/ProviderStreamContinuation.ts b/apps/server/src/orchestration-v2/ProviderStreamContinuation.ts new file mode 100644 index 0000000000000..bb0511a1fd687 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderStreamContinuation.ts @@ -0,0 +1,68 @@ +import { type RunId, type ThreadId } from "@t3tools/contracts"; +import { + isProviderEventStreamFailure, + hasAcceptedProviderTurn, + latestExecutedRun, + latestRootProviderFailure, +} from "@t3tools/shared/orchestrationV2ThreadError"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Threads from "./ThreadManagementService.ts"; + +/** One automatic continuation of saved native history; another failure requires the user. */ +export const continueProviderStream = Effect.fn( + "ProviderStreamContinuation.continueProviderStream", +)(function* (input: { readonly threadId: ThreadId; readonly sourceRunId: RunId }) { + const threads = yield* Threads.ThreadManagementService; + const records = yield* threads.getThreadRecords( + input.threadId, + ["runs", "providerThreads", "providerTurns", "turnItems", "runtimeRequests"], + { + turnItemRunIds: [input.sourceRunId], + turnItemTypes: ["error", "secret_request", "run_interrupt_request"], + }, + ); + const source = latestExecutedRun(records.runs); + const thread = records.thread; + if ( + source?.id !== input.sourceRunId || + source.status !== "failed" || + !hasAcceptedProviderTurn(source, records.providerTurns) || + thread.deletedAt !== null || + thread.archivedAt !== null || + thread.settledOverride === "settled" || + (thread.snoozedUntil != null && + DateTime.isGreaterThan(thread.snoozedUntil, yield* DateTime.now)) || + !isProviderEventStreamFailure(latestRootProviderFailure(source, records.turnItems)) || + source.userMessageId.startsWith("message:codex-retry:") || + records.runtimeRequests.some((request) => request.status === "pending") || + records.turnItems.some( + (item) => + item.type === "run_interrupt_request" || + (item.type === "secret_request" && item.secretStatus === "pending"), + ) + ) + return; + const native = records.providerThreads.find( + (candidate) => candidate.id === thread.activeProviderThreadId, + ); + if ( + native?.driver !== "codex" || + native.nativeThreadRef?.strength !== "strong" || + native.providerInstanceId !== source.providerInstanceId || + thread.modelSelection.instanceId !== source.providerInstanceId + ) + return; + const original = yield* threads.getThreadRecords(input.threadId, ["messages"], { + messageIds: [source.userMessageId], + }); + const message = original.messages.find((candidate) => candidate.id === source.userMessageId); + if (message === undefined || message.text.trimStart().startsWith("/")) return; + // Reconnection uses the saved native id. Admission rechecks the latest failed + // run under the thread lock, so a new user submission always takes precedence. + yield* threads.restartCodex({ + threadId: input.threadId, + retryRunId: input.sourceRunId, + automatic: true, + }); +}); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 0e68d9f562e29..1a19936b86fd9 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3713,28 +3713,80 @@ it.effect("does not refresh pull requests for auxiliary or stale provider termin }), ); -it.effect("refreshes pull requests after a provider stream exits with an error", () => - Effect.gen(function* () { - const { written, observed } = yield* captureRootRunTermination({ - key: "pull-request-refresh:stream-error", - shouldFinalizeRun: () => Effect.succeed(true), - events: () => - Stream.fail( - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver, - providerSessionId: ProviderSessionId.make("session:exited"), - cause: "provider process exited", - }), - ), - }); - assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); - assert.deepEqual( - written.map((item) => item.type), - ["error"], - ); - const error = written.find((item) => item.type === "error"); - assert.include(error?.failure.message ?? "", "provider event stream closed unexpectedly"); - }), +it.effect.each([false, true])( + "continues a failed stream only after the provider accepted the turn (accepted: %s)", + (accepted) => + Effect.gen(function* () { + const { written, observed, committedEffects } = yield* captureRootRunTermination({ + key: "pull-request-refresh:stream-error", + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => + Stream.fromIterable( + accepted + ? [ + { + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + nodeId: ids.rootNodeId, + runAttemptId: ids.attemptId, + nativeTurnRef: { + driver, + nativeId: "accepted-native-turn", + strength: "strong" as const, + }, + ordinal: 1, + status: "running" as const, + startedAt: DateTime.makeUnsafe("2026-10-15T00:00:00Z"), + completedAt: null, + }, + }, + ] + : [], + ).pipe( + Stream.concat( + Stream.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver, + providerSessionId: ProviderSessionId.make("session:exited"), + cause: "provider process exited", + }), + ), + ), + ), + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.deepEqual( + written.map((item) => item.type), + ["error"], + ); + const error = written.find((item) => item.type === "error"); + assert.include( + error?.failure.message ?? "", + accepted + ? "provider event stream closed unexpectedly" + : "before this turn was acknowledged", + ); + assert.equal( + error?.failure.code, + accepted ? "event_stream_closed" : "event_stream_closed_unacknowledged", + ); + assert.deepEqual( + committedEffects.map((effect) => effect.request), + accepted + ? [ + { + type: "provider-runtime.continue", + sourceRunId: backgroundScenarioIds("pull-request-refresh:stream-error").runId, + reason: "event_stream_closed", + }, + ] + : [], + ); + }), ); it.effect("fails the run when its event stream ends without a root terminal", () => @@ -3974,6 +4026,7 @@ function captureRootRunTermination(input: { threadId: ids.threadId, ordinal: 1, providerInstanceId, + startedAt: DateTime.makeUnsafe("2026-10-15T00:00:00Z"), } as OrchestrationV2Run, rootNode: { id: ids.rootNodeId, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 61ab0a3f09543..76cae0a8c7267 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -700,7 +700,23 @@ export const layer: Layer.Layer< }, }, ] - : [], + : input.terminal.status === "failed" && + input.terminal.driver === "codex" && + input.terminal.failure.code === "event_stream_closed" && + input.run.startedAt != null + ? [ + { + id: `effect:restart-continuation:${input.run.id}`, + commandId: CommandId.make(`command:provider-stream.continue:${input.run.id}`), + threadId: input.run.threadId, + request: { + type: "provider-runtime.continue" as const, + sourceRunId: input.run.id, + reason: "event_stream_closed" as const, + }, + }, + ] + : [], events: [ ...cascadedSubagentEvents, ...(finalizedAttempt === null @@ -824,6 +840,7 @@ export const layer: Layer.Layer< ), ), ); + let providerAccepted = false; const makeFailedTerminalEvent = ( failure: OrchestrationV2ProviderFailure, failureItemOrdinal: number, @@ -840,7 +857,17 @@ export const layer: Layer.Layer< runOrdinal: input.run.ordinal, failureItemOrdinal, status: "failed", - failure, + failure: + input.providerThread.driver === "codex" && + !providerAccepted && + failure.code === "event_stream_closed" + ? { + ...failure, + code: "event_stream_closed_unacknowledged", + message: + "The provider connection closed before this turn was acknowledged. Retry the message if it did not start.", + } + : failure, threadDisposition: "reusable", }); const responseStreamingMode = yield* Effect.gen(function* () { @@ -1201,6 +1228,13 @@ export const layer: Layer.Layer< ), Stream.tap((event) => Effect.gen(function* () { + if ( + event.type === "provider_turn.updated" && + event.providerTurn.runAttemptId === input.attempt.id && + event.providerTurn.nativeTurnRef?.strength === "strong" + ) { + providerAccepted = true; + } let storedEventCount = 0; const deliveredEvent = filterAssistantEvent( event, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 1f05d1c8d4dee..af555fe22bf0c 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -38,6 +38,7 @@ import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, type DispatchModeRefusal } from "./DispatchModeLimit.ts"; @@ -547,6 +548,7 @@ it.effect("preserves failed legacy materialization when reading checkpoint conte cause: new Error("checkpoint import failed"), }); const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe( + Layer.provide(RuntimePolicy.layer), Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), Layer.provide( Layer.mergeAll( @@ -1077,3 +1079,209 @@ it.effect.each([ expect(dispatched).toEqual(settles ? ["thread.settle"] : []); }), ); + +it.effect.each([ + "resuming", + "running", + "unsupported", + "stale-retry", + "request-pending", + "shared-busy", + "open-failed", + "resume-failed", + "disabled-reconnect", + "disabled-retry", +] as const)( + "reconnects Codex in state %s without losing native history or replaying a turn", + (state) => + Effect.gen(function* () { + const threadId = ThreadId.make("manual-reset-thread"); + const providerThreadId = ProviderThreadId.make("manual-reset-provider-thread"); + const providerSessionId = ProviderSessionId.make("manual-reset-session"); + const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" }; + const runtimePolicy = { + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + cwd: "/saved/worktree", + }; + const providerThread = { + id: providerThreadId, + providerInstanceId: modelSelection.instanceId, + driver: state === "unsupported" ? "claudeAgent" : "codex", + providerSessionId, + nativeThreadRef: { driver: "codex", nativeId: "saved-native-thread", strength: "strong" }, + nativeMetadata: { itemIdentityVersion: 2 }, + }; + const runId = RunId.make("failed-run"); + const messageId = MessageId.make("failed-message"); + const sourceMessage = { + id: messageId, + role: "user", + creationSource: "web", + text: "original request", + attachments: [], + context: { version: 1, records: [] }, + }; + const savedSession = { id: providerSessionId, status: "error" }; + const calls: Array = []; + const started = yield* Deferred.make(); + const allowResume = yield* Deferred.make(); + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: () => + Effect.die("Reconnection must not dispatch before native resume succeeds"), + getThreadRecords: () => + Effect.succeed({ + thread: { + id: threadId, + projectId: ProjectId.make("retry-project"), + deletedAt: null, + archivedAt: null, + activeProviderThreadId: providerThreadId, + modelSelection, + runtimeMode: runtimePolicy.runtimeMode, + interactionMode: runtimePolicy.interactionMode, + worktreePath: runtimePolicy.cwd, + }, + providerThreads: [providerThread], + providerSessions: [savedSession], + providerTurns: [], + runtimeRequests: state === "request-pending" ? [{ status: "pending" }] : [], + turnItems: [], + messages: [sourceMessage], + runs: [ + { + id: runId, + userMessageId: messageId, + ordinal: 1, + status: state === "running" ? "running" : "failed", + }, + ], + } as unknown as OrchestrationV2ThreadProjection), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + isLive: () => Effect.succeed(false), + release: (input) => + state === "shared-busy" + ? Effect.fail( + new ProviderSessionManager.ProviderSessionBusyError({ providerSessionId }), + ) + : Effect.sync(() => { + expect(input).toEqual({ + providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + alreadyLockedThreadId: threadId, + }); + calls.push("release"); + }), + open: (input) => + Effect.gen(function* () { + calls.push("open"); + expect(input).toEqual({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + resumeFromSession: savedSession, + initialNativeThreadId: "saved-native-thread", + initialProviderItemIdentityVersion: 2, + }); + if (state === "open-failed") + return yield* new ProviderSessionManager.ProviderSessionOpenError({ + instanceId: modelSelection.instanceId, + providerSessionId, + }); + return { + resumeThread: (input: unknown) => + Effect.gen(function* () { + calls.push("resume"); + expect(input).toEqual({ + providerThread, + threadId, + modelSelection, + runtimePolicy, + }); + yield* Deferred.succeed(started, undefined); + if (state === "resume-failed") + return yield* new ProviderAdapter.ProviderAdapterResumeThreadError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId, + providerThreadId, + }); + if (state === "resuming") yield* Deferred.await(allowResume); + return providerThread; + }), + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime; + }), + }), + ), + ), + Layer.provide( + ServerSettings.layerTest({ + projectSettingsOverrides: { + "retry-project": { + providerInstances: { + codex: { enabled: state !== "disabled-reconnect" && state !== "disabled-retry" }, + }, + }, + }, + }), + ), + Layer.provide(layerReceiptsTest), + ); + yield* Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + const done = yield* Ref.make(false); + const pending = yield* service + .restartCodex({ + threadId, + ...(state === "open-failed" || state === "resume-failed" || state === "disabled-retry" + ? { retryRunId: runId } + : state === "stale-retry" + ? { retryRunId: RunId.make("older-run") } + : {}), + }) + .pipe( + Effect.result, + Effect.tap(() => Ref.set(done, true)), + Effect.forkChild, + ); + if (state === "resuming") { + yield* Deferred.await(started); + expect(yield* Ref.get(done)).toBe(false); + yield* Deferred.succeed(allowResume, undefined); + } + const result = yield* Fiber.join(pending); + if (state === "resuming") { + expect(result._tag).toBe("Success"); + expect(calls).toEqual(["release", "open", "resume"]); + } else if (state === "open-failed" || state === "resume-failed") { + expect(result).toMatchObject({ _tag: "Failure", failure: { reason: "restart-failed" } }); + expect(calls).toEqual( + state === "open-failed" + ? ["release", "open", "release"] + : ["release", "open", "resume", "release"], + ); + } else { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: + state === "unsupported" + ? "unsupported" + : state === "stale-retry" || + state === "request-pending" || + state === "disabled-reconnect" || + state === "disabled-retry" + ? "unavailable" + : "busy", + }, + }); + expect(calls).toEqual([]); + } + }).pipe(Effect.provide(layerTest)); + }), +); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index d83dd9578c279..d83aa75b0d97b 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -12,6 +12,8 @@ import { CommandId, MessageId, OrchestrationV2StopWorkflowError, + OrchestrationV2RestartCodexError, + type OrchestrationV2RestartCodexInput, type OrchestrationV2StopWorkflowInput, type ModelSelection, type OrchestrationV2Actor, @@ -36,6 +38,12 @@ import { type TurnItemId, } from "@t3tools/contracts"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; +import { + latestExecutedRun, + latestRootProviderFailure, + isProviderEventStreamFailure, + hasAcceptedProviderTurn, +} from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -51,6 +59,7 @@ import * as Orchestrator from "./Orchestrator.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; +import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; import { projectTurnItemForDetail } from "./WireProjection.ts"; @@ -417,6 +426,10 @@ export interface ThreadManagementServiceShape { readonly interruptThread: ( input: ThreadManagementInterruptInput, ) => Effect.Effect; + /** Resumes saved native history and optionally recovers the latest failed run. */ + readonly restartCodex: ( + input: OrchestrationV2RestartCodexInput & { readonly automatic?: boolean }, + ) => Effect.Effect; readonly stopWorkflow: ( input: OrchestrationV2StopWorkflowInput, ) => Effect.Effect; @@ -510,6 +523,7 @@ const make = Effect.gen(function* () { const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor; const orchestrator = yield* Orchestrator.OrchestratorV2; const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2; const layerScope = yield* Effect.scope; const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -1006,6 +1020,222 @@ const make = Effect.gen(function* () { return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const; }); + const restartCodex: ThreadManagementServiceShape["restartCodex"] = (input) => + Effect.gen(function* () { + if (input.retryRunId !== undefined) { + const receipt = yield* receipts.getByCommandId( + CommandId.make( + `command:codex-retry:${input.automatic ? "auto:" : ""}${input.retryRunId}`, + ), + ); + if (Option.isSome(receipt)) { + if (receipt.value.threadId !== input.threadId || receipt.value.status !== "accepted") { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + return; + } + } + const records = yield* orchestrator + .getThreadRecords( + input.threadId, + [ + "providerThreads", + "providerSessions", + "runs", + "turnItems", + "providerTurns", + "runtimeRequests", + ], + { turnItemTypes: ["error"] }, + ) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable", cause }), + ), + ); + if (records.thread.deletedAt !== null || records.thread.archivedAt !== null) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + const providerThread = records.providerThreads.find( + (candidate) => candidate.id === records.thread.activeProviderThreadId, + ); + if ( + providerThread?.driver !== "codex" || + providerThread.providerSessionId === null || + providerThread.nativeThreadRef?.nativeId == null || + providerThread.providerInstanceId !== records.thread.modelSelection.instanceId + ) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unsupported" }); + } + if ( + records.runs.some((run) => + ["preparing", "starting", "running", "waiting"].includes(run.status), + ) + ) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "busy" }); + } + const retrySource = + input.retryRunId === undefined ? undefined : (latestExecutedRun(records.runs) ?? undefined); + if ( + input.retryRunId !== undefined && + (retrySource?.id !== input.retryRunId || retrySource.status !== "failed") + ) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + const retryMessage = + retrySource === undefined + ? undefined + : (yield* orchestrator + .getThreadRecords(input.threadId, ["messages"], { + messageIds: [retrySource.userMessageId], + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationV2RestartCodexError({ + ...input, + reason: "unavailable", + cause, + }), + ), + )).messages.find((message) => message.id === retrySource.userMessageId); + if (retrySource !== undefined && retryMessage?.role !== "user") { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + const accepted = + retrySource !== undefined && hasAcceptedProviderTurn(retrySource, records.providerTurns); + const continueWork = + accepted && + isProviderEventStreamFailure( + latestRootProviderFailure(retrySource ?? null, records.turnItems), + ); + // Never resend a prompt that the provider already accepted. + if ( + ((accepted || input.automatic) && !continueWork) || + records.runtimeRequests.some((request) => request.status === "pending") + ) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + if ( + !(yield* isProviderInstanceEnabledForProject({ + projectId: records.thread.projectId, + instanceId: providerThread.providerInstanceId, + })) + ) { + return yield* new OrchestrationV2RestartCodexError({ ...input, reason: "unavailable" }); + } + const modelSelection = records.thread.modelSelection; + // A live shared runtime can retry this thread without stopping its siblings. + const shouldReconnect = + input.retryRunId === undefined || + !(yield* sessions.isLive(providerThread.providerSessionId)); + if (shouldReconnect) { + const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ + thread: records.thread, + modelSelection, + }); + const providerSessionId = providerThread.providerSessionId; + const nativeThreadId = providerThread.nativeThreadRef.nativeId; + const savedSession = records.providerSessions.find( + (session) => session.id === providerSessionId, + ); + yield* sessions + .release({ + providerSessionId: providerThread.providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + alreadyLockedThreadId: input.threadId, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationV2RestartCodexError({ + ...input, + reason: cause._tag === "ProviderSessionBusyError" ? "busy" : "restart-failed", + cause, + }), + ), + ); + yield* Effect.gen(function* () { + const runtime = yield* sessions.open({ + threadId: input.threadId, + providerSessionId, + modelSelection, + runtimePolicy: resolvedRuntimePolicy, + ...(savedSession === undefined ? {} : { resumeFromSession: savedSession }), + initialNativeThreadId: nativeThreadId, + ...(providerThread.nativeMetadata?.itemIdentityVersion === undefined + ? {} + : { + initialProviderItemIdentityVersion: + providerThread.nativeMetadata.itemIdentityVersion, + }), + }); + yield* runtime.resumeThread({ + providerThread, + threadId: input.threadId, + modelSelection, + runtimePolicy: resolvedRuntimePolicy, + }); + }).pipe( + Effect.timeout("30 seconds"), + Effect.onError(() => + sessions + .release({ + providerSessionId, + reason: "manual_shutdown", + rejectIfBusy: true, + alreadyLockedThreadId: input.threadId, + }) + .pipe(Effect.ignoreCause({ log: true })), + ), + ); + } + if (retrySource !== undefined && retryMessage !== undefined) { + return { + type: "message.dispatch", + commandId: CommandId.make( + `command:codex-retry:${input.automatic ? "auto:" : ""}${retrySource.id}`, + ), + messageId: MessageId.make(`message:codex-retry:${retrySource.id}`), + threadId: input.threadId, + retryOfRunId: retrySource.id, + ...(continueWork ? { restartContinuationOfRunId: retrySource.id } : {}), + ...(continueWork && input.automatic + ? { + notification: { + source: { kind: "system" as const }, + outcome: "updated" as const, + summary: "Codex reconnected and continued this turn", + detail: "Continue", + }, + } + : {}), + text: continueWork ? "Continue" : retryMessage.text, + attachments: continueWork ? [] : retryMessage.attachments, + ...(continueWork || retryMessage.context === undefined + ? {} + : { context: retryMessage.context }), + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: input.automatic ? "agent" : "user", + creationSource: input.automatic ? "server" : retryMessage.creationSource, + } satisfies Extract; + } + }).pipe( + (effect) => threadDispatch.withLock(input.threadId, effect), + // Standard admission acquires the thread (and any parent) locks itself. + // It revalidates retryOfRunId before committing a new message. + Effect.flatMap((command) => (command === undefined ? Effect.void : dispatch(command))), + Effect.asVoid, + Effect.mapError((cause) => + cause._tag === "OrchestrationV2RestartCodexError" + ? cause + : new OrchestrationV2RestartCodexError({ ...input, reason: "restart-failed", cause }), + ), + ); + const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = (input) => Effect.gen(function* () { const records = yield* orchestrator @@ -1175,6 +1405,7 @@ const make = Effect.gen(function* () { interruptThread, stopDelegatedTasks, stopWorkflow, + restartCodex, getThreadEventSequence: orchestrator.getThreadEventSequence, recoverDelegatedTask: orchestrator.recoverDelegatedTask, delegatedTaskResultPending: orchestrator.delegatedTaskResultPending, @@ -1204,6 +1435,7 @@ export const layer: Layer.Layer< > = Layer.effect(ThreadManagementService, make).pipe( Layer.provide(layerLegacyV1ThreadImporterNoop), Layer.provide(ThreadCommandExecutor.layer), + Layer.provide(RuntimePolicy.layer), ); export const layerWithLegacyImporter: Layer.Layer< @@ -1214,4 +1446,5 @@ export const layerWithLegacyImporter: Layer.Layer< | ProviderSessionManager.ProviderSessionManagerV2 | ServerSettings.ServerSettingsService | CommandReceiptStore.CommandReceiptStoreV2 + | RuntimePolicy.RuntimePolicyV2 > = Layer.effect(ThreadManagementService, make).pipe(Layer.provide(ThreadCommandExecutor.layer)); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 0eb6579e2002e..4e18a0455ba1e 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,3 +1,5 @@ +import { continueProviderStream } from "./ProviderStreamContinuation.ts"; +import { makeProviderFailureTurnItem } from "@t3tools/provider-core/server/failure"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; @@ -11,6 +13,7 @@ import { CheckpointRef, CommandId, ContextTransferId, + ComposerContextId, EventId, MessageId, NodeId, @@ -18,12 +21,14 @@ import { TurnItemId, type ModelSelection, type OrchestrationV2Run, + type OrchestrationV2ProviderThread, ProjectId, type PullRequestDetail, type PullRequestComment, PullRequestOperationError, ProviderDriverKind, ProviderInstanceId, + ProviderSessionId, ProviderThreadId, ProviderTurnId, RunId, @@ -5053,7 +5058,329 @@ it.layer(layerSharedApplicationDataPlaneTest)("shared application data plane", ( }); it.layer(layerTest)("usage-limit recovery", (it) => { - it.effect.each(["interrupted", "usage_limit"] as const)( + it.effect.each([ + { live: false, declined: null }, + { live: true, declined: null }, + { live: false, declined: "settled" }, + { live: false, declined: "snoozed" }, + ] as const)( + "retries through real admission (live: $live, automatic decline: $declined)", + ({ live, declined }) => + Effect.gen(function* () { + const scenario = `${live}:${declined}`; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const events = yield* EventSink.EventSinkV2; + const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const threadId = ThreadId.make(`reconnect-admission:${scenario}`); + const projectId = ProjectId.make(`reconnect-admission-project:${scenario}`); + const now = yield* DateTime.now; + yield* seedProject({ + projectId, + title: "Retry", + workspaceRoot: process.cwd(), + defaultModelSelection: modelSelection, + createdAt: DateTime.formatIso(now), + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`retry:create:${scenario}`), + threadId, + projectId, + title: "Retry", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + const attachment = { + type: "file" as const, + id: "retry-file", + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const message = { + text: "Preserve [notes](t3-context://v1/file/retry-file)", + attachments: [attachment], + context: { + version: 1 as const, + records: [ + { + version: 1 as const, + kind: "file" as const, + contextId: ComposerContextId.make("retry-file"), + label: attachment.name, + attachmentId: attachment.id, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + }, + ], + }, + }; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`retry:first:${scenario}`), + threadId, + messageId: MessageId.make(`retry:first:${scenario}`), + ...message, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const source = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* events.write({ + events: [ + { + id: EventId.make(`retry:failed:${scenario}`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...source, + status: "failed", + startedAt: now, + completedAt: now, + }, + }, + ], + }); + const native: OrchestrationV2ProviderThread = { + id: ProviderThreadId.make(`retry:native:${scenario}`), + appThreadId: threadId, + driver, + providerInstanceId: modelSelection.instanceId, + providerSessionId: ProviderSessionId.make(`retry:session:${scenario}`), + nativeThreadRef: { driver, nativeId: "saved-native", strength: "strong" as const }, + ownerNodeId: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const acceptTurn = (run: OrchestrationV2Run, ordinal: number) => + events.write({ + events: [ + { + id: EventId.make(`retry:accepted:${ordinal}:${scenario}`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`retry:accepted:${ordinal}:${scenario}`), + providerThreadId: native.id, + nodeId: run.rootNodeId!, + runAttemptId: run.activeAttemptId, + nativeTurnRef: { driver, nativeId: `native-turn:${ordinal}`, strength: "strong" }, + ordinal, + status: "failed", + startedAt: now, + completedAt: now, + }, + }, + ], + }); + const readRecords = orchestrator.getThreadRecords; + const readSpy = vi + .spyOn(orchestrator, "getThreadRecords") + .mockImplementation((id, fields, filter) => + readRecords(id, fields, filter).pipe( + Effect.map((records) => + id === threadId && fields.includes("providerThreads") + ? { + ...records, + thread: { ...records.thread, activeProviderThreadId: native.id }, + providerThreads: [native], + providerSessions: [], + } + : records, + ), + ), + ); + const liveSpy = vi.spyOn(sessions, "isLive").mockReturnValue(Effect.succeed(live)); + let opens = 0; + const releaseSpy = vi.spyOn(sessions, "release").mockImplementation(() => Effect.void); + const openSpy = vi.spyOn(sessions, "open").mockImplementation(() => + Effect.sync(() => { + opens += 1; + return { + resumeThread: () => Effect.succeed(native), + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime; + }), + ); + try { + if (!live) { + yield* acceptTurn(source, 1); + yield* events.write({ + events: [ + { + id: EventId.make(`retry:stream-error:${scenario}`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: makeProviderFailureTurnItem({ + driver, + threadId, + runId: source.id, + nodeId: source.rootNodeId, + providerThreadId: native.id, + providerTurnId: ProviderTurnId.make("stream-failure"), + itemOrdinal: 1, + occurredAt: now, + failure: { + class: "provider_error", + code: "event_stream_closed", + retryable: true, + message: "The provider event stream closed unexpectedly.", + }, + }), + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`retry:wrong-provider:${scenario}`), + messageId: MessageId.make(`retry:wrong-provider:${scenario}`), + threadId, + retryOfRunId: source.id, + restartContinuationOfRunId: source.id, + modelSelection: { + ...modelSelection, + instanceId: ProviderInstanceId.make("different-codex"), + }, + text: "Continue", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const unchanged = yield* orchestrator.getThreadProjection(threadId); + assert.lengthOf(unchanged.runs, 1); + assert.lengthOf(unchanged.messages, 1); + assert.equal(unchanged.thread.providerInstanceId, source.providerInstanceId); + if (declined !== null) { + yield* events.write({ + events: [ + { + id: EventId.make(`retry:automatic-blocked:${scenario}`), + type: "thread.metadata-updated", + threadId, + occurredAt: now, + payload: { + ...unchanged.thread, + ...(declined === "settled" + ? { settledOverride: "settled" as const, settledAt: now } + : { snoozedUntil: DateTime.add(now, { days: 1 }), snoozedAt: now }), + }, + }, + ], + }); + // Model the state changing after the automatic preflight, before admission. + yield* threads.restartCodex({ threadId, retryRunId: source.id, automatic: true }); + yield* threads.restartCodex({ threadId, retryRunId: source.id, automatic: true }); + const blocked = yield* orchestrator.getThreadProjection(threadId); + assert.lengthOf(blocked.runs, 1); + assert.lengthOf(blocked.messages, 1); + assert.equal(opens, 1, "the declined automatic command has an accepted receipt"); + yield* threads.restartCodex({ threadId, retryRunId: source.id }); + yield* threads.restartCodex({ threadId, retryRunId: source.id }); + } else { + yield* continueProviderStream({ threadId, sourceRunId: source.id }); + yield* continueProviderStream({ threadId, sourceRunId: source.id }); + } + } else { + // App startedAt alone must not send Continue for an unaccepted prompt. + yield* continueProviderStream({ threadId, sourceRunId: source.id }); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 1); + yield* threads.restartCodex({ threadId, retryRunId: source.id }); + yield* threads.restartCodex({ threadId, retryRunId: source.id }); + } + const after = yield* orchestrator.getThreadProjection(threadId); + const expectedOpens = live ? 0 : declined === null ? 1 : 2; + assert.equal(opens, expectedOpens); + assert.equal(releaseSpy.mock.calls.length, expectedOpens); + assert.lengthOf(after.runs, 2); + assert.equal(after.runs[1]?.status, "starting"); + assert.isNull(after.thread.settledOverride); + assert.isNull(after.thread.snoozedUntil); + assert.lengthOf(after.messages, 2); + assert.equal( + after.runs[1]?.userMessageId, + MessageId.make(`message:codex-retry:${source.id}`), + ); + const retried = after.messages.at(-1); + assert.deepEqual( + { text: retried?.text, attachments: retried?.attachments, context: retried?.context }, + live ? message : { text: "Continue", attachments: [], context: undefined }, + ); + if (!live) { + const continued = after.runs[1]!; + assert.equal(continued.restartContinuationOfRunId, source.id); + yield* acceptTurn(continued, 2); + yield* events.write({ + events: [ + { + id: EventId.make(`retry:continued-failed:${scenario}`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...continued, status: "failed", startedAt: now, completedAt: now }, + }, + { + id: EventId.make(`retry:continued-error:${scenario}`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: makeProviderFailureTurnItem({ + driver, + threadId, + runId: continued.id, + nodeId: continued.rootNodeId, + providerThreadId: native.id, + providerTurnId: ProviderTurnId.make("continued-stream-failure"), + itemOrdinal: 2, + occurredAt: now, + failure: { + class: "provider_error", + code: "event_stream_closed", + retryable: true, + message: "The provider event stream closed unexpectedly.", + }, + }), + }, + ], + }); + yield* continueProviderStream({ threadId, sourceRunId: continued.id }); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 2); + assert.equal( + opens, + expectedOpens, + "a failed automatic continuation must not restart endlessly", + ); + yield* threads.restartCodex({ threadId, retryRunId: continued.id }); + const manual = (yield* orchestrator.getThreadProjection(threadId)).messages.at(-1); + assert.equal(manual?.text, "Continue"); + assert.deepEqual(manual?.attachments, []); + assert.equal(opens, expectedOpens + 1); + } + } finally { + liveSpy.mockRestore(); + readSpy.mockRestore(); + releaseSpy.mockRestore(); + openSpy.mockRestore(); + } + }), + ); + + it.effect.each(["interrupted", "usage_limit", "provider-error"] as const)( "manually resumes an %s run ahead of its queued message only once", (reason) => Effect.gen(function* () { @@ -5189,7 +5516,9 @@ it.layer(layerTest)("usage-limit recovery", (it) => { commandId: CommandId.make(`manual-resume:${suffix}:${reason}`), threadId, messageId: MessageId.make(`manual-resume:${suffix}:${reason}`), - manualContinuationOfRunId: source.id, + ...(reason === "provider-error" + ? { retryOfRunId: source.id } + : { manualContinuationOfRunId: source.id }), text: "Continue where you left off.", attachments: [], dispatchMode: { type: "start_immediately" as const }, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 52e9adf187064..a16aee3d7bc57 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -139,6 +139,7 @@ const layerProviderSessionManagerProvided = ProviderSessionManager.layer.pipe( IdAllocator.layer, layerProviderEventIngestorProvided, ProjectionStore.layer, + ThreadCommandExecutor.layer, ), ), ); @@ -253,6 +254,7 @@ const layerThreadManagementProvided = ThreadManagementService.layerWithLegacyImp layerLegacyV1ThreadImporterProvided, layerCommandReceiptStoreProvided, layerProviderSessionManagerProvided, + layerRuntimePolicyProvided, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 14c08d4922146..b866f10b53d51 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -370,6 +370,7 @@ export function layerWithRegistry( McpSessionRegistryTestkit.layer, layerProviderEventIngestorProvided, layerStores, + ThreadCommandExecutor.layer, ), ), ); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 285f2cfe1f9bc..c5738c8c91535 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -214,6 +214,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( settleThread: unused, interruptThread: unused, stopWorkflow: () => Effect.die("unused stopWorkflow"), + restartCodex: () => Effect.die("unused restartCodex"), stopDelegatedTasks: unused, getThreadEventSequence: unused, recoverDelegatedTask: unused, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 84cfb8430fbbc..a0bc48e9fcc8d 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1835,6 +1835,7 @@ const layerWsRpc = ( ), ), ), + [ORCHESTRATION_V2_WS_METHODS.restartCodex]: (input) => threadManagement.restartCodex(input), [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => readWorkflowScript({ scriptPath: input.scriptPath }), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3e76a11c45bae..521c890ec5edd 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -108,6 +108,7 @@ import { deriveThreadRuntime, presentPendingBackgroundWork, presentProviderGoal, + deriveCodexRecoveryAction, } from "@t3tools/client-runtime/state/thread-execution"; import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; @@ -1783,6 +1784,10 @@ export default function ChatView(props: ChatViewProps) { }); const serverThreadProjection = useThreadProjection(routeThreadDetailRef); const serverProjection = serverThreadProjection?.projection ?? null; + const codexRecovery = useMemo( + () => deriveCodexRecoveryAction(serverProjection), + [serverProjection], + ); const reportedModelSelection = serverProjection ? deriveReportedModelSelection(serverProjection) : null; @@ -10935,6 +10940,7 @@ export default function ChatView(props: ChatViewProps) {
void; onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void; onCancelWorktreeSetup: (() => void) | null; + codexRecovery: CodexRecoveryAction | null; retryableWorkspacePreparationRunIds: ReadonlySet; onRetryWorkspacePreparation: ((runId: RunId) => void) | null; onWorktreeSetupWorkLocally: (() => void) | null; @@ -419,6 +422,7 @@ export interface MessagesTimelineHistoryControls { } interface MessagesTimelineProps { + codexRecovery?: CodexRecoveryAction | null; citationRequest?: AssistantCitationRequest | null; citationHistoryLoading?: boolean; onCiteAssistantText?: ( @@ -533,6 +537,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ worktreeSetup = null, footer = null, onCancelWorktreeSetup, + codexRecovery = null, retryableWorkspacePreparationRunIds = EMPTY_RUN_IDS, onRetryWorkspacePreparation, onWorktreeSetupWorkLocally, @@ -1307,6 +1312,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ onToggleWorkGroup, onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure, onCancelWorktreeSetup: onCancelWorktreeSetup ?? null, + codexRecovery, retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null, onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null, @@ -1345,6 +1351,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ onToggleWorkGroup, suspendEndScrollMaintenanceForDisclosure, onCancelWorktreeSetup, + codexRecovery, retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation, onWorktreeSetupWorkLocally, @@ -5354,6 +5361,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: WorkEntryRowP function WorkEntryLogRow(props: WorkEntryRowProps) { const { workEntry, workspaceRoot, displayLabel } = props; + const activity = use(TimelineRowActivityCtx); const ctx = use(TimelineRowCtx); const { threadRef, onImageExpand, timestampFormat } = ctx; const { retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation } = ctx; @@ -5425,6 +5433,21 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { {failureItem.failure.message}

) : null} + {!warning && + ctx.codexRecovery !== null && + !activity.isWorking && + failureItem.runId !== null && + failureItem.runId === ctx.codexRecovery.runId && + threadRef ? ( +
+ +
+ ) : null} {retryRunId !== null && onRetryWorkspacePreparation ? (
+ {message ? ( +

+ {message} +

+ ) : null} +
+ ); +} diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 2a9735f61c6da..47e2ffa884bb9 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -215,6 +215,12 @@ the snooze. Enable **Snooze limited threads** in thread behavior settings to snooze limit stops by default. Providers without a reset time offer manual retry and the normal snooze choices. +If Codex loses its connection after acknowledging a turn, T3 tries once to +reconnect the saved conversation and send `Continue`. If that attempt fails, +use **Continue** on the error. Without an acknowledgment, **Retry message** +resends the original message and attachments when you choose it. Check the +conversation first: a lost acknowledgment can hide work that already started. + On web and desktop, use **Agents** to follow work delegated to subagents. Stop on a thread also stops the subagents it delegated to. diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 58a77730a4011..beac1fc54fdbf 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import { AuthOrchestrationOperateScope, + ORCHESTRATION_V2_WS_METHODS, AuthSettingsWriteScope, AuthSourceControlWriteScope, ThreadId, @@ -59,6 +60,25 @@ const setup = Effect.gen(function* () { }); describe("command permissions", () => { + it.effect("requires the destination orchestration grant to restart Codex", () => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + const restart = createCommandPermissions(runtime, ORCHESTRATION_V2_WS_METHODS.restartCodex); + registry.set(sessions(env), AsyncResult.success(grant(false))); + expect(registry.get(restart.permissionAtom(env))).toBe(false); + expect((yield* restart.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(restart.permissionAtom(env))).toBe(true); + yield* restart.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(restart.permissionAtom(other))).toBe(false); + }), + ), + ); + it.effect("requires the destination settings grant to run storage cleanup", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index e01759225aa8a..0530d3420317f 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -91,6 +91,10 @@ export function createOrchestrationEnvironmentAtoms( staleTimeMs: 300_000, idleTtlMs: 300_000, }), + restartCodex: createEnvironmentRpcCommand(runtime, { + label: "environment-data:orchestration:restart-codex", + tag: ORCHESTRATION_V2_WS_METHODS.restartCodex, + }), stopWorkflow: createEnvironmentRpcCommand(runtime, { label: "environment-data:orchestration:stop-workflow", tag: ORCHESTRATION_V2_WS_METHODS.stopWorkflow, diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index 2d61f6d95f0eb..56cc8982f47ba 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -7,6 +7,8 @@ import { ProviderSessionId, ProviderDriverKind, RunId, + RunAttemptId, + ProviderTurnId, ThreadId, type OrchestrationV2ExecutionNode, type OrchestrationV2RunStatus, @@ -20,6 +22,7 @@ import { presentPendingBackgroundWork, presentProviderGoal, deriveReportedModelSelection, + deriveCodexRecoveryAction, deriveLatestThreadRun, deriveProviderSubagentStatus, formatModelSelectionEffort, @@ -714,3 +717,131 @@ describe("presentProviderGoal", () => { ).toBe("Goal set"); }); }); + +describe("Codex recovery action", () => { + const driver = ProviderDriverKind.make("codex"); + const providerThreadId = ProviderThreadId.make("recovery-native"); + const failed = { + ...run("recovery", 1, "failed"), + activeAttemptId: RunAttemptId.make("recovery-attempt"), + rootNodeId: NodeId.make("recovery-root"), + providerThreadId, + completedAt: now, + }; + const providerThread = { + id: providerThreadId, + appThreadId: v2Projection.thread.id, + driver, + providerInstanceId: failed.providerInstanceId, + providerSessionId: ProviderSessionId.make("recovery-session"), + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "saved-native", strength: "strong" as const }, + nativeConversationHeadRef: null, + status: "idle" as const, + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const projection = { + ...v2Projection, + thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, + runs: [failed], + providerThreads: [providerThread], + }; + + it.each([ + { accepted: false, code: "event_stream_closed_unacknowledged", expected: false }, + { accepted: false, code: "provider_rejected", expected: false }, + { accepted: true, code: "event_stream_closed", expected: true }, + { accepted: true, code: "provider_rejected", expected: null }, + { accepted: true, code: "event_stream_closed_unacknowledged", expected: null }, + { accepted: true, code: null, expected: true }, + { accepted: false, code: null, expected: false }, + ])( + "uses native acceptance for code $code (accepted: $accepted)", + ({ accepted, code, expected }) => { + const providerTurnId = ProviderTurnId.make("recovery-turn"); + const action = deriveCodexRecoveryAction({ + ...projection, + providerTurns: accepted + ? [ + { + id: providerTurnId, + providerThreadId, + nodeId: failed.rootNodeId, + runAttemptId: failed.activeAttemptId, + nativeTurnRef: { driver, nativeId: "accepted-native-turn", strength: "strong" }, + ordinal: 1, + status: "failed", + startedAt: now, + completedAt: now, + }, + ] + : [], + turnItems: [ + { + id: TurnItemId.make("recovery-error"), + threadId: v2Projection.thread.id, + runId: failed.id, + nodeId: failed.rootNodeId, + providerThreadId, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + type: "error", + status: "failed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error", + code, + message: "The provider event stream closed unexpectedly.", + retryable: true, + }, + }, + ], + }); + expect(action).toEqual( + expected === null ? null : { runId: failed.id, continueWork: expected }, + ); + }, + ); + + it("withholds recovery until a saved Codex thread is available and work is idle", () => { + expect( + deriveCodexRecoveryAction({ ...projection, runs: [{ ...failed, startedAt: null }] }), + ).toEqual({ + runId: failed.id, + continueWork: false, + }); + expect( + deriveCodexRecoveryAction({ + ...projection, + runs: [{ ...failed, providerInstanceId: ProviderInstanceId.make("previous-codex") }], + }), + ).toBeNull(); + expect(deriveCodexRecoveryAction(null)).toBeNull(); + expect(deriveCodexRecoveryAction({ ...projection, providerThreads: [] })).toBeNull(); + expect( + deriveCodexRecoveryAction({ ...projection, runs: [failed, run("newer", 2, "running")] }), + ).toBeNull(); + expect( + deriveCodexRecoveryAction({ + ...projection, + providerThreads: [{ ...providerThread, nativeThreadRef: null }], + }), + ).toBeNull(); + expect( + deriveCodexRecoveryAction({ + ...projection, + thread: { ...projection.thread, archivedAt: now }, + }), + ).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 75ae3404e4ba1..fd663d5c19bbd 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -1,4 +1,7 @@ import { + hasAcceptedProviderTurn, + isProviderEventStreamFailure, + latestExecutedRun, latestRootProviderFailure, latestUnheldRun, threadErrorSummary, @@ -16,6 +19,7 @@ import { type OrchestrationV2ThreadProjection, orchestrationV2RunWorkStartedAt, type ThreadId, + type RunId, } from "@t3tools/contracts"; import { backgroundWorkHoldsCompletion, @@ -35,6 +39,40 @@ import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]); const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]); +export interface CodexRecoveryAction { + readonly runId: RunId; + readonly continueWork: boolean; +} + +/** Match the saved-thread and acceptance checks used by restartCodex. */ +export function deriveCodexRecoveryAction( + projection: OrchestrationV2ThreadProjection | null, +): CodexRecoveryAction | null { + if (projection === null) return null; + const { thread, runs, providerThreads, providerTurns, runtimeRequests, turnItems } = projection; + const run = latestExecutedRun(runs); + const native = providerThreads.find( + (candidate) => candidate.id === thread.activeProviderThreadId, + ); + if ( + run?.status !== "failed" || + thread.archivedAt !== null || + thread.deletedAt !== null || + native?.driver !== "codex" || + native.providerSessionId === null || + native.nativeThreadRef?.nativeId == null || + native.providerInstanceId !== thread.modelSelection.instanceId || + run.providerInstanceId !== thread.providerInstanceId || + runs.some((candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) || + runtimeRequests.some((request) => request.status === "pending") + ) + return null; + const accepted = hasAcceptedProviderTurn(run, providerTurns); + if (accepted && !isProviderEventStreamFailure(latestRootProviderFailure(run, turnItems))) + return null; + return { runId: run.id, continueWork: accepted }; +} + function latestMatchingRun( projection: OrchestrationV2ThreadProjection, predicate: (run: OrchestrationV2ThreadProjection["runs"][number]) => boolean, diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index e111eb244c5b1..b9140f9035f48 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -45,6 +45,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope, + [ORCHESTRATION_V2_WS_METHODS.restartCodex]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index fa4b7738eaaed..eb2e7d4be1966 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2767,6 +2767,8 @@ export const OrchestrationV2Command = Schema.Union([ restartContinuationOfRunId: Schema.optional(RunId), usageLimitContinuationOfRunId: Schema.optional(RunId), manualContinuationOfRunId: Schema.optional(RunId), + /** Retry only if this is still the latest executed failed run at admission. */ + retryOfRunId: Schema.optional(RunId), usageLimitRecoveryRequestId: Schema.optional(CommandId), deliveryIntent: Schema.optional(Schema.Literals(["auto", "steer", "restart"])), delegatedCompletion: Schema.optional( @@ -3053,6 +3055,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { getThreadProjection: "orchestration.getThreadProjection", getWorkflowScript: "orchestration.getWorkflowScript", stopWorkflow: "orchestration.stopWorkflow", + restartCodex: "orchestration.restartCodex", getTurnItem: "orchestration.getTurnItem", launchThread: "orchestration.launchThread", subscribeArchivedShell: "orchestration.subscribeArchivedShell", @@ -3337,6 +3340,34 @@ export class OrchestrationV2ThreadLaunchError extends Schema.TaggedError()( + "OrchestrationV2RestartCodexError", + { + threadId: ThreadId, + reason: Schema.Literals(["unsupported", "busy", "unavailable", "restart-failed"]), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + switch (this.reason) { + case "unsupported": + return "This thread does not have a Codex session."; + case "busy": + return "Codex is still working in this or another thread. Stop that work before restarting."; + case "unavailable": + return "This thread is unavailable."; + case "restart-failed": + return "Could not recover the Codex session. Try again."; + } + } +} + export const OrchestrationV2StopWorkflowInput = Schema.Struct({ threadId: ThreadId, subagentId: NodeId, @@ -3372,6 +3403,7 @@ export const OrchestrationV2RpcError = Schema.Union([ OrchestrationV2GetShellSnapshotError, OrchestrationV2ThreadLaunchError, OrchestrationV2StopWorkflowError, + OrchestrationV2RestartCodexError, ]); export type OrchestrationV2RpcError = typeof OrchestrationV2RpcError.Type; @@ -3545,6 +3577,10 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2GetThreadProjectionInput, output: OrchestrationV2ThreadProjection, }, + restartCodex: { + input: OrchestrationV2RestartCodexInput, + output: Schema.Void, + }, stopWorkflow: { input: OrchestrationV2StopWorkflowInput, output: Schema.Void, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 9536aa93a7ee3..1ac4b543f5390 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -210,6 +210,7 @@ import { ORCHESTRATION_V2_WS_METHODS, OrchestrationGetWorkflowScriptError, OrchestrationV2StopWorkflowError, + OrchestrationV2RestartCodexError, OrchestrationV2DispatchCommandError, OrchestrationV2GetShellSnapshotError, OrchestrationV2CommandOutputError, @@ -1651,6 +1652,12 @@ const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make( }, ); +const WsOrchestrationV2RestartCodexRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.restartCodex, { + payload: OrchestrationV2RpcSchemas.restartCodex.input, + success: OrchestrationV2RpcSchemas.restartCodex.output, + error: Schema.Union([OrchestrationV2RestartCodexError, EnvironmentAuthorizationError]), +}); + const WsOrchestrationV2StopWorkflowRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.stopWorkflow, { payload: OrchestrationV2RpcSchemas.stopWorkflow.input, success: OrchestrationV2RpcSchemas.stopWorkflow.output, @@ -2032,6 +2039,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2StopWorkflowRpc, + WsOrchestrationV2RestartCodexRpc, WsOrchestrationV2GetTurnItemRpc, WsOrchestrationV2GetTurnDiffRpc, WsOrchestrationV2GetFullThreadDiffRpc, diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a4429213db28e..298fe07542909 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -111,6 +111,8 @@ it("does not expose defect text nested inside a known error category", () => { }, }); assert.include(failure.message, "provider event stream closed unexpectedly"); + assert.equal(failure.code, "event_stream_closed"); + assert.include(failure.message, "Continue the saved conversation"); assert.notInclude(failure.message, "Session rejected:"); assert.notInclude(failure.message, "nested-secret"); assert.notInclude(failure.message, "user:pass"); diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 8921df5b5e8be..2d79d9d7da7ea 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -29,6 +29,8 @@ export const MAX_PROVIDER_FAILURE_MESSAGE_LENGTH = 4_096; export const MAX_PROVIDER_FAILURE_CODE_LENGTH = 128; const DEFAULT_PROVIDER_FAILURE_MESSAGE = "Provider turn failed."; +const STREAM_FAILURE_MESSAGE = + "The provider event stream closed unexpectedly. Continue the saved conversation; if it keeps failing, check the provider and server logs."; function causeMessage(cause: unknown): string | undefined { const seen = new Set(); @@ -53,8 +55,7 @@ function causeMessage(cause: unknown): string | undefined { "The provider could not start this turn. Retry the turn; if it keeps failing, check the provider setup and server logs."; break; case "ProviderAdapterEventStreamError": - message = - "The provider event stream closed unexpectedly. Retry the turn; if it keeps failing, check the provider and server logs."; + message = STREAM_FAILURE_MESSAGE; break; case "ProviderAdapterOpenSessionError": message = @@ -149,9 +150,13 @@ export function makeProviderFailure(input: { readonly retryable?: boolean | null; readonly resetAt?: string | null; }): OrchestrationV2ProviderFailure { - const rawMessage = input.message ?? causeMessage(input.cause) ?? DEFAULT_PROVIDER_FAILURE_MESSAGE; + const knownMessage = causeMessage(input.cause); + const rawMessage = input.message ?? knownMessage ?? DEFAULT_PROVIDER_FAILURE_MESSAGE; const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH); - const rawCode = input.code ?? stringField(input.cause, "code") ?? null; + const rawCode = + input.code ?? + stringField(input.cause, "code") ?? + (knownMessage === STREAM_FAILURE_MESSAGE ? "event_stream_closed" : null); const code = rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null; diff --git a/packages/shared/src/KeyedLock.test.ts b/packages/shared/src/KeyedLock.test.ts index d58df7b5be390..52dc59c402874 100644 --- a/packages/shared/src/KeyedLock.test.ts +++ b/packages/shared/src/KeyedLock.test.ts @@ -3,6 +3,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; @@ -94,6 +95,33 @@ describe("KeyedLock", () => { }), ); + it.effect("refuses a held key without running or waiting and releases attempted locks", () => + Effect.gen(function* () { + const lock = yield* KeyedLock.make(); + yield* lock.withLock( + "held", + Effect.gen(function* () { + const refused = yield* lock.withLockIfAvailable("held", Effect.die("must not run")); + assert.isTrue(Option.isNone(refused)); + assert.deepStrictEqual( + yield* lock.withLockIfAvailable("other", Effect.succeed("ran")), + Option.some("ran"), + ); + assert.deepStrictEqual(yield* lock.activeKeys, ["held"]); + }), + ); + assert.strictEqual( + yield* lock.withLockIfAvailable("held", Effect.fail("boom")).pipe(Effect.flip), + "boom", + ); + assert.deepStrictEqual(yield* lock.activeKeys, []); + assert.deepStrictEqual( + yield* lock.withLockIfAvailable("held", Effect.succeed("reused")), + Option.some("reused"), + ); + }), + ); + it.effect("keeps working after the scope that made it closes", () => Effect.gen(function* () { const lock = yield* Effect.scoped(KeyedLock.make()); diff --git a/packages/shared/src/KeyedLock.ts b/packages/shared/src/KeyedLock.ts index 0411d7ef7e76f..efac1c0aa73ea 100644 --- a/packages/shared/src/KeyedLock.ts +++ b/packages/shared/src/KeyedLock.ts @@ -1,9 +1,14 @@ import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; export interface KeyedLock { readonly withLock: (key: Key, effect: Effect.Effect) => Effect.Effect; + readonly withLockIfAvailable: ( + key: Key, + effect: Effect.Effect, + ) => Effect.Effect, E, R>; readonly activeKeys: Effect.Effect>; } @@ -50,6 +55,12 @@ export const make = (): Effect.Effect> => (semaphore) => semaphore.withPermit(effect), () => release(key), ), + withLockIfAvailable: (key, effect) => + Effect.acquireUseRelease( + acquire(key), + (semaphore) => semaphore.withPermitsIfAvailable(1)(effect), + () => release(key), + ), activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())), } satisfies KeyedLock; }); diff --git a/packages/shared/src/orchestrationV2ThreadError.test.ts b/packages/shared/src/orchestrationV2ThreadError.test.ts new file mode 100644 index 0000000000000..6e2b2c5dcafc4 --- /dev/null +++ b/packages/shared/src/orchestrationV2ThreadError.test.ts @@ -0,0 +1,12 @@ +import { assert, it } from "@effect/vitest"; +import { isProviderEventStreamFailure } from "./orchestrationV2ThreadError.ts"; + +it("uses legacy stream text only when no explicit failure code was recorded", () => { + const message = "The provider event stream closed unexpectedly."; + assert.isTrue(isProviderEventStreamFailure({ code: null, message })); + assert.isTrue(isProviderEventStreamFailure({ code: "event_stream_closed", message })); + assert.isFalse( + isProviderEventStreamFailure({ code: "event_stream_closed_unacknowledged", message }), + ); + assert.isFalse(isProviderEventStreamFailure({ code: "provider_rejected", message })); +}); diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index c1e92cc133523..b2851b3b3e976 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -1,10 +1,36 @@ import type { OrchestrationV2ProviderFailure, + OrchestrationV2ProviderTurn, OrchestrationV2Run, OrchestrationV2TurnItem, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +/** App run.startedAt is recorded before the provider accepts the prompt. */ +export function hasAcceptedProviderTurn( + run: Pick, + providerTurns: ReadonlyArray, +): boolean { + return ( + run.activeAttemptId !== null && + providerTurns.some( + (turn) => + turn.runAttemptId === run.activeAttemptId && turn.nativeTurnRef?.strength === "strong", + ) + ); +} + +/** Includes retained failures recorded before event-stream errors had a code. */ +export function isProviderEventStreamFailure( + failure: Pick | null | undefined, +): boolean { + return ( + failure?.code === "event_stream_closed" || + (failure?.code == null && + failure?.message.startsWith("The provider event stream closed unexpectedly.") === true) + ); +} + export function latestRootProviderFailure( run: OrchestrationV2Run | null, turnItems: ReadonlyArray,