From 0d295cf09863e1d0a34cbc1a74faacd731d5f908 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 22 Jun 2026 17:08:00 -0700 Subject: [PATCH] Handle preparing turns across provider orchestration - Treat preparing as an active turn state in mobile and server flows - Tighten ACP model option validation and selection reconfiguration - Add coverage for turn mapping, raw protocol logging, and recovery paths --- .../features/threads/threadPresentation.ts | 2 +- apps/mobile/src/lib/threadActivity.ts | 1 + apps/server/src/claudeModelOptions.test.ts | 53 + apps/server/src/claudeModelOptions.ts | 56 + apps/server/src/cli/project.test.ts | 2 + apps/server/src/cli/project.ts | 2 + apps/server/src/mcp/OrchestratorMcpService.ts | 3 + ...OrchestratorMcpToolkit.integration.test.ts | 14 +- .../Adapters/AcpAdapterV2.test.ts | 200 ++- .../orchestration-v2/Adapters/AcpAdapterV2.ts | 235 ++-- .../Adapters/AcpRegistryAdapterV2.ts | 15 + .../Adapters/ClaudeAdapterV2.test.ts | 288 ++++- .../Adapters/ClaudeAdapterV2.testkit.ts | 20 +- .../Adapters/ClaudeAdapterV2.ts | 247 +++- .../Adapters/CodexAdapterV2.test.ts | 132 +- .../Adapters/CodexAdapterV2.ts | 307 ++++- .../Adapters/CursorAdapterV2.ts | 61 +- .../Adapters/GrokAdapterV2.ts | 30 +- .../Adapters/OpenCodeAdapterV2.test.ts | 44 + .../Adapters/OpenCodeAdapterV2.testkit.ts | 8 +- .../Adapters/OpenCodeAdapterV2.ts | 219 +++- .../src/orchestration-v2/CommandPolicy.ts | 6 +- .../src/orchestration-v2/EffectOutbox.ts | 80 +- .../src/orchestration-v2/EffectWorker.test.ts | 181 +++ .../src/orchestration-v2/EffectWorker.ts | 110 +- apps/server/src/orchestration-v2/EventSink.ts | 96 +- .../FoundationPersistence.test.ts | 476 +++++++- .../KeyedSerialExecutor.test.ts | 67 + .../orchestration-v2/KeyedSerialExecutor.ts | 55 + .../src/orchestration-v2/Orchestrator.ts | 1086 ++++++++++++++--- .../src/orchestration-v2/ProjectionStore.ts | 10 +- .../src/orchestration-v2/ProviderAdapter.ts | 31 +- .../ProviderAdapterRegistry.test.ts | 1 + .../ProviderEventIngestor.test.ts | 71 +- .../orchestration-v2/ProviderEventIngestor.ts | 119 +- .../orchestration-v2/ProviderFailure.test.ts | 124 ++ .../src/orchestration-v2/ProviderFailure.ts | 147 +++ .../ProviderRuntimeRecoveryService.test.ts | 91 +- .../ProviderRuntimeRecoveryService.ts | 17 +- .../ProviderSelectionTransition.test.ts | 55 + .../ProviderSelectionTransition.ts | 37 + .../ProviderSessionManager.test.ts | 233 +++- .../ProviderSessionManager.ts | 12 +- .../ProviderSessionTransitionPolicy.test.ts | 28 +- .../ProviderSessionTransitionPolicy.ts | 25 +- .../ProviderSwitchService.test.ts | 15 + .../orchestration-v2/ProviderSwitchService.ts | 87 +- .../ProviderTurnControlService.test.ts | 282 +++++ .../ProviderTurnControlService.ts | 34 +- .../ProviderTurnStartService.ts | 31 +- .../RunExecutionService.test.ts | 118 +- .../orchestration-v2/RunExecutionService.ts | 199 ++- .../SelectionRestart.integration.test.ts | 639 ++++++++++ .../ThreadLaunchService.test.ts | 885 +++++++++----- .../orchestration-v2/ThreadLaunchService.ts | 687 ++++++----- .../ThreadManagementService.ts | 9 +- .../src/orchestration-v2/runtimeLayer.test.ts | 92 +- .../src/orchestration-v2/runtimeLayer.ts | 1 + ...estratorReplayFixtures.integration.test.ts | 11 +- .../testkit/OrchestratorScenario.ts | 42 +- .../testkit/ProviderReplayHarness.ts | 27 +- .../ProviderSwitch.integration.test.ts | 6 +- .../testkit/ReplayTranscriptNdjson.test.ts | 29 +- .../testkit/ReplayTranscriptNdjson.ts | 41 + .../testkit/ThreadFork.integration.test.ts | 21 +- .../ThreadMergeBack.integration.test.ts | 14 +- .../message_steering/codex_transcript.ndjson | 2 +- .../multi_turn/codex_transcript.ndjson | 4 +- .../plan_questions/codex_transcript.ndjson | 2 +- .../proposed_plan/codex_transcript.ndjson | 2 +- .../codex_transcript.ndjson | 4 +- .../queued_turn/codex_transcript.ndjson | 4 +- .../testkit/fixtures/shared.ts | 6 + .../fixtures/simple/codex_transcript.ndjson | 2 +- .../fixtures/subagent/codex_transcript.ndjson | 2 +- .../subagent_continue/codex_transcript.ndjson | 4 +- .../codex_transcript.ndjson | 4 +- .../codex_transcript.ndjson | 6 +- .../codex_transcript.ndjson | 6 +- .../codex_transcript.ndjson | 6 +- .../codex_transcript.ndjson | 8 +- .../codex_transcript.ndjson | 12 +- .../thread_rollback/codex_transcript.ndjson | 6 +- .../todo_list/codex_transcript.ndjson | 2 +- .../codex_transcript.ndjson | 2 +- .../codex_transcript.ndjson | 2 +- .../codex_transcript.ndjson | 2 +- .../turn_interrupt/codex_transcript.ndjson | 2 +- .../codex_transcript.ndjson | 2 +- .../web_search/codex_transcript.ndjson | 2 +- .../ProjectEnrichmentProjection.test.ts | 101 ++ .../Layers/ProjectionSnapshotQuery.ts | 327 ++--- .../Services/ProjectionSnapshotQuery.ts | 11 + .../project/ProjectEnrichmentService.test.ts | 239 ++++ .../src/project/ProjectEnrichmentService.ts | 285 +++++ .../server/src/project/ProjectService.test.ts | 267 +++- apps/server/src/project/ProjectService.ts | 78 +- .../src/provider/NativeProtocolLogging.ts | 40 + .../src/provider/acp/AcpNativeLogging.ts | 50 +- apps/server/src/server.ts | 4 + apps/server/src/serverRuntimeStartup.ts | 6 - apps/server/src/ws.ts | 65 +- apps/web/src/components/ChatView.tsx | 14 +- apps/web/src/components/Sidebar.logic.ts | 6 +- .../chat/MessagesTimeline.logic.test.ts | 137 +++ .../components/chat/MessagesTimeline.logic.ts | 92 +- .../components/chat/MessagesTimeline.test.tsx | 118 ++ .../src/components/chat/MessagesTimeline.tsx | 90 +- .../src/components/chat/QueuedRunsControl.tsx | 6 +- .../web/src/routes/debug.orchestration-v2.tsx | 8 + apps/web/src/session-logic.test.ts | 152 +++ apps/web/src/session-logic.ts | 89 +- .../client-runtime/src/operations/commands.ts | 12 +- packages/client-runtime/src/state/models.ts | 18 +- .../contracts/src/orchestrationV2.test.ts | 36 + packages/contracts/src/orchestrationV2.ts | 63 + packages/contracts/src/orchestratorMcp.ts | 1 + packages/shared/src/agentAwareness.ts | 1 + packages/shared/src/model.test.ts | 26 +- packages/shared/src/model.ts | 29 + 120 files changed, 9121 insertions(+), 1711 deletions(-) create mode 100644 apps/server/src/claudeModelOptions.test.ts create mode 100644 apps/server/src/claudeModelOptions.ts create mode 100644 apps/server/src/orchestration-v2/EffectWorker.test.ts create mode 100644 apps/server/src/orchestration-v2/KeyedSerialExecutor.test.ts create mode 100644 apps/server/src/orchestration-v2/KeyedSerialExecutor.ts create mode 100644 apps/server/src/orchestration-v2/ProviderFailure.test.ts create mode 100644 apps/server/src/orchestration-v2/ProviderFailure.ts create mode 100644 apps/server/src/orchestration-v2/ProviderSelectionTransition.test.ts create mode 100644 apps/server/src/orchestration-v2/ProviderSelectionTransition.ts create mode 100644 apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts create mode 100644 apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts create mode 100644 apps/server/src/orchestration/Layers/ProjectEnrichmentProjection.test.ts create mode 100644 apps/server/src/project/ProjectEnrichmentService.test.ts create mode 100644 apps/server/src/project/ProjectEnrichmentService.ts create mode 100644 apps/server/src/provider/NativeProtocolLogging.ts diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 547e4f4930..79222f0add 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -31,7 +31,7 @@ export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { pulse: false, }; } - if (status === "queued" || status === "starting") { + if (status === "preparing" || status === "queued" || status === "starting") { return { kind: "working", label: "Working", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 34f50ee6db..b9479ccb6d 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -626,6 +626,7 @@ function maxIsoTimestamp(left: string | null, right: string | null): string | nu function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null { if (!latestRun) return null; return latestRun.completedAt === null || + latestRun.status === "preparing" || latestRun.status === "starting" || latestRun.status === "running" || latestRun.status === "waiting" diff --git a/apps/server/src/claudeModelOptions.test.ts b/apps/server/src/claudeModelOptions.test.ts new file mode 100644 index 0000000000..620a7ef0b3 --- /dev/null +++ b/apps/server/src/claudeModelOptions.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; + +import { ProviderInstanceId, type ModelSelection } from "@t3tools/contracts"; + +import { compileClaudeModelSelection } from "./claudeModelOptions.ts"; + +const selection = ( + model: string, + options: NonNullable, +): ModelSelection => ({ + instanceId: ProviderInstanceId.make("claude_test"), + model, + options, +}); + +describe("compileClaudeModelSelection", () => { + it("compiles context, effort, and settings together", () => { + expect( + compileClaudeModelSelection( + selection("claude-fable-5", [ + { id: "contextWindow", value: "1m" }, + { id: "effort", value: "ultracode" }, + ]), + ), + ).toMatchObject({ + apiModelId: "claude-fable-5[1m]", + effort: "xhigh", + settings: { ultracode: true }, + }); + }); + + it("compiles fast mode only for models that expose it", () => { + expect( + compileClaudeModelSelection(selection("claude-opus-4-6", [{ id: "fastMode", value: true }])) + .settings, + ).toEqual({ fastMode: true }); + }); + + it("uses the model default SDK effort alongside prompt-injected effort", () => { + expect( + compileClaudeModelSelection( + selection("claude-sonnet-4-6", [{ id: "effort", value: "ultrathink" }]), + ), + ).toMatchObject({ effort: "high", promptEffort: "ultrathink" }); + }); + + it("compiles the thinking toggle for models that expose it", () => { + expect( + compileClaudeModelSelection(selection("claude-haiku-4-5", [{ id: "thinking", value: false }])) + .settings, + ).toEqual({ alwaysThinkingEnabled: false }); + }); +}); diff --git a/apps/server/src/claudeModelOptions.ts b/apps/server/src/claudeModelOptions.ts new file mode 100644 index 0000000000..16cb27cb11 --- /dev/null +++ b/apps/server/src/claudeModelOptions.ts @@ -0,0 +1,56 @@ +import type { ModelSelection } from "@t3tools/contracts"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, + getProviderOptionDescriptors, + resolvePromptInjectedEffort, +} from "@t3tools/shared/model"; + +import { + getClaudeModelCapabilities, + isClaudeUltracodeEffort, + normalizeClaudeCliEffort, + resolveClaudeApiModelId, + resolveClaudeEffort, +} from "./provider/Layers/ClaudeProvider.ts"; + +export interface CompiledClaudeModelSelection { + readonly apiModelId: string; + readonly effort: string | undefined; + readonly promptEffort: string | undefined; + readonly settings: Readonly>; + readonly queryIdentity: string; +} + +/** Compile every Claude model option at the provider boundary. */ +export function compileClaudeModelSelection( + selection: ModelSelection, +): CompiledClaudeModelSelection { + const capabilities = getClaudeModelCapabilities(selection.model); + const descriptors = getProviderOptionDescriptors({ caps: capabilities }); + const supportsBoolean = (id: string) => + descriptors.some((descriptor) => descriptor.type === "boolean" && descriptor.id === id); + const rawEffort = getModelSelectionStringOptionValue(selection, "effort"); + const resolvedEffort = resolveClaudeEffort(capabilities, rawEffort); + const effort = normalizeClaudeCliEffort(resolvedEffort, selection.model); + const fastMode = + supportsBoolean("fastMode") && + getModelSelectionBooleanOptionValue(selection, "fastMode") === true; + const thinking = supportsBoolean("thinking") + ? getModelSelectionBooleanOptionValue(selection, "thinking") + : undefined; + const settings = { + ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), + ...(fastMode ? { fastMode: true } : {}), + ...(isClaudeUltracodeEffort(resolvedEffort) ? { ultracode: true } : {}), + }; + const apiModelId = resolveClaudeApiModelId(selection); + const promptEffort = resolvePromptInjectedEffort(capabilities, rawEffort) ?? undefined; + return { + apiModelId, + effort, + promptEffort, + settings, + queryIdentity: JSON.stringify({ apiModelId, effort: effort ?? null, settings }), + }; +} diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 26ed39e922..82e8d420db 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -16,6 +16,7 @@ import { cli } from "../bin.ts"; import * as ServerConfig from "../config.ts"; import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts"; +import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; @@ -66,6 +67,7 @@ const readProjects = (baseDir: string) => Effect.gen(function* () { const config = yield* makeConfig(baseDir); const layer = ProjectServiceLayerLive.pipe( + Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(RepositoryIdentityResolver.layer), Layer.provideMerge(ProjectFaviconResolver.layer), Layer.provideMerge(WorkspacePaths.layer), diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 871a7b0c74..b9a3a3511e 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -26,6 +26,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts"; import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; +import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -195,6 +196,7 @@ const projectCommandUuid = Crypto.Crypto.pipe( ); const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe( + Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(RepositoryIdentityResolver.layer), Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))), Layer.provideMerge(WorkspacePaths.layer), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 9001cd78da..04d55bc66e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -175,6 +175,7 @@ function taskStatusForRun( return "cancelled"; case "interrupted": return "interrupted"; + case "preparing": case "starting": case "running": case undefined: @@ -436,6 +437,8 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { case "run_interrupt_request": case "run_interrupt_result": return item.message; + case "error": + return item.failure.message; case "compaction": return item.summary ?? null; case "handoff": diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 146a0faa08..28d6021aaa 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -136,6 +136,7 @@ function makeDeterministicAdapter(input: { instanceId: input.instanceId, driver: input.driver, getCapabilities: () => Effect.succeed(input.capabilities), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (sessionInput) => Effect.gen(function* () { const events = yield* PubSub.unbounded(); @@ -157,13 +158,13 @@ function makeDeterministicAdapter(input: { Effect.forEach(providerEvents, (event) => PubSub.publish(events, event), { discard: true, }); + const runOrdinals = new Map(); return { instanceId: input.instanceId, driver: input.driver, providerSessionId: sessionInput.providerSessionId, providerSession, - rawEvents: Stream.empty, events: Stream.fromPubSub(events), ensureThread: (threadInput) => Effect.gen(function* () { @@ -206,6 +207,7 @@ function makeDeterministicAdapter(input: { const providerTurnId = ProviderTurnId.make( `provider-turn:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}`, ); + runOrdinals.set(providerTurnId, turnInput.runOrdinal); yield* publish([ { type: "provider_turn.updated", @@ -282,18 +284,26 @@ function makeDeterministicAdapter(input: { { type: "turn.terminal", driver: input.driver, + providerThreadId: turnInput.providerThread.id, providerTurnId, + runOrdinal: turnInput.runOrdinal, status: "completed", + failure: null, + threadDisposition: "reusable", }, ]); }), steerTurn: () => Effect.void, - interruptTurn: ({ providerTurnId }) => + interruptTurn: ({ providerThread, providerTurnId }) => PubSub.publish(events, { type: "turn.terminal", driver: input.driver, + providerThreadId: providerThread.id, providerTurnId, + runOrdinal: runOrdinals.get(providerTurnId) ?? 1, status: "interrupted", + failure: null, + threadDisposition: "reusable", }).pipe(Effect.asVoid), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index f4fd97a677..c53fa28710 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2,11 +2,13 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { MessageId, + type ModelSelection, NodeId, ProjectId, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + ProviderThreadId, RunAttemptId, RunId, ThreadId, @@ -19,9 +21,12 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { ChildProcessSpawner } from "effect/unstable/process"; +import type * as EffectAcpProtocol from "effect-acp/protocol"; import { ServerConfig } from "../../config.ts"; import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts"; @@ -42,17 +47,32 @@ const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer); const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test"); +const decodeUnknownJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString); function makeMockRuntime(input: { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly mockAgentPath: string; readonly environment?: Readonly>; + readonly protocolEvents?: Queue.Queue; }): AcpAdapterV2Flavor["makeRuntime"] { return (runtimeInput) => Effect.gen(function* () { + const protocolEvents = input.protocolEvents; + const protocolLogging = + protocolEvents === undefined + ? runtimeInput.protocolLogging + : { + ...runtimeInput.protocolLogging, + logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) => + Queue.offer(protocolEvents, event).pipe( + Effect.andThen(runtimeInput.protocolLogging.logger?.(event) ?? Effect.void), + Effect.asVoid, + ), + }; const context = yield* Layer.build( AcpSessionRuntime.layer({ ...runtimeInput, + protocolLogging, spawn: { command: process.execPath, args: [input.mockAgentPath], @@ -72,6 +92,20 @@ function makeMockRuntime(input: { }); } +function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string | undefined { + if (event.stage !== "raw" || typeof event.payload !== "string") return undefined; + for (const line of event.payload.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed)); + if (typeof decoded === "object" && decoded !== null && "method" in decoded) { + const method = (decoded as { readonly method?: unknown }).method; + if (typeof method === "string") return method; + } + } + return undefined; +} + function makeTurnInput(input: { readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; @@ -79,10 +113,12 @@ function makeTurnInput(input: { readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; readonly now: DateTime.Utc; readonly ordinal?: number; + readonly modelSelection?: ModelSelection; }): ProviderAdapterV2TurnInput { const ordinal = input.ordinal ?? 1; const suffix = `${input.threadId}:${ordinal}`; - const modelSelection = { instanceId: input.instanceId, model: "default" } as const; + const modelSelection = + input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const); return { appThread: { createdBy: "user", @@ -187,6 +223,156 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(testLayer), Effect.scoped), ); + it.effect("rejects requested options that the active ACP session does not expose", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }), + }, + fileSystem, + idAllocator, + serverConfig, + }); + const threadId = ThreadId.make("thread-acp-unsupported-option"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const error = yield* adapter + .openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-unsupported-option"), + modelSelection: { + instanceId, + model: "default", + options: [{ id: "missing-option", value: "high" }], + }, + runtimePolicy, + }) + .pipe(Effect.flip); + + assert.equal(error._tag, "ProviderAdapterOpenSessionError"); + assert.include(String(error.cause), "does not expose requested configuration option(s)"); + assert.include(String(error.cause), "missing-option"); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); + + it.effect("reconfigures a loaded ACP session from its own active setup metadata", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }), + }, + fileSystem, + idAllocator, + serverConfig, + }); + const firstThreadId = ThreadId.make("thread-acp-active-setup:first"); + const secondThreadId = ThreadId.make("thread-acp-active-setup:second"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const initialSelection = { instanceId, model: "default" } satisfies ModelSelection; + const alternateSelection = { + instanceId, + model: "grok-mock-alt", + } satisfies ModelSelection; + const originalSelection = { instanceId, model: "grok-build" } satisfies ModelSelection; + const runtime = yield* adapter.openSession({ + threadId: firstThreadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-active-setup"), + modelSelection: initialSelection, + runtimePolicy, + }); + const firstProviderThread = yield* runtime.ensureThread({ + threadId: firstThreadId, + modelSelection: initialSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ + threadId: firstThreadId, + providerThread: firstProviderThread, + instanceId, + runtimePolicy, + modelSelection: alternateSelection, + now, + }), + ); + yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + + const secondProviderThread: OrchestrationV2ProviderThread = { + ...firstProviderThread, + id: ProviderThreadId.make("provider-thread-acp-active-setup:second"), + appThreadId: secondThreadId, + nativeThreadRef: { + driver: ACP_TEST_DRIVER, + nativeId: "mock-session-2", + strength: "strong", + }, + status: "idle", + }; + yield* runtime.resumeThread({ + providerThread: secondProviderThread, + modelSelection: alternateSelection, + runtimePolicy, + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId: secondThreadId, + providerThread: secondProviderThread, + instanceId, + runtimePolicy, + modelSelection: originalSelection, + now, + ordinal: 2, + }), + ); + yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + + const setModelRequests = Array.from(yield* Queue.takeAll(protocolEvents)).filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/set_model", + ); + assert.lengthOf(setModelRequests, 2); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); + it.effect("cancels pending permission requests while interrupting an ACP turn", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -283,6 +469,7 @@ describe("AcpAdapterV2", () => { new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); const instanceId = ProviderInstanceId.make("acp-test"); + const protocolEvents = yield* Queue.bounded(256); const adapter = makeAcpAdapterV2({ instanceId, flavor: { @@ -292,6 +479,7 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_PROMPT_DELAY_MS: "5000" }, + protocolEvents, }), }, fileSystem, @@ -325,9 +513,10 @@ describe("AcpAdapterV2", () => { now, }); yield* runtime.startTurn(firstTurn); - yield* runtime.rawEvents.pipe( + yield* Stream.fromQueue(protocolEvents).pipe( Stream.filter( - (event) => event.direction === "outgoing" && event.method === "session/prompt", + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", ), Stream.runHead, ); @@ -338,9 +527,10 @@ describe("AcpAdapterV2", () => { const interruptFiber = yield* runtime .interruptTurn({ providerThread, providerTurnId }) .pipe(Effect.flip, Effect.forkScoped); - yield* runtime.rawEvents.pipe( + yield* Stream.fromQueue(protocolEvents).pipe( Stream.filter( - (event) => event.direction === "outgoing" && event.method === "session/cancel", + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/cancel", ), Stream.runHead, ); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index 1a21d33d74..6f44a2268b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -6,10 +6,10 @@ import { type OrchestrationV2PlanArtifact, type OrchestrationV2PlanStep, type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, - type OrchestrationV2RawProviderEvent, type OrchestrationV2RuntimeRequest, type OrchestrationV2TurnItem, type OrchestrationV2UserInputQuestion, @@ -21,6 +21,8 @@ import { type RuntimeRequestId, type ThreadId, } from "@t3tools/contracts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -31,7 +33,6 @@ import * as Ref from "effect/Ref"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as EffectAcpErrors from "effect-acp/errors"; -import type * as EffectAcpProtocol from "effect-acp/protocol"; import type * as EffectAcpSchema from "effect-acp/schema"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; @@ -50,6 +51,8 @@ import type { } from "../../provider/acp/AcpSessionRuntime.ts"; import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { makeProviderFailure } from "../ProviderFailure.ts"; +import { acpSelectionTransition } from "../ProviderSelectionTransition.ts"; import { ProviderAdapterEnsureThreadError, ProviderAdapterForkThreadError, @@ -80,9 +83,15 @@ export interface AcpAdapterV2RuntimeInput { readonly mcpServers: ReadonlyArray; readonly clientCapabilities: EffectAcpSchema.InitializeRequest["clientCapabilities"]; readonly clientInfo: AcpSessionRuntimeOptions["clientInfo"]; + readonly requestLogger?: NonNullable; readonly protocolLogging: NonNullable; } +export type AcpAdapterV2NativeLogging = Pick< + AcpSessionRuntimeOptions, + "requestLogger" | "protocolLogging" +>; + export interface AcpAdapterV2UserInputRequest { readonly nativeItemId: string; readonly nativeRequestId: string; @@ -119,6 +128,7 @@ export interface AcpAdapterV2Options { readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2Shape; readonly serverConfig: ServerConfig["Service"]; + readonly nativeLogging?: (threadId: ThreadId) => AcpAdapterV2NativeLogging; } export const AcpProviderCapabilitiesV2 = { @@ -489,12 +499,6 @@ export function acpPermissionDisposition( } } -function jsonRpcId(value: unknown): string | number | null { - return (typeof value === "string" && value.length > 0) || typeof value === "number" - ? value - : null; -} - function elicitationContent( answers: ProviderUserInputAnswers, allowedKeys: ReadonlySet, @@ -511,32 +515,6 @@ function elicitationContent( return content; } -function rawJsonRpcMessages(payload: unknown): ReadonlyArray> { - if (typeof payload !== "string") { - return []; - } - const messages: Array> = []; - for (const line of payload.split("\n")) { - const trimmed = line.trim(); - if (trimmed.length === 0) continue; - try { - const decoded: unknown = JSON.parse(trimmed); - if (Array.isArray(decoded)) { - for (const entry of decoded) { - const record = unknownRecord(entry); - if (record !== undefined) messages.push(record); - } - } else { - const record = unknownRecord(decoded); - if (record !== undefined) messages.push(record); - } - } catch { - messages.push({ raw: trimmed }); - } - } - return messages; -} - interface ActiveTextSegment { readonly nativeItemId: string; readonly startedAt: DateTime.Utc; @@ -589,19 +567,6 @@ interface SnapshotMessageState { loadingIndex: number; } -interface RawProtocolState { - readonly pendingMethods: Map; - sequence: number; -} - -function requestKey(direction: "incoming" | "outgoing", id: string | number): string { - return `${direction}:${String(id)}`; -} - -function oppositeDirection(direction: "incoming" | "outgoing"): "incoming" | "outgoing" { - return direction === "incoming" ? "outgoing" : "incoming"; -} - export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV2Shape { const { flavor, fileSystem, idAllocator, serverConfig } = options; const driver = flavor.driver; @@ -610,17 +575,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV instanceId: options.instanceId, driver, getCapabilities: () => Effect.succeed(flavor.capabilities), + planSelectionTransition: (input) => Effect.succeed(acpSelectionTransition(input)), openSession: Effect.fn("AcpAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { const sessionScope = yield* Effect.scope; const events = yield* Queue.unbounded(); - const rawEvents = yield* Queue.unbounded(); - const rawState = yield* Ref.make({ - pendingMethods: new Map(), - sequence: 0, - }); const activeTurn = yield* Ref.make(null); const activeSessionId = yield* Ref.make(null); + const activeSessionSetup = yield* Ref.make(null); + const activeSelection = yield* Ref.make(null); const pendingRuntimeRequests = yield* Ref.make(new Map()); const nextElicitationOrdinal = yield* Ref.make(0); const itemOrdinals = yield* Ref.make(new Map()); @@ -636,61 +599,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const emitProviderEvent = (event: ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); - const protocolLogger = ( - event: EffectAcpProtocol.AcpProtocolLogEvent, - ): Effect.Effect => - Effect.gen(function* () { - if (event.stage !== "raw") return; - for (const message of rawJsonRpcMessages(event.payload)) { - const methodValue = message.method; - const id = jsonRpcId(message.id); - let method = typeof methodValue === "string" ? methodValue : null; - let messageKind: OrchestrationV2RawProviderEvent["messageKind"]; - if (method !== null) { - messageKind = id === null ? "notification" : "request"; - } else if ("error" in message) { - messageKind = "error"; - } else { - messageKind = "response"; - } - const state = yield* Ref.get(rawState); - if (method !== null && id !== null) { - state.pendingMethods.set(requestKey(event.direction, id), method); - } else if (id !== null) { - method = - state.pendingMethods.get(requestKey(oppositeDirection(event.direction), id)) ?? - null; - state.pendingMethods.delete(requestKey(oppositeDirection(event.direction), id)); - } - state.sequence += 1; - const now = yield* DateTime.now; - const rawEventId = yield* idAllocator.allocate.rawEvent({ - providerSessionId: input.providerSessionId, - method, - }); - yield* Queue.offer(rawEvents, { - id: rawEventId, - driver, - providerInstanceId: options.instanceId, - providerSessionId: input.providerSessionId, - sequence: state.sequence, - direction: event.direction, - messageKind, - method, - jsonRpcId: id, - payload: message, - observedAt: now, - }); - } - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.acp-raw-event-failed", { - driver, - providerSessionId: input.providerSessionId, - cause, - }), - ), - ); + const nativeLogging = options.nativeLogging?.(input.threadId); const runtime = yield* flavor.makeRuntime({ cwd: input.runtimePolicy.cwd ?? process.cwd(), @@ -701,10 +610,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV elicitation: { form: {} }, }, clientInfo: { name: "t3-code", version: "0.0.0" }, - protocolLogging: { + ...(nativeLogging?.requestLogger === undefined + ? {} + : { requestLogger: nativeLogging.requestLogger }), + protocolLogging: nativeLogging?.protocolLogging ?? { logIncoming: true, logOutgoing: true, - logger: protocolLogger, + logger: () => Effect.void, }, }); @@ -720,7 +632,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV updated.set(context.nativeTurnId, next); return [next, updated] as const; }); - const ordinal = context.input.runOrdinal * 100 + nextWithinTurn; + const ordinal = context.input.providerTurnOrdinal * 100 + nextWithinTurn; yield* Ref.update(itemOrdinals, (current) => { const updated = new Map(current); updated.set(nativeItemId, ordinal); @@ -1633,6 +1545,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const started = yield* runtime.start(); yield* Ref.set(activeSessionId, started.sessionId); + yield* Ref.set(activeSessionSetup, started); const capabilities = negotiatedCapabilities(flavor.capabilities, started); const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = @@ -1678,10 +1591,18 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } } const configOptions = yield* runtime.getConfigOptions; + const availableConfigIds = new Set(configOptions.map((option) => option.id)); + const unsupportedConfigIds = (modelSelection.options ?? []) + .map((selection) => selection.id) + .filter((id) => !availableConfigIds.has(id)); + if (unsupportedConfigIds.length > 0) { + return yield* new ProviderAdapterProtocolError({ + driver, + detail: `ACP session ${startResult.sessionId} does not expose requested configuration option(s): ${unsupportedConfigIds.join(", ")}`, + }); + } for (const selection of modelSelection.options ?? []) { - if (configOptions.some((option) => option.id === selection.id)) { - yield* runtime.setConfigOption(selection.id, selection.value); - } + yield* runtime.setConfigOption(selection.id, selection.value); } const modeState = yield* runtime.getModeState; if (runtimePolicy.interactionMode === "plan" && modeState !== undefined) { @@ -1693,6 +1614,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* configureSession(started, input.modelSelection, input.runtimePolicy); + yield* Ref.set(activeSelection, input.modelSelection); const createdAt = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: input.providerSessionId, @@ -1730,6 +1652,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const finalizeTurn = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", + failure?: OrchestrationV2ProviderFailure, ) { if (context.finalized) return; context.finalized = true; @@ -1753,19 +1676,40 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV providerThread: { ...context.input.providerThread, providerSessionId: input.providerSessionId, - status: "idle", + status: "active", lastRunOrdinal: context.input.runOrdinal, firstRunOrdinal: context.input.providerThread.firstRunOrdinal ?? context.input.runOrdinal, updatedAt: now, }, }); - yield* emitProviderEvent({ - type: "turn.terminal", - driver, - providerTurnId: context.providerTurnId, - status, - }); + yield* emitProviderEvent( + status === "failed" + ? { + type: "turn.terminal", + driver, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + runOrdinal: context.input.runOrdinal, + failureItemOrdinal: yield* resolveItemOrdinal( + context, + `terminal-failure:${context.providerTurnId}`, + ), + status, + failure: failure ?? makeProviderFailure({ class: "provider_error" }), + threadDisposition: "reusable", + } + : { + type: "turn.terminal", + driver, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + runOrdinal: context.input.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }, + ); yield* Ref.set(activeTurn, null); yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore); }); @@ -1832,7 +1776,29 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV if ((yield* Ref.get(activeSessionId)) !== requestedSessionId) { const activated = yield* activateSession(requestedSessionId); yield* Ref.set(activeSessionId, activated.sessionId); + yield* Ref.set(activeSessionSetup, activated); yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); + yield* Ref.set(activeSelection, turnInput.modelSelection); + } else { + const configuredSelection = yield* Ref.get(activeSelection); + if ( + configuredSelection === null || + !modelSelectionsEqual(configuredSelection, turnInput.modelSelection) + ) { + const currentSessionSetup = yield* Ref.get(activeSessionSetup); + if (currentSessionSetup === null) { + return yield* new ProviderAdapterProtocolError({ + driver, + detail: `ACP session ${requestedSessionId} has no active setup metadata`, + }); + } + yield* configureSession( + currentSessionSetup, + turnInput.modelSelection, + turnInput.runtimePolicy, + ); + yield* Ref.set(activeSelection, turnInput.modelSelection); + } } const prompt = yield* resolvePromptParts(turnInput); const startedAt = yield* DateTime.now; @@ -1901,7 +1867,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV return finalizeTurn(context, status); }), Effect.catchCause((cause) => - finalizeTurn(context, context.interrupted ? "interrupted" : "failed").pipe( + finalizeTurn( + context, + context.interrupted ? "interrupted" : "failed", + makeProviderFailure({ + cause: Cause.squash(cause), + class: "provider_error", + }), + ).pipe( Effect.andThen( Effect.logWarning("orchestration-v2.acp-prompt-failed", { driver, @@ -1958,7 +1931,6 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV driver, providerSessionId: input.providerSessionId, providerSession, - rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( function* (threadInput: ProviderAdapterV2EnsureThreadInput) { @@ -1993,7 +1965,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ), ), resumeThread: Effect.fn("AcpAdapterV2.resumeThread")( - function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { + function* (threadInput: { + readonly providerThread: OrchestrationV2ProviderThread; + readonly modelSelection?: ModelSelection; + readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; + }) { const sessionId = nativeThreadId(driver, threadInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId) { yield* Ref.set(snapshot, { @@ -2004,7 +1980,14 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); const activated = yield* activateSession(sessionId); yield* Ref.set(activeSessionId, activated.sessionId); - yield* configureSession(activated, input.modelSelection, input.runtimePolicy); + yield* Ref.set(activeSessionSetup, activated); + const nextSelection = threadInput.modelSelection ?? input.modelSelection; + yield* configureSession( + activated, + nextSelection, + threadInput.runtimePolicy ?? input.runtimePolicy, + ); + yield* Ref.set(activeSelection, nextSelection); } const now = yield* DateTime.now; return { @@ -2119,6 +2102,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); const activated = yield* runtime.loadSession(sessionId); yield* Ref.set(activeSessionId, activated.sessionId); + yield* Ref.set(activeSessionSetup, activated); + yield* Ref.set(activeSelection, null); } const state = yield* Ref.get(snapshot); const now = yield* DateTime.now; @@ -2176,6 +2161,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread); const forked = yield* runtime.forkSession(sourceSessionId); yield* Ref.set(activeSessionId, forked.sessionId); + yield* Ref.set(activeSessionSetup, forked); + yield* Ref.set(activeSelection, null); const now = yield* DateTime.now; return makeProviderThread({ driver, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts index ecc59dc162..66e64d94d1 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts @@ -4,6 +4,7 @@ import { ProviderDriverKind, } from "@t3tools/contracts"; import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -20,6 +21,8 @@ import { type AcpRegistryResolverShape, } from "../../provider/acp/AcpRegistrySupport.ts"; import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts"; +import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import { IdAllocatorV2 } from "../IdAllocator.ts"; import { @@ -50,6 +53,7 @@ export interface AcpRegistryAdapterV2Options { readonly idAllocator: IdAllocatorV2["Service"]; readonly resolver: AcpRegistryResolverShape; readonly serverConfig: ServerConfig["Service"]; + readonly nativeLogging?: Parameters[0]["nativeLogging"]; readonly makeRuntime?: ( input: AcpAdapterV2RuntimeInput, ) => Effect.Effect< @@ -110,15 +114,18 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) { fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, + ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }), }); } export type AcpRegistryAdapterV2DriverEnv = | ChildProcessSpawner.ChildProcessSpawner + | Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | IdAllocatorV2 | Path.Path + | ProviderEventLoggers | ServerConfig; export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< @@ -134,7 +141,9 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; + const providerEventLoggers = yield* ProviderEventLoggers; const serverConfig = yield* ServerConfig; + const makeNativeLogger = yield* makeAcpNativeLoggerFactory(); const resolver = yield* makeAcpRegistryResolver({ cacheDir: serverConfig.providerStatusCacheDir, }); @@ -147,6 +156,12 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< idAllocator, resolver, serverConfig, + nativeLogging: (threadId) => + makeNativeLogger({ + nativeEventLogger: providerEventLoggers.native, + provider: ACP_REGISTRY_PROVIDER, + threadId, + }), }); }, (effect, input) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 27f5d5150e..54e96ffa08 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1,8 +1,15 @@ +import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { + ChatAttachmentId, + ChatImageAttachment, ClaudeSettings, EnvironmentId, MessageId, + type ModelSelection, NodeId, + type OrchestrationV2AppThread, + type OrchestrationV2ProviderThread, ProjectId, ProviderInstanceId, ProviderSessionId, @@ -14,12 +21,19 @@ import { import { assert, describe, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import { attachmentRelativePath } from "../../attachmentStore.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; -import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; +import { + ProviderAdapterV2RuntimePolicy, + type ProviderAdapterV2TurnInput, +} from "../ProviderAdapter.ts"; import { CLAUDE_AGENT_SDK_QUERY_PROTOCOL, CLAUDE_DEFAULT_INSTANCE_ID, @@ -38,6 +52,76 @@ import { import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); +const CLAUDE_TEST_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", + options: [{ id: "effort", value: "ultrathink" }], +} satisfies ModelSelection; +const CLAUDE_TEST_RUNTIME_POLICY = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); + +function makeClaudeTestAppThread(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly now: DateTime.Utc; +}): OrchestrationV2AppThread { + return { + createdBy: "user", + creationSource: "web", + id: input.threadId, + projectId: ProjectId.make(`project-${input.threadId}`), + title: "Claude attachment test", + providerInstanceId: ProviderInstanceId.make(CLAUDE_PROVIDER), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: input.providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: input.threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + deletedAt: null, + }; +} + +function makeClaudeTestTurnInput(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly now: DateTime.Utc; + readonly attemptId: RunAttemptId; + readonly text: string; + readonly attachments: ProviderAdapterV2TurnInput["message"]["attachments"]; +}): ProviderAdapterV2TurnInput { + return { + appThread: makeClaudeTestAppThread(input), + threadId: input.threadId, + runId: RunId.make(`run-${input.attemptId}`), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: input.attemptId, + rootNodeId: NodeId.make(`node-${input.attemptId}`), + providerThread: input.providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`message-${input.attemptId}`), + text: input.text, + attachments: input.attachments, + }, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }; +} describe("ClaudeAdapterV2 runtime query policy", () => { it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => { @@ -275,6 +359,200 @@ describe("ClaudeAdapterV2 native protocol logging", () => { }); }); +describe("ClaudeAdapterV2 attachments", () => { + it.effect("forwards persisted images on initial turns and live steering", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-attachments-", + }); + const offeredMessages: Array = []; + const adapter = makeClaudeAdapterV2({ + instanceId: CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-attachments"), + open: () => + Effect.succeed({ + messages: Stream.never, + offer: (message) => + Effect.sync(() => { + offeredMessages.push(message); + }), + setModel: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }), + forkSession: () => Effect.die("unused forkSession"), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-attachments"); + const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const attachment = ChatImageAttachment.make({ + type: "image", + id: ChatAttachmentId.make( + "thread-claude-attachments-12345678-1234-1234-1234-123456789abc", + ), + name: "diagram.png", + mimeType: "image/png", + sizeBytes: 4, + }); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(attachment)), + Uint8Array.from([1, 2, 3, 4]), + ); + const attemptId = RunAttemptId.make("attempt-claude-attachments"); + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId, + text: "What's in this image?", + attachments: [attachment], + }), + ); + + const expectedImageBlock = { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQIDBA==", + }, + } as const; + assert.deepEqual(offeredMessages[0]?.message.content, [ + { type: "text", text: "Ultrathink:\nWhat's in this image?" }, + expectedImageBlock, + ]); + + const providerTurnId = idAllocator.derive.providerTurn({ + driver: CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + yield* runtime.steerTurn({ + threadId, + runId: RunId.make("run-claude-attachments"), + providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-claude-attachments-steer"), + text: "Focus on the diagram labels.", + attachments: [attachment], + }, + }); + + assert.equal(offeredMessages[1]?.priority, "now"); + assert.deepEqual(offeredMessages[1]?.message.content, [ + { type: "text", text: "Ultrathink:\nFocus on the diagram labels." }, + expectedImageBlock, + ]); + }).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))), + ), + ); + + it.effect("rejects unsupported image types before opening a provider query", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-unsupported-attachment-", + }); + let openCount = 0; + const adapter = makeClaudeAdapterV2({ + instanceId: CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir, + fileSystem, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-unsupported-attachment"), + open: () => + Effect.sync(() => { + openCount += 1; + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused forkSession"), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-unsupported-attachment"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-claude-unsupported-attachment", + ), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }); + const attachment = ChatImageAttachment.make({ + type: "image", + id: ChatAttachmentId.make( + "thread-claude-unsupported-12345678-1234-1234-1234-123456789abc", + ), + name: "diagram.svg", + mimeType: "image/svg+xml", + sizeBytes: 4, + }); + const now = yield* DateTime.now; + + const error = yield* runtime + .startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-unsupported-attachment"), + text: "Inspect this image.", + attachments: [attachment], + }), + ) + .pipe(Effect.flip); + + assert.equal(error._tag, "ProviderAdapterTurnStartError"); + assert.include(String(error.cause), "Unsupported Claude image attachment type"); + assert.equal(openCount, 0); + }).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))), + ), + ); +}); + describe("ClaudeAdapterV2 native fork", () => { it("advertises Claude Agent SDK session forks", () => { assert.equal(ClaudeProviderCapabilitiesV2.threads.canForkThread, true); @@ -284,7 +562,11 @@ describe("ClaudeAdapterV2 native fork", () => { it.effect("forks at the source assistant cursor and resumes the forked session", () => Effect.scoped( Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-v2-fork-attachments-", + }); const openedQueries: Array = []; const forkCalls: Array<{ readonly sessionId: string; @@ -296,6 +578,8 @@ describe("ClaudeAdapterV2 native fork", () => { instanceId: CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, environment: {}, + attachmentsDir, + fileSystem, idAllocator, queryRunner: { allocateSessionId: Effect.succeed("source-native-session"), @@ -441,7 +725,7 @@ describe("ClaudeAdapterV2 native fork", () => { assert.equal(openedQueries[0]?.options.resume, "forked-native-session"); assert.equal(openedQueries[0]?.options.sessionId, undefined); - }).pipe(Effect.provide(idAllocatorLayer)), + }).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))), ), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index a60a4057ad..1215882be4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -20,6 +20,7 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import { ServerConfig } from "../../config.ts"; import { CLAUDE_PROVIDER, ClaudeAgentSdkQueryRunner, @@ -36,7 +37,10 @@ import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts"; import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts"; import { randomUuidV4 } from "../RandomUuid.ts"; -import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts"; +import { + makeReplayServerConfig, + type OrchestratorV2ProviderReplayHarness, +} from "../testkit/ProviderReplayHarness.ts"; export const CLAUDE_AGENT_SDK_REPLAY_PROTOCOL = "claude-agent-sdk.query" as const; @@ -722,6 +726,10 @@ export function makeClaudeAgentSdkReplayLayer( export function makeClaudeProviderAdapterRegistryReplayLayer( transcript: ClaudeAgentSdkReplayTranscript, ) { + const serverConfigLayer = Layer.effect( + ServerConfig, + makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); return makeProviderAdapterRegistryDriverLayer({ drivers: [ClaudeAdapterV2Driver], configMap: { @@ -730,8 +738,14 @@ export function makeClaudeProviderAdapterRegistryReplayLayer( }, }, }).pipe( - Layer.provide(makeClaudeAgentSdkReplayLayer(transcript)), - Layer.provide(idAllocatorLayer), + Layer.provide( + Layer.mergeAll( + makeClaudeAgentSdkReplayLayer(transcript), + idAllocatorLayer, + NodeServices.layer, + serverConfigLayer, + ), + ), ); return layerFromProviderAdapter.pipe(Layer.provide(adapterLayer)); } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f9121e66d3..746b6f8a1b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -17,11 +17,16 @@ import { import type { WebSearchOutput } from "@anthropic-ai/claude-agent-sdk/sdk-tools"; import { parseCliArgs } from "@t3tools/shared/cliArgs"; import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model"; import { + type ChatAttachment, + ClaudeSettings, + defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, @@ -43,6 +48,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -51,6 +57,8 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { compileClaudeModelSelection } from "../../claudeModelOptions.ts"; import { ServerConfig } from "../../config.ts"; import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts"; import { @@ -60,6 +68,8 @@ import { import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { makeProviderFailure } from "../ProviderFailure.ts"; +import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts"; import { ProviderAdapterEnsureThreadError, ProviderAdapterForkThreadError, @@ -316,6 +326,8 @@ export interface ClaudeAgentSdkLoggedQueryOptions { readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"]; readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"]; readonly settings?: ClaudeAgentSdkQueryOptions["settings"]; + readonly effort?: ClaudeAgentSdkQueryOptions["effort"]; + readonly includePartialMessages?: true; readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"]; readonly extraArgs?: ClaudeAgentSdkQueryOptions["extraArgs"]; readonly allowDangerouslySkipPermissions?: true; @@ -404,6 +416,8 @@ export function loggedClaudeQueryOptions( ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }), ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }), ...(options.settings === undefined ? {} : { settings: options.settings }), + ...(options.effort === undefined ? {} : { effort: options.effort }), + ...(options.includePartialMessages === true ? { includePartialMessages: true } : {}), ...(options.pathToClaudeCodeExecutable === undefined ? {} : { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }), @@ -618,16 +632,33 @@ export function makeClaudeQueryOptions(input: { readonly canUseTool?: CanUseTool; readonly allowDangerouslySkipPermissions?: boolean; }): ClaudeAgentSdkQueryOptions { + const compiledSelection = compileClaudeModelSelection(input.modelSelection); const extraArgs = input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags; const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume ? { resume: input.nativeThreadId } : { sessionId: input.nativeThreadId }; const selectedTools = input.tools ?? CLAUDE_CODE_PRESET_TOOLS; + const selectionSettings = + Object.keys(compiledSelection.settings).length === 0 + ? undefined + : (compiledSelection.settings as ClaudeSdkSettings); + const querySettings = + selectionSettings === undefined + ? input.sdkSettings + : typeof input.sdkSettings === "object" && input.sdkSettings !== null + ? ({ ...input.sdkSettings, ...selectionSettings } as ClaudeSdkSettings) + : selectionSettings; const options: ClaudeAgentSdkQueryOptions = { - model: input.modelSelection.model, + model: compiledSelection.apiModelId, tools: claudeAgentSdkQueryToolsForSdk(selectedTools), permissionMode: input.permissionMode ?? "default", + includePartialMessages: true, + ...(compiledSelection.effort === undefined + ? {} + : { + effort: compiledSelection.effort as NonNullable, + }), ...threadIdentity, ...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }), ...(input.allowedTools === undefined ? {} : { allowedTools: [...input.allowedTools] }), @@ -636,7 +667,7 @@ export function makeClaudeQueryOptions(input: { ...(input.allowDangerouslySkipPermissions === true ? { allowDangerouslySkipPermissions: true } : {}), - ...(input.sdkSettings === undefined ? {} : { settings: input.sdkSettings }), + ...(querySettings === undefined ? {} : { settings: querySettings }), ...(input.settings?.binaryPath ? { pathToClaudeCodeExecutable: input.settings.binaryPath } : {}), @@ -884,6 +915,24 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn( } }); +type ClaudeUserContent = SDKUserMessage["message"]["content"]; +type ClaudeUserContentBlock = Exclude[number]; + +const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = [ + "image/gif", + "image/jpeg", + "image/png", + "image/webp", +] as const; +type SupportedClaudeImageMimeType = (typeof SUPPORTED_CLAUDE_IMAGE_MIME_TYPES)[number]; +const supportedClaudeImageMimeTypes = new Set(SUPPORTED_CLAUDE_IMAGE_MIME_TYPES); + +function isSupportedClaudeImageMimeType( + mimeType: string, +): mimeType is SupportedClaudeImageMimeType { + return supportedClaudeImageMimeTypes.has(mimeType); +} + export function makeClaudeUserMessage(input: { readonly text: string; readonly priority?: SDKUserMessage["priority"]; @@ -899,6 +948,75 @@ export function makeClaudeUserMessage(input: { }; } +const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: { + readonly text: string; + readonly attachments: ReadonlyArray; + readonly priority?: SDKUserMessage["priority"]; + readonly attachmentsDir: string; + readonly fileSystem: FileSystem.FileSystem; +}) { + if (input.attachments.length === 0) { + return makeClaudeUserMessage({ + text: input.text, + ...(input.priority === undefined ? {} : { priority: input.priority }), + }); + } + + const content: Array = []; + if (input.text.length > 0) { + content.push({ type: "text", text: input.text }); + } + + for (const attachment of input.attachments) { + if (!isSupportedClaudeImageMimeType(attachment.mimeType)) { + return yield* new ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Unsupported Claude image attachment type '${attachment.mimeType}'`, + }); + } + + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: input.attachmentsDir, + attachment, + }); + if (attachmentPath === null) { + return yield* new ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Invalid attachment id '${attachment.id}'`, + }); + } + + const bytes = yield* input.fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Failed to read attachment '${attachment.id}'`, + payload: cause, + }), + ), + ); + content.push({ + type: "image", + source: { + type: "base64", + media_type: attachment.mimeType, + data: Buffer.from(bytes).toString("base64"), + }, + }); + } + + return { + type: "user", + message: { + role: "user", + content, + }, + parent_tool_use_id: null, + ...(input.priority === undefined ? {} : { priority: input.priority }), + } satisfies SDKUserMessage; +}); + type ClaudeAssistantContentBlock = SDKAssistantMessage["message"]["content"][number]; type ClaudeToolUseContentBlock = Extract< ClaudeAssistantContentBlock, @@ -908,8 +1026,6 @@ type ClaudeToolUseContentBlock = Extract< readonly input: unknown; } >; -type ClaudeUserContent = SDKUserMessage["message"]["content"]; -type ClaudeUserContentBlock = Exclude[number]; type ClaudeAssistantToolResultContentBlock = Extract< ClaudeAssistantContentBlock, { @@ -1660,8 +1776,8 @@ interface ClaudeLiveQueryContext { readonly nativeThreadId: string; readonly query: ClaudeAgentSdkQuerySession; readonly queryPolicyKey: string; + readonly selectionKey: string; readonly closed: Deferred.Deferred; - currentModel: string; } interface ActiveClaudeToolCall { @@ -1687,6 +1803,8 @@ export interface ClaudeAdapterV2Options { readonly instanceId: ProviderInstanceId; readonly settings: ClaudeSettings; readonly environment: NodeJS.ProcessEnv; + readonly attachmentsDir: string; + readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2Shape; readonly queryRunner: ClaudeAgentSdkQueryRunnerShape; } @@ -1694,12 +1812,13 @@ export interface ClaudeAdapterV2Options { export function makeClaudeAdapterV2( adapterOptions: ClaudeAdapterV2Options, ): ProviderAdapterV2Shape { - const { idAllocator, queryRunner } = adapterOptions; + const { attachmentsDir, fileSystem, idAllocator, queryRunner } = adapterOptions; return ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, driver: CLAUDE_PROVIDER, getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), openSession: Effect.fn("ClaudeAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { const sessionScope = yield* Effect.scope; @@ -1744,7 +1863,7 @@ export function makeClaudeAdapterV2( updated.set(context.nativeTurnId, next); return [next, updated]; }); - const nextOrdinal = context.input.runOrdinal * 100 + nextWithinTurn; + const nextOrdinal = context.input.providerTurnOrdinal * 100 + nextWithinTurn; yield* Ref.update(itemOrdinals, (current) => { const updated = new Map(current); updated.set(nativeItemId, nextOrdinal); @@ -2351,6 +2470,8 @@ export function makeClaudeAdapterV2( "completed" | "interrupted" | "failed" | "cancelled" >; readonly completedAt: DateTime.Utc; + readonly failure?: OrchestrationV2ProviderFailure; + readonly threadDisposition?: "reusable" | "broken"; }) { for (const toolCall of input.context.toolCalls.values()) { const artifacts = buildToolCallArtifacts({ @@ -2410,6 +2531,33 @@ export function makeClaudeAdapterV2( ); } + const threadDisposition = input.threadDisposition ?? "reusable"; + const terminalEvent: ProviderAdapterV2Event = + input.status === "failed" + ? { + type: "turn.terminal", + driver: CLAUDE_PROVIDER, + providerThreadId: input.context.input.providerThread.id, + providerTurnId: input.context.providerTurnId, + runOrdinal: input.context.input.runOrdinal, + failureItemOrdinal: yield* resolveItemOrdinal( + input.context, + `terminal-failure:${input.context.providerTurnId}`, + ), + status: input.status, + failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), + threadDisposition, + } + : { + type: "turn.terminal", + driver: CLAUDE_PROVIDER, + providerThreadId: input.context.input.providerThread.id, + providerTurnId: input.context.providerTurnId, + runOrdinal: input.context.input.runOrdinal, + status: input.status, + failure: null, + threadDisposition, + }; yield* Effect.all( [ emitProviderEvent({ @@ -2431,7 +2579,7 @@ export function makeClaudeAdapterV2( ...input.context.input.providerThread, providerSessionId: session.id, nativeConversationHeadRef: null, - status: "idle" as const, + status: "active" as const, firstRunOrdinal: input.context.input.providerThread.firstRunOrdinal ?? input.context.input.runOrdinal, @@ -2441,12 +2589,7 @@ export function makeClaudeAdapterV2( }), ] : []), - emitProviderEvent({ - type: "turn.terminal", - driver: CLAUDE_PROVIDER, - providerTurnId: input.context.providerTurnId, - status: input.status, - }), + emitProviderEvent(terminalEvent), ], { concurrency: 1 }, ); @@ -2460,7 +2603,9 @@ export function makeClaudeAdapterV2( }); }); - const finalizeActiveTurnAfterQueryExit = Effect.fnUntraced(function* (cause?: unknown) { + const finalizeActiveTurnAfterQueryExit = Effect.fnUntraced(function* ( + cause?: Cause.Cause, + ) { const context = yield* Ref.get(activeTurn); if (context === null) { return; @@ -2471,6 +2616,14 @@ export function makeClaudeAdapterV2( context, status: interrupted ? "interrupted" : "failed", completedAt, + ...(interrupted + ? {} + : { + failure: makeProviderFailure({ + cause: cause === undefined ? undefined : Cause.squash(cause), + class: "transport_error", + }), + }), }); yield* Ref.update(interruptedTurns, (current) => { const next = new Set(current); @@ -2622,6 +2775,15 @@ export function makeClaudeAdapterV2( context, status: interrupted ? "interrupted" : terminalStatusFromResult(message), completedAt, + ...(message.subtype === "success" || interrupted + ? {} + : { + failure: makeProviderFailure({ + message: message.errors.join("\n"), + code: message.subtype, + class: "provider_error", + }), + }), }); } }); @@ -2736,17 +2898,15 @@ export function makeClaudeAdapterV2( : { allowedTools: queryPolicy.allowedTools }), }); const queryPolicyKey = claudeRuntimeQueryPolicyKey(queryPolicy); + const compiledSelection = compileClaudeModelSelection(turnInput.modelSelection); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); const existing = yield* Ref.get(queryContext); if ( existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey + existing.queryPolicyKey === queryPolicyKey && + existing.selectionKey === compiledSelection.queryIdentity ) { - if (existing.currentModel !== turnInput.modelSelection.model) { - yield* existing.query.setModel(turnInput.modelSelection.model); - existing.currentModel = turnInput.modelSelection.model; - } return existing; } @@ -2789,8 +2949,8 @@ export function makeClaudeAdapterV2( nativeThreadId, query: querySession, queryPolicyKey, + selectionKey: compiledSelection.queryIdentity, closed, - currentModel: turnInput.modelSelection.model, }; yield* Ref.set(queryContext, context); yield* querySession.messages.pipe( @@ -2847,6 +3007,15 @@ export function makeClaudeAdapterV2( subagentsByToolUseId: new Map(), subagentNodesByTaskId: new Map(), }; + const userMessage = yield* makeClaudeUserMessageWithAttachments({ + text: applyClaudePromptEffortPrefix( + turnInput.message.text, + compileClaudeModelSelection(turnInput.modelSelection).promptEffort, + ), + attachments: turnInput.message.attachments, + attachmentsDir, + fileSystem, + }); const querySession = yield* openQuery(turnInput, nativeThreadId); yield* Ref.set(activeTurn, context); yield* emitProviderEvent({ @@ -2858,9 +3027,7 @@ export function makeClaudeAdapterV2( completedAt: null, }), }); - yield* querySession.query.offer( - makeClaudeUserMessage({ text: turnInput.message.text }), - ); + yield* querySession.query.offer(userMessage); }, (effect, turnInput) => effect.pipe( @@ -2953,14 +3120,22 @@ export function makeClaudeAdapterV2( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } + const userMessage = yield* makeClaudeUserMessageWithAttachments({ + text: applyClaudePromptEffortPrefix( + turnInput.message.text, + compileClaudeModelSelection(currentTurn.input.modelSelection).promptEffort, + ), + attachments: turnInput.message.attachments, + priority: "now", + attachmentsDir, + fileSystem, + }); yield* Ref.update(steeredTurns, (current) => { const next = new Set(current); next.add(turnInput.providerTurnId); return next; }); - yield* existing.query.offer( - makeClaudeUserMessage({ text: turnInput.message.text, priority: "now" }), - ); + yield* existing.query.offer(userMessage); }, (effect, turnInput) => effect.pipe( @@ -3022,7 +3197,6 @@ export function makeClaudeAdapterV2( driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, - rawEvents: Stream.empty, events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")( function* (threadInput: ProviderAdapterV2EnsureThreadInput) { @@ -3274,7 +3448,12 @@ export function makeClaudeAdapterV2( }); } -export type ClaudeAdapterV2DriverEnv = ClaudeAgentSdkQueryRunner | IdAllocatorV2 | Path.Path; +export type ClaudeAdapterV2DriverEnv = + | ClaudeAgentSdkQueryRunner + | FileSystem.FileSystem + | IdAllocatorV2 + | Path.Path + | ServerConfig; export const ClaudeAdapterV2Driver: ProviderAdapterDriver< ClaudeSettings, @@ -3286,15 +3465,19 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver< create: Effect.fn("ClaudeAdapterV2Driver.create")( function* (input: ProviderAdapterDriverCreateInput) { const { instanceId, environment, enabled, config } = input; + const fileSystem = yield* FileSystem.FileSystem; const hostEnvironment = yield* HostProcessEnvironment; const idAllocator = yield* IdAllocatorV2; const queryRunner = yield* ClaudeAgentSdkQueryRunner; + const serverConfig = yield* ServerConfig; const baseEnvironment = mergeProviderInstanceEnvironment(environment, hostEnvironment); const claudeEnvironment = yield* makeClaudeEnvironment(config, baseEnvironment); return makeClaudeAdapterV2({ instanceId, settings: { ...config, enabled }, environment: claudeEnvironment, + attachmentsDir: serverConfig.attachmentsDir, + fileSystem, idAllocator, queryRunner, }); @@ -3315,14 +3498,18 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver< }; const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function* () { + const fileSystem = yield* FileSystem.FileSystem; const hostEnvironment = yield* HostProcessEnvironment; const idAllocator = yield* IdAllocatorV2; const queryRunner = yield* ClaudeAgentSdkQueryRunner; + const serverConfig = yield* ServerConfig; return makeClaudeAdapterV2({ instanceId: CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, environment: hostEnvironment, + attachmentsDir: serverConfig.attachmentsDir, + fileSystem, idAllocator, queryRunner, }); @@ -3331,5 +3518,5 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function* export const layer: Layer.Layer< ProviderAdapterV2, never, - ClaudeAgentSdkQueryRunner | IdAllocatorV2 + ClaudeAgentSdkQueryRunner | FileSystem.FileSystem | IdAllocatorV2 | ServerConfig > = Layer.effect(ProviderAdapterV2, makeDefaultClaudeAdapterV2()); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index f73ddffd4f..e7e33e8544 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -16,6 +16,8 @@ import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hos import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; +import { TestClock } from "effect/testing"; import { ChildProcess } from "effect/unstable/process"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; @@ -24,12 +26,102 @@ import { buildCodexTurnStartParams, CODEX_DRIVER_KIND, codexThreadRuntimeParams, + type CodexAgentMessageDeltaUpdate, + makeCodexAgentMessageDeltaCoalescer, makeCodexAppServerProtocolLogger, makeCodexAppServerSpawnCommand, projectCodexDynamicToolItem, resolveCodexRollbackTurnCount, } from "./CodexAdapterV2.ts"; +describe("CodexAdapterV2 assistant message streaming", () => { + it.effect("makes accumulated assistant text visible after the bounded flush interval", () => + Effect.gen(function* () { + const updates = yield* Ref.make< + ReadonlyArray<{ + readonly turnId: string; + readonly itemId: string; + readonly text: string; + readonly completed: boolean; + }> + >([]); + const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({ + flushIntervalMs: 50, + emit: (update) => Ref.update(updates, (current) => [...current, update]), + }); + + yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "partial" }); + assert.deepEqual(yield* Ref.get(updates), []); + yield* Effect.yieldNow; + yield* TestClock.adjust("50 millis"); + yield* Effect.yieldNow; + + assert.deepEqual(yield* Ref.get(updates), [ + { + turnId: "turn-1", + itemId: "message-1", + text: "partial", + completed: false, + }, + ]); + }), + ); + + it.effect("coalesces multiple token deltas into one assistant update per interval", () => + Effect.gen(function* () { + const updates = yield* Ref.make>([]); + const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({ + flushIntervalMs: 50, + emit: (update) => Ref.update(updates, (current) => [...current, update]), + }); + + yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "one" }); + yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " two" }); + yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " three" }); + yield* Effect.yieldNow; + yield* TestClock.adjust("50 millis"); + yield* Effect.yieldNow; + + assert.deepEqual(yield* Ref.get(updates), [ + { + turnId: "turn-1", + itemId: "message-1", + text: "one two three", + completed: false, + }, + ]); + }), + ); + + it.effect("flushes buffered text synchronously before item and turn completion", () => + Effect.gen(function* () { + const updates = yield* Ref.make>([]); + const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({ + flushIntervalMs: 50, + emit: (update) => Ref.update(updates, (current) => [...current, update]), + }); + + yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "item final" }); + const completedText = yield* coalescer.complete({ + turnId: "turn-1", + itemId: "message-1", + }); + yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "turn final" }); + yield* coalescer.flushTurn("turn-1"); + + assert.equal(completedText, "item final"); + assert.deepEqual(yield* Ref.get(updates), [ + { turnId: "turn-1", itemId: "message-1", text: "item final", completed: true }, + { turnId: "turn-1", itemId: "message-2", text: "turn final", completed: true }, + ]); + yield* Effect.yieldNow; + yield* TestClock.adjust("50 millis"); + yield* Effect.yieldNow; + assert.equal((yield* Ref.get(updates)).length, 2); + }), + ); +}); + describe("CodexAdapterV2 runtime policy", () => { it.effect("derives concrete Codex turn policies from every T3 runtime mode", () => Effect.gen(function* () { @@ -42,7 +134,10 @@ describe("CodexAdapterV2 runtime policy", () => { interactionMode: "default", cwd: null, }, - model: "gpt-5.4", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, }); const approvalRequired = yield* build("approval-required"); @@ -72,13 +167,46 @@ describe("CodexAdapterV2 runtime policy", () => { type: "readOnly", }, }, - model: "gpt-5.4", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, }); assert.equal(params.approvalPolicy, "on-request"); assert.equal(params.sandboxPolicy?.type, "readOnly"); }), ); + + it.effect("compiles per-turn Codex model options and cwd from their owning inputs", () => + Effect.gen(function* () { + const params = yield* buildCodexTurnStartParams({ + nativeThreadId: "native-model-options", + codexInput: [{ type: "text", text: "test" }], + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "plan", + cwd: "/workspace/model-options", + reasoningEffort: "low", + }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + options: [ + { id: "reasoningEffort", value: "xhigh" }, + { id: "serviceTier", value: "priority" }, + ], + }, + }); + + assert.equal(params.model, "gpt-5.4"); + assert.equal(params.effort, "xhigh"); + assert.equal(params.serviceTier, "priority"); + assert.equal(params.cwd, "/workspace/model-options"); + assert.equal(params.collaborationMode?.settings.model, "gpt-5.4"); + assert.equal(params.collaborationMode?.settings.reasoning_effort, "xhigh"); + }), + ); }); describe("CodexAdapterV2 process spawning", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09a978c41e..cac42a567b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1,10 +1,12 @@ import { CodexSettings, defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts"; import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import type { ChatAttachment, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + ModelSelection, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderSession, @@ -28,6 +30,7 @@ import * as CodexSchema from "effect-codex-app-server/schema"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -36,10 +39,12 @@ import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts"; import { ServerConfig } from "../../config.ts"; import { CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS } from "../../provider/CodexDeveloperInstructions.ts"; import { @@ -57,6 +62,8 @@ import { type ProviderAdapterDriver, } from "../ProviderAdapterDriver.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { makeProviderFailure } from "../ProviderFailure.ts"; +import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts"; import { ProviderAdapterEnsureThreadError, ProviderAdapterForkThreadError, @@ -88,6 +95,7 @@ const CODEX_PROVIDER = ProviderDriverKind.make("codex"); export const CODEX_DRIVER_KIND = CODEX_PROVIDER; export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND); const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({}); +const CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS = 50; const CODEX_CLIENT_INFO = { name: "t3code_desktop", title: "T3 Code Desktop", @@ -465,6 +473,12 @@ const CodexTurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams. ); type CodexTurnStartParamsWithCollaborationMode = typeof CodexTurnStartParamsWithCollaborationMode.Type; +const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect( + CodexTurnStartParamsWithCollaborationMode, +); +const isProviderAdapterRuntimeRequestResponseError = Schema.is( + ProviderAdapterRuntimeRequestResponseError, +); function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): { readonly approvalPolicy: CodexSchema.V2TurnStartParams__AskForApproval; @@ -499,7 +513,7 @@ export function buildCodexTurnStartParams(input: { readonly nativeThreadId: string; readonly codexInput: ReadonlyArray; readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; - readonly model: string; + readonly modelSelection: ModelSelection; }) { return Effect.gen(function* () { const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode); @@ -511,28 +525,34 @@ export function buildCodexTurnStartParams(input: { input.runtimePolicy.sandboxPolicy === undefined ? runtimeModeDefaults.sandboxPolicy : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy); + const selectedEffort = getModelSelectionStringOptionValue( + input.modelSelection, + "reasoningEffort", + ); const effort = - input.runtimePolicy.reasoningEffort === undefined - ? undefined - : yield* decodeTurnReasoningEffort(input.runtimePolicy.reasoningEffort); - const collaborationMode: CodexSchema.V2TurnStartParams__CollaborationMode | undefined = + selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort); + const serviceTier = getCodexServiceTierOptionValue(input.modelSelection); + const collaborationMode: CodexSchema.ClientRequest__CollaborationMode | undefined = input.runtimePolicy.interactionMode === "plan" ? { mode: "plan", settings: { - model: input.model, + model: input.modelSelection.model, reasoning_effort: effort ?? "medium", developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, }, } : undefined; - return yield* Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({ + return yield* decodeCodexTurnStartParamsWithCollaborationMode({ threadId: input.nativeThreadId, input: input.codexInput, + cwd: input.runtimePolicy.cwd, + model: input.modelSelection.model, ...(approvalPolicy === undefined ? {} : { approvalPolicy }), ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }), ...(effort === undefined ? {} : { effort }), + ...(serviceTier === undefined ? {} : { serviceTier }), ...(collaborationMode === undefined ? {} : { collaborationMode }), }); }); @@ -756,6 +776,145 @@ export type CodexDynamicToolItem = Extract< { readonly type: "mcpToolCall" | "dynamicToolCall" } >; +export interface CodexAgentMessageDeltaUpdate { + readonly turnId: string; + readonly itemId: string; + readonly text: string; + readonly completed: boolean; +} + +export interface CodexAgentMessageDeltaCoalescer { + readonly append: (input: { + readonly turnId: string; + readonly itemId: string; + readonly delta: string; + }) => Effect.Effect; + readonly complete: (input: { + readonly turnId: string; + readonly itemId: string; + readonly finalText?: string; + }) => Effect.Effect; + readonly flushTurn: (turnId: string) => Effect.Effect; +} + +interface BufferedCodexAgentMessage { + readonly turnId: string; + readonly itemId: string; + readonly text: string; + readonly dirty: boolean; +} + +function codexAgentMessageBufferKey(turnId: string, itemId: string): string { + return `${turnId}\u0000${itemId}`; +} + +export const makeCodexAgentMessageDeltaCoalescer = Effect.fn( + "CodexAdapterV2.makeCodexAgentMessageDeltaCoalescer", +)(function* (input: { + readonly flushIntervalMs: number; + readonly emit: (update: CodexAgentMessageDeltaUpdate) => Effect.Effect; +}): Effect.fn.Return { + const buffered = yield* Ref.make(new Map()); + const flushScheduled = yield* Ref.make(false); + const flushLock = yield* Semaphore.make(1); + const coalescerScope = yield* Effect.scope; + + const drain = (options: { + readonly predicate: (message: BufferedCodexAgentMessage) => boolean; + readonly completed: boolean; + readonly onlyDirty: boolean; + readonly releaseSchedule?: boolean; + }) => + flushLock.withPermit( + Effect.gen(function* () { + const updates = yield* Ref.modify(buffered, (current) => { + const next = new Map(current); + const pending: Array = []; + for (const [key, message] of current) { + if (!options.predicate(message) || (options.onlyDirty && !message.dirty)) { + continue; + } + pending.push({ + turnId: message.turnId, + itemId: message.itemId, + text: message.text, + completed: options.completed, + }); + if (options.completed) { + next.delete(key); + } else { + next.set(key, { ...message, dirty: false }); + } + } + return [pending, next] as const; + }); + if (options.releaseSchedule === true) { + yield* Ref.set(flushScheduled, false); + } + yield* Effect.forEach(updates, input.emit, { discard: true }); + }), + ); + + const flushDirty = drain({ + predicate: () => true, + completed: false, + onlyDirty: true, + releaseSchedule: true, + }); + + return { + append: ({ turnId, itemId, delta }) => + Effect.uninterruptible( + Effect.gen(function* () { + const shouldSchedule = yield* flushLock.withPermit( + Effect.gen(function* () { + yield* Ref.update(buffered, (current) => { + const key = codexAgentMessageBufferKey(turnId, itemId); + const existing = current.get(key); + const next = new Map(current); + next.set(key, { + turnId, + itemId, + text: `${existing?.text ?? ""}${delta}`, + dirty: true, + }); + return next; + }); + return yield* Ref.modify(flushScheduled, (scheduled) => [!scheduled, true]); + }), + ); + if (shouldSchedule) { + yield* Effect.sleep(Duration.millis(Math.max(1, input.flushIntervalMs))).pipe( + Effect.andThen(flushDirty), + Effect.interruptible, + Effect.forkIn(coalescerScope), + ); + } + }), + ), + complete: ({ turnId, itemId, finalText }) => + flushLock.withPermit( + Effect.gen(function* () { + const text = yield* Ref.modify(buffered, (current) => { + const key = codexAgentMessageBufferKey(turnId, itemId); + const existing = current.get(key); + const next = new Map(current); + next.delete(key); + return [finalText && finalText.length > 0 ? finalText : (existing?.text ?? ""), next]; + }); + yield* input.emit({ turnId, itemId, text, completed: true }); + return text; + }), + ), + flushTurn: (turnId) => + drain({ + predicate: (message) => message.turnId === turnId, + completed: true, + onlyDirty: false, + }), + }; +}); + export interface CodexAppServerClientFactoryShape { readonly open: (input: { readonly threadId: ThreadId; @@ -1070,6 +1229,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi instanceId: adapterOptions.instanceId, driver: CODEX_PROVIDER, getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), openSession: (input) => Effect.gen(function* () { const client = yield* clientFactory.open({ @@ -1113,7 +1273,6 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const nextProviderTurnOrdinals = yield* Ref.make(new Map()); const itemOrdinals = yield* Ref.make(new Map()); const nextItemOrdinalsByTurn = yield* Ref.make(new Map()); - const agentMessageDeltas = yield* Ref.make(new Map()); const planDeltas = yield* Ref.make(new Map()); const planIds = yield* Ref.make(new Map()); const pendingRuntimeRequests = yield* Ref.make( @@ -2376,13 +2535,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const buildAgentMessageArtifacts = ( context: ActiveCodexTurnContext, - item: Extract< - CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "agentMessage" } - >, + item: { readonly id: string; readonly text: string }, + completed: boolean, ) => Effect.gen(function* () { - const completedAt = yield* DateTime.now; + const updatedAt = yield* DateTime.now; + const completedAt = completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CODEX_PROVIDER, nativeItemId: item.id, @@ -2403,7 +2561,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi parentNodeId: context.itemParentNodeId, rootNodeId: context.rootNodeId, kind: "assistant_message", - status: "completed", + status: completed ? "completed" : "running", countsForRun: false, providerThreadId: context.providerThread.id, providerTurnId: context.providerTurnId, @@ -2423,9 +2581,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi role: "assistant", text: item.text, attachments: [], - streaming: false, - createdAt: completedAt, - updatedAt: completedAt, + streaming: !completed, + createdAt: context.startedAt, + updatedAt, }; const turnItem: OrchestrationV2TurnItem = { id: turnItemId, @@ -2437,19 +2595,50 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nativeItemRef: codexNativeItemRef(item.id), parentItemId: null, ordinal, - status: "completed", + status: completed ? "completed" : "running", title: null, startedAt: context.startedAt, completedAt, - updatedAt: completedAt, + updatedAt, type: "assistant_message", messageId, text: item.text, - streaming: false, + streaming: !completed, }; return { node, message, turnItem }; }); + const agentMessageDeltas = yield* makeCodexAgentMessageDeltaCoalescer({ + flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS, + emit: (update) => + Effect.gen(function* () { + const context = yield* awaitActiveTurn(update.turnId); + if (context === undefined) { + return; + } + const artifacts = yield* buildAgentMessageArtifacts( + context, + { id: update.itemId, text: update.text }, + update.completed, + ); + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "message.updated", + driver: CODEX_PROVIDER, + message: artifacts.message, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + }), + }); + const emitSubagentUserMessage = ( context: ActiveCodexTurnContext, item: Extract< @@ -3069,10 +3258,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* client.handleServerNotification("item/agentMessage/delta", (payload) => - Ref.update(agentMessageDeltas, (current) => { - const updated = new Map(current); - updated.set(payload.itemId, `${updated.get(payload.itemId) ?? ""}${payload.delta}`); - return updated; + agentMessageDeltas.append({ + turnId: payload.turnId, + itemId: payload.itemId, + delta: payload.delta, }), ); @@ -3381,29 +3570,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return; } - const deltas = yield* Ref.get(agentMessageDeltas); - const text = - payload.item.text.length > 0 - ? payload.item.text - : (deltas.get(payload.item.id) ?? ""); - const artifacts = yield* buildAgentMessageArtifacts(context, { - ...payload.item, - text, - }); - yield* emitProviderEvent({ - type: "node.updated", - driver: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "message.updated", - driver: CODEX_PROVIDER, - message: artifacts.message, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - driver: CODEX_PROVIDER, - turnItem: artifacts.turnItem, + const text = yield* agentMessageDeltas.complete({ + turnId: payload.turnId, + itemId: payload.item.id, + finalText: payload.item.text, }); if ( context.subagent !== null && @@ -3792,6 +3962,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi if (context === undefined) { return; } + yield* agentMessageDeltas.flushTurn(payload.turn.id); const completedAt = codexTimestamp(payload.turn.completedAt); const status = mapCodexTurnStatus(payload.turn.status); yield* emitProviderEvent({ @@ -3875,12 +4046,37 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi } } if (context.subagent === null) { - yield* emitProviderEvent({ - type: "turn.terminal", - driver: CODEX_PROVIDER, - providerTurnId: context.providerTurnId, - status: providerTurnStatusToTerminal(status), - }); + const terminalStatus = providerTurnStatusToTerminal(status); + yield* emitProviderEvent( + terminalStatus === "failed" + ? { + type: "turn.terminal", + driver: CODEX_PROVIDER, + providerThreadId: context.providerThread.id, + providerTurnId: context.providerTurnId, + runOrdinal: context.input.runOrdinal, + failureItemOrdinal: yield* resolveItemOrdinal( + context, + `terminal-failure:${context.providerTurnId}`, + ), + status: terminalStatus, + failure: makeProviderFailure({ + message: payload.turn.error?.message, + class: "provider_error", + }), + threadDisposition: "reusable", + } + : { + type: "turn.terminal", + driver: CODEX_PROVIDER, + providerThreadId: context.providerThread.id, + providerTurnId: context.providerTurnId, + runOrdinal: context.input.runOrdinal, + status: terminalStatus, + failure: null, + threadDisposition: "reusable", + }, + ); } const waiter = (yield* Ref.get(turnWaiters)).get(payload.turn.id); if (waiter !== undefined) { @@ -3899,7 +4095,6 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, - rawEvents: Stream.empty, events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: (threadInput) => ensureInitialized.pipe( @@ -3989,7 +4184,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nativeThreadId: threadId, codexInput, runtimePolicy: turnInput.runtimePolicy, - model: turnInput.modelSelection.model, + modelSelection: turnInput.modelSelection, }); yield* Ref.update(pendingRootTurns, (current) => { const updated = new Map(current); @@ -4232,7 +4427,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* Deferred.succeed(pending.decision, requestInput.decision); }).pipe( Effect.mapError((cause) => - Schema.is(ProviderAdapterRuntimeRequestResponseError)(cause) + isProviderAdapterRuntimeRequestResponseError(cause) ? cause : new ProviderAdapterRuntimeRequestResponseError({ driver: CODEX_PROVIDER, diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts index eff2a11c4d..c95f571c57 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts @@ -19,6 +19,7 @@ import { type OrchestrationV2PlanArtifact, type OrchestrationV2PlanStep, type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, @@ -44,6 +45,8 @@ import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import { cursorSdkParameterId } from "../../provider/cursorSdkModel.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { makeProviderFailure } from "../ProviderFailure.ts"; +import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts"; import { ProviderAdapterEnsureThreadError, ProviderAdapterForkThreadError, @@ -831,6 +834,7 @@ export function makeCursorAdapterV2( instanceId: adapterOptions.instanceId, driver: CURSOR_PROVIDER, getCapabilities: () => Effect.succeed(CursorProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), openSession: Effect.fn("CursorAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { const sessionScope = yield* Effect.scope; @@ -866,7 +870,7 @@ export function makeCursorAdapterV2( updated.set(context.run.runId, next); return [next, updated]; }); - const ordinal = context.input.runOrdinal * 100 + nextWithinTurn; + const ordinal = context.input.providerTurnOrdinal * 100 + nextWithinTurn; yield* Ref.update(itemOrdinals, (current) => { const updated = new Map(current); updated.set(nativeItemId, ordinal); @@ -1885,6 +1889,8 @@ export function makeCursorAdapterV2( OrchestrationV2ProviderTurn["status"], "completed" | "interrupted" | "failed" | "cancelled" >; + readonly failure?: OrchestrationV2ProviderFailure; + readonly threadDisposition?: "reusable" | "broken"; }) { if (input.context.finalized) { return; @@ -1912,7 +1918,7 @@ export function makeCursorAdapterV2( providerThread: { ...input.context.input.providerThread, providerSessionId: session.id, - status: input.status === "failed" ? "error" : "idle", + status: "active", firstRunOrdinal: input.context.input.providerThread.firstRunOrdinal ?? input.context.input.runOrdinal, @@ -1920,12 +1926,34 @@ export function makeCursorAdapterV2( updatedAt: completedAt, }, }); - yield* emitProviderEvent({ - type: "turn.terminal", - driver: CURSOR_PROVIDER, - providerTurnId: input.context.providerTurnId, - status: input.status, - }); + const threadDisposition = input.threadDisposition ?? "reusable"; + yield* emitProviderEvent( + input.status === "failed" + ? { + type: "turn.terminal", + driver: CURSOR_PROVIDER, + providerThreadId: input.context.input.providerThread.id, + providerTurnId: input.context.providerTurnId, + runOrdinal: input.context.input.runOrdinal, + failureItemOrdinal: yield* resolveItemOrdinal( + input.context, + `terminal-failure:${input.context.providerTurnId}`, + ), + status: input.status, + failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), + threadDisposition, + } + : { + type: "turn.terminal", + driver: CURSOR_PROVIDER, + providerThreadId: input.context.input.providerThread.id, + providerTurnId: input.context.providerTurnId, + runOrdinal: input.context.input.runOrdinal, + status: input.status, + failure: null, + threadDisposition, + }, + ); yield* Ref.update(activeTurn, (current) => current?.providerTurnId === input.context.providerTurnId ? null : current, ); @@ -2142,9 +2170,18 @@ export function makeCursorAdapterV2( }); } if (context !== null) { + const status = terminalStatus(context, result); yield* finalizeTurn({ context, - status: terminalStatus(context, result), + status, + ...(status === "failed" + ? { + failure: makeProviderFailure({ + cause: (result as { readonly error?: unknown }).error, + class: "provider_error", + }), + } + : {}), }); } }), @@ -2155,6 +2192,11 @@ export function makeCursorAdapterV2( yield* finalizeTurn({ context, status: context.interrupted ? "interrupted" : "failed", + ...(context.interrupted + ? {} + : { + failure: makeProviderFailure({ cause, class: "transport_error" }), + }), }); } yield* Effect.logWarning("orchestration-v2.cursor-run-failed", { @@ -2205,7 +2247,6 @@ export function makeCursorAdapterV2( driver: CURSOR_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, - rawEvents: Stream.empty, events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: Effect.fn("CursorAdapterV2.ensureThread")( function* (threadInput: ProviderAdapterV2EnsureThreadInput) { diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts index 7757d603e3..75adf57d94 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -5,6 +5,7 @@ import { ProviderDriverKind, type OrchestrationV2ProviderCapabilities, } from "@t3tools/contracts"; +import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -14,6 +15,7 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import type * as EffectAcpErrors from "effect-acp/errors"; import { ServerConfig } from "../../config.ts"; +import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts"; import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId, @@ -27,6 +29,7 @@ import { } from "../../provider/acp/XAiAcpExtension.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; import { IdAllocatorV2 } from "../IdAllocator.ts"; import { ProviderAdapterV2 } from "../ProviderAdapter.ts"; import { @@ -81,6 +84,7 @@ export interface GrokAdapterV2Options { readonly fileSystem: FileSystem.FileSystem; readonly idAllocator: IdAllocatorV2["Service"]; readonly serverConfig: ServerConfig["Service"]; + readonly nativeLogging?: Parameters[0]["nativeLogging"]; readonly makeRuntime?: ( input: AcpAdapterV2RuntimeInput, ) => Effect.Effect< @@ -144,13 +148,16 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) { fileSystem: options.fileSystem, idAllocator: options.idAllocator, serverConfig: options.serverConfig, + ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }), }); } export type GrokAdapterV2DriverEnv = | ChildProcessSpawner.ChildProcessSpawner + | Crypto.Crypto | FileSystem.FileSystem | IdAllocatorV2 + | ProviderEventLoggers | ServerConfig; export const GrokAdapterV2Driver: ProviderAdapterDriver = { @@ -163,7 +170,9 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver + makeNativeLogger({ + nativeEventLogger: providerEventLoggers.native, + provider: GROK_PROVIDER, + threadId, + }), }); }, (effect, input) => @@ -192,7 +207,12 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver = Layer.effect( ProviderAdapterV2, Effect.gen(function* () { @@ -200,7 +220,9 @@ export const layer: Layer.Layer< const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocatorV2; + const providerEventLoggers = yield* ProviderEventLoggers; const serverConfig = yield* ServerConfig; + const makeNativeLogger = yield* makeAcpNativeLoggerFactory(); return makeGrokAdapterV2({ instanceId: GROK_DEFAULT_INSTANCE_ID, settings: DEFAULT_GROK_SETTINGS, @@ -209,6 +231,12 @@ export const layer: Layer.Layer< fileSystem, idAllocator, serverConfig, + nativeLogging: (threadId) => + makeNativeLogger({ + nativeEventLogger: providerEventLoggers.native, + provider: GROK_PROVIDER, + threadId, + }), }); }), ); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts index 7686740ee1..5f38eff2ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts @@ -1,10 +1,18 @@ import { assert, describe, it } from "@effect/vitest"; import { NodeId, + ProviderInstanceId, + ProviderSessionId, ProviderThreadId, ProviderTurnId, + ThreadId, type OrchestrationV2ProviderTurn, } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; +import { IdAllocatorV2, layer as idAllocatorLayer } from "../IdAllocator.ts"; import { openCodeBoundaryAfterProviderTurn, @@ -12,11 +20,14 @@ import { openCodePermissionRules, openCodePermissionRequestKind, openCodeToolProjectionKind, + makeOpenCodeProtocolLogger, OPENCODE_PROVIDER, OpenCodeProviderCapabilitiesV2, } from "./OpenCodeAdapterV2.ts"; import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; +const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString); + function runtimePolicy( runtimeMode: ProviderAdapterV2RuntimePolicy["runtimeMode"], override: Partial = {}, @@ -56,6 +67,39 @@ function providerTurn(input: { } describe("OpenCodeAdapterV2", () => { + it.effect("logs bounded structural protocol diagnostics without native payload values", () => + Effect.gen(function* () { + const idAllocator = yield* IdAllocatorV2; + const records: Array = []; + const nativeEventLogger: EventNdjsonLogger = { + filePath: "/tmp/provider-native.ndjson", + write: (event) => Effect.sync(() => void records.push(event)), + close: () => Effect.void, + }; + const logProtocolEvent = makeOpenCodeProtocolLogger({ + nativeEventLogger, + idAllocator, + providerInstanceId: ProviderInstanceId.make("opencode-test"), + providerSessionId: ProviderSessionId.make("provider-session-opencode-test"), + threadId: ThreadId.make("thread-opencode-test"), + }); + const secret = "secret-opencode-prompt"; + + yield* logProtocolEvent({ + direction: "outgoing", + messageKind: "request", + method: "session.prompt", + payload: { prompt: secret, nested: { token: secret } }, + }); + + const serialized = encodeUnknownJson(records); + assert.notInclude(serialized, secret); + assert.include(serialized, '"protocol":"opencode-sdk.sse"'); + assert.include(serialized, '"method":"session.prompt"'); + assert.include(serialized, '"fieldCount":2'); + }).pipe(Effect.provide(idAllocatorLayer)), + ); + it("advertises the identity strengths exposed by the SDK boundary", () => { assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeThreadIds, "strong"); assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeTurnIds, "weak"); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts index e5457c8daf..472c249362 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts @@ -12,6 +12,10 @@ import { OpenCodeRuntimeError, type OpenCodeRuntimeShape, } from "../../provider/opencodeRuntime.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../../provider/Layers/ProviderEventLoggers.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts"; import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts"; @@ -23,10 +27,11 @@ import { OPENCODE_DEFAULT_INSTANCE_ID, OPENCODE_DRIVER_KIND, OPENCODE_PROVIDER, + OPENCODE_SDK_PROTOCOL, OpenCodeAdapterV2Driver, } from "./OpenCodeAdapterV2.ts"; -export const OPENCODE_SDK_REPLAY_PROTOCOL = "opencode-sdk.sse" as const; +export const OPENCODE_SDK_REPLAY_PROTOCOL = OPENCODE_SDK_PROTOCOL; const OpenCodeSdkReplayTranscript = Schema.Struct({ provider: Schema.Literal(OPENCODE_PROVIDER), @@ -353,6 +358,7 @@ export function makeOpenCodeProviderAdapterRegistryReplayLayer( serverConfigLayer, NodeServices.layer, idAllocatorLayer, + Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), ), ), ); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts index 1255e9330e..7d8b8a8c47 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts @@ -11,6 +11,7 @@ import type { } from "@opencode-ai/sdk/v2"; import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { causeErrorTag } from "@t3tools/shared/observability"; import { defaultInstanceIdForDriver, type ModelSelection, @@ -20,11 +21,11 @@ import { type OrchestrationV2ExecutionNode, type OrchestrationV2PlanStep, type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderRef, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, - type OrchestrationV2RawProviderEvent, type OrchestrationV2RuntimeRequest, type OrchestrationV2Subagent, type OrchestrationV2TurnItem, @@ -33,6 +34,7 @@ import { ProviderDriverKind, type ProviderInstanceId, type ProviderRequestKind, + type ProviderSessionId, type RuntimeRequestId, type ThreadId, } from "@t3tools/contracts"; @@ -43,7 +45,6 @@ import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -51,6 +52,12 @@ import * as Stream from "effect/Stream"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; +import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; +import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts"; +import { + structuralProtocolMethod, + summarizeNativeProtocolPayload, +} from "../../provider/NativeProtocolLogging.ts"; import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; import { OpenCodeRuntime, @@ -65,6 +72,8 @@ import { type OpenCodeRuntimeShape, } from "../../provider/opencodeRuntime.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { makeProviderFailure } from "../ProviderFailure.ts"; +import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts"; import { ProviderAdapterEnsureThreadError, ProviderAdapterForkThreadError, @@ -95,6 +104,7 @@ import { makeSubagentChildThread, subagentThreadTitle } from "../SubagentProject export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode"); export const OPENCODE_DRIVER_KIND = OPENCODE_PROVIDER; export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_DRIVER_KIND); +export const OPENCODE_SDK_PROTOCOL = "opencode-sdk.sse" as const; const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({}); /** @@ -211,6 +221,7 @@ interface ActiveOpenCodeTurn { readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerTurnOrdinal: number; + readonly runOrdinal: number; readonly runAttemptId: OrchestrationV2ProviderTurn["runAttemptId"]; readonly startedAt: DateTime.Utc; readonly itemOrdinals: Map; @@ -272,6 +283,69 @@ export interface OpenCodeAdapterV2Options { readonly runtime: OpenCodeRuntimeShape; readonly idAllocator: IdAllocatorV2Shape; readonly serverConfig: ServerConfig["Service"]; + readonly nativeEventLogger?: EventNdjsonLogger; +} + +export interface OpenCodeProtocolLogEvent { + readonly direction: "incoming" | "outgoing"; + readonly messageKind: "request" | "response" | "notification" | "error"; + readonly method: string; + readonly payload: unknown; +} + +export function formatOpenCodeProtocolLogPayload(event: OpenCodeProtocolLogEvent) { + return { + direction: event.direction, + messageKind: event.messageKind, + method: structuralProtocolMethod(event.method), + payload: summarizeNativeProtocolPayload(event.payload), + }; +} + +export function makeOpenCodeProtocolLogger(input: { + readonly nativeEventLogger: EventNdjsonLogger | undefined; + readonly idAllocator: IdAllocatorV2Shape; + readonly providerInstanceId: ProviderInstanceId; + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; +}): (event: OpenCodeProtocolLogEvent) => Effect.Effect { + return (event) => + Effect.gen(function* () { + if (!input.nativeEventLogger) return; + const observedAt = DateTime.formatIso(yield* DateTime.now); + const method = structuralProtocolMethod(event.method); + yield* input.nativeEventLogger.write( + { + observedAt, + event: { + id: yield* input.idAllocator.allocate.rawEvent({ + providerSessionId: input.providerSessionId, + method, + }), + kind: "protocol", + protocol: OPENCODE_SDK_PROTOCOL, + provider: OPENCODE_PROVIDER, + providerInstanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + createdAt: observedAt, + threadId: input.threadId, + payload: formatOpenCodeProtocolLogPayload(event), + }, + }, + input.threadId, + ); + }).pipe( + Effect.catchCause((cause) => + Cause.hasInterrupts(cause) + ? Effect.interrupt + : Effect.logWarning("Failed to write native OpenCode event log.", { + errorTag: causeErrorTag(cause), + reasonCount: cause.reasons.length, + provider: OPENCODE_PROVIDER, + threadId: input.threadId, + }), + ), + ); } function protocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError { @@ -707,6 +781,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid instanceId: options.instanceId, driver: OPENCODE_PROVIDER, getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), openSession: Effect.fn("OpenCodeAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { const scope = yield* Effect.scope; @@ -753,8 +828,6 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid lastError: null, }; const events = yield* Queue.unbounded(); - const rawEvents = yield* Queue.unbounded(); - const rawSequence = yield* Ref.make(0); const threads = new Map(); const pendingRequests = new Map(); const pendingRequestsByNativeId = new Map(); @@ -765,47 +838,20 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const emitProviderEvent = (event: ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); - const emitRawEvent = (raw: { - readonly direction: "incoming" | "outgoing"; - readonly messageKind: OrchestrationV2RawProviderEvent["messageKind"]; - readonly method: string; - readonly payload: unknown; - }): Effect.Effect => - Effect.gen(function* () { - const sequence = yield* Ref.updateAndGet(rawSequence, (value) => value + 1); - const observedAt = yield* DateTime.now; - const rawEventId = yield* idAllocator.allocate.rawEvent({ - providerSessionId: input.providerSessionId, - method: raw.method, - }); - yield* Queue.offer(rawEvents, { - id: rawEventId, - driver: OPENCODE_PROVIDER, - providerInstanceId: options.instanceId, - providerSessionId: input.providerSessionId, - sequence, - direction: raw.direction, - messageKind: raw.messageKind, - method: raw.method, - jsonRpcId: null, - payload: raw.payload, - observedAt, - }); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.opencode-raw-event-failed", { - providerSessionId: input.providerSessionId, - cause, - }), - ), - ); + const logProtocolEvent = makeOpenCodeProtocolLogger({ + nativeEventLogger: options.nativeEventLogger, + idAllocator, + providerInstanceId: options.instanceId, + providerSessionId: input.providerSessionId, + threadId: input.threadId, + }); const sdkCall = ( method: string, payload: unknown, call: () => Promise, ): Effect.Effect => - emitRawEvent({ + logProtocolEvent({ direction: "outgoing", messageKind: "request", method, @@ -813,7 +859,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }).pipe( Effect.andThen(runOpenCodeSdk(method, call)), Effect.tap((response) => - emitRawEvent({ + logProtocolEvent({ direction: "incoming", messageKind: "response", method, @@ -1690,6 +1736,10 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state: OpenCodeThreadState, turn: ActiveOpenCodeTurn, status: TerminalTurnStatus, + terminal?: { + readonly failure?: OrchestrationV2ProviderFailure; + readonly threadDisposition?: "reusable" | "broken"; + }, ) { if (turn.finalized) return; turn.finalized = true; @@ -1705,8 +1755,9 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid } } yield* emitProviderTurn(state, turn, status, completedAt); + const threadDisposition = terminal?.threadDisposition ?? "reusable"; yield* updateProviderThread(state, { - status: status === "failed" ? "error" : "idle", + status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle", nativeConversationHeadRef: turn.nativeUserMessageId === null ? state.providerThread.nativeConversationHeadRef @@ -1744,12 +1795,35 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready", status === "failed" ? sessionEntity.lastError : null, ); - yield* emitProviderEvent({ - type: "turn.terminal", - driver: OPENCODE_PROVIDER, - providerTurnId: turn.providerTurnId, - status, - }); + yield* emitProviderEvent( + status === "failed" + ? { + type: "turn.terminal", + driver: OPENCODE_PROVIDER, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + runOrdinal: turn.runOrdinal, + failureItemOrdinal: itemOrdinal(turn, `terminal-failure:${turn.providerTurnId}`), + status, + failure: + terminal?.failure ?? + makeProviderFailure({ + message: sessionEntity.lastError ?? undefined, + class: "provider_error", + }), + threadDisposition, + } + : { + type: "turn.terminal", + driver: OPENCODE_PROVIDER, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + runOrdinal: turn.runOrdinal, + status, + failure: null, + threadDisposition, + }, + ); }); const createChildTurn = Effect.fnUntraced(function* ( @@ -1788,6 +1862,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, providerTurnId, providerTurnOrdinal: providerTurn.ordinal, + runOrdinal: state.parentSubagent.parentTurn.runOrdinal, runAttemptId: null, startedAt, itemOrdinals: new Map(), @@ -1976,7 +2051,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); const handleEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) { - yield* emitRawEvent({ + yield* logProtocolEvent({ direction: "incoming", messageKind: "notification", method: event.type, @@ -2077,6 +2152,15 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state, state.activeTurn, terminalStatusForError(event, state.activeTurn), + { + failure: makeProviderFailure({ + message, + code: event.properties.error?.name ?? null, + class: "provider_error", + }), + threadDisposition: + event.properties.sessionID === undefined ? "broken" : "reusable", + }, ); } } @@ -2114,7 +2198,10 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid yield* updateProviderSession("error", detail); for (const state of threads.values()) { if (state.activeTurn !== null) - yield* finalizeTurn(state, state.activeTurn, "failed"); + yield* finalizeTurn(state, state.activeTurn, "failed", { + failure: makeProviderFailure({ message: detail, class: "transport_error" }), + threadDisposition: "broken", + }); } }), ), @@ -2131,7 +2218,13 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid yield* updateProviderSession("error", detail); for (const state of threads.values()) { if (state.activeTurn !== null) { - yield* finalizeTurn(state, state.activeTurn, "failed"); + yield* finalizeTurn(state, state.activeTurn, "failed", { + failure: makeProviderFailure({ + message: detail, + class: "transport_error", + }), + threadDisposition: "broken", + }); } } }), @@ -2248,7 +2341,6 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid driver: OPENCODE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: sessionEntity, - rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: (threadInput) => Effect.gen(function* () { @@ -2364,13 +2456,14 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid runtimePolicy: turnInput.runtimePolicy, providerTurnId, providerTurnOrdinal: turnInput.providerTurnOrdinal, + runOrdinal: turnInput.runOrdinal, runAttemptId: turnInput.attemptId, startedAt, itemOrdinals: new Map(), parts: new Map(), partIdsByMessage: new Map(), providerTurn, - nextItemOrdinal: 100, + nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1, nativeUserMessageId: null, interrupted: false, finalized: false, @@ -2410,7 +2503,13 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid ...(variant === undefined ? {} : { variant }), parts, }), - ).pipe(Effect.tapError(() => finalizeTurn(state, turn, "failed"))); + ).pipe( + Effect.tapError((cause) => + finalizeTurn(state, turn, "failed", { + failure: makeProviderFailure({ cause, class: "provider_error" }), + }), + ), + ); }).pipe( Effect.mapError( (cause) => @@ -2705,7 +2804,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); } -export type OpenCodeAdapterV2DriverEnv = OpenCodeRuntime | IdAllocatorV2 | ServerConfig; +export type OpenCodeAdapterV2DriverEnv = + | OpenCodeRuntime + | IdAllocatorV2 + | ProviderEventLoggers + | ServerConfig; export const OpenCodeAdapterV2Driver: ProviderAdapterDriver< OpenCodeSettings, @@ -2719,6 +2822,7 @@ export const OpenCodeAdapterV2Driver: ProviderAdapterDriver< const hostEnvironment = yield* HostProcessEnvironment; const openCodeRuntime = yield* OpenCodeRuntime; const idAllocator = yield* IdAllocatorV2; + const providerEventLoggers = yield* ProviderEventLoggers; const serverConfig = yield* ServerConfig; return makeOpenCodeAdapterV2({ instanceId: input.instanceId, @@ -2727,6 +2831,9 @@ export const OpenCodeAdapterV2Driver: ProviderAdapterDriver< runtime: openCodeRuntime, idAllocator, serverConfig, + ...(providerEventLoggers.native === undefined + ? {} + : { nativeEventLogger: providerEventLoggers.native }), }); }, (effect, input) => @@ -2751,6 +2858,7 @@ export const layer: Layer.Layer { const activeRun = input.projection.runs.find( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", ); const modelSelection = input.requestedModelSelection ?? input.projection.thread.modelSelection; diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index cba016a53e..75ead58516 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -15,6 +15,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -52,6 +53,15 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ providerTurnId: ProviderTurnId, interruptedAttemptId: RunAttemptId, runId: RunId, + sessionTransition: Schema.optional( + Schema.Union([ + Schema.Struct({ + type: Schema.Literal("replace"), + replacementProviderSessionId: ProviderSessionId, + }), + Schema.Struct({ type: Schema.Literal("detach") }), + ]), + ), }), Schema.Struct({ type: Schema.Literal("runtime-request.respond"), @@ -143,6 +153,8 @@ export class EffectOutboxError extends Schema.TaggedErrorClass; readonly notifyAvailable: Effect.Effect; @@ -159,7 +171,10 @@ export interface EffectOutboxV2Shape { readonly threadId: ThreadId; readonly effectTypes: ReadonlyArray; readonly reason: string; - }) => Effect.Effect; + }) => Effect.Effect, EffectOutboxError>; + readonly signalCancellations: (effectIds: ReadonlyArray) => Effect.Effect; + readonly awaitCancellation: (effectId: string) => Effect.Effect; + readonly clearCancellation: (effectId: string) => Effect.Effect; readonly reconcileAfterProcessLoss: Effect.Effect< { readonly requeued: number; readonly cancelled: number }, EffectOutboxError @@ -236,7 +251,19 @@ export const layer: Layer.Layer = La EffectOutboxV2, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const available = yield* Queue.unbounded(); + // Availability is only a bounded latency hint; durable rows remain + // authoritative. Retaining a small burst lets multiple worker slots wake + // for distinct threads without allowing notifications to grow unbounded. + const available = yield* Queue.dropping(64); + const cancellationSignals = new Map>(); + + const cancellationSignal = (effectId: string) => { + const existing = cancellationSignals.get(effectId); + if (existing !== undefined) return existing; + const created = Deferred.makeUnsafe(); + cancellationSignals.set(effectId, created); + return created; + }; const decodeRows = (operation: string, rows: ReadonlyArray) => Effect.forEach(rows, rowToEffect).pipe( @@ -280,7 +307,10 @@ export const layer: Layer.Layer = La { concurrency: 1, discard: true }, ); if (effects.length > 0) { - yield* Queue.offer(available, undefined); + yield* Queue.offerAll( + available, + Array.from({ length: Math.min(effects.length, 64) }, () => undefined), + ); } }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))), get: (effectId) => @@ -309,14 +339,14 @@ export const layer: Layer.Layer = La `.pipe( Effect.flatMap((rows) => decodeRows("list", rows)), Effect.mapError((cause) => - Schema.is(EffectOutboxError)(cause) + isEffectOutboxError(cause) ? cause : new EffectOutboxError({ operation: "list", cause }), ), ), cancelUnsettled: ({ threadId, effectTypes, reason }) => Effect.gen(function* () { - if (effectTypes.length === 0) return 0; + if (effectTypes.length === 0) return []; const now = DateTime.formatIso(yield* DateTime.now); const rows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox @@ -332,12 +362,26 @@ export const layer: Layer.Layer = La AND effect_type IN ${sql.in(effectTypes)} RETURNING effect_id `; - return rows.length; + return rows.map(({ effect_id }) => effect_id); }).pipe( Effect.mapError( (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }), ), ), + signalCancellations: (effectIds) => + Effect.forEach( + effectIds, + (effectId) => { + const signal = cancellationSignals.get(effectId); + return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined); + }, + { discard: true }, + ), + awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)), + clearCancellation: (effectId) => + Effect.sync(() => { + cancellationSignals.delete(effectId); + }), reconcileAfterProcessLoss: Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); const cancelledRows = yield* sql<{ readonly effect_id: string }>` @@ -390,20 +434,25 @@ export const layer: Layer.Layer = La updated_at = ${nowIso}, last_error = NULL WHERE effect_id = ( - SELECT effect_id - FROM orchestration_v2_effect_outbox - WHERE available_at <= ${nowIso} - AND ( - status = 'pending' - OR (status = 'running' AND lease_expires_at <= ${nowIso}) + SELECT candidate.effect_id + FROM orchestration_v2_effect_outbox AS candidate + WHERE candidate.available_at <= ${nowIso} + AND candidate.status = 'pending' + AND NOT EXISTS ( + SELECT 1 + FROM orchestration_v2_effect_outbox AS active + WHERE active.thread_id = candidate.thread_id + AND active.status = 'running' ) - ORDER BY available_at ASC, created_at ASC, effect_id ASC + ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC LIMIT 1 ) RETURNING * `; const row = rows[0]; - return row === undefined ? Option.none() : Option.some(yield* rowToEffect(row)); + if (row === undefined) return Option.none(); + cancellationSignals.set(row.effect_id, Deferred.makeUnsafe()); + return Option.some(yield* rowToEffect(row)); }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))), succeed: ({ effectId, workerId }) => Effect.gen(function* () { @@ -422,6 +471,7 @@ export const layer: Layer.Layer = La AND lease_owner = ${workerId} RETURNING effect_id `; + if (rows.length === 1) cancellationSignals.delete(effectId); return rows.length === 1; }).pipe( Effect.mapError( @@ -449,6 +499,7 @@ export const layer: Layer.Layer = La AND lease_owner = ${workerId} RETURNING effect_id `; + if (rows.length === 1) cancellationSignals.delete(effectId); return rows.length === 1; }).pipe( Effect.mapError( @@ -472,6 +523,7 @@ export const layer: Layer.Layer = La AND lease_owner = ${workerId} RETURNING effect_id `; + if (rows.length === 1) cancellationSignals.delete(effectId); return rows.length === 1; }).pipe( Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })), diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts new file mode 100644 index 0000000000..5b0e4d2620 --- /dev/null +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -0,0 +1,181 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; + +import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts"; +import type { OrchestrationEffectV2 } from "./EffectOutbox.ts"; +import { executorLayer, OrchestrationEffectExecutorV2 } from "./EffectWorker.ts"; +import { RunFinalizationService } from "./RunFinalizationService.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts"; +import { ProviderTurnStartError, ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts"; +import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts"; + +const threadId = ThreadId.make("thread:effect-worker-restart"); +const oldSessionId = ProviderSessionId.make("provider-session:effect-worker-restart:old"); +const replacementSessionId = ProviderSessionId.make( + "provider-session:effect-worker-restart:replacement", +); +const providerThreadId = ProviderThreadId.make("provider-thread:effect-worker-restart"); +const providerTurnId = ProviderTurnId.make("provider-turn:effect-worker-restart"); +const attemptId = RunAttemptId.make("run-attempt:effect-worker-restart"); +const runId = RunId.make("run:effect-worker-restart"); + +function restartEffect( + now: DateTime.Utc, + sessionTransition: NonNullable< + Extract< + OrchestrationEffectV2["request"], + { readonly type: "provider-turn.restart" } + >["sessionTransition"] + >, +): OrchestrationEffectV2 { + const timestamp = DateTime.formatIso(now); + return { + id: `effect:restart:${sessionTransition.type}`, + commandId: CommandId.make(`command:restart:${sessionTransition.type}`), + threadId, + request: { + type: "provider-turn.restart", + providerSessionId: oldSessionId, + providerThreadId, + providerTurnId, + interruptedAttemptId: attemptId, + runId, + sessionTransition, + }, + status: "running", + attemptCount: 1, + availableAt: timestamp, + leaseOwner: "test-worker", + leaseExpiresAt: timestamp, + createdAt: timestamp, + updatedAt: timestamp, + completedAt: null, + lastError: null, + }; +} + +function makeExecutorLayer(input: { + readonly events: Ref.Ref>; + readonly failFirstStart?: Ref.Ref; +}) { + const record = (event: string) => Ref.update(input.events, (events) => [...events, event]); + const dependencies = Layer.mergeAll( + Layer.succeed( + ProviderTurnControlServiceV2, + ProviderTurnControlServiceV2.of({ + interrupt: () => Effect.void, + steer: () => Effect.void, + interruptAndAwaitTerminal: (request) => + record( + request.replacementProviderSessionId === undefined + ? "interrupt" + : `interrupt:${request.replacementProviderSessionId}`, + ), + }), + ), + Layer.succeed( + ProviderSessionManagerV2, + ProviderSessionManagerV2.of({ + shutdown: Effect.void, + open: () => Effect.die("unused open"), + get: () => Effect.succeed(Option.none()), + close: () => Effect.void, + release: () => record("release"), + detach: () => record("detach"), + }), + ), + Layer.succeed( + ProviderTurnStartServiceV2, + ProviderTurnStartServiceV2.of({ + start: () => + Effect.gen(function* () { + yield* record("start"); + if ( + input.failFirstStart !== undefined && + (yield* Ref.getAndSet(input.failFirstStart, false)) + ) { + return yield* new ProviderTurnStartError({ + runId, + cause: "simulated first start failure", + }); + } + }), + }), + ), + Layer.succeed( + RunFinalizationService, + RunFinalizationService.of({ finalize: () => Effect.void }), + ), + Layer.succeed( + CheckpointRollbackServiceV2, + CheckpointRollbackServiceV2.of({ execute: () => Effect.void }), + ), + Layer.succeed( + RuntimeRequestServiceV2, + RuntimeRequestServiceV2.of({ respond: () => Effect.void }), + ), + ); + return executorLayer.pipe(Layer.provide(dependencies)); +} + +it.effect("detaches a handed-off session only after the old turn terminalizes", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Ref.make>([]); + + yield* Effect.gen(function* () { + const executor = yield* OrchestrationEffectExecutorV2; + yield* executor.execute(restartEffect(now, { type: "detach" })); + }).pipe(Effect.provide(makeExecutorLayer({ events }))); + + assert.deepEqual(yield* Ref.get(events), ["interrupt", "detach", "start"]); + }), +); + +it.effect("safely retries after replacement cleanup succeeds and start fails", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Ref.make>([]); + const failFirstStart = yield* Ref.make(true); + const effect = restartEffect(now, { + type: "replace", + replacementProviderSessionId: replacementSessionId, + }); + const layer = makeExecutorLayer({ events, failFirstStart }); + + const first = yield* Effect.gen(function* () { + const executor = yield* OrchestrationEffectExecutorV2; + return yield* Effect.exit(executor.execute(effect)); + }).pipe(Effect.provide(layer)); + assert.isTrue(Exit.isFailure(first)); + + yield* Effect.gen(function* () { + const executor = yield* OrchestrationEffectExecutorV2; + yield* executor.execute(effect); + }).pipe(Effect.provide(layer)); + + assert.deepEqual(yield* Ref.get(events), [ + `interrupt:${replacementSessionId}`, + "detach", + "start", + `interrupt:${replacementSessionId}`, + "detach", + "start", + ]); + }), +); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 86d092d7fa..612c26c44c 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -133,8 +133,29 @@ export const executorLayer: Layer.Layer< providerThreadId: effect.request.providerThreadId, providerTurnId: effect.request.providerTurnId, interruptedAttemptId: effect.request.interruptedAttemptId, + ...(effect.request.sessionTransition?.type === "replace" + ? { + replacementProviderSessionId: + effect.request.sessionTransition.replacementProviderSessionId, + } + : {}), }) .pipe( + Effect.andThen( + effect.request.sessionTransition?.type === "replace" + ? providerSessions.detach({ + providerSessionId: effect.request.providerSessionId, + threadId: effect.threadId, + detail: "Selection change requires a provider session restart.", + }) + : effect.request.sessionTransition?.type === "detach" + ? providerSessions.detach({ + providerSessionId: effect.request.providerSessionId, + threadId: effect.threadId, + detail: "Provider thread handoff replaced this session binding.", + }) + : Effect.void, + ), Effect.andThen( providerTurnStart.start({ threadId: effect.threadId, @@ -245,6 +266,8 @@ export class OrchestrationEffectWorkerError extends Schema.TaggedErrorClass; readonly runOnce: Effect.Effect; @@ -277,6 +300,15 @@ export const layerWithOptions = ( const workerId = options.workerId ?? `orchestration-v2:${process.pid}`; const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000); const maxAttempts = Math.max(1, options.maxAttempts ?? 5); + const wasCancelled = (effectId: string) => + outbox.get(effectId).pipe( + Effect.map( + Option.match({ + onNone: () => false, + onSome: (effect) => effect.status === "cancelled", + }), + ), + ); const runOnce = Effect.gen(function* () { const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs }); @@ -284,10 +316,28 @@ export const layerWithOptions = ( return false; } const effect = claimed.value; - const exit = yield* Effect.exit(executor.execute(effect)); + // Cancellation can commit after the durable claim but before the + // process-local Deferred is registered. Re-read the authoritative row + // once before starting external work; later cancellations use the + // Deferred raced below. + if (yield* wasCancelled(effect.id)) { + yield* outbox.clearCancellation(effect.id); + return true; + } + const execution = executor.execute(effect).pipe(Effect.as("executed" as const)); + const cancellation = outbox + .awaitCancellation(effect.id) + .pipe(Effect.as("cancelled" as const)); + const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe( + Effect.ensuring(outbox.clearCancellation(effect.id)), + ); + if (Exit.isSuccess(exit) && exit.value === "cancelled") { + return true; + } if (Exit.isSuccess(exit)) { const completed = yield* outbox.succeed({ effectId: effect.id, workerId }); if (!completed) { + if (yield* wasCancelled(effect.id)) return true; return yield* new OrchestrationEffectWorkerError({ operation: "complete", effectId: effect.id, @@ -314,6 +364,7 @@ export const layerWithOptions = ( delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)), }); if (!updated) { + if (yield* wasCancelled(effect.id)) return true; return yield* new OrchestrationEffectWorkerError({ operation: "reschedule", effectId: effect.id, @@ -323,7 +374,7 @@ export const layerWithOptions = ( return true; }).pipe( Effect.mapError((cause) => - Schema.is(OrchestrationEffectWorkerError)(cause) + isOrchestrationEffectWorkerError(cause) ? cause : new OrchestrationEffectWorkerError({ operation: "run", cause }), ), @@ -346,21 +397,48 @@ export const layerWithOptions = ( export const layer = layerWithOptions(); -export const runDaemon = Effect.gen(function* () { - const worker = yield* OrchestrationEffectWorkerV2; - return yield* Effect.forever( - worker.runOnce.pipe( - Effect.catchCause((cause) => - Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)), - ), - Effect.flatMap((worked) => - worked - ? Effect.yieldNow - : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))), - ), - ), +export interface OrchestrationEffectDaemonOptions { + readonly concurrency?: number; +} + +export const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4; + +export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) => + Effect.scoped( + Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY; + const concurrency = Number.isFinite(requestedConcurrency) + ? Math.max(1, Math.floor(requestedConcurrency)) + : DEFAULT_EFFECT_WORKER_CONCURRENCY; + // Notifications only reduce latency; the durable outbox remains authoritative. + // Every slot polls after a bounded delay so a missed or coalesced wakeup can + // never strand committed work. Consuming the outbox signal directly also + // avoids lifecycle coupling between a separate fan-out fiber and subscribers. + const runWorker = Effect.forever( + worker.runOnce.pipe( + Effect.catchCause((cause) => + Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)), + ), + Effect.flatMap((worked) => + worked + ? Effect.yieldNow + : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))), + ), + ), + ); + + return yield* Effect.all( + Array.from({ length: concurrency }, () => runWorker), + { + concurrency: "unbounded", + discard: true, + }, + ); + }), ); -}); + +export const runDaemon = runDaemonWithOptions(); export const daemonLayer: Layer.Layer = Layer.effectDiscard(runDaemon.pipe(Effect.forkScoped)); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index dd8ce3885a..5e226553e7 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -1,7 +1,10 @@ import { CommandId, + type OrchestrationV2Run, OrchestrationV2DomainEvent, OrchestrationV2StoredEvent, + RunAttemptId, + RunId, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -82,6 +85,20 @@ export interface EventSinkV2Shape { readonly events: ReadonlyArray; readonly effects: ReadonlyArray; }) => Effect.Effect, EventSinkV2Error>; + readonly writeIfRunCurrent: (input: { + readonly commandId?: CommandId; + readonly threadId: ThreadId; + readonly runId: RunId; + readonly activeAttemptId: RunAttemptId; + readonly expectedStatus: OrchestrationV2Run["status"]; + readonly events: ReadonlyArray; + }) => Effect.Effect< + { + readonly committed: boolean; + readonly storedEvents: ReadonlyArray; + }, + EventSinkV2Error + >; readonly commitCommand: (input: { readonly commandId: CommandId; readonly threadId: ThreadId; @@ -230,6 +247,58 @@ const baseLayer: Layer.Layer< return storedEvents; }); + const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")( + function* (input: Parameters[0]) { + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.command_id": input.commandId ?? null, + "orchestration_v2.event_count": input.events.length, + "orchestration_v2.run_id": input.runId, + "orchestration_v2.thread_id": input.threadId, + }); + + const result = yield* sql.withTransaction( + Effect.gen(function* () { + const rows = yield* sql<{ + readonly status: string; + readonly active_attempt_id: string | null; + }>` + SELECT + status, + json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id + FROM orchestration_v2_projection_runs + WHERE run_id = ${input.runId} + AND thread_id = ${input.threadId} + LIMIT 1 + `; + const current = rows[0]; + if ( + current === undefined || + current.status !== input.expectedStatus || + current.active_attempt_id !== input.activeAttemptId + ) { + return { + committed: false as const, + storedEvents: [] as ReadonlyArray, + }; + } + + const normalized = yield* normalizeEvents(input.events); + const storedEvents = yield* eventStore.append({ + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + events: normalized, + }); + yield* applyStoredEvents(storedEvents); + return { committed: true as const, storedEvents }; + }), + ); + if (result.committed) { + yield* eventStore.publishCommitted(result.storedEvents); + yield* PubSub.publishAll(liveEvents, result.storedEvents); + } + return result; + }, + ); + const existingCommandResult = (commandId: CommandId) => Effect.gen(function* () { const existing = yield* commandReceipts.getByCommandId(commandId); @@ -261,7 +330,7 @@ const baseLayer: Layer.Layer< }); if (!reserved) { const existing = yield* existingCommandResult(input.commandId); - return { ...existing, committed: false as const, cancelledEffectCount: 0 }; + return { ...existing, committed: false as const, cancelledEffectIds: [] }; } const normalized = yield* normalizeEvents(input.events); @@ -287,16 +356,17 @@ const baseLayer: Layer.Layer< error: null, }; yield* commandReceipts.upsert(receipt); - const cancelledEffectCount = + const cancelledEffectIds = input.cancelUnsettledEffects === undefined - ? 0 + ? [] : yield* effectOutbox.cancelUnsettled({ threadId: input.threadId, ...input.cancelUnsettledEffects, }); - return { receipt, storedEvents, committed: true as const, cancelledEffectCount }; + return { receipt, storedEvents, committed: true as const, cancelledEffectIds }; }), ); + yield* effectOutbox.signalCancellations(result.cancelledEffectIds); if (input.effects.length > 0) { yield* effectOutbox.notifyAvailable; } @@ -304,7 +374,12 @@ const baseLayer: Layer.Layer< yield* eventStore.publishCommitted(result.storedEvents); yield* PubSub.publishAll(liveEvents, result.storedEvents); } - return result; + return { + receipt: result.receipt, + storedEvents: result.storedEvents, + committed: result.committed, + cancelledEffectCount: result.cancelledEffectIds.length, + }; }); const commitRejectedCommandEffect = Effect.fn( @@ -411,6 +486,17 @@ const baseLayer: Layer.Layer< }), ), ), + writeIfRunCurrent: (input) => + writeIfRunCurrentEffect(input).pipe( + Effect.mapError( + (cause) => + new EventSinkWriteError({ + eventCount: input.events.length, + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + cause, + }), + ), + ), commitCommand: (input) => commitCommandEffect(input).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index c2a8ca4151..3ad27a3f4e 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -10,16 +10,19 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, + type OrchestrationV2Run, ProjectId, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, ProviderThreadId, + RunAttemptId, RunId, ThreadId, TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -36,6 +39,7 @@ import { layerWithOptions as effectWorkerLayerWithOptions, OrchestrationEffectExecutorV2, OrchestrationEffectWorkerV2, + runDaemonWithOptions as runEffectWorkerDaemonWithOptions, } from "./EffectWorker.ts"; import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts"; import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts"; @@ -402,6 +406,279 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); + it.effect("does not publish a stale provider start after an interrupt wins", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const projectionStore = yield* ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:foundation-stale-provider-start"); + const runId = RunId.make("run:foundation-stale-provider-start"); + const attemptId = RunAttemptId.make("run-attempt:foundation-stale-provider-start"); + const thread = makeThread(threadId, now); + const startingRun: OrchestrationV2Run = { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message:foundation-stale-provider-start"), + rootNodeId: null, + activeAttemptId: attemptId, + status: "starting", + queuePosition: null, + requestedAt: now, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + yield* eventSink.write({ + events: [ + threadCreatedEvent({ + id: "event:foundation-stale-provider-start:thread", + thread, + now, + }), + { + id: EventId.make("event:foundation-stale-provider-start:run"), + type: "run.created", + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: startingRun, + }, + ], + }); + + const reachedPrecommitGap = yield* Deferred.make(); + const releaseStaleStart = yield* Deferred.make(); + const providerStartCount = yield* Ref.make(0); + const staleStartFiber = yield* Effect.gen(function* () { + yield* Deferred.succeed(reachedPrecommitGap, undefined); + yield* Deferred.await(releaseStaleStart); + const result = yield* eventSink.writeIfRunCurrent({ + threadId, + runId, + activeAttemptId: attemptId, + expectedStatus: "starting", + events: [ + { + id: EventId.make("event:foundation-stale-provider-start:running"), + type: "run.updated", + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: { ...startingRun, status: "running", startedAt: now }, + }, + ], + }); + if (result.committed) { + yield* Ref.update(providerStartCount, (count) => count + 1); + } + return result; + }).pipe(Effect.forkChild); + + yield* Deferred.await(reachedPrecommitGap); + const interruptedAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:foundation-stale-provider-start:cancelled"), + type: "run.updated", + threadId, + runId, + providerInstanceId, + occurredAt: interruptedAt, + payload: { + ...startingRun, + status: "cancelled", + completedAt: interruptedAt, + }, + }, + ], + }); + yield* Deferred.succeed(releaseStaleStart, undefined); + + const staleResult = yield* Fiber.join(staleStartFiber); + assert.isFalse(staleResult.committed); + assert.deepEqual(staleResult.storedEvents, []); + assert.equal(yield* Ref.get(providerStartCount), 0); + const projection = yield* projectionStore.getThreadProjection(threadId); + assert.equal(projection.runs[0]?.status, "cancelled"); + }), + ); + + it.effect("interrupts a running process-bound effect when it is cancelled", () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const commandId = CommandId.make("command:foundation-cancel-running-effect"); + const threadId = ThreadId.make("thread:foundation-cancel-running-effect"); + const effectId = "effect:foundation-cancel-running-effect"; + const started = yield* Deferred.make(); + const interrupted = yield* Deferred.make(); + yield* outbox.enqueue([ + { + id: effectId, + commandId, + threadId, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-cancel-running-effect"), + }, + }, + ]); + + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: () => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => + Deferred.succeed(interrupted, undefined).pipe(Effect.ignore), + ), + ), + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "cancellation-worker", + }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer))); + + yield* Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + const workerFiber = yield* worker.runOnce.pipe(Effect.forkChild); + yield* Deferred.await(started); + const cancelledEffectIds = yield* outbox.cancelUnsettled({ + threadId, + effectTypes: ["provider-turn.start"], + reason: "The owning run was interrupted.", + }); + assert.deepEqual(cancelledEffectIds, [effectId]); + yield* outbox.signalCancellations(cancelledEffectIds); + assert.isTrue(yield* Fiber.join(workerFiber)); + yield* Deferred.await(interrupted); + }).pipe(Effect.provide(workerLayer)); + + const cancelled = yield* outbox.get(effectId); + assert.isTrue(Option.isSome(cancelled)); + if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled"); + }), + ); + + it.effect("treats cancellation between execution and settlement as a normal outcome", () => + Effect.gen(function* () { + const effectId = "effect:foundation-cancel-before-settlement"; + const threadId = ThreadId.make("thread:foundation-cancel-before-settlement"); + const commandId = CommandId.make("command:foundation-cancel-before-settlement"); + const now = DateTime.formatIso(yield* DateTime.now); + const claimedEffect = { + id: effectId, + commandId, + threadId, + request: { type: "terminal.cleanup" as const }, + status: "running" as const, + attemptCount: 1, + availableAt: now, + leaseOwner: "settlement-race-worker", + leaseExpiresAt: now, + createdAt: now, + updatedAt: now, + completedAt: null, + lastError: null, + }; + const outboxLayer = Layer.mock(EffectOutboxV2)({ + claimNext: () => Effect.succeed(Option.some(claimedEffect)), + awaitCancellation: () => Effect.never, + clearCancellation: () => Effect.void, + succeed: () => Effect.succeed(false), + get: () => + Effect.succeed( + Option.some({ + ...claimedEffect, + status: "cancelled" as const, + leaseOwner: null, + leaseExpiresAt: null, + completedAt: now, + }), + ), + }); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ execute: () => Effect.void }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "settlement-race-worker", + }).pipe(Layer.provide(Layer.merge(outboxLayer, executorLayer))); + + assert.isTrue( + yield* OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide(workerLayer), + ), + ); + }), + ); + + it.effect("does not start an effect that was cancelled during claim registration", () => + Effect.gen(function* () { + const effectId = "effect:foundation-cancelled-during-claim"; + const threadId = ThreadId.make("thread:foundation-cancelled-during-claim"); + const commandId = CommandId.make("command:foundation-cancelled-during-claim"); + const now = DateTime.formatIso(yield* DateTime.now); + const claimedEffect = { + id: effectId, + commandId, + threadId, + request: { type: "terminal.cleanup" as const }, + status: "running" as const, + attemptCount: 1, + availableAt: now, + leaseOwner: "claim-cancellation-worker", + leaseExpiresAt: now, + createdAt: now, + updatedAt: now, + completedAt: null, + lastError: null, + }; + const executionCount = yield* Ref.make(0); + const outboxLayer = Layer.mock(EffectOutboxV2)({ + claimNext: () => Effect.succeed(Option.some(claimedEffect)), + get: () => + Effect.succeed( + Option.some({ + ...claimedEffect, + status: "cancelled" as const, + leaseOwner: null, + leaseExpiresAt: null, + completedAt: now, + }), + ), + clearCancellation: () => Effect.void, + awaitCancellation: () => Effect.never, + }); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: () => Ref.update(executionCount, (count) => count + 1), + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "claim-cancellation-worker", + }).pipe(Layer.provide(Layer.merge(outboxLayer, executorLayer))); + + assert.isTrue( + yield* OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide(workerLayer), + ), + ); + assert.equal(yield* Ref.get(executionCount), 0); + }), + ); + it.effect("allows only one worker to claim an available effect", () => Effect.gen(function* () { const outbox = yield* EffectOutboxV2; @@ -438,6 +715,162 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); + it.effect("runs distinct threads concurrently while serializing effects within a thread", () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const commandId = CommandId.make("command:foundation-concurrent-effects"); + const threadA = ThreadId.make("thread:foundation-concurrent-effects:a"); + const threadB = ThreadId.make("thread:foundation-concurrent-effects:b"); + const effectA1 = "effect:foundation-concurrent-effects:a1"; + const effectA2 = "effect:foundation-concurrent-effects:a2"; + const effectB1 = "effect:foundation-concurrent-effects:b1"; + const startedA1 = yield* Deferred.make(); + const startedA2 = yield* Deferred.make(); + const startedB1 = yield* Deferred.make(); + const releaseA1 = yield* Deferred.make(); + const releaseA2 = yield* Deferred.make(); + const releaseB1 = yield* Deferred.make(); + const gates = new Map([ + [effectA1, { started: startedA1, release: releaseA1 }], + [effectA2, { started: startedA2, release: releaseA2 }], + [effectB1, { started: startedB1, release: releaseB1 }], + ]); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: (effect) => { + const gate = gates.get(effect.id); + if (gate === undefined) return Effect.die(`Missing gate for ${effect.id}`); + return Deferred.succeed(gate.started, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + ); + }, + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "concurrency-worker", + }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer))); + + yield* Effect.gen(function* () { + yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped); + // Let both slots reach the idle wait before work becomes available. + yield* Effect.yieldNow; + yield* Effect.yieldNow; + yield* outbox.enqueue([ + { + id: effectA1, + commandId, + threadId: threadA, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-concurrent-effects:a1"), + }, + }, + { + id: effectA2, + commandId, + threadId: threadA, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-concurrent-effects:a2"), + }, + }, + { + id: effectB1, + commandId, + threadId: threadB, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-concurrent-effects:b1"), + }, + }, + ]); + + yield* Effect.all([Deferred.await(startedA1), Deferred.await(startedB1)]); + assert.isFalse(yield* Deferred.isDone(startedA2)); + + yield* Deferred.succeed(releaseA1, undefined); + yield* Deferred.succeed(releaseB1, undefined); + yield* Deferred.await(startedA2); + yield* Deferred.succeed(releaseA2, undefined); + let settled = false; + while (!settled) { + settled = (yield* outbox.listByCommandId(commandId)).every( + (effect) => effect.status === "succeeded", + ); + if (!settled) yield* Effect.yieldNow; + } + }).pipe(Effect.provide(workerLayer), Effect.scoped); + }), + ); + + it.effect("does not reclaim a running effect after its process-local lease expires", () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const sql = yield* SqlClient.SqlClient; + const commandId = CommandId.make("command:foundation-no-live-reclaim"); + const threadId = ThreadId.make("thread:foundation-no-live-reclaim"); + const firstEffectId = "effect:foundation-no-live-reclaim:first"; + const secondEffectId = "effect:foundation-no-live-reclaim:second"; + const firstStarted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const executions = yield* Ref.make>([]); + yield* outbox.enqueue([ + { + id: firstEffectId, + commandId, + threadId, + request: { type: "terminal.cleanup" }, + }, + { + id: secondEffectId, + commandId, + threadId, + request: { type: "terminal.cleanup" }, + }, + ]); + + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: (effect) => + Ref.update(executions, (current) => [...current, effect.id]).pipe( + Effect.andThen( + effect.id === firstEffectId + ? Deferred.succeed(firstStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseFirst)), + ) + : Effect.void, + ), + ), + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "no-live-reclaim-worker", + leaseDurationMs: 1, + }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer))); + + yield* Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + const firstFiber = yield* worker.runOnce.pipe(Effect.forkChild); + yield* Deferred.await(firstStarted); + yield* sql` + UPDATE orchestration_v2_effect_outbox + SET lease_expires_at = '1970-01-01T00:00:00.000Z' + WHERE effect_id = ${firstEffectId} + `; + + assert.isFalse(yield* worker.runOnce); + assert.deepEqual(yield* Ref.get(executions), [firstEffectId]); + + yield* Deferred.succeed(releaseFirst, undefined); + assert.isTrue(yield* Fiber.join(firstFiber)); + assert.isTrue(yield* worker.runOnce); + assert.deepEqual(yield* Ref.get(executions), [firstEffectId, secondEffectId]); + }).pipe(Effect.provide(workerLayer)); + }), + ); + it.effect( "retires live provider effects and requeues replay-safe effects after process loss", () => @@ -457,7 +890,7 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { { id: "effect:b-foundation-requeue-cleanup", commandId, - threadId: ThreadId.make("thread:foundation-reclaim-running"), + threadId: ThreadId.make("thread:foundation-reclaim-cleanup"), request: { type: "terminal.cleanup" }, }, ]); @@ -718,3 +1151,44 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); }); + +it.live("keeps claiming new work after repeated idle periods", () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const completed = new Map>(); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: (effect) => { + const completion = completed.get(effect.id); + return completion === undefined + ? Effect.die(`Missing completion signal for ${effect.id}`) + : Deferred.succeed(completion, undefined).pipe(Effect.asVoid); + }, + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ + workerId: "idle-wave-worker", + }).pipe(Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer))); + + yield* Effect.gen(function* () { + yield* runEffectWorkerDaemonWithOptions({ concurrency: 2 }).pipe(Effect.forkScoped); + for (let wave = 1; wave <= 6; wave += 1) { + yield* Effect.sleep("125 millis"); + const effectId = `effect:foundation-idle-wave:${wave}`; + const completion = yield* Deferred.make(); + completed.set(effectId, completion); + yield* outbox.enqueue([ + { + id: effectId, + commandId: CommandId.make(`command:foundation-idle-wave:${wave}`), + threadId: ThreadId.make(`thread:foundation-idle-wave:${wave}`), + request: { type: "terminal.cleanup" }, + }, + ]); + const observed = yield* Deferred.await(completion).pipe(Effect.timeoutOption("2 seconds")); + assert.isTrue(Option.isSome(observed), `worker stopped before idle wave ${wave}`); + } + }).pipe(Effect.provide(workerLayer), Effect.scoped); + }).pipe(Effect.provide(TestLayer)), +); diff --git a/apps/server/src/orchestration-v2/KeyedSerialExecutor.test.ts b/apps/server/src/orchestration-v2/KeyedSerialExecutor.test.ts new file mode 100644 index 0000000000..6f376b9f33 --- /dev/null +++ b/apps/server/src/orchestration-v2/KeyedSerialExecutor.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "@effect/vitest"; + +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; + +import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts"; + +describe("makeKeyedSerialExecutor", () => { + it.effect("allows unrelated keys to run concurrently", () => + Effect.gen(function* () { + const executor = yield* makeKeyedSerialExecutor(); + const arrivals = yield* Queue.unbounded(); + const release = yield* Deferred.make(); + const run = (key: string) => + executor.withLock( + key, + Queue.offer(arrivals, key).pipe(Effect.andThen(Deferred.await(release))), + ); + + const fibers = yield* Effect.forEach(["a", "b"], run, { + concurrency: "unbounded", + discard: false, + }).pipe(Effect.forkChild); + const observed = [yield* Queue.take(arrivals), yield* Queue.take(arrivals)]; + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(fibers); + expect(new Set(observed)).toEqual(new Set(["a", "b"])); + }).pipe(Effect.timeout("1 second")), + ); + + it.effect("serializes work for the same key", () => + Effect.gen(function* () { + const executor = yield* makeKeyedSerialExecutor(); + const firstEntered = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const events = yield* Ref.make>([]); + + const first = yield* executor + .withLock( + "thread", + Ref.update(events, (current) => [...current, "first:start"]).pipe( + Effect.andThen(Deferred.succeed(firstEntered, undefined)), + Effect.andThen(Deferred.await(releaseFirst)), + Effect.andThen(Ref.update(events, (current) => [...current, "first:end"])), + ), + ) + .pipe(Effect.forkChild); + yield* Deferred.await(firstEntered); + const second = yield* executor + .withLock( + "thread", + Ref.update(events, (current) => [...current, "second:start"]), + ) + .pipe(Effect.forkChild); + + yield* Effect.yieldNow; + expect(yield* Ref.get(events)).toEqual(["first:start"]); + yield* Deferred.succeed(releaseFirst, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + expect(yield* Ref.get(events)).toEqual(["first:start", "first:end", "second:start"]); + }).pipe(Effect.timeout("1 second")), + ); +}); diff --git a/apps/server/src/orchestration-v2/KeyedSerialExecutor.ts b/apps/server/src/orchestration-v2/KeyedSerialExecutor.ts new file mode 100644 index 0000000000..93dbe04bbb --- /dev/null +++ b/apps/server/src/orchestration-v2/KeyedSerialExecutor.ts @@ -0,0 +1,55 @@ +import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; +import * as Semaphore from "effect/Semaphore"; + +interface LockEntry { + readonly semaphore: Semaphore.Semaphore; + readonly users: number; +} + +export interface KeyedSerialExecutor { + readonly withLock: (key: Key, effect: Effect.Effect) => Effect.Effect; +} + +/** + * Serializes work that targets the same domain identity without coupling + * unrelated identities to a process-wide mutex. + */ +export const makeKeyedSerialExecutor = (): Effect.Effect> => + Effect.gen(function* () { + const locks = yield* Ref.make(new Map()); + + const acquireLock = (key: Key) => + Effect.gen(function* () { + const candidate = yield* Semaphore.make(1); + return yield* Ref.modify(locks, (current) => { + const existing = current.get(key); + const semaphore = existing?.semaphore ?? candidate; + const next = new Map(current); + next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 }); + return [semaphore, next] as const; + }); + }); + + const releaseLock = (key: Key) => + Ref.update(locks, (current) => { + const existing = current.get(key); + if (existing === undefined) return current; + const next = new Map(current); + if (existing.users === 1) { + next.delete(key); + } else { + next.set(key, { ...existing, users: existing.users - 1 }); + } + return next; + }); + + return { + withLock: (key, effect) => + Effect.acquireUseRelease( + acquireLock(key), + (semaphore) => semaphore.withPermit(effect), + () => releaseLock(key), + ), + } satisfies KeyedSerialExecutor; + }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 68355093a4..9443e6d77b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -21,8 +21,10 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, ProviderInstanceId, + type ProviderSessionId, ThreadId, } from "@t3tools/contracts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -31,16 +33,15 @@ import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as Semaphore from "effect/Semaphore"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { CommandPolicyV2 } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts"; import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts"; import { EventSinkV2 } from "./EventSink.ts"; -import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; -import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts"; +import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; +import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts"; import { applyToProjection, emptyProjection, ProjectionStoreV2 } from "./ProjectionStore.ts"; import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; @@ -181,6 +182,9 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { case "thread.model-selection.set": case "provider-session.detach": case "message.dispatch": + case "prepared-run.release": + case "prepared-run.progress": + case "prepared-run.fail": case "run.interrupt": case "queued-message.promote-to-steer": case "queued-run.reorder": @@ -200,8 +204,15 @@ function nextTurnItemOrdinal(projection: OrchestrationV2ThreadProjection): numbe return Math.max(0, ...projection.turnItems.map((item) => item.ordinal)) + 1; } +const WORKSPACE_PREPARATION_INPUT = "Preparing workspace"; + function isBlockingRun(run: OrchestrationV2Run): boolean { - return run.status === "starting" || run.status === "running" || run.status === "waiting"; + return ( + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting" + ); } function delegatedTaskTerminalStatus( @@ -215,6 +226,7 @@ function delegatedTaskTerminalStatus( return status; case "rolled_back": return "cancelled"; + case "preparing": case "queued": case "starting": case "running": @@ -389,7 +401,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandPolicy = yield* CommandPolicyV2; const contextHandoffService = yield* ContextHandoffServiceV2; const eventSink = yield* EventSinkV2; - const effectWorker = yield* OrchestrationEffectWorkerV2; const commandReceipts = yield* CommandReceiptStoreV2; const idAllocator = yield* IdAllocatorV2; const projectionStore = yield* ProjectionStoreV2; @@ -398,7 +409,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const providerSwitchService = yield* ProviderSwitchServiceV2; const runtimePolicy = yield* RuntimePolicyV2; const threadForkService = yield* ThreadForkServiceV2; - const dispatchSemaphore = yield* Semaphore.make(1); + const threadDispatch = yield* makeKeyedSerialExecutor(); const mapDispatchError = (command: OrchestrationV2Command) => @@ -556,14 +567,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const queuedProviderThread = projection.providerThreads.find( (candidate) => candidate.id === providerThreadId, ); - const checkpointScope = projection.checkpointScopes.find( + const storedCheckpointScope = projection.checkpointScopes.find( (scope) => scope.id === rootNode?.checkpointScopeId, ); if ( rootNode === undefined || attempt === undefined || queuedProviderThread === undefined || - checkpointScope === undefined + (rootNode.checkpointScopeId !== null && storedCheckpointScope === undefined) ) { return yield* new OrchestratorDispatchError({ commandId: CommandId.make(`command:system:start-queued:${queuedRun.id}`), @@ -573,6 +584,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const commandId = CommandId.make(`command:system:start-queued:${queuedRun.id}`); + const now = yield* DateTime.now; + const checkpointScope = + storedCheckpointScope ?? + (yield* runtimePolicy + .resolve({ thread: projection.thread, modelSelection: queuedRun.modelSelection }) + .pipe( + Effect.flatMap((resolvedRuntimePolicy) => + checkpointService.prepareRootRunScope({ + threadId, + runId: queuedRun.id, + rootNodeId: rootNode.id, + providerThreadId: queuedProviderThread.id, + cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), + createdAt: now, + }), + ), + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId, + commandType: "message.dispatch", + cause, + }), + ), + )); const providerSessionId = queuedProviderThread.providerSessionId ?? (yield* providerAdapters.get(queuedRun.providerInstanceId).pipe( @@ -592,7 +628,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), )); - const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...queuedProviderThread, providerSessionId, @@ -607,8 +642,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuePosition: null, startedAt: null, }; + const checkpointEvents: ReadonlyArray> = + storedCheckpointScope === undefined + ? [ + { + type: "checkpoint-scope.created", + threadId, + runId: queuedRun.id, + nodeId: rootNode.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: checkpointScope, + }, + { + type: "node.updated", + threadId, + runId: queuedRun.id, + nodeId: rootNode.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { ...rootNode, checkpointScopeId: checkpointScope.id }, + }, + ] + : []; yield* writeSystemEvents( [ + ...checkpointEvents, { type: "provider-thread.updated", threadId, @@ -635,7 +694,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ], ); - yield* effectWorker.drain(1); }); const resumeQueuedRuns = Effect.gen(function* () { @@ -647,7 +705,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (projection.runs.some(isBlockingRun) || nextQueuedRun(projection) === undefined) { return false; } - yield* dispatchSemaphore.withPermit(startNextQueuedRun(thread.id)); + yield* threadDispatch.withLock(thread.id, startNextQueuedRun(thread.id)); return true; }).pipe( Effect.catch((cause) => @@ -858,7 +916,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const emitEvent = emit(events, command); const activeRunIds = new Set( projection.runs - .filter((run) => ["queued", "starting", "running", "waiting"].includes(run.status)) + .filter((run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + ) .map((run) => run.id), ); for (const run of projection.runs.filter((candidate) => activeRunIds.has(candidate.id))) { @@ -1388,10 +1448,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const session = sessionOption.value; const now = yield* DateTime.now; const emitEvent = emit(input.events, input.command); + const selectionChanged = !modelSelectionsEqual( + targetRun.modelSelection, + input.modelSelection, + ); + const providerInstanceChanged = + targetRun.providerInstanceId !== input.modelSelection.instanceId; + const selectionTransition = + selectionChanged && !providerInstanceChanged + ? yield* providerAdapters.get(targetRun.providerInstanceId).pipe( + Effect.flatMap((adapter) => + adapter.planSelectionTransition({ + current: targetRun.modelSelection, + target: input.modelSelection, + sessionCapabilities: session.providerSession.capabilities, + }), + ), + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: input.command.commandId, + providerInstanceId: targetRun.providerInstanceId, + cause, + }), + ), + ) + : null; + if (selectionTransition?.type === "reject") { + return yield* new OrchestratorDispatchError({ + commandId: input.command.commandId, + commandType: input.command.type, + cause: selectionTransition.reason, + }); + } const appendSteeringMessage = (messageInput: { readonly runId: OrchestrationV2Run["id"]; readonly nodeId: OrchestrationV2ExecutionNode["id"]; readonly providerTurnId: typeof providerTurn.id | null; + readonly providerThreadId: OrchestrationV2ProviderThread["id"]; + readonly providerInstanceId: ProviderInstanceId; }) => Effect.gen(function* () { const message: OrchestrationV2ConversationMessage = { @@ -1415,7 +1510,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: messageInput.runId, nodeId: messageInput.nodeId, - providerThreadId: providerThread.id, + providerThreadId: messageInput.providerThreadId, providerTurnId: messageInput.providerTurnId, nativeItemRef: null, parentItemId: null, @@ -1439,7 +1534,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: messageInput.runId, nodeId: messageInput.nodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: messageInput.providerInstanceId, occurredAt: now, payload: message, }); @@ -1448,7 +1543,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: messageInput.runId, nodeId: messageInput.nodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: messageInput.providerInstanceId, occurredAt: now, payload: turnItem, }); @@ -1460,7 +1555,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, providerInstanceId: targetRun.providerInstanceId, capabilities: session.providerSession.capabilities, - forceRestart: input.forceRestart, + forceRestart: input.forceRestart || selectionChanged, }), ); @@ -1469,6 +1564,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: targetRun.id, nodeId: rootNodeId, providerTurnId: providerTurn.id, + providerThreadId: providerThread.id, + providerInstanceId: targetRun.providerInstanceId, }); yield* Ref.update(input.effects, (existing) => [ ...existing, @@ -1509,6 +1606,158 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: targetRun.id, attemptOrdinal, }); + let restartProviderThread = providerThread; + let restartSessionTransition: + | { + readonly type: "replace"; + readonly replacementProviderSessionId: ProviderSessionId; + } + | { readonly type: "detach" } + | null = null; + let restartHandoff: OrchestrationV2ContextHandoff | null = null; + let restartTransfer: OrchestrationV2ContextTransfer | null = null; + const requiresProviderThreadHandoff = + providerInstanceChanged || selectionTransition?.type === "create_with_handoff"; + const requiresProviderSessionRestart = selectionTransition?.type === "restart_session"; + if (requiresProviderThreadHandoff) { + const targetAdapter = yield* providerAdapters.get(input.modelSelection.instanceId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: input.command.commandId, + providerInstanceId: input.modelSelection.instanceId, + cause, + }), + ), + ); + const targetCapabilities = yield* targetAdapter.getCapabilities().pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: input.command.commandId, + providerInstanceId: input.modelSelection.instanceId, + cause, + }), + ), + ); + yield* enforceCommandPolicy(input.command)( + commandPolicy.ensureContextHandoff({ + commandId: input.command.commandId, + threadId: input.command.threadId, + providerInstanceId: input.modelSelection.instanceId, + capabilities: targetCapabilities, + strategy: "full_thread_summary", + }), + ); + const existingTargetProviderThread = rootProviderThreadsForProvider( + input.projection, + input.modelSelection.instanceId, + ).find((candidate) => candidate.id !== providerThread.id); + const targetProviderSessionId = + existingTargetProviderThread?.providerSessionId ?? + (yield* mapDispatchError(input.command)( + providerSessionIdFor({ + adapter: targetAdapter, + providerInstanceId: input.modelSelection.instanceId, + threadId: input.command.threadId, + }), + )); + const targetProviderThreadBase: OrchestrationV2ProviderThread = + existingTargetProviderThread === undefined + ? { + id: idAllocator.derive.providerThread({ + driver: targetAdapter.driver, + nativeThreadId: `pending:${targetRun.id}:attempt:${attemptOrdinal}`, + }), + driver: targetAdapter.driver, + providerInstanceId: input.modelSelection.instanceId, + providerSessionId: targetProviderSessionId, + appThreadId: input.command.threadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: targetRun.ordinal, + lastRunOrdinal: targetRun.ordinal, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + } + : { + ...existingTargetProviderThread, + providerSessionId: targetProviderSessionId, + lastRunOrdinal: targetRun.ordinal, + updatedAt: now, + }; + const transferId = yield* mapDispatchError(input.command)( + idAllocator.allocate.contextTransfer({ + sourceThreadId: input.command.threadId, + targetThreadId: input.command.threadId, + type: "provider_handoff", + }), + ); + restartHandoff = yield* contextHandoffService + .prepareProviderHandoff({ + threadId: input.command.threadId, + targetRunId: targetRun.id, + transferId, + fromProviderThreadIds: [providerThread.id], + toProviderThreadId: targetProviderThreadBase.id, + fromProviderInstanceId: targetRun.providerInstanceId, + toProviderInstanceId: input.modelSelection.instanceId, + coveredRunOrdinals: { from: 1, to: targetRun.ordinal }, + strategy: "full_thread_summary", + items: input.projection.turnItems, + createdAt: now, + }) + .pipe(mapDispatchError(input.command)); + restartProviderThread = { + ...targetProviderThreadBase, + handoffIds: Array.from( + new Set([...targetProviderThreadBase.handoffIds, restartHandoff.id]), + ), + }; + restartTransfer = { + id: transferId, + type: "provider_handoff", + sourceThreadId: input.command.threadId, + targetThreadId: input.command.threadId, + sourcePoint: contextSourcePointForRun(input.projection, targetRun), + basePoint: null, + sourceProviderInstanceId: targetRun.providerInstanceId, + targetProviderInstanceId: input.modelSelection.instanceId, + targetRunId: targetRun.id, + status: "consumed", + resolution: { + strategy: "portable_context", + contextHandoffId: restartHandoff.id, + }, + createdBy: input.createdBy, + error: null, + createdAt: now, + updatedAt: now, + consumedAt: now, + }; + restartSessionTransition = { type: "detach" }; + } else if (requiresProviderSessionRestart) { + const nextProviderSessionId = yield* mapDispatchError(input.command)( + idAllocator.allocate.providerSession({ + providerInstanceId: input.modelSelection.instanceId, + threadId: input.command.threadId, + }), + ); + restartProviderThread = { + ...providerThread, + providerSessionId: nextProviderSessionId, + status: "not_loaded", + updatedAt: now, + }; + restartSessionTransition = { + type: "replace", + replacementProviderSessionId: nextProviderSessionId, + }; + } const resolvedRuntimePolicy = yield* runtimePolicy .resolve({ thread: input.projection.thread, modelSelection: input.modelSelection }) .pipe( @@ -1526,8 +1775,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, rootNodeId: nextRootNodeId, - providerThreadId: providerThread.id, - cwd: resolvedRuntimePolicy.cwd ?? session.providerSession.cwd, + providerThreadId: restartProviderThread.id, + cwd: + resolvedRuntimePolicy.cwd ?? + input.projection.thread.worktreePath ?? + session.providerSession.cwd, createdAt: now, }) .pipe( @@ -1552,18 +1804,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); const restartedRun: OrchestrationV2Run = { ...targetRun, + providerInstanceId: input.modelSelection.instanceId, + modelSelection: input.modelSelection, + providerThreadId: restartProviderThread.id, rootNodeId: nextRootNodeId, activeAttemptId: nextAttemptId, userMessageId: input.messageId, status: "starting", + contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId, }; const nextAttempt: OrchestrationV2RunAttempt = { id: nextAttemptId, runId: targetRun.id, attemptOrdinal, rootNodeId: nextRootNodeId, - providerInstanceId: targetRun.providerInstanceId, - providerThreadId: providerThread.id, + providerInstanceId: input.modelSelection.instanceId, + providerThreadId: restartProviderThread.id, providerTurnId: null, reason: "steering_restart", status: "pending", @@ -1579,7 +1835,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio kind: "root_turn", status: "pending", countsForRun: true, - providerThreadId: providerThread.id, + providerThreadId: restartProviderThread.id, providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, @@ -1609,12 +1865,42 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...currentRootNode, status: "interrupted", completedAt: now }, }); } + if (requiresProviderThreadHandoff || requiresProviderSessionRestart) { + yield* emitEvent({ + type: "provider-thread.updated", + threadId: input.command.threadId, + driver: restartProviderThread.driver, + providerInstanceId: input.modelSelection.instanceId, + occurredAt: now, + payload: restartProviderThread, + }); + } + if (restartHandoff !== null) { + yield* emitEvent({ + type: "context-handoff.updated", + threadId: input.command.threadId, + runId: targetRun.id, + providerInstanceId: input.modelSelection.instanceId, + occurredAt: now, + payload: restartHandoff, + }); + } + if (restartTransfer !== null) { + yield* emitEvent({ + type: "context-transfer.created", + threadId: input.command.threadId, + runId: targetRun.id, + providerInstanceId: input.modelSelection.instanceId, + occurredAt: now, + payload: restartTransfer, + }); + } yield* emitEvent({ type: "run.updated", threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: input.modelSelection.instanceId, occurredAt: now, payload: restartedRun, }); @@ -1623,7 +1909,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: input.modelSelection.instanceId, occurredAt: now, payload: nextAttempt, }); @@ -1632,7 +1918,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: input.modelSelection.instanceId, occurredAt: now, payload: nextRootNode, }); @@ -1641,7 +1927,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - providerInstanceId: targetRun.providerInstanceId, + providerInstanceId: input.modelSelection.instanceId, occurredAt: now, payload: ensuredCheckpointScope, }); @@ -1649,6 +1935,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: targetRun.id, nodeId: nextRootNodeId, providerTurnId: null, + providerThreadId: restartProviderThread.id, + providerInstanceId: input.modelSelection.instanceId, }); const interruptedAttemptId = targetRun.activeAttemptId; if (interruptedAttemptId === null) { @@ -1671,6 +1959,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: providerTurn.id, interruptedAttemptId, runId: targetRun.id, + ...(restartSessionTransition === null + ? {} + : { sessionTransition: restartSessionTransition }), }, } satisfies PendingOrchestrationEffectV2, ]); @@ -1759,7 +2050,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection); const shouldQueue = activeRun !== undefined && - (dispatchMode.type === "start_immediately" || dispatchMode.type === "queue_after_active"); + (dispatchMode.type === "defer_start" || + dispatchMode.type === "start_immediately" || + dispatchMode.type === "queue_after_active"); if (shouldQueue) { if (pendingMergeBackTransfers.length > 0) { return yield* new OrchestratorDispatchError({ @@ -1804,46 +2097,38 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); } - const resolvedRuntimePolicy = yield* runtimePolicy - .resolve({ thread: projection.thread, modelSelection }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); const now = yield* DateTime.now; const ordinal = nextRunOrdinal(projection); const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal }); const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); - const checkpointScope = yield* checkpointService - .prepareRootRunScope({ - threadId: command.threadId, - runId, - rootNodeId, - providerThreadId: queueProviderThread.id, - cwd: - resolvedRuntimePolicy.cwd ?? - existingProviderSession?.cwd ?? - projection.thread.worktreePath ?? - process.cwd(), - createdAt: now, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); + const checkpointScope = + activeRun.status === "preparing" + ? null + : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe( + Effect.flatMap((resolvedRuntimePolicy) => + checkpointService.prepareRootRunScope({ + threadId: command.threadId, + runId, + rootNodeId, + providerThreadId: queueProviderThread.id, + cwd: + resolvedRuntimePolicy.cwd ?? + existingProviderSession?.cwd ?? + projection.thread.worktreePath ?? + process.cwd(), + createdAt: now, + }), + ), + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ); const run: OrchestrationV2Run = { id: runId, threadId: command.threadId, @@ -1895,7 +2180,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, - checkpointScopeId: checkpointScope.id, + checkpointScopeId: checkpointScope?.id ?? null, startedAt: null, completedAt: null, }; @@ -1965,24 +2250,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: rootNode, }); - yield* emitEvent({ - type: "checkpoint-scope.created", - threadId: command.threadId, - runId, - nodeId: rootNodeId, - providerInstanceId: modelSelection.instanceId, - occurredAt: now, - payload: yield* checkpointService.ensureScope(checkpointScope).pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), + if (checkpointScope !== null) { + yield* emitEvent({ + type: "checkpoint-scope.created", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: yield* checkpointService.ensureScope(checkpointScope).pipe( + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), ), - ), - }); + }); + } yield* emitEvent({ type: "message.updated", threadId: command.threadId, @@ -2083,22 +2370,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); - const resolvedRuntimePolicy = yield* runtimePolicy - .resolve({ - thread: projection.thread, - modelSelection, - }) - .pipe(mapDispatchError(command)); - const checkpointScope = yield* checkpointService - .prepareRootRunScope({ - threadId: command.threadId, - runId, - rootNodeId, - providerThreadId, - cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), - createdAt: now, - }) - .pipe(mapDispatchError(command)); + const checkpointScope = + dispatchMode.type === "defer_start" + ? null + : yield* runtimePolicy + .resolve({ + thread: projection.thread, + modelSelection, + }) + .pipe( + mapDispatchError(command), + Effect.flatMap((resolvedRuntimePolicy) => + checkpointService.prepareRootRunScope({ + threadId: command.threadId, + runId, + rootNodeId, + providerThreadId, + cwd: + resolvedRuntimePolicy.cwd ?? + projection.thread.worktreePath ?? + process.cwd(), + createdAt: now, + }), + ), + mapDispatchError(command), + ); const run: OrchestrationV2Run = { id: runId, threadId: command.threadId, @@ -2109,7 +2405,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio userMessageId: command.messageId, rootNodeId, activeAttemptId: attemptId, - status: "starting", + status: dispatchMode.type === "defer_start" ? "preparing" : "starting", queuePosition: null, requestedAt: now, startedAt: null, @@ -2144,7 +2440,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, - checkpointScopeId: checkpointScope.id, + checkpointScopeId: checkpointScope?.id ?? null, startedAt: null, completedAt: null, }; @@ -2185,6 +2481,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: command.text, attachments: command.attachments, }; + const preparationTurnItem: OrchestrationV2TurnItem | null = + dispatchMode.type === "defer_start" + ? { + id: idAllocator.derive.turnItemFromProviderItem({ + driver: adapter.driver, + nativeItemId: `workspace-preparation:${runId}`, + }), + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: turnItem.ordinal + 1, + status: "running", + title: WORKSPACE_PREPARATION_INPUT, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "command_execution", + input: WORKSPACE_PREPARATION_INPUT, + } + : null; const emitEvent = emit(events, command); yield* emitEvent({ type: "provider-thread.updated", @@ -2222,15 +2542,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: rootNode, }); - yield* emitEvent({ - type: "checkpoint-scope.created", - threadId: command.threadId, - runId, - nodeId: rootNodeId, - providerInstanceId: modelSelection.instanceId, - occurredAt: now, - payload: checkpointScope, - }); + if (checkpointScope !== null) { + yield* emitEvent({ + type: "checkpoint-scope.created", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: checkpointScope, + }); + } yield* emitEvent({ type: "message.updated", threadId: command.threadId, @@ -2249,13 +2571,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: turnItem, }); + if (preparationTurnItem !== null) { + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: preparationTurnItem, + }); + } const pendingEffect = { id: `effect:${command.commandId}:provider-turn.start:${runId}`, commandId: command.commandId, threadId: command.threadId, request: { type: "provider-turn.start", runId }, } satisfies PendingOrchestrationEffectV2; - yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + if (dispatchMode.type !== "defer_start") { + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + } return; } const sourceProjection = @@ -3661,66 +3996,428 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + const preparedRunState = ( + command: Extract< + OrchestrationV2Command, + { + readonly type: "prepared-run.release" | "prepared-run.progress" | "prepared-run.fail"; + } + >, + projection: OrchestrationV2ThreadProjection, + ) => { + const run = projection.runs.find((candidate) => candidate.id === command.runId); + const attempt = projection.attempts.find((candidate) => candidate.id === run?.activeAttemptId); + const rootNode = projection.nodes.find((candidate) => candidate.id === run?.rootNodeId); + const providerThread = projection.providerThreads.find( + (candidate) => candidate.id === run?.providerThreadId, + ); + const preparationItem = projection.turnItems.find( + ( + candidate, + ): candidate is Extract => + candidate.runId === command.runId && + candidate.type === "command_execution" && + candidate.input === WORKSPACE_PREPARATION_INPUT, + ); + if ( + run?.status !== "preparing" || + attempt === undefined || + rootNode === undefined || + providerThread === undefined || + preparationItem === undefined + ) { + return null; + } + return { run, attempt, rootNode, providerThread, preparationItem } as const; + }; + + const dispatchPreparedRunProgress = ( + command: Extract, + events: Ref.Ref>, + ) => + Effect.gen(function* () { + const projection = yield* loadProjectionForCommand(command); + const state = preparedRunState(command, projection); + if (state === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not awaiting workspace preparation.`, + }); + } + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "turn-item.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { + ...state.preparationItem, + title: command.phase === "worktree" ? "Preparing worktree" : "Starting setup script", + updatedAt: now, + }, + }); + }); + + const dispatchPreparedRunRelease = ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) => + Effect.gen(function* () { + const projection = yield* loadProjectionForCommand(command); + const state = preparedRunState(command, projection); + if (state === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not awaiting workspace preparation.`, + }); + } + const now = yield* DateTime.now; + const resolvedRuntimePolicy = yield* runtimePolicy + .resolve({ thread: projection.thread, modelSelection: state.run.modelSelection }) + .pipe(mapDispatchError(command)); + const checkpointScope = yield* checkpointService + .prepareRootRunScope({ + threadId: command.threadId, + runId: state.run.id, + rootNodeId: state.rootNode.id, + providerThreadId: state.providerThread.id, + cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), + createdAt: now, + }) + .pipe(mapDispatchError(command)); + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "checkpoint-scope.created", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: checkpointScope, + }); + yield* emitEvent({ + type: "node.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { ...state.rootNode, checkpointScopeId: checkpointScope.id }, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { + ...state.preparationItem, + status: "completed", + title: "Workspace ready", + output: "Workspace preparation completed.", + exitCode: 0, + completedAt: now, + updatedAt: now, + }, + }); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { ...state.run, status: "starting" }, + }); + yield* Ref.update(effects, (existing) => [ + ...existing, + { + id: `effect:${command.commandId}:provider-turn.start:${state.run.id}`, + commandId: command.commandId, + threadId: command.threadId, + request: { type: "provider-turn.start", runId: state.run.id }, + } satisfies PendingOrchestrationEffectV2, + ]); + }); + + const dispatchPreparedRunFail = ( + command: Extract, + events: Ref.Ref>, + ) => + Effect.gen(function* () { + const projection = yield* loadProjectionForCommand(command); + const state = preparedRunState(command, projection); + if (state === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not awaiting workspace preparation.`, + }); + } + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "run-attempt.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { ...state.attempt, status: "failed", completedAt: now }, + }); + yield* emitEvent({ + type: "node.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { ...state.rootNode, status: "failed", completedAt: now }, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { + ...state.preparationItem, + status: "failed", + title: "Workspace preparation failed", + output: command.failure.message, + exitCode: 1, + completedAt: now, + updatedAt: now, + }, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { + id: idAllocator.derive.turnItemFromProviderItem({ + driver: state.providerThread.driver, + nativeItemId: `workspace-preparation-failure:${state.run.id}`, + }), + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerThreadId: state.providerThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: nextTurnItemOrdinal(projection), + status: "failed", + title: "Workspace preparation failed", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "error", + failure: command.failure, + }, + }); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: state.run.id, + nodeId: state.rootNode.id, + providerInstanceId: state.run.providerInstanceId, + occurredAt: now, + payload: { ...state.run, status: "failed", completedAt: now }, + }); + }); + const dispatchRunInterrupt = ( command: Extract, events: Ref.Ref>, effects: Ref.Ref>, ) => Effect.gen(function* () { - const findInterruptTarget = ( - attemptsRemaining = 100, - ): Effect.Effect< - { - readonly projection: OrchestrationV2ThreadProjection; - readonly run: OrchestrationV2Run; - readonly rootNode: OrchestrationV2ExecutionNode; - readonly providerThread: OrchestrationV2ProviderThread; - readonly providerTurn: NonNullable< - OrchestrationV2ThreadProjection["providerTurns"][number] - >; - }, - OrchestratorV2Error - > => - Effect.gen(function* () { - const projection = yield* loadProjectionForCommand(command); - const run = projection.runs.find((candidate) => candidate.id === command.runId); - const rootNode = - run?.rootNodeId === null - ? undefined - : projection.nodes.find((candidate) => candidate.id === run?.rootNodeId); - const providerThread = - run?.providerThreadId === null - ? undefined - : projection.providerThreads.find( - (candidate) => candidate.id === run?.providerThreadId, - ); - const providerTurn = projection.providerTurns.find( - (candidate) => - candidate.runAttemptId === run?.activeAttemptId && candidate.status === "running", - ); - - if ( - run !== undefined && - rootNode !== undefined && - providerThread !== undefined && - providerTurn !== undefined - ) { - return { projection, run, rootNode, providerThread, providerTurn }; - } - - if (attemptsRemaining <= 0) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Run ${command.runId} is not interruptible.`, - }); - } - yield* Effect.yieldNow; - return yield* findInterruptTarget(attemptsRemaining - 1); + const projection = yield* loadProjectionForCommand(command); + const run = projection.runs.find((candidate) => candidate.id === command.runId); + const rootNode = + run?.rootNodeId === null + ? undefined + : projection.nodes.find((candidate) => candidate.id === run?.rootNodeId); + const providerThread = + run?.providerThreadId === null + ? undefined + : projection.providerThreads.find((candidate) => candidate.id === run?.providerThreadId); + const providerTurn = projection.providerTurns.find( + (candidate) => + candidate.runAttemptId === run?.activeAttemptId && candidate.status === "running", + ); + if (run === undefined || rootNode === undefined || providerThread === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not interruptible.`, }); + } - const { projection, run, rootNode, providerThread, providerTurn } = - yield* findInterruptTarget(); + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + const interruptRequestItem: OrchestrationV2TurnItem = { + id: idAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: "interrupt-request", + }), + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerThreadId: providerThread.id, + providerTurnId: providerTurn?.id ?? null, + nativeItemRef: null, + parentItemId: null, + ordinal: nextTurnItemOrdinal(projection), + status: "completed", + title: "Interrupt requested", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_request", + message: command.reason ?? "Interrupt requested", + }; + + if ( + providerTurn === undefined && + (run.status === "preparing" || run.status === "starting" || run.status === "running") + ) { + const attempt = projection.attempts.find( + (candidate) => candidate.id === run.activeAttemptId, + ); + if (attempt === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} has no active attempt to interrupt.`, + }); + } + const interruptResultItem: OrchestrationV2TurnItem = { + id: idAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: "interrupt-result", + }), + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerThreadId: providerThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: interruptRequestItem.id, + ordinal: interruptRequestItem.ordinal + 1, + status: "interrupted", + title: "Interrupted", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "run_interrupt_result", + message: "Run interrupted before provider start", + }; + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: interruptRequestItem, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: interruptResultItem, + }); + const preparationItem = projection.turnItems.find( + ( + candidate, + ): candidate is Extract< + OrchestrationV2TurnItem, + { readonly type: "command_execution" } + > => + candidate.runId === run.id && + candidate.type === "command_execution" && + candidate.input === WORKSPACE_PREPARATION_INPUT && + candidate.status === "running", + ); + if (preparationItem !== undefined) { + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + ...preparationItem, + status: "interrupted", + title: "Workspace preparation interrupted", + output: command.reason ?? "Interrupted before provider start", + completedAt: now, + updatedAt: now, + }, + }); + } + yield* emitEvent({ + type: "run-attempt.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...attempt, status: "interrupted", completedAt: now }, + }); + yield* emitEvent({ + type: "node.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...rootNode, status: "interrupted", completedAt: now }, + }); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "interrupted", completedAt: now }, + }); + return { + effectTypes: ["provider-turn.start", "provider-turn.restart"], + reason: `Run ${run.id} was interrupted before its provider turn started.`, + } satisfies { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }; + } + + if (providerTurn === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not interruptible.`, + }); + } if (providerThread.providerSessionId === null) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, @@ -3755,8 +4452,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ); - const now = yield* DateTime.now; - const emitEvent = emit(events, command); /* * TODO(interrupt-hardening): before shipping, make these interrupt * semantics explicit in tests and policy. @@ -3783,27 +4478,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio * an explicit policy decision because it can weaken native-item * correlation. */ - const interruptRequestItem: OrchestrationV2TurnItem = { - id: idAllocator.derive.runSignalTurnItem({ - runId: run.id, - signal: "interrupt-request", - }), - threadId: command.threadId, - runId: run.id, - nodeId: rootNode.id, - providerThreadId: providerThread.id, - providerTurnId: providerTurn.id, - nativeItemRef: null, - parentItemId: null, - ordinal: nextTurnItemOrdinal(projection), - status: "completed", - title: "Interrupt requested", - startedAt: now, - completedAt: now, - updatedAt: now, - type: "run_interrupt_request", - message: command.reason ?? "Interrupt requested", - }; yield* emitEvent({ type: "turn-item.updated", threadId: command.threadId, @@ -3827,6 +4501,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, } satisfies PendingOrchestrationEffectV2, ]); + return undefined; }); const dispatchCheckpointRollback = ( @@ -4171,6 +4846,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio { readonly events: ReadonlyArray; readonly effects: ReadonlyArray; + readonly cancelUnsettledEffects?: { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }; }, OrchestratorV2Error > { @@ -4182,6 +4861,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const events = yield* Ref.make>([]); const effects = yield* Ref.make>([]); + let cancelUnsettledEffects: + | { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + } + | undefined; switch (command.type) { case "thread.create": yield* dispatchThreadCreate(command, events); @@ -4202,11 +4887,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "message.dispatch": yield* dispatchMessage(command, events, effects); break; + case "prepared-run.release": + yield* dispatchPreparedRunRelease(command, events, effects); + break; + case "prepared-run.progress": + yield* dispatchPreparedRunProgress(command, events); + break; + case "prepared-run.fail": + yield* dispatchPreparedRunFail(command, events); + break; case "runtime-request.respond": yield* dispatchRuntimeRequestRespond(command, events, effects); break; case "run.interrupt": - yield* dispatchRunInterrupt(command, events, effects); + cancelUnsettledEffects = yield* dispatchRunInterrupt(command, events, effects); break; case "queued-message.promote-to-steer": yield* dispatchQueuedMessagePromoteToSteer(command, events, effects); @@ -4232,6 +4926,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { events: yield* Ref.get(events), effects: yield* Ref.get(effects), + ...(cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects }), }; }); @@ -4329,6 +5024,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio acceptedAt, events: plan.events, effects: plan.effects, + ...(plan.cancelUnsettledEffects === undefined + ? {} + : { cancelUnsettledEffects: plan.cancelUnsettledEffects }), }) .pipe( Effect.mapError( @@ -4349,20 +5047,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } - // The receipt and outbox rows are already committed here. Draining makes - // direct callers deterministic; the daemon remains responsible for work - // left behind by a crash between commit and this wake-up. - yield* effectWorker.drain(100).pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - return { sequence: committed.receipt.resultSequence, storedEvents: committed.storedEvents, @@ -4370,7 +5054,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); const dispatchWithReceipt = (command: OrchestrationV2Command) => - dispatchSemaphore.withPermit(dispatchWithReceiptEffect(command)); + threadDispatch.withLock(commandThreadId(command), dispatchWithReceiptEffect(command)); yield* eventSink.stream().pipe( Stream.filter( @@ -4384,8 +5068,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio stored.event.payload.status === "rolled_back"), ), Stream.runForEach((stored) => - dispatchSemaphore - .withPermit( + threadDispatch + .withLock( + stored.event.threadId, finalizeAppOwnedSubagent(stored.event.threadId).pipe( Effect.andThen(startNextQueuedRun(stored.event.threadId)), ), @@ -4457,7 +5142,6 @@ export const layer: Layer.Layer< | CommandReceiptStoreV2 | ContextHandoffServiceV2 | EventSinkV2 - | OrchestrationEffectWorkerV2 | IdAllocatorV2 | ProviderAdapterRegistryV2 | ProviderSessionManagerV2 diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 81ec3e6582..9122f8dd79 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -796,7 +796,12 @@ export function threadShellFromProjection( } function isBlockingRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean { - return run.status === "starting" || run.status === "running" || run.status === "waiting"; + return ( + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting" + ); } type ShellThreadState = { @@ -818,6 +823,7 @@ function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2S switch (status) { case null: return "idle"; + case "preparing": case "queued": case "starting": case "running": @@ -2047,7 +2053,7 @@ export const layer: Layer.Layer = SELECT r.run_id FROM orchestration_v2_projection_runs r WHERE r.thread_id = t.thread_id - AND r.status IN ('starting', 'running', 'waiting') + AND r.status IN ('preparing', 'starting', 'running', 'waiting') ORDER BY r.ordinal DESC, r.run_id DESC LIMIT 1 ) AS active_run_id, diff --git a/apps/server/src/orchestration-v2/ProviderAdapter.ts b/apps/server/src/orchestration-v2/ProviderAdapter.ts index 62b521cf45..d8cf1c9c82 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapter.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapter.ts @@ -10,9 +10,9 @@ import { OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, + OrchestrationV2ProviderFailure, OrchestrationV2ProviderThread, OrchestrationV2ProviderTurn, - OrchestrationV2RawProviderEvent, OrchestrationV2RuntimeRequest, OrchestrationV2Subagent, OrchestrationV2TurnItem, @@ -20,6 +20,7 @@ import { ProviderInteractionMode, ProviderDriverKind, ProviderInstanceId, + PositiveInt, ProviderUserInputAnswers, ProviderSessionId, ProviderThreadId, @@ -36,6 +37,11 @@ import type * as Effect from "effect/Effect"; import type * as Scope from "effect/Scope"; import type * as Stream from "effect/Stream"; +import type { + ProviderSelectionTransitionInput, + ProviderSelectionTransitionPlan, +} from "./ProviderSelectionTransition.ts"; + export const ProviderAdapterV2RuntimePolicy = Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, @@ -121,8 +127,23 @@ export const ProviderAdapterV2Event = Schema.Union([ Schema.Struct({ type: Schema.Literal("turn.terminal"), driver: ProviderDriverKind, + providerThreadId: ProviderThreadId, providerTurnId: ProviderTurnId, - status: Schema.Literals(["completed", "interrupted", "failed", "cancelled"]), + runOrdinal: PositiveInt, + status: Schema.Literals(["completed", "interrupted", "cancelled"]), + failure: Schema.Null, + threadDisposition: Schema.Literals(["reusable", "broken"]), + }), + Schema.Struct({ + type: Schema.Literal("turn.terminal"), + driver: ProviderDriverKind, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + runOrdinal: PositiveInt, + failureItemOrdinal: PositiveInt, + status: Schema.Literal("failed"), + failure: OrchestrationV2ProviderFailure, + threadDisposition: Schema.Literals(["reusable", "broken"]), }), ]); export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type; @@ -446,12 +467,11 @@ export interface ProviderAdapterV2SessionRuntime { readonly driver: ProviderDriverKind; readonly providerSessionId: ProviderSessionId; readonly providerSession: OrchestrationV2ProviderSession; - readonly rawEvents: Stream.Stream; readonly events: Stream.Stream; /** * Manager-owned runtimes expose a synchronous subscription so concurrent * provider threads receive independent copies of the process event stream. - * Adapter runtimes may omit this and expose only their raw single-consumer stream. + * Adapter runtimes may omit this and expose only their single-consumer event stream. */ readonly subscribeEvents?: Effect.Effect; readonly ensureThread: ( @@ -493,6 +513,9 @@ export interface ProviderAdapterV2Shape { OrchestrationV2ProviderCapabilities, ProviderAdapterV2Error >; + readonly planSelectionTransition: ( + input: ProviderSelectionTransitionInput, + ) => Effect.Effect; readonly openSession: ( input: ProviderAdapterV2OpenSessionInput, ) => Effect.Effect; diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts index 6a600c9b8a..0abbcba2fb 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts @@ -21,6 +21,7 @@ const makeAdapter = (instanceId: ProviderInstanceId): ProviderAdapterV2Shape => instanceId, driver, getCapabilities: () => Effect.die("capabilities are not used by this registry test"), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: () => Effect.die("sessions are not used by this registry test"), }) as ProviderAdapterV2Shape; diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 49555e28c8..0149d43ac3 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -27,6 +27,7 @@ import { ProviderEventIngestorV2, layer as providerEventIngestorLayer, } from "./ProviderEventIngestor.ts"; +import { makeProviderFailure } from "./ProviderFailure.ts"; const TestDatabaseLayer = SqlitePersistenceMemory; const TestStoresLayer = Layer.merge(eventStoreLayer, projectionStoreLayer).pipe( @@ -187,7 +188,7 @@ layer("ProviderEventIngestorV2", (it) => { ); it.effect( - "treats provider terminal markers as orchestration control signals, not persisted domain events", + "treats successful provider terminal markers as non-persisted orchestration control signals", () => Effect.gen(function* () { const ingestor = yield* ProviderEventIngestorV2; @@ -210,11 +211,18 @@ layer("ProviderEventIngestorV2", (it) => { event: { type: "turn.terminal", driver: CODEX_DRIVER, + providerThreadId: idAllocator.derive.providerThread({ + driver: CODEX_DRIVER, + nativeThreadId: "native-thread", + }), providerTurnId: idAllocator.derive.providerTurn({ driver: CODEX_DRIVER, nativeTurnId: "native-turn", }), + runOrdinal: 1, status: "completed", + failure: null, + threadDisposition: "reusable", }, }); @@ -222,6 +230,67 @@ layer("ProviderEventIngestorV2", (it) => { }), ); + it.effect("persists a failed provider terminal as one expected error item", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const eventSink = yield* EventSinkV2; + const projectionStore = yield* ProjectionStoreV2; + const ingestor = yield* ProviderEventIngestorV2; + const idAllocator = yield* IdAllocatorV2; + const threadEvent = yield* threadCreatedEvent(now); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: threadEvent.threadId, + }); + const providerThreadId = idAllocator.derive.providerThread({ + driver: CODEX_DRIVER, + nativeThreadId: "native-thread-failed", + }); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-turn-failed", + }); + + yield* eventSink.write({ events: [threadEvent] }); + const stored = yield* ingestor.ingestNormalized({ + providerSessionId, + providerInstanceId: modelSelection.instanceId, + threadId: threadEvent.threadId, + event: { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId, + providerTurnId, + runOrdinal: 1, + failureItemOrdinal: 102, + status: "failed", + failure: makeProviderFailure({ + message: "Invalid reasoning effort.", + code: "invalid_request", + class: "validation_error", + }), + threadDisposition: "reusable", + }, + }); + + const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId); + const errorItems = projection.visibleTurnItems.filter( + (candidate) => candidate.item.type === "error", + ); + + assert.equal(stored.length, 1); + assert.equal(stored[0]?.event.type, "turn-item.updated"); + assert.equal(errorItems.length, 1); + const errorItem = errorItems[0]?.item; + assert.equal(errorItem?.type, "error"); + if (errorItem?.type !== "error") return; + assert.equal(errorItem.failure.message, "Invalid reasoning effort."); + assert.equal(errorItem.failure.code, "invalid_request"); + assert.equal(errorItem.providerThreadId, providerThreadId); + assert.equal(errorItem.providerTurnId, providerTurnId); + }), + ); + it.effect("routes provider-owned child artifacts to their child app thread", () => Effect.gen(function* () { const now = yield* DateTime.now; diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 7f40457c90..91e4a97439 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -3,9 +3,11 @@ import { CommandId, OrchestrationV2DomainEvent, OrchestrationV2StoredEvent, + type OrchestrationV2Run, ProviderInstanceId, ProviderSessionId, RawEventId, + RunAttemptId, RunId, ThreadId, } from "@t3tools/contracts"; @@ -18,6 +20,7 @@ import * as Schema from "effect/Schema"; import { EventSinkV2 } from "./EventSink.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { ProviderAdapterV2Event } from "./ProviderAdapter.ts"; +import { makeProviderFailureTurnItem } from "./ProviderFailure.ts"; export class ProviderEventNormalizeError extends Schema.TaggedErrorClass()( "ProviderEventNormalizeError", @@ -52,27 +55,34 @@ export const ProviderEventIngestorV2Error = Schema.Union([ ]); export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type; +export interface ProviderEventIngestInput { + readonly providerSessionId: ProviderSessionId; + readonly providerInstanceId: ProviderInstanceId; + readonly commandId?: CommandId; + readonly threadId: ThreadId; + readonly runId?: RunId; + readonly nodeId?: NodeId; + readonly rawEventId?: RawEventId; + readonly event: ProviderAdapterV2Event; +} + export interface ProviderEventIngestorV2Shape { - readonly normalize: (input: { - readonly providerSessionId: ProviderSessionId; - readonly providerInstanceId: ProviderInstanceId; - readonly commandId?: CommandId; - readonly threadId: ThreadId; - readonly runId?: RunId; - readonly nodeId?: NodeId; - readonly rawEventId?: RawEventId; - readonly event: ProviderAdapterV2Event; - }) => Effect.Effect, ProviderEventIngestorV2Error>; - readonly ingestNormalized: (input: { - readonly providerSessionId: ProviderSessionId; - readonly providerInstanceId: ProviderInstanceId; - readonly commandId?: CommandId; - readonly threadId: ThreadId; - readonly runId?: RunId; - readonly nodeId?: NodeId; - readonly rawEventId?: RawEventId; - readonly event: ProviderAdapterV2Event; - }) => Effect.Effect, ProviderEventIngestorV2Error>; + readonly normalize: ( + input: ProviderEventIngestInput, + ) => Effect.Effect, ProviderEventIngestorV2Error>; + readonly ingestNormalized: ( + input: ProviderEventIngestInput & { + /** + * Atomically reject mutable provider state emitted by an attempt that + * lost ownership while the adapter event was in flight. + */ + readonly writeIfRunCurrent?: { + readonly runId: RunId; + readonly activeAttemptId: RunAttemptId; + readonly expectedStatus: OrchestrationV2Run["status"]; + }; + }, + ) => Effect.Effect, ProviderEventIngestorV2Error>; } export class ProviderEventIngestorV2 extends Context.Service< @@ -84,6 +94,8 @@ function compactUndefined>(record: T): T { return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T; } +const decodeDomainEvent = Schema.decodeUnknownEffect(OrchestrationV2DomainEvent); + export const layer: Layer.Layer = Layer.effect( ProviderEventIngestorV2, @@ -92,16 +104,7 @@ export const layer: Layer.Layer + new ProviderEventPublishError({ + providerSessionId: input.providerSessionId, + eventCount: events.length, + cause, + }); + if (input.writeIfRunCurrent === undefined) { + return yield* eventSink + .write({ + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + events, + }) + .pipe(Effect.mapError(mapWriteError)); + } + const result = yield* eventSink + .writeIfRunCurrent({ ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + threadId: input.threadId, + ...input.writeIfRunCurrent, events, }) - .pipe( - Effect.mapError( - (cause) => - new ProviderEventPublishError({ - providerSessionId: input.providerSessionId, - eventCount: events.length, - cause, - }), - ), - ); + .pipe(Effect.mapError(mapWriteError)); + return result.storedEvents; }), }); }), diff --git a/apps/server/src/orchestration-v2/ProviderFailure.test.ts b/apps/server/src/orchestration-v2/ProviderFailure.test.ts new file mode 100644 index 0000000000..68cd5e2d22 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderFailure.test.ts @@ -0,0 +1,124 @@ +import { assert, it } from "@effect/vitest"; +import { + NodeId, + ProviderDriverKind, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; + +import { + makeProviderFailure, + makeProviderFailureTurnItem, + MAX_PROVIDER_FAILURE_CODE_LENGTH, + MAX_PROVIDER_FAILURE_MESSAGE_LENGTH, +} from "./ProviderFailure.ts"; +import { IdAllocatorV2, layer as idAllocatorLayer } from "./IdAllocator.ts"; + +it("redacts credentials and URL secrets from provider failures", () => { + const failure = makeProviderFailure({ + message: + 'request failed: Authorization: Bearer bearer-secret https://user:pass@example.test/path?access_token=url-secret#fragment {"token":"json-secret"} api_key=key-secret sk-abcdefghijklmnop', + code: "provider_rejected", + class: "provider_error", + }); + + assert.equal(failure.class, "provider_error"); + assert.equal(failure.code, "provider_rejected"); + assert.include(failure.message, "[REDACTED]"); + assert.include(failure.message, "https://example.test/path"); + assert.notInclude(failure.message, "bearer-secret"); + assert.notInclude(failure.message, "user:pass"); + assert.notInclude(failure.message, "url-secret"); + assert.notInclude(failure.message, "json-secret"); + assert.notInclude(failure.message, "key-secret"); + assert.notInclude(failure.message, "sk-abcdefghijklmnop"); +}); + +it("replaces unsafe control characters without stripping whitespace", () => { + const failure = makeProviderFailure({ message: "before\u0000\u0007\t\nafter\u007f" }); + + assert.equal(failure.message, "before \t\nafter"); +}); + +it("bounds provider-controlled failure strings", () => { + const failure = makeProviderFailure({ + message: "m".repeat(MAX_PROVIDER_FAILURE_MESSAGE_LENGTH + 500), + code: "c".repeat(MAX_PROVIDER_FAILURE_CODE_LENGTH + 50), + }); + + assert.equal(failure.message.length, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH); + assert.equal(failure.code?.length, MAX_PROVIDER_FAILURE_CODE_LENGTH); + assert.match(failure.message, /…$/u); + assert.match(failure.code ?? "", /…$/u); +}); + +it("does not split a surrogate pair at the truncation boundary", () => { + const failure = makeProviderFailure({ + message: `${"a".repeat(MAX_PROVIDER_FAILURE_MESSAGE_LENGTH - 2)}🚀tail`, + }); + + assert.equal(failure.message.length, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH - 1); + assert.equal(failure.message.at(-1), "…"); + assert.notMatch(failure.message.slice(0, -1), /[\uD800-\uDBFF]$/u); +}); + +it("does not serialize arbitrary provider causes", () => { + const failure = makeProviderFailure({ + cause: { + payload: { authorization: "Bearer nested-secret" }, + stack: "private provider stack", + }, + class: "transport_error", + }); + + assert.deepEqual(failure, { + class: "transport_error", + message: "Provider turn failed.", + code: null, + retryable: null, + }); +}); + +it.effect("keys terminal failure items by provider turn across retries and fallback paths", () => + Effect.gen(function* () { + const idAllocator = yield* IdAllocatorV2; + const driver = ProviderDriverKind.make("codex"); + const runId = RunId.make("run:provider-failure-id"); + const base = { + idAllocator, + driver, + threadId: ThreadId.make("thread:provider-failure-id"), + runId, + nodeId: NodeId.make("node:provider-failure-id"), + providerThreadId: ProviderThreadId.make("provider-thread:provider-failure-id"), + itemOrdinal: 101, + failure: makeProviderFailure({ message: "Provider failed" }), + occurredAt: DateTime.makeUnsafe("2026-06-22T12:00:00.000Z"), + } as const; + const firstTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:first"); + const secondTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:second"); + + const firstAttempt = makeProviderFailureTurnItem({ + ...base, + providerTurnId: firstTurnId, + }); + const retriedAttempt = makeProviderFailureTurnItem({ + ...base, + providerTurnId: secondTurnId, + }); + const ingestorFallback = makeProviderFailureTurnItem({ + ...base, + runId: null, + nodeId: null, + providerTurnId: firstTurnId, + }); + + assert.notEqual(firstAttempt.id, retriedAttempt.id); + assert.equal(firstAttempt.id, ingestorFallback.id); + assert.equal(firstAttempt.ordinal, 101); + }).pipe(Effect.provide(idAllocatorLayer)), +); diff --git a/apps/server/src/orchestration-v2/ProviderFailure.ts b/apps/server/src/orchestration-v2/ProviderFailure.ts new file mode 100644 index 0000000000..866d774066 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderFailure.ts @@ -0,0 +1,147 @@ +import type { + NodeId, + OrchestrationV2ProviderFailure, + OrchestrationV2ProviderFailureClass, + OrchestrationV2TurnItem, + ProviderDriverKind, + ProviderThreadId, + ProviderTurnId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import type * as DateTime from "effect/DateTime"; + +import type { IdAllocatorV2Shape } from "./IdAllocator.ts"; + +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."; + +function stringField(value: unknown, key: "message" | "code"): string | undefined { + if (typeof value !== "object" || value === null) return undefined; + try { + const candidate = (value as Record)[key]; + return typeof candidate === "string" ? candidate : undefined; + } catch { + return undefined; + } +} + +function redactUrl(match: string): string { + const trailing = /[),.;!?]+$/u.exec(match)?.[0] ?? ""; + const candidate = trailing.length === 0 ? match : match.slice(0, -trailing.length); + try { + const url = new URL(candidate); + url.username = ""; + url.password = ""; + url.search = ""; + url.hash = ""; + return `${url.toString()}${trailing}`; + } catch { + return "[REDACTED_URL]"; + } +} + +function replaceUnsafeControlCharacters(value: string): string { + const sanitized: Array = []; + for (const character of value) { + const codePoint = character.codePointAt(0) ?? 0; + sanitized.push( + codePoint <= 0x08 || + (codePoint >= 0x0b && codePoint <= 0x0c) || + (codePoint >= 0x0e && codePoint <= 0x1f) || + codePoint === 0x7f + ? " " + : character, + ); + } + return sanitized.join(""); +} + +/** Removes common credential forms before provider text crosses a transport boundary. */ +export function redactProviderFailureText(value: string): string { + return replaceUnsafeControlCharacters(value) + .replace(/\bhttps?:\/\/[^\s<>"']+/giu, redactUrl) + .replace(/\b(Bearer|Basic)\s+[^\s,;]+/giu, "$1 [REDACTED]") + .replace( + /(["'](?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)["']\s*:\s*["'])[^"']*(["'])/giu, + "$1[REDACTED]$2", + ) + .replace( + /(\b(?:access[_-]?token|api[_-]?key|authorization|credential|password|secret|token)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu, + "$1[REDACTED]", + ) + .replace(/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[REDACTED]") + .trim(); +} + +function boundedText(value: string, maxLength: number): string { + const redacted = redactProviderFailureText(value); + if (redacted.length <= maxLength) return redacted; + let end = Math.max(0, maxLength - 1); + const finalCodeUnit = redacted.charCodeAt(end - 1); + if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) { + end -= 1; + } + return `${redacted.slice(0, end)}…`; +} + +export function makeProviderFailure(input: { + readonly cause?: unknown; + readonly message?: string | undefined; + readonly code?: string | null | undefined; + readonly class?: OrchestrationV2ProviderFailureClass; + readonly retryable?: boolean | null; +}): OrchestrationV2ProviderFailure { + const rawMessage = + input.message ?? + (input.cause instanceof Error ? input.cause.message : stringField(input.cause, "message")) ?? + DEFAULT_PROVIDER_FAILURE_MESSAGE; + const message = boundedText(rawMessage, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH); + const rawCode = input.code ?? stringField(input.cause, "code") ?? null; + const code = + rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null; + + return { + class: input.class ?? "unknown", + message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE, + code, + retryable: input.retryable ?? null, + }; +} + +export function makeProviderFailureTurnItem(input: { + readonly idAllocator: IdAllocatorV2Shape; + readonly driver: ProviderDriverKind; + readonly threadId: ThreadId; + readonly runId: RunId | null; + readonly nodeId: NodeId | null; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + readonly itemOrdinal: number; + readonly failure: OrchestrationV2ProviderFailure; + readonly occurredAt: DateTime.Utc; +}): Extract { + return { + id: input.idAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), + threadId: input.threadId, + runId: input.runId, + nodeId: input.nodeId, + providerThreadId: input.providerThreadId, + providerTurnId: input.providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: input.itemOrdinal, + status: "failed", + title: "Provider error", + startedAt: input.occurredAt, + completedAt: input.occurredAt, + updatedAt: input.occurredAt, + type: "error", + failure: input.failure, + }; +} diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index d1434e2ddd..932beec899 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -227,7 +227,8 @@ it.effect("preserves a waiting run while its replay-safe checkpoint capture is u status: "running", }, ] as never), - cancelUnsettled: () => Effect.succeed(0), + cancelUnsettled: () => Effect.succeed([]), + signalCancellations: () => Effect.void, reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }), }), ), @@ -305,6 +306,94 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it" }).pipe(Effect.provide(layer)); }); +it.effect("cancels accepted queued work instead of replaying it after restart", () => { + const threadId = ThreadId.make("thread_queued_restart"); + const runId = RunId.make("run_queued_restart"); + const attemptId = RunAttemptId.make("attempt_queued_restart"); + const rootNodeId = NodeId.make("node_queued_restart"); + let committedInput: Parameters[0] | null = + null; + const projection = { + thread: { id: threadId }, + runtimeRequests: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runs: [ + { + id: runId, + status: "queued", + queuePosition: 1, + providerInstanceId: ProviderInstanceId.make("codex"), + }, + ], + attempts: [ + { + id: attemptId, + runId, + rootNodeId, + status: "pending", + }, + ], + nodes: [ + { + id: rootNodeId, + runId, + status: "pending", + }, + ], + subagents: [], + messages: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection; + const layer = ProviderRuntimeRecovery.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 2, + snapshotSequence: 0, + threads: [{ id: threadId }], + archivedThreads: [], + } as never), + getThreadProjection: () => Effect.succeed(projection), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => { + committedInput = input; + return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never); + }, + }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), + }), + ), + ), + ); + + return Effect.gen(function* () { + const summary = + yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup"); + assert.equal(summary.terminalizedRuns, 1); + const command = committedInput; + assert.isNotNull(command); + if (command === null) return; + const runEvent = command.events.find((event) => event.type === "run.updated"); + const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated"); + const nodeEvent = command.events.find((event) => event.type === "node.updated"); + assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled"); + assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : 1, null); + assert.equal( + attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null, + "cancelled", + ); + assert.equal(nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null, "cancelled"); + }).pipe(Effect.provide(layer)); +}); + it.effect( "cancels the complete in-flight subtree and stops its persisted session without reopening it", () => { diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 576ea35ee5..5dadaa7b01 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -57,9 +57,16 @@ export class ProviderRuntimeRecoveryService extends Context.Service< >()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {} function nonterminalRuns(projection: OrchestrationV2ThreadProjection) { - return projection.runs.filter( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", - ); + return projection.runs.filter((run) => { + const status: string = run.status; + return ( + run.status === "queued" || + status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting" + ); + }); } export const make = Effect.gen(function* () { @@ -277,7 +284,7 @@ export const make = Effect.gen(function* () { ).length; let retiredEffects: number; if (events.length === 0) { - retiredEffects = yield* outbox + const retiredEffectIds = yield* outbox .cancelUnsettled({ threadId: projection.thread.id, effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES, @@ -293,6 +300,8 @@ export const make = Effect.gen(function* () { }), ), ); + yield* outbox.signalCancellations(retiredEffectIds); + retiredEffects = retiredEffectIds.length; } else { const result = yield* eventSink .commitCommand({ diff --git a/apps/server/src/orchestration-v2/ProviderSelectionTransition.test.ts b/apps/server/src/orchestration-v2/ProviderSelectionTransition.test.ts new file mode 100644 index 0000000000..ee8114b693 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderSelectionTransition.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; + +import { + type ModelSelection, + type OrchestrationV2ProviderCapabilities, + ProviderInstanceId, +} from "@t3tools/contracts"; + +import { AcpProviderCapabilitiesV2 } from "./Adapters/AcpAdapterV2.ts"; +import { acpSelectionTransition } from "./ProviderSelectionTransition.ts"; + +const selection = (model: string, effort = "medium"): ModelSelection => ({ + instanceId: ProviderInstanceId.make("acp_test"), + model, + options: [{ id: "effort", value: effort }], +}); + +describe("acpSelectionTransition", () => { + it("rejects model changes when the negotiated session cannot apply them", () => { + expect( + acpSelectionTransition({ + current: selection("old"), + target: selection("new"), + sessionCapabilities: AcpProviderCapabilitiesV2, + }).type, + ).toBe("reject"); + }); + + it("allows model changes when the negotiated session can apply them", () => { + const sessionCapabilities: OrchestrationV2ProviderCapabilities = { + ...AcpProviderCapabilitiesV2, + sessions: { + ...AcpProviderCapabilitiesV2.sessions, + supportsModelSwitchInSession: true, + }, + }; + expect( + acpSelectionTransition({ + current: selection("old"), + target: selection("new"), + sessionCapabilities, + }), + ).toEqual({ type: "apply_on_next_turn" }); + }); + + it("allows option-only changes to be applied through ACP config options", () => { + expect( + acpSelectionTransition({ + current: selection("same", "medium"), + target: selection("same", "high"), + sessionCapabilities: AcpProviderCapabilitiesV2, + }), + ).toEqual({ type: "apply_on_next_turn" }); + }); +}); diff --git a/apps/server/src/orchestration-v2/ProviderSelectionTransition.ts b/apps/server/src/orchestration-v2/ProviderSelectionTransition.ts new file mode 100644 index 0000000000..d4ca82d314 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderSelectionTransition.ts @@ -0,0 +1,37 @@ +import type { ModelSelection, OrchestrationV2ProviderCapabilities } from "@t3tools/contracts"; + +export interface ProviderSelectionTransitionInput { + readonly current: ModelSelection; + readonly target: ModelSelection; + readonly sessionCapabilities: OrchestrationV2ProviderCapabilities; +} + +/** + * Provider-owned classification of how a complete selection can be applied. + * The orchestrator remains responsible for attempts and resource lifecycle. + */ +export type ProviderSelectionTransitionPlan = + | { readonly type: "apply_on_next_turn" } + | { readonly type: "restart_session" } + | { readonly type: "create_with_handoff" } + | { readonly type: "reject"; readonly reason: string }; + +export function turnScopedSelectionTransition(): ProviderSelectionTransitionPlan { + return { type: "apply_on_next_turn" }; +} + +/** ACP models require a negotiated model/config mutation capability. */ +export function acpSelectionTransition( + input: ProviderSelectionTransitionInput, +): ProviderSelectionTransitionPlan { + if ( + input.current.model !== input.target.model && + !input.sessionCapabilities.sessions.supportsModelSwitchInSession + ) { + return { + type: "reject", + reason: "The active ACP session does not expose a model-switch capability.", + }; + } + return { type: "apply_on_next_turn" }; +} diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 7e36efff7d..31a1603b34 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -14,7 +14,9 @@ import { ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -227,14 +229,21 @@ function makeProviderAdapter( readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly beforeOpen?: (input: { + readonly providerSessionId: ProviderSessionId; + }) => Effect.Effect; } = {}, ): ProviderAdapterV2Shape { return { instanceId: ProviderInstanceId.make("codex"), driver: CODEX_DRIVER, getCapabilities: () => Effect.succeed(options.capabilities ?? CodexCapabilities), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (input) => Effect.gen(function* () { + if (options.beforeOpen !== undefined) { + yield* options.beforeOpen({ providerSessionId: input.providerSessionId }); + } if (options.mcpConfigs !== undefined) { yield* Ref.update(options.mcpConfigs, (configs) => [ ...configs, @@ -269,7 +278,6 @@ function makeProviderAdapter( driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, providerSession: session, - rawEvents: Stream.empty, events: options.failEventStream ? Stream.fail( new ProviderAdapterEventStreamError({ @@ -309,6 +317,9 @@ function makeTestLayer(input: { readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly beforeOpen?: (input: { + readonly providerSessionId: ProviderSessionId; + }) => Effect.Effect; readonly failReleaseEventWrites?: boolean; }) { const configuredEventSinkLayer = input.failReleaseEventWrites @@ -319,6 +330,7 @@ function makeTestLayer(input: { failEventStream: input.failEventStream ?? false, ...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }), ...(input.mcpConfigs === undefined ? {} : { mcpConfigs: input.mcpConfigs }), + ...(input.beforeOpen === undefined ? {} : { beforeOpen: input.beforeOpen }), }), ); return Layer.mergeAll( @@ -467,6 +479,143 @@ function makePendingRuntimeRequestEvents(input: { }); } +it.effect("ProviderSessionManagerV2 opens independent sessions concurrently", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const openStartedCount = yield* Ref.make(0); + const firstOpenStarted = yield* Deferred.make(); + const secondOpenStarted = yield* Deferred.make(); + const releaseOpens = yield* Deferred.make(); + const beforeOpen = () => + Effect.gen(function* () { + const openNumber = yield* Ref.modify(openStartedCount, (count) => [count + 1, count + 1]); + yield* Deferred.succeed(openNumber === 1 ? firstOpenStarted : secondOpenStarted, undefined); + yield* Deferred.await(releaseOpens); + }); + + const effect = Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const manager = yield* ProviderSessionManagerV2; + const now = yield* DateTime.now; + const firstThreadId = ThreadId.make("thread-provider-session-manager-concurrent-a"); + const secondThreadId = ThreadId.make("thread-provider-session-manager-concurrent-b"); + const firstProviderSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: firstThreadId, + }); + const secondProviderSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: secondThreadId, + }); + + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: firstThreadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: secondThreadId, now }), + ], + }); + const firstFiber = yield* manager + .open({ + threadId: firstThreadId, + providerSessionId: firstProviderSessionId, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(firstOpenStarted); + const secondFiber = yield* manager + .open({ + threadId: secondThreadId, + providerSessionId: secondProviderSessionId, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.forkScoped); + + yield* Deferred.await(secondOpenStarted); + assert.equal(yield* Ref.get(openStartedCount), 2); + yield* Deferred.succeed(releaseOpens, undefined); + const [firstRuntime, secondRuntime] = yield* Effect.all([ + Fiber.join(firstFiber), + Fiber.join(secondFiber), + ]); + assert.notStrictEqual(firstRuntime, secondRuntime); + assert.equal((yield* Ref.get(state)).openCount, 2); + }); + + yield* effect.pipe( + Effect.provide( + makeTestLayer({ + state, + idleTimeoutMs: 60_000, + beforeOpen, + }), + ), + ); + }), +); + +it.effect("ProviderSessionManagerV2 opens a duplicate session only once", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const openStartedCount = yield* Ref.make(0); + const firstOpenStarted = yield* Deferred.make(); + const releaseOpen = yield* Deferred.make(); + const beforeOpen = () => + Ref.updateAndGet(openStartedCount, (count) => count + 1).pipe( + Effect.tap(() => Deferred.succeed(firstOpenStarted, undefined)), + Effect.andThen(Deferred.await(releaseOpen)), + ); + + const effect = Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const manager = yield* ProviderSessionManagerV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-single-flight"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const open = manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const firstFiber = yield* open.pipe(Effect.forkScoped); + yield* Deferred.await(firstOpenStarted); + const secondFiber = yield* open.pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + assert.equal(yield* Ref.get(openStartedCount), 1); + + yield* Deferred.succeed(releaseOpen, undefined); + const [firstRuntime, secondRuntime] = yield* Effect.all([ + Fiber.join(firstFiber), + Fiber.join(secondFiber), + ]); + assert.strictEqual(firstRuntime, secondRuntime); + assert.equal((yield* Ref.get(state)).openCount, 1); + }); + + yield* effect.pipe( + Effect.provide( + makeTestLayer({ + state, + idleTimeoutMs: 60_000, + beforeOpen, + }), + ), + ); + }), +); + it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts down", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); @@ -661,6 +810,76 @@ it.effect("ProviderSessionManagerV2 revokes MCP credentials when release persist }), ); +it.effect("ProviderSessionManagerV2 duplicate detach preserves replacement MCP credentials", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const mcpConfigs = yield* Ref.make< + ReadonlyArray + >([]); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const manager = yield* ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-replacement-mcp"); + const oldSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const replacementSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + yield* manager.open({ + threadId, + providerSessionId: oldSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.detach({ providerSessionId: oldSessionId, threadId }); + yield* manager.open({ + threadId, + providerSessionId: replacementSessionId, + modelSelection, + runtimePolicy, + }); + + const replacement = (yield* Ref.get(mcpConfigs)).at(-1); + assert.isDefined(replacement); + const replacementToken = replacement?.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.isDefined(replacementToken); + assert.equal( + McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId, + replacement?.providerSessionId, + ); + + yield* manager.detach({ providerSessionId: oldSessionId, threadId }); + + assert.equal( + McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId, + replacement?.providerSessionId, + ); + assert.equal((yield* registry.resolve(replacementToken!))?.threadId, threadId); + }); + + yield* effect.pipe( + Effect.provide( + makeTestLayer({ + state, + idleTimeoutMs: 1_000, + capabilities: ExclusiveCapabilities, + mcpConfigs, + }), + ), + ); + }), +); + it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all sessions", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); @@ -785,8 +1004,12 @@ it.effect( yield* Queue.offer(queue!, { type: "turn.terminal", driver: CODEX_DRIVER, + providerThreadId: providerThread.id, providerTurnId, + runOrdinal: 1, status: "completed", + failure: null, + threadDisposition: "reusable", }); yield* TestClock.adjust("1 second"); yield* Effect.yieldNow; @@ -1091,8 +1314,12 @@ it.effect( yield* Queue.offer(queue!, { type: "turn.terminal", driver: CODEX_DRIVER, + providerThreadId: firstProviderThread.id, providerTurnId: firstProviderTurnId, + runOrdinal: 1, status: "completed", + failure: null, + threadDisposition: "reusable", }); yield* TestClock.adjust("2 seconds"); yield* Effect.yieldNow; @@ -1101,8 +1328,12 @@ it.effect( yield* Queue.offer(queue!, { type: "turn.terminal", driver: CODEX_DRIVER, + providerThreadId: secondProviderThread.id, providerTurnId: secondProviderTurnId, + runOrdinal: 1, status: "completed", + failure: null, + threadDisposition: "reusable", }); yield* TestClock.adjust("1 second"); yield* Effect.yieldNow; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index ec24038e0b..9c9b9a11fe 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -21,13 +21,13 @@ import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as McpProviderSession from "../mcp/McpProviderSession.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import { EventSinkV2 } from "./EventSink.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; +import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts"; import { ProviderAdapterEventStreamError, ProviderAdapterV2RuntimePolicy, @@ -250,7 +250,7 @@ export const layerWithOptions = ( const layerScope = yield* Effect.scope; const sessions = yield* Ref.make(new Map()); const nextSubscriberId = yield* Ref.make(0); - const openSemaphore = yield* Semaphore.make(1); + const sessionOpen = yield* makeKeyedSerialExecutor(); const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS); const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => options.configureMcp === false @@ -1071,7 +1071,8 @@ export const layerWithOptions = ( return ProviderSessionManagerV2.of({ shutdown, open: (input) => - openSemaphore.withPermit( + sessionOpen.withLock( + input.providerSessionId, Effect.gen(function* () { const key = sessionKey(input.providerSessionId); const existing = (yield* Ref.get(sessions)).get(key); @@ -1271,10 +1272,13 @@ export const layerWithOptions = ( updated.set(key, updatedEntry); return [Option.some(updatedEntry), updated] as const; }); - yield* clearMcpSession(input.threadId); if (Option.isNone(detached)) { return; } + // Detach effects are retried. Once the old entry is gone, its + // retry must not revoke credentials issued by a replacement + // session for the same app thread. + yield* clearMcpSession(input.threadId); if ( detached.value.attachedThreadIds.size === 0 && !detached.value.supportsMultipleProviderThreads diff --git a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts index 85da958523..af30203605 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts @@ -26,7 +26,7 @@ it("reuses compatible sessions and treats interaction mode as turn-scoped", () = ); }); -it("switches models in-session only when supported", () => { +it("uses the adapter's selection transition classification", () => { assert.deepEqual( decideProviderSessionTransition({ current: base, @@ -35,6 +35,7 @@ it("switches models in-session only when supported", () => { modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" }, available: true, }, + selectionTransition: { type: "apply_on_next_turn" }, }), { type: "switch_model_in_session" }, ); @@ -56,11 +57,36 @@ it("switches models in-session only when supported", () => { modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" }, available: true, }, + selectionTransition: { type: "restart_session" }, }), { type: "restart_and_resume" }, ); }); +it("treats provider option changes as selection changes", () => { + assert.deepEqual( + decideProviderSessionTransition({ + current: { + ...base, + modelSelection: { + ...base.modelSelection, + options: [{ id: "reasoningEffort", value: "medium" }], + }, + }, + target: { + ...base, + modelSelection: { + ...base.modelSelection, + options: [{ id: "reasoningEffort", value: "high" }], + }, + available: true, + }, + selectionTransition: { type: "apply_on_next_turn" }, + }), + { type: "switch_model_in_session" }, + ); +}); + it("restarts compatible instances for workspace or runtime changes", () => { assert.deepEqual( decideProviderSessionTransition({ diff --git a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.ts b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.ts index 2415f2de8e..4d13d27a4f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.ts @@ -5,8 +5,10 @@ import type { ProviderInteractionMode, RuntimeMode, } from "@t3tools/contracts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; import type { ProviderContinuationIdentity } from "../provider/ProviderDriver.ts"; +import type { ProviderSelectionTransitionPlan } from "./ProviderSelectionTransition.ts"; export type ProviderSessionTransition = | { readonly type: "reuse" } @@ -32,6 +34,7 @@ export interface ProviderSessionTransitionTarget extends ProviderSessionTransiti export function decideProviderSessionTransition(input: { readonly current: ProviderSessionTransitionState | null; readonly target: ProviderSessionTransitionTarget; + readonly selectionTransition?: ProviderSelectionTransitionPlan; }): ProviderSessionTransition { if (!input.target.available) { return { type: "reject", reason: "The target provider instance is unavailable." }; @@ -56,11 +59,23 @@ export function decideProviderSessionTransition(input: { return { type: "restart_and_resume" }; } - const modelChanged = current.modelSelection.model !== target.modelSelection.model; - if (modelChanged) { - return target.capabilities.sessions.supportsModelSwitchInSession - ? { type: "switch_model_in_session" } - : { type: "restart_and_resume" }; + const selectionChanged = !modelSelectionsEqual(current.modelSelection, target.modelSelection); + if (selectionChanged) { + switch (input.selectionTransition?.type) { + case "apply_on_next_turn": + return { type: "switch_model_in_session" }; + case "restart_session": + return { type: "restart_and_resume" }; + case "create_with_handoff": + return { type: "create_with_handoff" }; + case "reject": + return { type: "reject", reason: input.selectionTransition.reason }; + case undefined: + return { + type: "reject", + reason: "The provider adapter did not classify the selection change.", + }; + } } // Interaction mode is turn-scoped and is applied when the next turn starts. diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts index 1e361ecc88..35bc1b8036 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts @@ -11,6 +11,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProviderSwitch from "./ProviderSwitchService.ts"; @@ -50,7 +51,21 @@ function projection(): OrchestrationV2ThreadProjection { } function testLayer(metadata: Readonly>) { + const adapter = (instanceId: ProviderInstanceId): ProviderAdapterV2Shape => ({ + instanceId, + driver, + getCapabilities: () => Effect.succeed(capabilitiesWithoutModelSwitch), + planSelectionTransition: () => Effect.succeed({ type: "restart_session" }), + openSession: () => Effect.die("ProviderSwitchService tests do not open sessions."), + }); const registry = Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + get: (instanceId) => + metadata[instanceId] === undefined + ? Effect.fail( + new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }), + ) + : Effect.succeed(adapter(instanceId)), + list: () => Effect.succeed(Object.keys(metadata).map((id) => ProviderInstanceId.make(id))), getMetadata: (instanceId) => { const value = metadata[instanceId]; return value === undefined diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts index 87d7eb6a3c..669c4b3728 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts @@ -5,6 +5,7 @@ import { ProviderThreadId, ThreadId, } from "@t3tools/contracts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -78,50 +79,64 @@ export const layer: Layer.Layer< ); const currentInstance = yield* Effect.option(getMetadata(current.instanceId)); const targetInstance = yield* Effect.option(getMetadata(targetModelSelection.instanceId)); + const targetAdapter = yield* Effect.option(adapters.get(targetModelSelection.instanceId)); const currentSession = projection.providerSessions .filter((session) => session.providerInstanceId === current.instanceId) .toSorted( (left, right) => DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), )[0]; - const transition = Option.isNone(targetInstance) - ? ({ - type: "reject", - reason: "The target provider instance is unavailable.", - } as const) - : decideProviderSessionTransition({ - current: - Option.isNone(currentInstance) || currentSession === undefined - ? null - : { - driver: currentInstance.value.driver, - continuationIdentity: { - driverKind: currentInstance.value.driver, - continuationKey: currentInstance.value.continuationKey, + const selectionTransition = + current.instanceId === targetModelSelection.instanceId && + !modelSelectionsEqual(current, targetModelSelection) && + Option.isSome(targetAdapter) && + currentSession !== undefined + ? yield* targetAdapter.value.planSelectionTransition({ + current, + target: targetModelSelection, + sessionCapabilities: currentSession.capabilities, + }) + : undefined; + const transition = + Option.isNone(targetInstance) || Option.isNone(targetAdapter) + ? ({ + type: "reject", + reason: "The target provider instance is unavailable.", + } as const) + : decideProviderSessionTransition({ + current: + Option.isNone(currentInstance) || currentSession === undefined + ? null + : { + driver: currentInstance.value.driver, + continuationIdentity: { + driverKind: currentInstance.value.driver, + continuationKey: currentInstance.value.continuationKey, + }, + modelSelection: current, + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + workspace: currentSession.cwd, + capabilities: currentSession.capabilities, }, - modelSelection: current, - runtimeMode: projection.thread.runtimeMode, - interactionMode: projection.thread.interactionMode, - workspace: currentSession.cwd, - capabilities: currentSession.capabilities, - }, - target: { - driver: targetInstance.value.driver, - continuationIdentity: { - driverKind: targetInstance.value.driver, - continuationKey: targetInstance.value.continuationKey, + target: { + driver: targetInstance.value.driver, + continuationIdentity: { + driverKind: targetInstance.value.driver, + continuationKey: targetInstance.value.continuationKey, + }, + modelSelection: targetModelSelection, + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + workspace: + projection.thread.worktreePath ?? + currentSession?.cwd ?? + "", + capabilities: targetInstance.value.capabilities, + available: targetInstance.value.enabled, }, - modelSelection: targetModelSelection, - runtimeMode: projection.thread.runtimeMode, - interactionMode: projection.thread.interactionMode, - workspace: - projection.thread.worktreePath ?? - currentSession?.cwd ?? - "", - capabilities: targetInstance.value.capabilities, - available: targetInstance.value.enabled, - }, - }); + ...(selectionTransition === undefined ? {} : { selectionTransition }), + }); if (transition.type === "reject") { return yield* new ProviderSwitchPlanError({ threadId: projection.thread.id, diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts new file mode 100644 index 0000000000..dc5e7232c9 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -0,0 +1,282 @@ +import { assert, it } from "@effect/vitest"; +import { + type ModelSelection, + NodeId, + type OrchestrationV2ProviderThread, + type OrchestrationV2ThreadProjection, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; + +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import type { ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { + layer as providerTurnControlLayer, + ProviderTurnControlServiceV2, +} from "./ProviderTurnControlService.ts"; + +const driver = ProviderDriverKind.make("codex"); +const providerInstanceId = ProviderInstanceId.make("codex"); +const modelSelection = { + instanceId: providerInstanceId, + model: "gpt-5.4", +} satisfies ModelSelection; + +function makeProjection(input: { + readonly now: DateTime.Utc; + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly providerTurnId: ProviderTurnId; + readonly attemptId: RunAttemptId; +}): OrchestrationV2ThreadProjection { + const runId = RunId.make("run:restart-session"); + const nodeId = NodeId.make("node:restart-session"); + return { + thread: { + createdBy: "user", + creationSource: "web", + id: input.threadId, + projectId: ProjectId.make("project:restart-session"), + title: "Restart session", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: "/workspace", + activeProviderThreadId: input.providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: input.threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [ + { + id: input.attemptId, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId: input.providerThread.id, + providerTurnId: input.providerTurnId, + reason: "initial", + status: "superseded", + startedAt: input.now, + completedAt: input.now, + }, + ], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [input.providerThread], + providerTurns: [ + { + id: input.providerTurnId, + providerThreadId: input.providerThread.id, + nodeId, + runAttemptId: input.attemptId, + nativeTurnRef: { + driver, + nativeId: "native-turn:restart-session", + strength: "strong", + }, + ordinal: 1, + status: "running", + startedAt: input.now, + completedAt: null, + }, + ], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: input.now, + }; +} + +it.effect( + "interrupts the historical session only for the exact committed restart replacement", + () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:restart-session"); + const oldSessionId = ProviderSessionId.make("provider-session:restart-session:old"); + const replacementSessionId = ProviderSessionId.make( + "provider-session:restart-session:replacement", + ); + const unrelatedSessionId = ProviderSessionId.make( + "provider-session:restart-session:unrelated", + ); + const providerThreadId = ProviderThreadId.make("provider-thread:restart-session"); + const providerTurnId = ProviderTurnId.make("provider-turn:restart-session"); + const attemptId = RunAttemptId.make("run-attempt:restart-session"); + const providerThread: OrchestrationV2ProviderThread = { + id: providerThreadId, + driver, + providerInstanceId, + // The restart command has already projected this replacement binding + // before the process-bound restart effect executes. + providerSessionId: replacementSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { + driver, + nativeId: "native-thread:restart-session", + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const projection = yield* Ref.make( + makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }), + ); + const interruptedThread = yield* Ref.make(null); + const providerSession = { + id: oldSessionId, + driver, + providerInstanceId, + status: "running" as const, + cwd: "/workspace", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }; + const runtime: ProviderAdapterV2SessionRuntime = { + instanceId: providerInstanceId, + driver, + providerSessionId: oldSessionId, + providerSession, + events: Stream.empty, + ensureThread: () => Effect.die("unused ensureThread"), + resumeThread: () => Effect.die("unused resumeThread"), + startTurn: () => Effect.die("unused startTurn"), + steerTurn: () => Effect.die("unused steerTurn"), + interruptTurn: ({ providerThread: target }) => + Effect.all( + [ + Ref.set(interruptedThread, target), + Ref.update(projection, (current) => ({ + ...current, + providerTurns: current.providerTurns.map((turn) => + turn.id === providerTurnId + ? { ...turn, status: "interrupted" as const, completedAt: now } + : turn, + ), + })), + ], + { discard: true }, + ), + respondToRuntimeRequest: () => Effect.die("unused respondToRuntimeRequest"), + readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"), + rollbackThread: () => Effect.die("unused rollbackThread"), + forkThread: () => Effect.die("unused forkThread"), + }; + const projectionLayer = Layer.succeed( + ProjectionStoreV2, + ProjectionStoreV2.of({ + apply: () => Effect.void, + getShellSnapshot: () => Effect.die("unused getShellSnapshot"), + getThreadProjection: () => Ref.get(projection), + getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"), + }), + ); + const sessionManagerLayer = Layer.succeed( + ProviderSessionManagerV2, + ProviderSessionManagerV2.of({ + shutdown: Effect.void, + open: () => Effect.die("unused open"), + get: (providerSessionId) => + Effect.succeed( + providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(), + ), + close: () => Effect.void, + release: () => Effect.void, + detach: () => Effect.void, + }), + ); + const controlLayer = providerTurnControlLayer.pipe( + Layer.provide(Layer.merge(projectionLayer, sessionManagerLayer)), + ); + + const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () { + const control = yield* ProviderTurnControlServiceV2; + const ordinary = yield* Effect.exit( + control.interrupt({ + threadId, + providerSessionId: oldSessionId, + providerThreadId, + providerTurnId, + }), + ); + const unrelated = yield* Effect.exit( + control.interruptAndAwaitTerminal({ + threadId, + providerSessionId: oldSessionId, + replacementProviderSessionId: unrelatedSessionId, + providerThreadId, + providerTurnId, + interruptedAttemptId: attemptId, + }), + ); + return [ordinary, unrelated] as const; + }).pipe(Effect.provide(controlLayer)); + + assert.isTrue(Exit.isFailure(ordinaryInterrupt)); + assert.isTrue(Exit.isFailure(unrelatedRestart)); + assert.isNull(yield* Ref.get(interruptedThread)); + + yield* Effect.gen(function* () { + const control = yield* ProviderTurnControlServiceV2; + yield* control.interruptAndAwaitTerminal({ + threadId, + providerSessionId: oldSessionId, + replacementProviderSessionId: replacementSessionId, + providerThreadId, + providerTurnId, + interruptedAttemptId: attemptId, + }); + }).pipe(Effect.provide(controlLayer)); + + const interrupted = yield* Ref.get(interruptedThread); + assert.isNotNull(interrupted); + assert.equal(interrupted?.providerSessionId, oldSessionId); + assert.equal(interrupted?.id, providerThreadId); + assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session"); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 87b7df5438..4ee7164261 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -36,6 +36,8 @@ export class ProviderTurnControlError extends Schema.TaggedErrorClass candidate.id === input.providerTurnId, ); + const targetsRecordedSession = + providerThread?.providerSessionId === input.providerSessionId; + const targetsCommittedReplacement = + input.operation === "restart" && + input.replacementProviderSessionId !== undefined && + providerThread?.providerSessionId === input.replacementProviderSessionId; if ( providerThread === undefined || providerTurn === undefined || - providerThread.providerSessionId !== input.providerSessionId || + (!targetsRecordedSession && !targetsCommittedReplacement) || providerTurn.providerThreadId !== providerThread.id ) { return yield* new ProviderTurnControlError({ @@ -102,8 +112,20 @@ export const layer: Layer.Layer< cause: "The recorded provider execution target is no longer valid.", }); } + // A restart-session command commits the replacement binding before its + // process-bound effect runs. The old live runtime must still receive + // the interrupt, but only when the projection matches the exact + // replacement captured by that same durable effect. + const interruptProviderThread = targetsRecordedSession + ? providerThread + : { ...providerThread, providerSessionId: input.providerSessionId }; if (providerTurn.status !== "running") { - return { projection, providerThread, providerTurn, session: Option.none() }; + return { + projection, + providerThread: interruptProviderThread, + providerTurn, + session: Option.none(), + }; } const session = yield* sessions.get(input.providerSessionId); if (Option.isNone(session)) { @@ -114,7 +136,7 @@ export const layer: Layer.Layer< cause: `Provider session ${input.providerSessionId} is not active.`, }); } - return { projection, providerThread, providerTurn, session }; + return { projection, providerThread: interruptProviderThread, providerTurn, session }; }); return ProviderTurnControlServiceV2.of({ @@ -128,7 +150,7 @@ export const layer: Layer.Layer< }); }).pipe( Effect.mapError((cause) => - Schema.is(ProviderTurnControlError)(cause) + isProviderTurnControlError(cause) ? cause : new ProviderTurnControlError({ threadId: input.threadId, @@ -178,7 +200,7 @@ export const layer: Layer.Layer< }); }).pipe( Effect.mapError((cause) => - Schema.is(ProviderTurnControlError)(cause) + isProviderTurnControlError(cause) ? cause : new ProviderTurnControlError({ threadId: input.threadId, @@ -221,7 +243,7 @@ export const layer: Layer.Layer< }); }).pipe( Effect.mapError((cause) => - Schema.is(ProviderTurnControlError)(cause) + isProviderTurnControlError(cause) ? cause : new ProviderTurnControlError({ threadId: input.threadId, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index b395a6ac0e..b8bd2b2fe8 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -33,6 +33,8 @@ export class ProviderTurnStartError extends Schema.TaggedErrorClass => + projectionStore.getThreadProjection(projection.thread.id).pipe( + Effect.map((current) => { + const currentRun = current.runs.find((candidate) => candidate.id === run.id); + return ( + currentRun?.activeAttemptId === attempt.id && currentRun.status === expectedStatus + ); + }), + Effect.catchCause(() => Effect.succeed(false)), + ); const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ thread: projection.thread, @@ -265,6 +279,9 @@ export const layer: Layer.Layer< }); return replacement; }); + if (!(yield* isCurrentAttemptInStatus("starting"))) { + return; + } const now = yield* DateTime.now; const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, @@ -376,7 +393,16 @@ export const layer: Layer.Layer< payload: runningRootNode, }, ]; - yield* eventSink.write({ events }); + const runningWrite = yield* eventSink.writeIfRunCurrent({ + threadId: projection.thread.id, + runId: run.id, + activeAttemptId: attempt.id, + expectedStatus: "starting", + events, + }); + if (!runningWrite.committed) { + return; + } yield* runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, @@ -401,6 +427,7 @@ export const layer: Layer.Layer< .filter((turn) => turn.providerThreadId === providerThread.id) .map((turn) => turn.ordinal), ) + 1, + shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"), shouldFinalizeRun: () => projectionStore.getThreadProjection(projection.thread.id).pipe( Effect.map((current) => { @@ -434,7 +461,7 @@ export const layer: Layer.Layer< start: (input) => start(input).pipe( Effect.mapError((cause) => - Schema.is(ProviderTurnStartError)(cause) + isProviderTurnStartError(cause) ? cause : new ProviderTurnStartError({ runId: input.runId, cause }), ), diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index c888fda230..cd9f177ea4 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -1,8 +1,18 @@ import { assert, it } from "@effect/vitest"; import { + CheckpointScopeId, + CommandId, MessageId, NodeId, + type OrchestrationV2AppThread, + type OrchestrationV2CheckpointScope, + type OrchestrationV2ExecutionNode, + type OrchestrationV2ProviderThread, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, ProviderThreadId, ProviderTurnId, RunAttemptId, @@ -11,16 +21,44 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; -import type { ProviderAdapterV2Event } from "./ProviderAdapter.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { CheckpointServiceV2 } from "./CheckpointService.ts"; +import { EventSinkV2 } from "./EventSink.ts"; +import { layer as idAllocatorLayer } from "./IdAllocator.ts"; +import type { ProviderAdapterV2Event, ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts"; +import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts"; import { + finalProviderThreadStatus, + layer as runExecutionServiceLayer, makeProviderEventRoutingState, type ProviderEventRouteIdentity, routeProviderEvent, + RunExecutionServiceV2, } from "./RunExecutionService.ts"; const driver = ProviderDriverKind.make("codex"); +const RunExecutionTestLayer = runExecutionServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }), + Layer.mock(EventSinkV2)({}), + idAllocatorLayer, + Layer.mock(ProviderEventIngestorV2)({ ingestNormalized: () => Effect.succeed([]) }), + ServerSettingsService.layerTest(), + ), + ), +); + +it("keeps recoverable turn failures reusable and reserves error for broken threads", () => { + assert.equal(finalProviderThreadStatus("reusable"), "idle"); + assert.equal(finalProviderThreadStatus("broken"), "error"); +}); + it.effect("routes shared-runtime events only to their owning root run", () => Effect.gen(function* () { const now = yield* DateTime.now; @@ -74,8 +112,12 @@ it.effect("routes shared-runtime events only to their owning root run", () => const terminalEvent: ProviderAdapterV2Event = { type: "turn.terminal", driver, + providerThreadId: first.providerThreadId, providerTurnId: firstTurnId, + runOrdinal: 1, status: "completed", + failure: null, + threadDisposition: "reusable", }; const firstInitial = makeProviderEventRoutingState({ @@ -135,3 +177,77 @@ it("does not route a superseded attempt through a reused provider thread", () => const newState = makeProviderEventRoutingState({ identity: newAttempt, providerTurnId: null }); assert.isFalse(routeProviderEvent(oldTurnEvent, newAttempt, newState)[0]); }); + +it.effect("rechecks run ownership immediately before calling the provider", () => + Effect.gen(function* () { + const runExecution = yield* RunExecutionServiceV2; + const guardCalls = yield* Ref.make(0); + const providerStarts = yield* Ref.make(0); + const threadId = ThreadId.make("thread:run-execution-start-guard"); + const runId = RunId.make("run:run-execution-start-guard"); + const attemptId = RunAttemptId.make("attempt:run-execution-start-guard"); + const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-start-guard"); + const providerInstanceId = ProviderInstanceId.make("codex"); + const providerSessionId = ProviderSessionId.make("session:run-execution-start-guard"); + const rootNodeId = NodeId.make("node:run-execution-start-guard"); + const run = { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + } as OrchestrationV2Run; + const rootNode = { id: rootNodeId } as OrchestrationV2ExecutionNode; + const providerThread = { + id: providerThreadId, + driver, + } as OrchestrationV2ProviderThread; + const attempt = { + id: attemptId, + providerTurnId: null, + } as OrchestrationV2RunAttempt; + const session = { + events: Stream.never, + startTurn: () => Ref.update(providerStarts, (count) => count + 1), + } as unknown as ProviderAdapterV2SessionRuntime; + + yield* runExecution.startRootRun({ + commandId: CommandId.make("command:run-execution-start-guard"), + appThread: { id: threadId } as OrchestrationV2AppThread, + providerSessionId, + session, + run, + rootNode, + checkpointScope: { + id: CheckpointScopeId.make("checkpoint-scope:run-execution-start-guard"), + } as OrchestrationV2CheckpointScope, + providerThread, + attempt, + attemptId, + providerTurnOrdinal: 1, + shouldStartProviderTurn: () => + Ref.modify(guardCalls, (calls) => [calls === 0, calls + 1] as const), + message: { + messageId: MessageId.make("message:run-execution-start-guard"), + text: "Do not start after ownership changes.", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }); + + assert.equal(yield* Ref.get(guardCalls), 2); + assert.equal(yield* Ref.get(providerStarts), 0); + }).pipe(Effect.provide(RunExecutionTestLayer)), +); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index a2e00a2fb1..4010f5f151 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -4,6 +4,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, type OrchestrationV2ExecutionNode, + type OrchestrationV2ProviderFailure, type OrchestrationV2ProviderThread, type OrchestrationV2Run, type OrchestrationV2RunAttempt, @@ -15,6 +16,7 @@ import { type ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -34,6 +36,7 @@ import type { ProviderAdapterV2TurnMessage, } from "./ProviderAdapter.ts"; import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts"; +import { makeProviderFailure, makeProviderFailureTurnItem } from "./ProviderFailure.ts"; export interface ProviderEventRoutingState { readonly ownedThreadIds: ReadonlySet; @@ -49,6 +52,14 @@ export interface ProviderEventRouteIdentity { readonly providerThreadId: ProviderThreadId; } +type ProviderTerminalEvent = Extract; + +export function finalProviderThreadStatus( + disposition: ProviderTerminalEvent["threadDisposition"], +): OrchestrationV2ProviderThread["status"] { + return disposition === "broken" ? "error" : "idle"; +} + export function makeProviderEventRoutingState(input: { readonly identity: ProviderEventRouteIdentity; readonly providerTurnId: ProviderTurnId | null; @@ -207,6 +218,7 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly providerTurnOrdinal: number; readonly relatedThreadIds?: ReadonlyArray; readonly relatedProviderThreadIds?: ReadonlyArray; + readonly shouldStartProviderTurn?: () => Effect.Effect; readonly shouldFinalizeRun?: () => Effect.Effect; readonly message: ProviderAdapterV2TurnMessage; readonly modelSelection: ModelSelection; @@ -271,16 +283,14 @@ export const layer: Layer.Layer< readonly providerThread: OrchestrationV2ProviderThread; readonly attempt: OrchestrationV2RunAttempt; readonly shouldFinalizeRun?: () => Effect.Effect; - readonly status: Extract< - OrchestrationV2Run["status"], - "completed" | "interrupted" | "failed" | "cancelled" - >; + readonly terminal: ProviderTerminalEvent; + readonly failureItemPersisted: boolean; }) => Effect.gen(function* () { const completedAt = yield* DateTime.now; const finalizedAttempt: OrchestrationV2RunAttempt | null = { ...input.attempt, - status: input.status, + status: input.terminal.status, completedAt, }; const shouldFinalizeRun = @@ -289,7 +299,7 @@ export const layer: Layer.Layer< // A newer attempt already owns the run and the command that created // it terminalized this attempt as superseded. Preserve that domain // status while retaining the provider's interruption artifact. - if (input.status === "interrupted") { + if (input.terminal.status === "interrupted") { yield* eventSink.write({ events: [ { @@ -313,21 +323,22 @@ export const layer: Layer.Layer< } return; } - const persistedStatus = input.status === "completed" ? "waiting" : input.status; + const persistedStatus = + input.terminal.status === "completed" ? "waiting" : input.terminal.status; const finalizedRun: OrchestrationV2Run = { ...input.run, status: persistedStatus, - completedAt: input.status === "completed" ? null : completedAt, + completedAt: input.terminal.status === "completed" ? null : completedAt, }; const finalizedRootNode: OrchestrationV2ExecutionNode = { ...input.rootNode, status: persistedStatus, - completedAt: input.status === "completed" ? null : completedAt, + completedAt: input.terminal.status === "completed" ? null : completedAt, checkpointScopeId: input.checkpointScope.id, }; const finalizedProviderThread: OrchestrationV2ProviderThread = { ...input.providerThread, - status: "idle", + status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; const runEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId }); @@ -340,7 +351,7 @@ export const layer: Layer.Layer< ); yield* eventSink.writeWithEffects({ effects: - input.status === "completed" + input.terminal.status === "completed" ? [ { id: `effect:checkpoint.capture:${input.run.id}`, @@ -369,7 +380,7 @@ export const layer: Layer.Layer< payload: finalizedAttempt, }, ]), - ...(input.status === "interrupted" + ...(input.terminal.status === "interrupted" ? [ { id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), @@ -389,6 +400,31 @@ export const layer: Layer.Layer< }, ] : []), + ...(input.terminal.status === "failed" && !input.failureItemPersisted + ? [ + { + id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + type: "turn-item.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: makeProviderFailureTurnItem({ + idAllocator, + driver: input.terminal.driver, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerThreadId: input.terminal.providerThreadId, + providerTurnId: input.terminal.providerTurnId, + itemOrdinal: input.terminal.failureItemOrdinal, + failure: input.terminal.failure, + occurredAt: completedAt, + }), + }, + ] + : []), { id: runEventId, type: "run.updated", @@ -450,10 +486,33 @@ export const layer: Layer.Layer< }), ), ); - const terminalStatus = yield* Ref.make | null>(null); + if ( + input.shouldStartProviderTurn !== undefined && + !(yield* input.shouldStartProviderTurn()) + ) { + return; + } + const terminalEvent = yield* Ref.make(null); + const makeFailedTerminalEvent = ( + failure: OrchestrationV2ProviderFailure, + failureItemOrdinal: number, + ): ProviderTerminalEvent => ({ + type: "turn.terminal", + driver: input.providerThread.driver, + providerThreadId: input.providerThread.id, + providerTurnId: + input.attempt.providerTurnId ?? + idAllocator.derive.providerTurn({ + driver: input.providerThread.driver, + nativeTurnId: `failed:${input.attempt.id}`, + }), + runOrdinal: input.run.ordinal, + failureItemOrdinal, + status: "failed", + failure, + threadDisposition: "reusable", + }); + const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100); const latestProviderThread = yield* Ref.make(input.providerThread); const routeIdentity: ProviderEventRouteIdentity = { threadId: input.run.threadId, @@ -484,31 +543,52 @@ export const layer: Layer.Layer< Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runForEach((event) => Effect.gen(function* () { + let storedEventCount = 0; if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) { - yield* providerEventIngestor.ingestNormalized({ + const storedEvents = yield* providerEventIngestor.ingestNormalized({ providerSessionId: input.providerSessionId, providerInstanceId: input.run.providerInstanceId, threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, event, + ...(event.type === "provider_thread.updated" && + event.providerThread.id === input.providerThread.id + ? { + writeIfRunCurrent: { + runId: input.run.id, + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + }, + } + : {}), }); + storedEventCount = storedEvents.length; } if (event.type === "provider_thread.updated") { - if (event.providerThread.id === input.providerThread.id) { + if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) { yield* Ref.set(latestProviderThread, event.providerThread); } } + if ( + event.type === "turn_item.updated" && + event.turnItem.providerTurnId === + (yield* Ref.get(eventRouting)).rootProviderTurnId + ) { + yield* Ref.update(latestTurnItemOrdinal, (current) => + Math.max(current, event.turnItem.ordinal), + ); + } if (event.type === "turn.terminal") { - yield* Ref.set(terminalStatus, event.status); + yield* Ref.set(terminalEvent, event); } }), ), Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })), Effect.flatMap(() => Effect.gen(function* () { - const status = yield* Ref.get(terminalStatus); - if (status === null) { + const terminal = yield* Ref.get(terminalEvent); + if (terminal === null) { return; } const providerThread = yield* Ref.get(latestProviderThread); @@ -521,7 +601,8 @@ export const layer: Layer.Layer< ...(input.shouldFinalizeRun === undefined ? {} : { shouldFinalizeRun: input.shouldFinalizeRun }), - status, + terminal, + failureItemPersisted: terminal.status === "failed", }).pipe( Effect.mapError( (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), @@ -536,17 +617,28 @@ export const layer: Layer.Layer< }).pipe( Effect.andThen(Ref.get(latestProviderThread)), Effect.flatMap((providerThread) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - status: "failed", - }), + Ref.get(latestTurnItemOrdinal).pipe( + Effect.flatMap((latestItemOrdinal) => + writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { shouldFinalizeRun: input.shouldFinalizeRun }), + terminal: makeFailedTerminalEvent( + makeProviderFailure({ + cause: Cause.squash(cause), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + failureItemPersisted: false, + }), + ), + ), ), Effect.mapError( (writeCause) => @@ -561,6 +653,14 @@ export const layer: Layer.Layer< Effect.forkDetach, ); + if ( + input.shouldStartProviderTurn !== undefined && + !(yield* input.shouldStartProviderTurn()) + ) { + yield* Fiber.interrupt(providerEventFiber); + return; + } + yield* input.session .startTurn({ appThread: input.appThread, @@ -584,17 +684,28 @@ export const layer: Layer.Layer< Effect.andThen(Fiber.interrupt(providerEventFiber)), Effect.andThen(Ref.get(latestProviderThread)), Effect.flatMap((providerThread) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { shouldFinalizeRun: input.shouldFinalizeRun }), - status: "failed", - }), + Ref.get(latestTurnItemOrdinal).pipe( + Effect.flatMap((latestItemOrdinal) => + writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { shouldFinalizeRun: input.shouldFinalizeRun }), + terminal: makeFailedTerminalEvent( + makeProviderFailure({ + cause: Cause.squash(cause), + class: "provider_error", + }), + latestItemOrdinal + 1, + ), + failureItemPersisted: false, + }), + ), + ), ), Effect.mapError( (writeCause) => diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts new file mode 100644 index 0000000000..143a1b451e --- /dev/null +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -0,0 +1,639 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + type ModelSelection, + type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderSession, + type OrchestrationV2ProviderThread, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + type RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; + +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { OrchestratorV2 } from "./Orchestrator.ts"; +import { + ProviderAdapterOpenSessionError, + type ProviderAdapterV2Event, + type ProviderAdapterV2Shape, + type ProviderAdapterV2TurnInput, +} from "./ProviderAdapter.ts"; +import { + makeLayer as makeProviderAdapterRegistryLayer, + makeSingleLayer as makeSingleProviderAdapterRegistryLayer, +} from "./ProviderAdapterRegistry.ts"; +import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts"; +import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts"; + +const driver = ProviderDriverKind.make("codex"); +const providerInstanceId = ProviderInstanceId.make("codex-restart-test"); +const initialSelection = { + instanceId: providerInstanceId, + model: "restart-model-a", +} satisfies ModelSelection; +const replacementSelection = { + instanceId: providerInstanceId, + model: "restart-model-b", +} satisfies ModelSelection; +const handoffDriver = ProviderDriverKind.make("claudeAgent"); +const handoffProviderInstanceId = ProviderInstanceId.make("claude-handoff-test"); +const handoffSelection = { + instanceId: handoffProviderInstanceId, + model: "handoff-model", +} satisfies ModelSelection; +const pooledCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2; +const exclusiveCapabilities: OrchestrationV2ProviderCapabilities = { + ...CodexProviderCapabilitiesV2, + sessions: { + ...CodexProviderCapabilitiesV2.sessions, + supportsMultipleProviderThreadsPerSession: false, + supportsModelSwitchInSession: false, + }, +}; + +interface ActiveTurn { + readonly input: ProviderAdapterV2TurnInput; + readonly providerTurnId: ProviderTurnId; +} + +interface RestartAdapterState { + readonly activeTurn: ActiveTurn | null; + readonly opened: ReadonlyArray<{ + readonly model: string | null; + readonly cwd: string | null; + }>; + readonly started: ReadonlyArray<{ + readonly model: string; + readonly cwd: string | null; + readonly attemptId: string; + }>; + readonly closedSessionCount: number; + readonly failedReplacementOpen: boolean; +} + +function makeRestartAdapter( + state: Ref.Ref, + sessionCapabilities: OrchestrationV2ProviderCapabilities = pooledCapabilities, +): ProviderAdapterV2Shape { + return { + instanceId: providerInstanceId, + driver, + getCapabilities: () => Effect.succeed(sessionCapabilities), + planSelectionTransition: ({ current, target }) => + Effect.succeed( + current.model === target.model + ? ({ type: "apply_on_next_turn" } as const) + : ({ type: "restart_session" } as const), + ), + openSession: (sessionInput) => + Effect.gen(function* () { + const failThisOpen = yield* Ref.modify(state, (current) => { + const shouldFail = + sessionInput.modelSelection.model === replacementSelection.model && + !current.failedReplacementOpen; + return [ + shouldFail, + { + ...current, + failedReplacementOpen: current.failedReplacementOpen || shouldFail, + opened: [ + ...current.opened, + { + model: sessionInput.modelSelection.model, + cwd: sessionInput.runtimePolicy.cwd, + }, + ], + }, + ] as const; + }); + if (failThisOpen) { + return yield* new ProviderAdapterOpenSessionError({ + driver, + providerSessionId: sessionInput.providerSessionId, + cause: "simulated replacement open failure", + }); + } + + const events = yield* Queue.unbounded(); + const now = yield* DateTime.now; + const providerSession: OrchestrationV2ProviderSession = { + id: sessionInput.providerSessionId, + driver, + providerInstanceId, + status: "ready", + cwd: sessionInput.runtimePolicy.cwd ?? "/fallback", + model: sessionInput.modelSelection.model, + capabilities: sessionCapabilities, + createdAt: now, + updatedAt: now, + lastError: null, + }; + yield* Effect.addFinalizer(() => + Ref.update(state, (current) => ({ + ...current, + closedSessionCount: current.closedSessionCount + 1, + })), + ); + + const publishTerminal = (active: ActiveTurn, status: "completed" | "interrupted") => + Effect.gen(function* () { + const occurredAt = yield* DateTime.now; + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: active.providerTurnId, + providerThreadId: active.input.providerThread.id, + nodeId: active.input.rootNodeId, + runAttemptId: active.input.attemptId, + nativeTurnRef: { + driver, + nativeId: `native:${active.providerTurnId}`, + strength: "strong", + }, + ordinal: active.input.providerTurnOrdinal, + status, + startedAt: occurredAt, + completedAt: occurredAt, + }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: active.input.providerThread.id, + providerTurnId: active.providerTurnId, + runOrdinal: active.input.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }); + }); + + return { + instanceId: providerInstanceId, + driver, + providerSessionId: sessionInput.providerSessionId, + providerSession, + events: Stream.fromQueue(events), + ensureThread: (threadInput) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + return { + id: ProviderThreadId.make(`provider-thread:${threadInput.threadId}`), + driver, + providerInstanceId, + providerSessionId: sessionInput.providerSessionId, + appThreadId: threadInput.threadId, + ownerNodeId: null, + nativeThreadRef: { + driver, + nativeId: `native-thread:${threadInput.threadId}`, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt, + updatedAt: createdAt, + } satisfies OrchestrationV2ProviderThread; + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (input) => + Effect.gen(function* () { + yield* Ref.update(state, (current) => ({ + ...current, + started: [ + ...current.started, + { + model: input.modelSelection.model, + cwd: input.runtimePolicy.cwd, + attemptId: input.attemptId, + }, + ], + })); + const active = { + input, + providerTurnId: ProviderTurnId.make(`provider-turn:${input.attemptId}`), + } satisfies ActiveTurn; + if (input.modelSelection.model === initialSelection.model) { + const occurredAt = yield* DateTime.now; + yield* Ref.update(state, (current) => ({ ...current, activeTurn: active })); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: active.providerTurnId, + providerThreadId: input.providerThread.id, + nodeId: input.rootNodeId, + runAttemptId: input.attemptId, + nativeTurnRef: { + driver, + nativeId: `native:${active.providerTurnId}`, + strength: "strong", + }, + ordinal: input.providerTurnOrdinal, + status: "running", + startedAt: occurredAt, + completedAt: null, + }, + }); + return; + } + yield* publishTerminal(active, "completed"); + }), + steerTurn: () => Effect.void, + interruptTurn: () => + Effect.gen(function* () { + const active = (yield* Ref.get(state)).activeTurn; + if (active !== null) { + const updatedAt = yield* DateTime.now; + yield* Queue.offer(events, { + type: "provider_thread.updated", + driver, + providerThread: { + ...active.input.providerThread, + status: "idle", + updatedAt, + }, + }); + yield* publishTerminal(active, "interrupted"); + yield* Ref.update(state, (current) => ({ ...current, activeTurn: null })); + } + }), + respondToRuntimeRequest: () => Effect.void, + readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"), + rollbackThread: () => Effect.die("unused rollbackThread"), + forkThread: () => Effect.die("unused forkThread"), + }; + }), + }; +} + +function makeCompletingHandoffAdapter(startCount: Ref.Ref): ProviderAdapterV2Shape { + return { + instanceId: handoffProviderInstanceId, + driver: handoffDriver, + getCapabilities: () => Effect.succeed(exclusiveCapabilities), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (sessionInput) => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const now = yield* DateTime.now; + return { + instanceId: handoffProviderInstanceId, + driver: handoffDriver, + providerSessionId: sessionInput.providerSessionId, + providerSession: { + id: sessionInput.providerSessionId, + driver: handoffDriver, + providerInstanceId: handoffProviderInstanceId, + status: "ready", + cwd: sessionInput.runtimePolicy.cwd ?? "/fallback", + model: sessionInput.modelSelection.model, + capabilities: exclusiveCapabilities, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: (threadInput) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + return { + id: ProviderThreadId.make(`provider-thread:handoff:${threadInput.threadId}`), + driver: handoffDriver, + providerInstanceId: handoffProviderInstanceId, + providerSessionId: sessionInput.providerSessionId, + appThreadId: threadInput.threadId, + ownerNodeId: null, + nativeThreadRef: { + driver: handoffDriver, + nativeId: `native-thread:handoff:${threadInput.threadId}`, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt, + updatedAt: createdAt, + } satisfies OrchestrationV2ProviderThread; + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (input) => + Effect.gen(function* () { + yield* Ref.update(startCount, (count) => count + 1); + const occurredAt = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make( + `provider-turn:handoff:${input.attemptId}`, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver: handoffDriver, + providerTurn: { + id: providerTurnId, + providerThreadId: input.providerThread.id, + nodeId: input.rootNodeId, + runAttemptId: input.attemptId, + nativeTurnRef: { + driver: handoffDriver, + nativeId: `native:${providerTurnId}`, + strength: "strong", + }, + ordinal: input.providerTurnOrdinal, + status: "completed", + startedAt: occurredAt, + completedAt: occurredAt, + }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver: handoffDriver, + providerThreadId: input.providerThread.id, + providerTurnId, + runOrdinal: input.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }), + steerTurn: () => Effect.void, + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.void, + readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"), + rollbackThread: () => Effect.die("unused rollbackThread"), + forkThread: () => Effect.die("unused forkThread"), + }; + }), + }; +} + +it.live("restarts selection as a new attempt and retries after old-session cleanup", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("selection-restart-lifecycle"); + const threadId = ThreadId.make("thread:selection-restart-lifecycle"); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: false, + }); + const registry = makeSingleProviderAdapterRegistryLayer(makeRestartAdapter(state)); + + const result = yield* Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart:create"), + threadId, + projectId: ProjectId.make("project:selection-restart"), + title: "Selection restart", + modelSelection: initialSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart:first"), + threadId, + messageId: MessageId.make("message:selection-restart:first"), + text: "first", + attachments: [], + modelSelection: initialSelection, + dispatchMode: { type: "start_immediately" }, + }); + for (let index = 0; index < 1_000; index += 1) { + const current = yield* orchestrator.getThreadProjection(threadId); + if (current.providerTurns.some((turn) => turn.status === "running")) break; + yield* Effect.sleep("5 millis"); + } + const activeProjection = yield* orchestrator.getThreadProjection(threadId); + assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running")); + const activeRunId = activeProjection.runs[0]?.id; + if (activeRunId === undefined) { + return yield* Effect.die("active restart test run is missing"); + } + + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-restart:second"), + threadId, + messageId: MessageId.make("message:selection-restart:second"), + text: "second", + attachments: [], + modelSelection: replacementSelection, + dispatchMode: { type: "restart_active", targetRunId: activeRunId }, + }); + for (let index = 0; index < 1_000; index += 1) { + const current = yield* orchestrator.getThreadProjection(threadId); + if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") { + const captured = yield* Ref.get(state); + return { projection: current, captured }; + } + yield* Effect.sleep("5 millis"); + } + const current = yield* orchestrator.getThreadProjection(threadId); + const adapterState = yield* Ref.get(state); + yield* Effect.logError("selection restart did not complete", { + runs: current.runs.map((run) => [run.status, run.activeAttemptId]), + attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]), + providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]), + providerThreads: current.providerThreads.map((thread) => [ + thread.providerSessionId, + thread.status, + ]), + adapterState, + }); + return yield* Effect.die("selection restart did not complete"); + }).pipe( + Effect.provide( + makeOrchestratorV2ReplayLayerWithRegistry( + { name: "selection-restart-lifecycle" }, + registry, + ), + ), + ); + const { projection, captured } = result; + + assert.lengthOf(projection.runs, 1); + assert.lengthOf(projection.attempts, 2); + assert.deepEqual( + projection.attempts.map((attempt) => attempt.status), + ["superseded", "completed"], + ); + assert.deepEqual( + projection.providerTurns.map((turn) => turn.status), + ["interrupted", "completed"], + ); + assert.isTrue(projection.turnItems.some((item) => item.type === "run_interrupt_result")); + assert.equal(projection.runs[0]?.modelSelection.model, replacementSelection.model); + assert.isTrue(captured.failedReplacementOpen); + // The old pooled process remains available to its other threads; this + // thread moved to a freshly allocated replacement session. + assert.equal(captured.closedSessionCount, 0); + assert.deepEqual( + captured.opened.map((open) => [open.model, open.cwd]), + [ + [initialSelection.model, cwd], + [replacementSelection.model, cwd], + [replacementSelection.model, cwd], + ], + ); + assert.deepEqual( + captured.started.map((turn) => [turn.model, turn.cwd]), + [ + [initialSelection.model, cwd], + [replacementSelection.model, cwd], + ], + ); + assert.notEqual( + projection.providerSessions[0]?.id, + projection.providerThreads[0]?.providerSessionId, + ); + assert.equal( + projection.providerThreads[0]?.providerSessionId, + projection.providerSessions.find((session) => session.model === replacementSelection.model) + ?.id, + ); + }), + ), +); + +it.live("detaches the old provider session after an active provider handoff", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("selection-provider-handoff-lifecycle"); + const threadId = ThreadId.make("thread:selection-provider-handoff-lifecycle"); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: false, + }); + const targetStartCount = yield* Ref.make(0); + const registry = makeProviderAdapterRegistryLayer([ + makeRestartAdapter(state, exclusiveCapabilities), + makeCompletingHandoffAdapter(targetStartCount), + ]); + + const result = yield* Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-handoff:create"), + threadId, + projectId: ProjectId.make("project:selection-handoff"), + title: "Selection provider handoff", + modelSelection: initialSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-handoff:first"), + threadId, + messageId: MessageId.make("message:selection-handoff:first"), + text: "first", + attachments: [], + modelSelection: initialSelection, + dispatchMode: { type: "start_immediately" }, + }); + let activeRunId: RunId | null = null; + for (let index = 0; index < 1_000; index += 1) { + const current = yield* orchestrator.getThreadProjection(threadId); + if (current.providerTurns.some((turn) => turn.status === "running")) { + activeRunId = current.runs[0]?.id ?? null; + break; + } + yield* Effect.sleep("5 millis"); + } + if (activeRunId === null) { + return yield* Effect.die("active provider-handoff run is missing"); + } + + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:selection-handoff:second"), + threadId, + messageId: MessageId.make("message:selection-handoff:second"), + text: "second", + attachments: [], + modelSelection: handoffSelection, + dispatchMode: { type: "restart_active", targetRunId: activeRunId }, + }); + for (let index = 0; index < 1_000; index += 1) { + const current = yield* orchestrator.getThreadProjection(threadId); + if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") { + const captured = yield* Ref.get(state); + return { projection: current, captured }; + } + yield* Effect.sleep("5 millis"); + } + const current = yield* orchestrator.getThreadProjection(threadId); + const adapterState = yield* Ref.get(state); + const capturedTargetStartCount = yield* Ref.get(targetStartCount); + yield* Effect.logError("active provider handoff did not complete", { + runs: current.runs.map((run) => [run.status, run.activeAttemptId]), + attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]), + providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]), + providerThreads: current.providerThreads.map((thread) => [ + thread.providerInstanceId, + thread.providerSessionId, + thread.status, + ]), + targetStartCount: capturedTargetStartCount, + adapterState, + }); + return yield* Effect.die("active provider handoff did not complete"); + }).pipe( + Effect.provide( + makeOrchestratorV2ReplayLayerWithRegistry( + { name: "selection-provider-handoff-lifecycle" }, + registry, + ), + ), + ); + + assert.lengthOf(result.projection.runs, 1); + assert.lengthOf(result.projection.attempts, 2); + assert.equal(result.projection.runs[0]?.providerInstanceId, handoffProviderInstanceId); + assert.equal(result.projection.contextHandoffs.length, 1); + assert.equal(result.captured.closedSessionCount, 1); + assert.equal(yield* Ref.get(targetStartCount), 1); + }), + ), +); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index ea151f9d06..de45bac5ae 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -1,30 +1,37 @@ import { assert, it, vi } from "@effect/vitest"; import { - EventId, CommandId, + MessageId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ThreadId, - type OrchestrationV2DomainEvent, - type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as CommandReceiptStore from "./CommandReceiptStore.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; import * as IdAllocator from "./IdAllocator.ts"; -import { OrchestratorDispatchError, type OrchestratorV2DispatchResult } from "./Orchestrator.ts"; -import { emptyProjection } from "./ProjectionStore.ts"; +import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ThreadLaunch from "./ThreadLaunchService.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; +import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts"; -const projectId = ProjectId.make("project_launch_test"); +const projectId = ProjectId.make("project:launch-test"); const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.1-codex", @@ -42,116 +49,42 @@ const project = { deletedAt: null, } as const; -function projectionFor(threadId: ThreadId): OrchestrationV2ThreadProjection { - const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); - const event = { - id: EventId.make(`event:${threadId}`), - type: "thread.created", - threadId, - providerInstanceId: modelSelection.instanceId, - occurredAt: now, - payload: { - id: threadId, - projectId, - title: "Thread", - providerInstanceId: modelSelection.instanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - activeProviderThreadId: null, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, - forkedFrom: null, - createdBy: "user", - creationSource: "web", - createdAt: now, - updatedAt: now, - archivedAt: null, - deletedAt: null, - }, - } satisfies Extract; - return emptyProjection(event); +const adapter = { + instanceId: modelSelection.instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("provider execution is disabled in launch tests"), +} as ProviderAdapterV2Shape; + +interface HarnessOptions { + readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"]; + readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]; + readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"]; } -const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup?: boolean }) => { - const projections = new Map(); - const dispatch = vi.fn( - ( - command: Parameters[0], - ): Effect.Effect => { - if (command.type === "thread.metadata.update") { - const existing = projections.get(command.threadId); - if (existing === undefined) return Effect.die("missing existing projection"); - projections.set(command.threadId, { - ...existing, - thread: { - ...existing.thread, - ...(command.title === undefined ? {} : { title: command.title }), - ...(command.branch === undefined ? {} : { branch: command.branch }), - ...(command.worktreePath === undefined ? {} : { worktreePath: command.worktreePath }), - }, - }); - return Effect.succeed({ sequence: 1, storedEvents: [] }); - } - if (command.type !== "thread.create") return Effect.die("unexpected command"); - if (options?.failCreate) { - return Effect.fail( - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: "create failed", - }), - ); - } - const projection = projectionFor(command.threadId); - projections.set(command.threadId, { - ...projection, - thread: { - ...projection.thread, - title: command.title, - branch: command.branch, - worktreePath: command.worktreePath, - }, - }); - return Effect.succeed({ sequence: 1, storedEvents: [] }); - }, +function makeHarness(options: HarnessOptions = {}) { + const database = SqlitePersistenceMemory; + const registry = ProviderAdapterRegistry.makeLayer([adapter]); + const orchestrator = makeOrchestratorV2ReplayLayerWithRegistry( + { name: "thread-launch" }, + registry, + { databaseLayer: database, runEffectWorker: false }, ); + const threadManagement = ThreadManagement.layer.pipe(Layer.provide(orchestrator)); + const receipts = CommandReceiptStore.layer.pipe(Layer.provide(database)); + const outbox = EffectOutbox.layer.pipe(Layer.provide(database)); const createWorktree = vi.fn( - (_input: Parameters[0]) => - Effect.succeed({ - worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" }, - } as never), + options.createWorktree ?? + (() => + Effect.succeed({ + worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" }, + } as never)), ); - const removeWorktree = vi.fn(() => Effect.void); - const fetchRemote = vi.fn( - (_input: Parameters[0]) => - Effect.void, + const runSetup = vi.fn( + options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })), ); - const resolveRemoteTrackingCommit = vi.fn( - ( - _input: Parameters< - GitWorkflow.GitWorkflowService["Service"]["resolveRemoteTrackingCommit"] - >[0], - ) => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }), - ); - const runForThread = vi.fn(() => - options?.failSetup - ? Effect.fail( - new ProjectSetupScriptRunner.ProjectSetupScriptOperationError({ - threadId: "thread", - worktreePath: "/repo-worktrees/feature", - operation: "openTerminal", - cause: "setup failed", - }), - ) - : Effect.succeed({ status: "no-script" as const }), - ); - const sendToThread = vi.fn(() => - Effect.succeed({} as ThreadManagement.ThreadManagementSendResult), - ); - - const dependencies = Layer.mergeAll( + const externalServices = Layer.mergeAll( Layer.succeed(ProjectService.ProjectService, { create: () => Effect.die("unused"), bootstrap: () => Effect.die("unused"), @@ -163,237 +96,549 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup }), Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, - fetchRemote, - removeWorktree, - resolveRemoteTrackingCommit, + fetchRemote: () => Effect.void, + removeWorktree: () => Effect.void, + resolveRemoteTrackingCommit: () => + Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }), }), Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { - runForThread, + runForThread: runSetup, }), Layer.mock(TextGeneration.TextGeneration)({ - generateThreadTitle: () => Effect.succeed({ title: "Generated title" }), + generateThreadTitle: + options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })), generateBranchName: () => Effect.succeed({ branch: "generated-branch" }), }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - dispatch, - getThreadProjection: (threadId) => - projections.has(threadId) - ? Effect.succeed(projections.get(threadId)!) - : Effect.die("missing projection"), - sendToThread, - }), - IdAllocator.layer, + ); + const launch = ThreadLaunch.layer.pipe( + Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)), ); return { - layer: ThreadLaunch.layer.pipe( - Layer.provideMerge(dependencies), - Layer.provideMerge(SqlitePersistenceMemory), - ), - dispatch, - fetchRemote, + layer: Layer.mergeAll(launch, threadManagement, outbox, database), createWorktree, - projections, - removeWorktree, - resolveRemoteTrackingCommit, - runForThread, - sendToThread, + runSetup, }; -}; +} -it.effect("persists root-workspace launches and returns the committed workflow on retry", () => { - const test = makeLayer(); +function launchInput(input: { + readonly command: string; + readonly thread: string; + readonly message?: string; + readonly workspace?: ThreadLaunch.ThreadLaunchWorkspaceStrategy; +}) { + return { + commandId: CommandId.make(input.command), + threadId: ThreadId.make(input.thread), + projectId, + title: "New thread", + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + workspaceStrategy: input.workspace ?? { type: "root" as const }, + ...(input.message === undefined + ? {} + : { + initialMessage: { + messageId: MessageId.make(`${input.message}:id`), + text: input.message, + attachments: [], + }, + }), + createdBy: "user" as const, + creationSource: "web" as const, + }; +} + +function waitUntil(predicate: () => Effect.Effect): Effect.Effect { return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - const input = { - commandId: CommandId.make("command_launch_root"), - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access" as const, - interactionMode: "default" as const, - workspaceStrategy: { type: "root" as const }, - createdBy: "user" as const, - creationSource: "web" as const, - }; - const first = yield* service.launch(input); - const retry = yield* service.launch(input); - assert.equal(first.threadId, retry.threadId); - assert.isFalse(first.resumed); - assert.isTrue(retry.resumed); - assert.equal(test.dispatch.mock.calls.length, 1); - }).pipe(Effect.provide(test.layer)); -}); + for (let attempt = 0; attempt < 200; attempt += 1) { + if (yield* predicate()) return; + yield* Effect.promise( + () => + new Promise((resolve) => { + setImmediate(resolve); + }), + ); + } + assert.fail("Condition was not reached before timeout."); + }); +} -it.effect( - "generates first-run title and branch, runs setup once, and sends the initial message", - () => { - const test = makeLayer(); - return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - const input = { - commandId: CommandId.make("command_launch_generated"), - projectId, - title: "New thread", - modelSelection, - runtimeMode: "full-access" as const, - interactionMode: "default" as const, - workspaceStrategy: { type: "worktree" as const, baseRef: "main" }, - initialMessage: { text: "Build the feature", attachments: [] }, - createdBy: "user" as const, - creationSource: "web" as const, - }; - yield* service.launch(input); - yield* service.launch(input); - const createCommand = test.dispatch.mock.calls[0]?.[0]; - assert.equal(createCommand?.type, "thread.create"); - if (createCommand?.type === "thread.create") { - assert.equal(createCommand.title, "Generated title"); - assert.equal(createCommand.branch, "feature"); +it.effect("returns a visible preparing message while provisioning is still blocked", () => + Effect.gen(function* () { + const worktreeEntered = yield* Deferred.make(); + const allowWorktree = yield* Deferred.make(); + const setupEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + createWorktree: () => + Deferred.succeed(worktreeEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowWorktree)), + Effect.as({ + worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" }, + } as never), + ), + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ status: "no-script" as const }), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: "command:launch:blocked", + thread: "thread:launch:blocked", + message: "Build the feature", + workspace: { type: "worktree", baseRef: "main" }, + }); + const launched = yield* launches.launch(input); + assert.equal(launched.projection.messages[0]?.text, "Build the feature"); + assert.equal(launched.projection.runs[0]?.status, "preparing"); + assert.equal( + launched.projection.turnItems.find((item) => item.type === "command_execution")?.status, + "running", + ); + yield* Deferred.await(worktreeEntered); + let current = yield* threads.getThreadProjection(launched.threadId); + assert.equal( + current.turnItems.find((item) => item.type === "command_execution")?.title, + "Preparing worktree", + ); + yield* Deferred.succeed(allowWorktree, undefined); + const entered = yield* Deferred.await(setupEntered).pipe( + Effect.timeoutOption(Duration.seconds(2)), + ); + if (Option.isNone(entered)) { + current = yield* threads.getThreadProjection(launched.threadId); + assert.fail( + `Setup was not reached; run=${current.runs[0]?.status ?? "missing"}, worklog=${current.turnItems.find((item) => item.type === "command_execution")?.title ?? "missing"}.`, + ); } - assert.equal(test.runForThread.mock.calls.length, 1); - assert.equal(test.sendToThread.mock.calls.length, 1); - }).pipe(Effect.provide(test.layer)); - }, + current = yield* threads.getThreadProjection(launched.threadId); + assert.equal( + current.turnItems.find((item) => item.type === "command_execution")?.title, + "Starting setup script", + ); + const prematureEffects = yield* outbox.listByCommandId( + CommandId.make("command:launch:blocked:initial-message"), + ); + assert.isEmpty(prematureEffects); + yield* Deferred.succeed(allowSetup, undefined); + }).pipe(Effect.provide(harness.layer)); + }), ); -it.effect("preserves an existing worktree when launching a new thread", () => { - const test = makeLayer(); - return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - const result = yield* service.launch({ - commandId: CommandId.make("command_launch_existing_worktree"), - threadId: ThreadId.make("thread_existing_worktree"), - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { - type: "existing_worktree", - worktreePath: "/repo-worktrees/existing", - branch: "existing", - }, - createdBy: "user", - creationSource: "web", +it.effect("provisions independent launches concurrently instead of behind a global semaphore", () => + Effect.gen(function* () { + const setupCount = yield* Ref.make(0); + const bothEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Ref.updateAndGet(setupCount, (count) => count + 1).pipe( + Effect.tap((count) => + count === 2 ? Deferred.succeed(bothEntered, undefined) : Effect.void, + ), + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ status: "no-script" as const }), + ), }); - assert.equal(result.projection.thread.worktreePath, "/repo-worktrees/existing"); - assert.equal(result.projection.thread.branch, "existing"); - assert.equal(test.createWorktree.mock.calls.length, 0); - assert.equal(test.removeWorktree.mock.calls.length, 0); - }).pipe(Effect.provide(test.layer)); -}); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const results = yield* Effect.all( + [ + launches.launch( + launchInput({ + command: "command:launch:concurrent-a", + thread: "thread:launch:concurrent-a", + message: "First", + }), + ), + launches.launch( + launchInput({ + command: "command:launch:concurrent-b", + thread: "thread:launch:concurrent-b", + message: "Second", + }), + ), + ], + { concurrency: "unbounded" }, + ); + assert.deepEqual( + results.map((result) => result.projection.runs[0]?.status), + ["preparing", "preparing"], + ); + yield* Deferred.await(bothEntered); + assert.equal(yield* Ref.get(setupCount), 2); + yield* Deferred.succeed(allowSetup, undefined); + }).pipe(Effect.provide(harness.layer)); + }), +); -it.effect("fetches and resolves origin before provisioning an origin-based worktree", () => { - const test = makeLayer(); - return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - yield* service.launch({ - commandId: CommandId.make("command_launch_origin_worktree"), - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { - type: "worktree", - baseRef: "main", - branch: "feature", - startFromOrigin: true, - }, - createdBy: "user", - creationSource: "web", +it.effect("enqueues provider work only after setup has been initiated", () => + Effect.gen(function* () { + const setupEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup", + cwd: "/repo", + }), + ), }); - assert.deepEqual(test.fetchRemote.mock.calls[0]?.[0], { - cwd: "/repo", - remoteName: "origin", - }); - assert.deepEqual(test.resolveRemoteTrackingCommit.mock.calls[0]?.[0], { - cwd: "/repo", - refName: "main", - fallbackRemoteName: "origin", - }); - assert.deepEqual(test.createWorktree.mock.calls[0]?.[0], { - cwd: "/repo", - refName: "remote-main-sha", - newRefName: "feature", - baseRefName: "main", - path: null, - }); - }).pipe(Effect.provide(test.layer)); -}); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: "command:launch:release", + thread: "thread:launch:release", + message: "Start after setup", + workspace: { type: "worktree", baseRef: "main" }, + }); + const launched = yield* launches.launch(input); + yield* Deferred.await(setupEntered); + assert.isEmpty( + yield* outbox.listByCommandId(CommandId.make("command:launch:release:release")), + ); + yield* Deferred.succeed(allowSetup, undefined); + yield* waitUntil(() => + outbox + .listByCommandId(CommandId.make("command:launch:release:release")) + .pipe(Effect.map((effects) => effects.length === 1)), + ); + const projection = yield* threads.getThreadProjection(launched.threadId); + assert.equal(projection.runs[0]?.status, "starting"); + assert.equal(projection.checkpointScopes[0]?.cwd, "/repo-worktrees/feature"); + assert.equal( + projection.turnItems.find((item) => item.type === "command_execution")?.status, + "completed", + ); + }).pipe(Effect.provide(harness.layer)); + }), +); -it.effect("provisions a worktree for an existing empty thread before sending", () => { - const test = makeLayer(); - const threadId = ThreadId.make("thread_existing_empty"); - test.projections.set(threadId, projectionFor(threadId)); - return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - yield* service.launch({ - commandId: CommandId.make("command_launch_existing_empty"), - threadId, - reuseExistingThread: true, - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" }, - initialMessage: { text: "Implement it", attachments: [] }, - createdBy: "user", - creationSource: "web", +it.effect( + "queues follow-up messages behind preparation and checkpoints them in the final workspace", + () => + Effect.gen(function* () { + const setupEntered = yield* Deferred.make(); + const failSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(failSetup)), + Effect.andThen(Effect.fail(new Error("setup failed") as never)), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const launched = yield* launches.launch( + launchInput({ + command: "command:launch:queued-during-preparation", + thread: "thread:launch:queued-during-preparation", + message: "Prepare the workspace", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + yield* Deferred.await(setupEntered); + + const followUp = yield* threads.sendToThread({ + projectId, + commandId: CommandId.make("command:launch:queued-follow-up"), + threadId: launched.threadId, + messageId: MessageId.make("message:launch:queued-follow-up"), + text: "Run after preparation", + attachments: [], + mode: "auto", + createdBy: "user", + creationSource: "web", + }); + assert.equal(followUp.delivery, "queued"); + assert.equal(followUp.run.status, "queued"); + assert.equal( + followUp.projection.nodes.find( + (node) => node.runId === followUp.run.id && node.kind === "root_turn", + )?.checkpointScopeId, + null, + ); + + yield* Deferred.succeed(failSetup, undefined); + yield* waitUntil(() => + threads + .getThreadProjection(launched.threadId) + .pipe( + Effect.map( + (projection) => + projection.runs.find((run) => run.id === followUp.run.id)?.status === "starting", + ), + ), + ); + + const projection = yield* threads.getThreadProjection(launched.threadId); + const rootNode = projection.nodes.find( + (node) => node.runId === followUp.run.id && node.kind === "root_turn", + ); + assert.isNotNull(rootNode?.checkpointScopeId); + assert.equal( + projection.checkpointScopes.find((scope) => scope.id === rootNode?.checkpointScopeId) + ?.cwd, + "/repo-worktrees/feature", + ); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("does not put optional title generation on the provisioning critical path", () => + Effect.gen(function* () { + const titleStarted = yield* Deferred.make(); + const allowTitle = yield* Deferred.make(); + const setupEntered = yield* Deferred.make(); + const harness = makeHarness({ + generateTitle: () => + Deferred.succeed(titleStarted, undefined).pipe( + Effect.andThen(Deferred.await(allowTitle)), + Effect.as({ title: "Generated later" }), + ), + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe(Effect.as({ status: "no-script" as const })), }); - const updateCommand = test.dispatch.mock.calls.find( - ([command]) => command.type === "thread.metadata.update", - )?.[0]; - assert.equal(updateCommand?.type, "thread.metadata.update"); - if (updateCommand?.type === "thread.metadata.update") { - assert.equal(updateCommand.worktreePath, "/repo-worktrees/feature"); - assert.equal(updateCommand.branch, "feature"); - } - assert.equal(test.sendToThread.mock.calls.length, 1); - }).pipe(Effect.provide(test.layer)); -}); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: "command:launch:title-independent", + thread: "thread:launch:title-independent", + message: "Generate my title slowly", + }); + const launched = yield* launches.launch(input); + yield* Deferred.await(titleStarted); + yield* Deferred.await(setupEntered); + yield* waitUntil(() => + threads + .getThreadProjection(launched.threadId) + .pipe(Effect.map((projection) => projection.runs[0]?.status === "starting")), + ); + assert.equal( + (yield* threads.getThreadProjection(launched.threadId)).thread.title, + "New thread", + ); + yield* Deferred.succeed(allowTitle, undefined); + yield* waitUntil(() => + threads + .getThreadProjection(launched.threadId) + .pipe(Effect.map((projection) => projection.thread.title === "Generated later")), + ); + }).pipe(Effect.provide(harness.layer)); + }), +); -it.effect("removes a new worktree and does not create a thread when setup fails", () => { - const test = makeLayer({ failSetup: true }); - return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - yield* service - .launch({ - commandId: CommandId.make("command_launch_setup_failure"), - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" }, - createdBy: "user", - creationSource: "web", - }) - .pipe(Effect.flip); - assert.equal(test.removeWorktree.mock.calls.length, 1); - assert.equal(test.dispatch.mock.calls.length, 0); - }).pipe(Effect.provide(test.layer)); -}); +for (const failurePoint of ["worktree", "setup"] as const) { + it.effect( + `${failurePoint} failure keeps the thread and message visible and emits failure items`, + () => + Effect.gen(function* () { + const failure = new Error(`${failurePoint} failed`); + const harness = makeHarness( + failurePoint === "worktree" + ? { createWorktree: () => Effect.fail(failure as never) } + : { runSetup: () => Effect.fail(failure as never) }, + ); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: `command:launch:${failurePoint}-failure`, + thread: `thread:launch:${failurePoint}-failure`, + message: `Fail during ${failurePoint}`, + workspace: { type: "worktree", baseRef: "main" }, + }); + const launched = yield* launches.launch(input); + yield* waitUntil(() => + threads + .getThreadProjection(launched.threadId) + .pipe(Effect.map((projection) => projection.runs[0]?.status === "failed")), + ); + const projection = yield* threads.getThreadProjection(launched.threadId); + assert.equal(projection.messages[0]?.text, `Fail during ${failurePoint}`); + assert.equal(projection.runs[0]?.status, "failed"); + assert.equal( + projection.turnItems.find((item) => item.type === "command_execution")?.status, + "failed", + ); + assert.match( + projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "", + new RegExp(`${failurePoint} failed`, "u"), + ); + }).pipe(Effect.provide(harness.layer)); + }), + ); +} -it.effect("compensates a newly-created worktree when thread creation fails", () => { - const test = makeLayer({ failCreate: true }); +it.effect("deduplicates retried launch side effects in-process", () => + Effect.gen(function* () { + const setupEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ status: "no-script" as const }), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const input = launchInput({ + command: "command:launch:retry", + thread: "thread:launch:retry", + message: "Only once", + }); + const [first, retry] = yield* Effect.all([launches.launch(input), launches.launch(input)], { + concurrency: "unbounded", + }); + yield* Deferred.await(setupEntered); + assert.equal(first.threadId, retry.threadId); + assert.isFalse(first.resumed); + assert.isTrue(retry.resumed); + assert.equal(harness.runSetup.mock.calls.length, 1); + yield* Deferred.succeed(allowSetup, undefined); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("does not let a failing same-command caller strand a concurrent durable launch", () => + Effect.gen(function* () { + const setupEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ status: "no-script" as const }), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const command = "command:launch:failed-owner-race"; + const [failed, launched] = yield* Effect.all( + [ + launches + .launch({ + ...launchInput({ + command, + thread: "thread:launch:failed-owner-race", + message: "This invalid reuse fails", + }), + reuseExistingThread: true, + }) + .pipe(Effect.exit), + launches.launch( + launchInput({ + command, + thread: "thread:launch:successful-peer", + message: "This peer persists", + }), + ), + ], + { concurrency: "unbounded" }, + ); + assert.isTrue(Exit.isFailure(failed)); + assert.equal(launched.projection.runs[0]?.status, "preparing"); + const entered = yield* Deferred.await(setupEntered).pipe( + Effect.timeoutOption(Duration.seconds(2)), + ); + assert.isTrue(Option.isSome(entered)); + assert.equal(harness.runSetup.mock.calls.length, 1); + yield* Deferred.succeed(allowSetup, undefined); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("schedules an accepted preparing message exactly once across concurrent retries", () => + Effect.gen(function* () { + const setupEntered = yield* Deferred.make(); + const allowSetup = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Deferred.succeed(setupEntered, undefined).pipe( + Effect.andThen(Deferred.await(allowSetup)), + Effect.as({ status: "no-script" as const }), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: "command:launch:accepted-before-fork", + thread: "thread:launch:accepted-before-fork", + message: "Resume preparation", + }); + const messageId = MessageId.make("message:launch:accepted-before-fork"); + + yield* threads.dispatch({ + type: "thread.create", + commandId: input.commandId, + threadId: input.threadId, + projectId: input.projectId, + title: input.title, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch: null, + worktreePath: null, + createdBy: input.createdBy, + creationSource: input.creationSource, + }); + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${input.commandId}:initial-message`), + threadId: input.threadId, + messageId, + text: "Resume preparation", + attachments: [], + modelSelection: input.modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: input.createdBy, + creationSource: input.creationSource, + }); + const preparing = yield* threads.getThreadProjection(input.threadId); + assert.equal(preparing.runs[0]?.status, "preparing"); + + const [first, second] = yield* Effect.all([launches.launch(input), launches.launch(input)], { + concurrency: "unbounded", + }); + yield* Deferred.await(setupEntered); + assert.isTrue(first.resumed); + assert.isTrue(second.resumed); + assert.equal(harness.runSetup.mock.calls.length, 1); + yield* Deferred.succeed(allowSetup, undefined); + }).pipe(Effect.provide(harness.layer)); + }), +); + +it.effect("does not depend on the legacy launch workflow table", () => { + const harness = makeHarness(); return Effect.gen(function* () { - const service = yield* ThreadLaunch.ThreadLaunchService; - yield* service - .launch({ - commandId: CommandId.make("command_launch_worktree"), - projectId, - title: "Thread", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" }, - createdBy: "user", - creationSource: "web", - }) - .pipe(Effect.flip); - assert.equal(test.createWorktree.mock.calls.length, 1); - assert.equal(test.removeWorktree.mock.calls.length, 1); - }).pipe(Effect.provide(test.layer)); + const sql = yield* SqlClient.SqlClient; + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* sql`DROP TABLE orchestration_v2_thread_launch_workflows`; + const launched = yield* launches.launch( + launchInput({ + command: "command:launch:no-workflow-table", + thread: "thread:launch:no-workflow-table", + message: "No private workflow state", + }), + ); + assert.equal(launched.projection.messages[0]?.text, "No private workflow state"); + }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index cef8b049d0..69e3fc83d8 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -8,23 +8,27 @@ import { type OrchestrationV2ThreadProjection, type ProviderInteractionMode, ProjectId, + type RunId, type RuntimeMode, ThreadId, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; -import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Semaphore from "effect/Semaphore"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Scope from "effect/Scope"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as IdAllocator from "./IdAllocator.ts"; +import { makeProviderFailure } from "./ProviderFailure.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; export type ThreadLaunchWorkspaceStrategy = @@ -73,15 +77,15 @@ export class ThreadLaunchError extends Schema.TaggedErrorClass()("t3/orchestration-v2/ThreadLaunchService") {} +const isThreadLaunchError = Schema.is(ThreadLaunchError); + +function fallbackBranchName(threadId: ThreadId): string { + const suffix = String(threadId) + .split(":") + .at(-1) + ?.replace(/[^a-zA-Z0-9-]+/gu, "-") + .replace(/^-+|-+$/gu, "") + .slice(0, 16); + return `thread-${suffix || "new"}`; +} + +function failureDetail(error: unknown): string { + if (isThreadLaunchError(error)) { + const cause = error.cause; + const detail = cause instanceof Error ? cause.message : String(cause); + return `Workspace preparation failed during ${error.operation.replaceAll("-", " ")}: ${detail}`; + } + return `Workspace preparation failed: ${error instanceof Error ? error.message : String(error)}`; +} + export const make = Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; const projects = yield* ProjectService.ProjectService; const git = yield* GitWorkflow.GitWorkflowService; const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const textGeneration = yield* TextGeneration.TextGeneration; + const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; const ids = yield* IdAllocator.IdAllocatorV2; const threads = yield* ThreadManagement.ThreadManagementService; - const launchSemaphore = yield* Semaphore.make(1); + const preparationScope = yield* Scope.make("sequential"); + const scheduledLaunches = yield* Ref.make>(new Set()); + yield* Effect.addFinalizer(() => Scope.close(preparationScope, Exit.void)); const mapError = (input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) => @@ -137,163 +151,110 @@ export const make = Effect.gen(function* () { cause, }); - const loadWorkflow = Effect.fn("ThreadLaunchService.loadWorkflow")(function* ( + const readReceipt = (input: ThreadLaunchInput, commandId: CommandId) => + receipts + .getByCommandId(commandId) + .pipe(Effect.mapError(mapError(input, "read-receipt", input.threadId))); + + const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(function* ( input: ThreadLaunchInput, + threadId: ThreadId, ) { - const rows = yield* sql` - SELECT * FROM orchestration_v2_thread_launch_workflows - WHERE command_id = ${input.commandId} - `.pipe(Effect.mapError(mapError(input, "load-workflow"))); - return rows[0] ?? null; + const projection = yield* threads + .getThreadProjection(threadId) + .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); + if ( + projection.thread.projectId !== input.projectId || + projection.thread.archivedAt !== null || + projection.thread.deletedAt !== null || + projection.messages.length > 0 || + projection.runs.length > 0 + ) { + return yield* mapError( + input, + "update-thread", + threadId, + )("Only an empty active thread in the target project can change workspace during launch."); + } }); - const saveWorkflow = Effect.fn("ThreadLaunchService.saveWorkflow")(function* ( + const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* ( input: ThreadLaunchInput, - row: { - readonly threadId: ThreadId; - readonly status: string; - readonly title: string; - readonly worktreePath: string | null; - readonly branch: string | null; - readonly setupCommitted: boolean; - readonly threadCommitted: boolean; - readonly messageCommitted: boolean; - readonly lastError?: string | null; - }, + threadId: ThreadId, + runId: RunId | null, ) { - const now = DateTime.formatIso(yield* DateTime.now); - yield* sql` - INSERT INTO orchestration_v2_thread_launch_workflows ( - command_id, thread_id, project_id, status, title, worktree_path, branch, setup_committed, - thread_committed, message_committed, last_error, created_at, updated_at - ) VALUES ( - ${input.commandId}, ${row.threadId}, ${input.projectId}, ${row.status}, ${row.title}, - ${row.worktreePath}, ${row.branch}, ${row.setupCommitted ? 1 : 0}, ${row.threadCommitted ? 1 : 0}, - ${row.messageCommitted ? 1 : 0}, ${row.lastError ?? null}, ${now}, ${now} - ) ON CONFLICT(command_id) DO UPDATE SET - status = excluded.status, - title = excluded.title, - worktree_path = excluded.worktree_path, - branch = excluded.branch, - setup_committed = excluded.setup_committed, - thread_committed = excluded.thread_committed, - message_committed = excluded.message_committed, - last_error = excluded.last_error, - updated_at = excluded.updated_at - `.pipe(Effect.mapError(mapError(input, "persist-workflow", row.threadId))); - }); - - const launchWorkflow: ThreadLaunchService["Service"]["launch"] = Effect.fn( - "ThreadLaunchService.launch", - )(function* (input) { const project = yield* projects.getById(input.projectId).pipe( - Effect.mapError(mapError(input, "resolve-project")), + Effect.mapError(mapError(input, "resolve-project", threadId)), Effect.flatMap( Option.match({ - onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")), + onNone: () => + Effect.fail(mapError(input, "resolve-project", threadId)("Project no longer exists.")), onSome: Effect.succeed, }), ), ); - const stored = yield* loadWorkflow(input); - if (input.reuseExistingThread === true && input.threadId === undefined) { - return yield* mapError( - input, - "update-thread", - )("Reusing an existing thread requires a thread id."); - } - const threadId = - stored === null - ? (input.threadId ?? - (yield* ids.allocate - .thread({ projectId: input.projectId }) - .pipe(Effect.mapError(mapError(input, "persist-workflow"))))) - : ThreadId.make(stored.thread_id); - if (stored?.status === "completed") { - return { - threadId, - projection: yield* threads - .getThreadProjection(threadId) - .pipe(Effect.mapError(mapError(input, "create-thread", threadId))), - resumed: true, - }; - } - const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")( - function* () { - const projection = yield* threads - .getThreadProjection(threadId) - .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); - if ( - projection.thread.projectId !== input.projectId || - projection.thread.archivedAt !== null || - projection.thread.deletedAt !== null || - projection.messages.length > 0 || - projection.runs.length > 0 - ) { - return yield* mapError( - input, - "update-thread", - threadId, - )( - "Only an empty active thread in the target project can change workspace during launch.", - ); - } - return projection; - }, - ); - if (input.reuseExistingThread === true && stored?.thread_committed !== 1) { - yield* validateReusableThread(); + if (input.title === "New thread" && input.initialMessage !== undefined) { + yield* textGeneration + .generateThreadTitle({ + cwd: project.workspaceRoot, + message: input.initialMessage.text, + attachments: input.initialMessage.attachments, + modelSelection: input.modelSelection, + }) + .pipe( + Effect.flatMap((result) => + threads.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${input.commandId}:title`), + threadId, + title: result.title, + }), + ), + Effect.catchCause((cause) => + Effect.logWarning("Thread title generation failed", { + commandId: input.commandId, + threadId, + cause, + }), + ), + Effect.forkIn(preparationScope), + ); } let branch = - stored?.branch ?? - (input.workspaceStrategy.type === "worktree" - ? null - : (input.workspaceStrategy.branch ?? null)); - let title = stored?.title ?? input.title; - if (input.initialMessage !== undefined) { - if (title === "New thread") { - title = yield* textGeneration - .generateThreadTitle({ - cwd: project.workspaceRoot, - message: input.initialMessage.text, - attachments: input.initialMessage.attachments, - modelSelection: input.modelSelection, - }) - .pipe( - Effect.map((result) => result.title), - Effect.mapError(mapError(input, "generate-metadata", threadId)), - ); - } - if (input.workspaceStrategy.type === "worktree" && branch === null) { - branch = yield* textGeneration - .generateBranchName({ - cwd: project.workspaceRoot, - message: input.initialMessage.text, - attachments: input.initialMessage.attachments, - modelSelection: input.modelSelection, - }) - .pipe( - Effect.map((result) => result.branch), - Effect.mapError(mapError(input, "generate-metadata", threadId)), - ); - } - } - if (input.workspaceStrategy.type === "worktree") { - branch = branch ?? input.workspaceStrategy.branch ?? `thread-${threadId}`; - } - + input.workspaceStrategy.type === "worktree" && + input.workspaceStrategy.branch === undefined && + input.initialMessage !== undefined + ? yield* textGeneration + .generateBranchName({ + cwd: project.workspaceRoot, + message: input.initialMessage.text, + attachments: input.initialMessage.attachments, + modelSelection: input.modelSelection, + }) + .pipe( + Effect.map((result) => result.branch), + Effect.mapError(mapError(input, "generate-metadata", threadId)), + ) + : (input.workspaceStrategy.branch ?? + (input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null)); let worktreePath = - stored?.worktree_path ?? - (input.workspaceStrategy.type === "existing_worktree" + input.workspaceStrategy.type === "existing_worktree" ? input.workspaceStrategy.worktreePath - : null); - const ownsProvisionedWorktree = input.workspaceStrategy.type === "worktree"; - const threadCommitted = stored?.thread_committed === 1; - let setupCommitted = stored?.setup_committed === 1; - let messageCommitted = stored?.message_committed === 1; - if (input.workspaceStrategy.type === "worktree" && worktreePath === null) { + : null; + if (input.workspaceStrategy.type === "worktree") { + if (runId !== null) { + yield* threads + .dispatch({ + type: "prepared-run.progress", + commandId: CommandId.make(`${input.commandId}:progress:worktree`), + threadId, + runId, + phase: "worktree", + }) + .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); + } let startRef = input.workspaceStrategy.baseRef; if (input.workspaceStrategy.startFromOrigin === true) { yield* git @@ -321,184 +282,272 @@ export const make = Effect.gen(function* () { .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))); worktreePath = worktree.worktree.path; branch = worktree.worktree.refName; - yield* saveWorkflow(input, { - threadId, - status: "workspace_ready", - title, - worktreePath, - branch, - setupCommitted, - threadCommitted, - messageCommitted, - }); } + + yield* threads + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${input.commandId}:workspace`), + threadId, + branch, + worktreePath, + }) + .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); + const cwd = worktreePath ?? project.workspaceRoot; - - if (!setupCommitted) { - const setupExit = yield* Effect.exit( - setupScripts.runForThread({ + if (runId !== null) { + yield* threads + .dispatch({ + type: "prepared-run.progress", + commandId: CommandId.make(`${input.commandId}:progress:setup`), threadId, - projectId: input.projectId, - projectCwd: project.workspaceRoot, - worktreePath: cwd, - project: { - workspaceRoot: project.workspaceRoot, - scripts: project.scripts, - }, - }), - ); - if (setupExit._tag === "Failure") { - if (ownsProvisionedWorktree && worktreePath !== null && !threadCommitted) { - yield* git - .removeWorktree({ cwd: project.workspaceRoot, path: worktreePath }) - .pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId))); - worktreePath = null; - } - yield* saveWorkflow(input, { - threadId, - status: "setup_failed", - title, - worktreePath, - branch, - setupCommitted: false, - threadCommitted, - messageCommitted, - lastError: "Project setup script failed.", - }); - return yield* Effect.failCause(setupExit.cause).pipe( - Effect.mapError(mapError(input, "run-setup-script", threadId)), - ); - } - setupCommitted = true; - yield* saveWorkflow(input, { - threadId, - status: "setup_ready", - title, - worktreePath, - branch, - setupCommitted, - threadCommitted, - messageCommitted, - }); + runId, + phase: "setup", + }) + .pipe(Effect.mapError(mapError(input, "update-thread", threadId))); } + yield* setupScripts + .runForThread({ + threadId, + projectId: input.projectId, + projectCwd: project.workspaceRoot, + worktreePath: cwd, + project: { + workspaceRoot: project.workspaceRoot, + scripts: project.scripts, + }, + }) + .pipe(Effect.mapError(mapError(input, "run-setup-script", threadId))); - if (!threadCommitted) { - const commitThread = - input.reuseExistingThread === true - ? Effect.gen(function* () { - yield* validateReusableThread(); - return yield* threads.dispatch({ - type: "thread.metadata.update", + if (runId !== null) { + yield* threads + .dispatch({ + type: "prepared-run.release", + commandId: CommandId.make(`${input.commandId}:release`), + threadId, + runId, + }) + .pipe(Effect.mapError(mapError(input, "release-run", threadId))); + } + }); + + const failPreparedRun = ( + input: ThreadLaunchInput, + threadId: ThreadId, + runId: RunId | null, + cause: unknown, + ) => + runId === null + ? Effect.logWarning("Thread workspace preparation failed", { + commandId: input.commandId, + threadId, + cause, + }) + : threads + .dispatch({ + type: "prepared-run.fail", + commandId: CommandId.make(`${input.commandId}:fail`), + threadId, + runId, + failure: makeProviderFailure({ + cause, + message: failureDetail(cause), + class: "validation_error", + retryable: false, + }), + }) + .pipe( + Effect.mapError(mapError(input, "fail-run", threadId)), + Effect.catchCause((persistCause) => + Effect.logWarning("Failed to persist thread workspace preparation failure", { commandId: input.commandId, threadId, - title, - branch, - worktreePath, - }); - }) - : threads.dispatch({ - type: "thread.create", - commandId: input.commandId, - threadId, - projectId: input.projectId, - title, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - branch, - worktreePath, - createdBy: input.createdBy, - creationSource: input.creationSource, - }); - const createExit = yield* Effect.exit(commitThread); - if (createExit._tag === "Failure") { - if (ownsProvisionedWorktree && worktreePath !== null) { - yield* git - .removeWorktree({ cwd: project.workspaceRoot, path: worktreePath }) - .pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId))); - worktreePath = null; - setupCommitted = false; + cause, + persistCause, + }), + ), + ); + + const reservePreparation = (commandId: CommandId) => + Ref.modify(scheduledLaunches, (scheduled) => { + if (scheduled.has(commandId)) return [false, scheduled] as const; + const next = new Set(scheduled); + next.add(commandId); + return [true, next] as const; + }); + + const releasePreparation = (commandId: CommandId) => + Ref.update(scheduledLaunches, (scheduled) => { + const next = new Set(scheduled); + next.delete(commandId); + return next; + }); + + const schedulePreparation = Effect.fn("ThreadLaunchService.schedulePreparation")(function* ( + input: ThreadLaunchInput, + threadId: ThreadId, + runId: RunId | null, + ) { + yield* prepareInBackground(input, threadId, runId).pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : failPreparedRun(input, threadId, runId, Cause.squash(cause)), + ), + Effect.ensuring(releasePreparation(input.commandId)), + Effect.forkIn(preparationScope), + ); + }); + + const launch: ThreadLaunchService["Service"]["launch"] = Effect.fn("ThreadLaunchService.launch")( + function* (input) { + const project = yield* projects.getById(input.projectId).pipe( + Effect.mapError(mapError(input, "resolve-project")), + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")), + onSome: Effect.succeed, + }), + ), + ); + if (input.reuseExistingThread === true && input.threadId === undefined) { + return yield* mapError( + input, + "update-thread", + )("Reusing an existing thread requires a thread id."); + } + + const launchReceipt = yield* readReceipt(input, input.commandId); + return yield* Effect.gen(function* () { + const candidateThreadId = + input.threadId ?? + (yield* ids.allocate + .thread({ projectId: input.projectId }) + .pipe(Effect.mapError(mapError(input, "create-thread")))); + + if (input.reuseExistingThread === true && Option.isNone(launchReceipt)) { + yield* validateReusableThread(input, candidateThreadId); } - yield* saveWorkflow(input, { - threadId, - status: - input.reuseExistingThread === true ? "thread_update_failed" : "thread_create_failed", - title, - worktreePath, - branch, - setupCommitted, - threadCommitted: false, - messageCommitted, - lastError: - input.reuseExistingThread === true - ? "Thread workspace update failed." - : "Thread creation failed.", - }); - return yield* Effect.failCause(createExit.cause).pipe( + + const initialBranch = input.workspaceStrategy.branch ?? null; + const initialWorktreePath = + input.workspaceStrategy.type === "existing_worktree" + ? input.workspaceStrategy.worktreePath + : null; + const claimDispatch = + input.reuseExistingThread === true + ? threads.dispatch({ + type: "thread.metadata.update", + commandId: input.commandId, + threadId: candidateThreadId, + }) + : threads.dispatch({ + type: "thread.create", + commandId: input.commandId, + threadId: candidateThreadId, + projectId: input.projectId, + title: input.title, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch: initialBranch, + worktreePath: initialWorktreePath, + createdBy: input.createdBy, + creationSource: input.creationSource, + }); + const claimed = yield* claimDispatch.pipe( Effect.mapError( mapError( input, input.reuseExistingThread === true ? "update-thread" : "create-thread", - threadId, + candidateThreadId, ), ), ); - } - yield* saveWorkflow(input, { - threadId, - status: "thread_created", - title, - worktreePath, - branch, - setupCommitted, - threadCommitted: true, - messageCommitted, - }); - } + const threadId = + claimed.storedEvents.find((stored) => stored.event.type.startsWith("thread."))?.event + .threadId ?? candidateThreadId; + if (project.id !== input.projectId) { + return yield* mapError(input, "resolve-project", threadId)("Project identity changed."); + } - if (input.initialMessage !== undefined && !messageCommitted) { - const messageId = - input.initialMessage.messageId ?? - (yield* ids.allocate - .message({ threadId, ordinal: 1 }) - .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)))); - yield* threads - .sendToThread({ - projectId: input.projectId, - commandId: CommandId.make(`${input.commandId}:initial-message`), + let runId: RunId | null = null; + let messageWasAlreadyAccepted = false; + if (input.initialMessage !== undefined) { + const messageCommandId = CommandId.make(`${input.commandId}:initial-message`); + const messageReceipt = yield* readReceipt(input, messageCommandId); + messageWasAlreadyAccepted = Option.isSome(messageReceipt); + const messageId = + input.initialMessage.messageId ?? + (yield* ids.allocate + .message({ threadId, ordinal: 1 }) + .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)))); + const dispatched = yield* threads + .dispatch({ + type: "message.dispatch", + commandId: messageCommandId, + threadId, + messageId, + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + modelSelection: input.modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: input.createdBy, + creationSource: input.creationSource, + }) + .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))); + const runCreated = dispatched.storedEvents.find( + (stored) => stored.event.type === "run.created", + ); + runId = runCreated?.event.type === "run.created" ? runCreated.event.payload.id : null; + if (runId === null) { + return yield* mapError( + input, + "dispatch-message", + threadId, + )("Initial message was accepted without a durable run."); + } + } + + const projection = yield* threads + .getThreadProjection(threadId) + .pipe(Effect.mapError(mapError(input, "create-thread", threadId))); + const runIsPreparing = + runId !== null && + projection.runs.some((run) => run.id === runId && run.status === "preparing"); + const shouldSchedule = runId === null ? Option.isNone(launchReceipt) : runIsPreparing; + if (shouldSchedule) { + const ownsPreparation = yield* reservePreparation(input.commandId); + if (ownsPreparation) { + yield* Effect.gen(function* () { + const preparationStillRequired = + runId === null + ? true + : yield* threads.getThreadProjection(threadId).pipe( + Effect.map((current) => + current.runs.some((run) => run.id === runId && run.status === "preparing"), + ), + Effect.mapError(mapError(input, "update-thread", threadId)), + ); + if (preparationStillRequired) { + yield* schedulePreparation(input, threadId, runId); + } else { + yield* releasePreparation(input.commandId); + } + }).pipe(Effect.onError(() => releasePreparation(input.commandId))); + } + } + + return { threadId, - messageId, - text: input.initialMessage.text, - attachments: input.initialMessage.attachments, - mode: "auto", - createdBy: input.createdBy, - creationSource: input.creationSource, - }) - .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))); - messageCommitted = true; - } - yield* saveWorkflow(input, { - threadId, - status: "completed", - title, - worktreePath, - branch, - setupCommitted, - threadCommitted: true, - messageCommitted, - }); - return { - threadId, - projection: yield* threads - .getThreadProjection(threadId) - .pipe(Effect.mapError(mapError(input, "create-thread", threadId))), - resumed: stored !== null, - }; - }); + projection, + resumed: Option.isSome(launchReceipt) || messageWasAlreadyAccepted, + }; + }); + }, + ); - return ThreadLaunchService.of({ - launch: (input) => launchSemaphore.withPermit(launchWorkflow(input)), - }); + return ThreadLaunchService.of({ launch }); }); export const layer = Layer.effect(ThreadLaunchService, make); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 821e324c5e..7a4301980e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -172,7 +172,12 @@ export class ThreadManagementService extends Context.Service< >()("t3/orchestration-v2/ThreadManagementService") {} export function isActiveRun(run: OrchestrationV2Run): boolean { - return run.status === "starting" || run.status === "running" || run.status === "waiting"; + return ( + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting" + ); } export function isTerminalRunStatus( @@ -421,7 +426,7 @@ const make = Effect.gen(function* () { }, } as const; } - const interruptibleRun = latestSteerableRun(target); + const interruptibleRun = latestActiveRun(target); if (input.runId === undefined && interruptibleRun === undefined) { return { type: "no_active_run" } as const; } diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 56144bbd95..72086134df 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3,6 +3,7 @@ import { assert, it } from "@effect/vitest"; import { type ApplicationStoredEvent, CommandId, + MessageId, type ModelSelection, ProjectId, ProviderDriverKind, @@ -22,7 +23,7 @@ import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSna import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts"; -import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts"; import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts"; @@ -30,10 +31,12 @@ import type { ProviderInstance } from "../provider/ProviderDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { OrchestratorV2 } from "./Orchestrator.ts"; +import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts"; import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { OrchestrationV2LayerLive } from "./runtimeLayer.ts"; import { shellStreamItemFromSnapshot } from "./ShellStream.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { ThreadManagementService } from "./ThreadManagementService.ts"; const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-orchestration-v2-runtime-layer-", @@ -53,6 +56,7 @@ const orchestrationAdapter = { instanceId: modelSelection.instanceId, driver, getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: () => Effect.die("sessions are not used by lifecycle tests"), } as ProviderAdapterV2Shape; const providerInstance = { @@ -93,8 +97,12 @@ const SharedApplicationDataPlaneTestLayer = Layer.merge( OrchestrationV2LayerLive, ).pipe( Layer.provide( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: () => Effect.succeed(null), + Layer.succeed(ProjectEnrichmentService, { + peek: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }), + request: () => Effect.void, + getAvailable: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }), + invalidate: () => Effect.void, + subscribeChanges: Effect.never, }), ), Layer.provide(mcpSessionRegistryTestLayer), @@ -273,6 +281,84 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => { ); }); +it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", (it) => { + it.effect("interrupts a pending provider start without launching provider work", () => + Effect.gen(function* () { + const applicationEngine = yield* OrchestrationEngineService; + const orchestrator = yield* OrchestratorV2; + const threadManagement = yield* ThreadManagementService; + const effectWorker = yield* OrchestrationEffectWorkerV2; + const projectId = ProjectId.make("runtime-layer-pending-interrupt-project"); + const threadId = ThreadId.make("runtime-layer-pending-interrupt-thread"); + + yield* applicationEngine.dispatch({ + type: "project.create", + commandId: CommandId.make("runtime-layer-pending-interrupt-project-create"), + projectId, + title: "Pending interrupt project", + workspaceRoot: "/tmp/runtime-layer-pending-interrupt-project", + defaultModelSelection: modelSelection, + scripts: [], + createdAt: "2026-06-22T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-pending-interrupt-create"), + threadId, + projectId, + title: "Pending interrupt", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-pending-interrupt-message"), + threadId, + messageId: MessageId.make("runtime-layer-pending-interrupt-message"), + text: "Do not reach the provider.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + + const starting = yield* orchestrator.getThreadProjection(threadId); + const run = starting.runs[0]; + assert.isDefined(run); + assert.equal(run.status, "starting"); + + const interrupt = yield* threadManagement.interruptThread({ + projectId, + commandId: CommandId.make("runtime-layer-pending-interrupt-command"), + threadId, + runId: run.id, + reason: "Cancelled before provider start", + }); + assert.equal(interrupt.type, "interrupt_requested"); + + const interrupted = yield* orchestrator.getThreadProjection(threadId); + assert.equal(interrupted.runs[0]?.status, "interrupted"); + assert.equal(interrupted.attempts[0]?.status, "interrupted"); + assert.equal( + interrupted.nodes.find((node) => node.kind === "root_turn")?.status, + "interrupted", + ); + assert.deepEqual( + interrupted.turnItems.filter((item) => item.runId === run.id).map((item) => item.type), + ["user_message", "run_interrupt_request", "run_interrupt_result"], + ); + assert.deepEqual(interrupted.providerTurns, []); + assert.isFalse(yield* effectWorker.runOnce); + }), + ); +}); + it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => { it.effect("orders retained project transactions and V2 thread transactions in one source", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 689a7f20c3..57241b23d4 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -216,6 +216,7 @@ const threadLaunchProvided = threadLaunchServiceLayer.pipe( ProjectServiceLayerLive, ProjectSetupScriptRunnerLayerLive, threadManagementProvided, + commandReceiptStoreProvided, idAllocatorLayer, ), ), diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts index 447c40a5f8..09b756655d 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -24,7 +24,10 @@ import { type OrchestratorV2ProviderReplayHarness, } from "./ProviderReplayHarness.ts"; import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts"; -import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts"; +import { + decodeProviderReplayNdjson, + materializeReplayTranscriptWorkspace, +} from "./ReplayTranscriptNdjson.ts"; const readTranscript = Effect.fn("readOrchestratorReplayTranscript")(function* (file: URL) { const fs = yield* FileSystem.FileSystem; @@ -60,8 +63,12 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < readonly enableAssistantStreaming?: boolean; }) { const rawTranscript = yield* readTranscript(input.driver.transcriptFile); - const transcript = yield* input.harness.decodeTranscript(rawTranscript); const workspace = yield* checkpointWorkspace(input.fixtureName); + const transcript = yield* input.harness.decodeTranscript( + input.driver.driver === "codex" + ? materializeReplayTranscriptWorkspace(rawTranscript, workspace) + : rawTranscript, + ); const materialized = yield* materializeFixtureInput({ scenario: input.fixtureName, fixtureInput: input.buildInput(), diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 0b596c0a98..073ac63995 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -49,6 +49,12 @@ export type OrchestratorV2ScenarioStep = readonly threadId: ThreadId; readonly runId: OrchestrationV2Run["id"]; } + | { + readonly type: "await_run_status"; + readonly threadId: ThreadId; + readonly runId: OrchestrationV2Run["id"]; + readonly status: OrchestrationV2Run["status"]; + } | { readonly type: "await_run_turn_item"; readonly threadId: ThreadId; @@ -101,6 +107,9 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray request.status === "pending"); const hasActiveRun = (projection: OrchestrationV2ThreadProjection) => - projection.runs.some((run) => ["queued", "starting", "running", "waiting"].includes(run.status)); + projection.runs.some((run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + ); const SCENARIO_WAIT_ATTEMPTS = 10_000; @@ -242,7 +253,9 @@ export function runOrchestratorV2Scenario( } if (attemptsRemaining <= 0) { const activeRuns = projection.runs - .filter((run) => ["queued", "starting", "running", "waiting"].includes(run.status)) + .filter((run) => + ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), + ) .map((run) => `${run.id}:${run.status}`) .join(","); const pendingRequests = projection.runtimeRequests @@ -285,6 +298,28 @@ export function runOrchestratorV2Scenario( return yield* waitForRunSteerable(threadId, runId, attemptsRemaining - 1); }); + const waitForRunStatus = ( + threadId: ThreadId, + runId: OrchestrationV2Run["id"], + status: OrchestrationV2Run["status"], + attemptsRemaining = SCENARIO_WAIT_ATTEMPTS, + ): Effect.Effect => + Effect.gen(function* () { + const projection = yield* orchestrator.getThreadProjection(threadId); + const run = projection.runs.find((candidate) => candidate.id === runId); + if (run?.status === status) { + return; + } + if (attemptsRemaining <= 0) { + return yield* new OrchestratorV2ScenarioStepError({ + scenario: scenario.name, + step: `await_run_status:${runId}:${status}:actual=${run?.status ?? "missing"}`, + }); + } + yield* yieldToRuntime; + return yield* waitForRunStatus(threadId, runId, status, attemptsRemaining - 1); + }); + const waitForRunTurnItem = ( threadId: ThreadId, runId: OrchestrationV2Run["id"], @@ -346,6 +381,9 @@ export function runOrchestratorV2Scenario( case "await_run_steerable": yield* waitForRunSteerable(step.threadId, step.runId); break; + case "await_run_status": + yield* waitForRunStatus(step.threadId, step.runId, step.status); + break; case "await_run_turn_item": yield* waitForRunTurnItem(step.threadId, step.runId, step.itemType); break; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 80d6437606..da34715e6f 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -24,16 +24,16 @@ import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts"; import { layer as contextHandoffServiceLayer } from "../ContextHandoffService.ts"; import { layer as effectOutboxLayer } from "../EffectOutbox.ts"; import { - daemonLayer as effectWorkerDaemonLayer, executorLayer as effectExecutorLayer, layer as effectWorkerLayer, + runDaemon as runEffectWorkerDaemon, } from "../EffectWorker.ts"; import { layerFromStores as eventSinkLayer } from "../EventSink.ts"; import { layer as eventStoreLayer } from "../EventStore.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { layer as orchestratorLayer } from "../Orchestrator.ts"; import { layer as projectionStoreLayer } from "../ProjectionStore.ts"; -import type { OrchestratorV2, OrchestratorV2Error } from "../Orchestrator.ts"; +import { OrchestratorV2, type OrchestratorV2Error } from "../Orchestrator.ts"; import { ProviderAdapterRegistryV2 } from "../ProviderAdapterRegistry.ts"; import { layer as providerEventIngestorLayer } from "../ProviderEventIngestor.ts"; import { layerWithOptions as providerSessionManagerLayerWithOptions } from "../ProviderSessionManager.ts"; @@ -169,6 +169,7 @@ export function runOrchestratorV2ProviderReplayScenario< MigrationError | PlatformError.PlatformError | SqlError >; readonly enableAssistantStreaming?: boolean; + readonly runEffectWorker?: boolean; } = {}, ): Effect.Effect< OrchestratorV2ScenarioResult, @@ -197,6 +198,7 @@ export function makeOrchestratorV2ProviderReplayLayer< MigrationError | PlatformError.PlatformError | SqlError >; readonly enableAssistantStreaming?: boolean; + readonly runEffectWorker?: boolean; } = {}, ): Layer.Layer { const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript); @@ -212,6 +214,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( MigrationError | PlatformError.PlatformError | SqlError >; readonly enableAssistantStreaming?: boolean; + readonly runEffectWorker?: boolean; } = {}, ): Layer.Layer { const serverConfigLayer = Layer.effect( @@ -344,9 +347,6 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( const effectWorkerProvided = effectWorkerLayer.pipe( Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)), ); - const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe( - Layer.provide(effectWorkerProvided), - ); const orchestratorProvided = orchestratorLayer.pipe( Layer.provide( Layer.mergeAll( @@ -364,5 +364,20 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( ), ), ); - return Layer.merge(orchestratorProvided, effectWorkerDaemonProvided); + const replayRuntime = Layer.merge(orchestratorProvided, effectWorkerProvided); + + // Build the daemon from the exact worker instance exposed alongside the + // orchestrator. Keeping this acquisition in the replay layer makes the + // outbox lifecycle explicit and prevents test-only command-side draining. + if (options.runEffectWorker === false) { + return orchestratorProvided; + } + return Layer.effect( + OrchestratorV2, + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + yield* runEffectWorkerDaemon.pipe(Effect.forkScoped); + return orchestrator; + }), + ).pipe(Layer.provide(replayRuntime)); } diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 41e3159835..44d9853be9 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -73,6 +73,7 @@ function makeTestAdapter(input: { instanceId: input.instanceId, driver: input.driver, getCapabilities: () => Effect.succeed(input.capabilities), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (sessionInput) => Effect.gen(function* () { const events = yield* PubSub.unbounded(); @@ -95,7 +96,6 @@ function makeTestAdapter(input: { driver: input.driver, providerSessionId: sessionInput.providerSessionId, providerSession, - rawEvents: Stream.empty, events: Stream.fromPubSub(events), ensureThread: (threadInput) => Effect.gen(function* () { @@ -198,8 +198,12 @@ function makeTestAdapter(input: { { type: "turn.terminal", driver: input.driver, + providerThreadId: turnInput.providerThread.id, providerTurnId, + runOrdinal: turnInput.runOrdinal, status: "completed", + failure: null, + threadDisposition: "reusable", }, ]; for (const event of providerEvents) { diff --git a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts index 9e6c8b76a5..f5b6283e06 100644 --- a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts @@ -3,7 +3,10 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts"; +import { + decodeProviderReplayNdjson, + materializeReplayTranscriptWorkspace, +} from "./ReplayTranscriptNdjson.ts"; const encodeParseError = Schema.encodeUnknownEffect(ProviderReplayNdjsonParseError); @@ -69,4 +72,28 @@ describe("decodeProviderReplayNdjson", () => { assert.doesNotThrow(() => JSON.stringify(encoded)); }), ); + + it.effect("materializes outbound workspace placeholders without weakening replay frames", () => + Effect.gen(function* () { + const transcript = yield* decodeProviderReplayNdjson(` + {"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.120.0","scenario":"workspace"} + {"type":"expect_outbound","frame":{"method":"turn/start","params":{"cwd":"","nested":[""]}}} + {"type":"emit_inbound","frame":{"method":"item/completed","params":{"text":""}}} + `); + + const materialized = materializeReplayTranscriptWorkspace(transcript, "/tmp/workspace"); + + assert.deepEqual(materialized.entries[0], { + type: "expect_outbound", + frame: { + method: "turn/start", + params: { cwd: "/tmp/workspace", nested: ["/tmp/workspace"] }, + }, + }); + assert.deepEqual(materialized.entries[1], { + type: "emit_inbound", + frame: { method: "item/completed", params: { text: "" } }, + }); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts index 87dbfc6f69..c7090917a1 100644 --- a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts +++ b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts @@ -47,6 +47,47 @@ export type ProviderReplayNdjsonParseError = typeof ProviderReplayNdjsonParseErr export type ProviderReplayTranscriptMetadata = Omit; +export const REPLAY_TRANSCRIPT_WORKSPACE_PLACEHOLDER = ""; + +function materializeWorkspacePlaceholder(value: unknown, workspace: string): unknown { + if (value === REPLAY_TRANSCRIPT_WORKSPACE_PLACEHOLDER) { + return workspace; + } + if (Array.isArray(value)) { + return value.map((entry) => materializeWorkspacePlaceholder(entry, workspace)); + } + if (typeof value !== "object" || value === null) { + return value; + } + return Object.fromEntries( + Object.entries(value).map(([key, entry]) => [ + key, + materializeWorkspacePlaceholder(entry, workspace), + ]), + ); +} + +/** + * Resolves portable fixture placeholders before a replay driver sees the transcript. + * The resulting outbound frames still use exact structural equality during replay. + */ +export function materializeReplayTranscriptWorkspace( + transcript: ProviderReplayTranscript, + workspace: string, +): ProviderReplayTranscript { + return { + ...transcript, + entries: transcript.entries.map((entry) => + entry.type === "expect_outbound" + ? { + ...entry, + frame: materializeWorkspacePlaceholder(entry.frame, workspace), + } + : entry, + ), + }; +} + const decodeReplayRecord = Schema.decodeUnknownSync( Schema.fromJsonString(ProviderReplayNdjsonRecord), ); diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts index b1e0c91f3d..063011b657 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts @@ -29,7 +29,10 @@ import { THREAD_FORK_NATIVE_TARGET_PROMPT, } from "./fixtures/shared.ts"; import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts"; -import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts"; +import { + decodeProviderReplayNdjson, + materializeReplayTranscriptWorkspace, +} from "./ReplayTranscriptNdjson.ts"; const CODEX_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("codex"), @@ -400,13 +403,15 @@ describe("orchestration V2 thread fork", () => { () => Effect.gen(function* () { const rawTranscript = yield* readTranscript(); - const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(rawTranscript); const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => Effect.service(FileSystem.FileSystem).pipe( Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), Effect.orDie, ), ); + const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( + materializeReplayTranscriptWorkspace(rawTranscript, cwd), + ); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocatorV2; @@ -714,13 +719,15 @@ describe("orchestration V2 thread fork", () => { () => Effect.gen(function* () { const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH); - const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(rawTranscript); const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => Effect.service(FileSystem.FileSystem).pipe( Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), Effect.orDie, ), ); + const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( + materializeReplayTranscriptWorkspace(rawTranscript, cwd), + ); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocatorV2; @@ -1068,6 +1075,7 @@ describe("orchestration V2 thread fork", () => { "thread-fork-native-prior-turn-source-rollback-target", ); const firstRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 1 }); + const secondRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 2 }); const checkpointScopeId = yield* ids.allocate.checkpointScope({ threadId: sourceThreadId, name: "root", @@ -1169,6 +1177,7 @@ describe("orchestration V2 thread fork", () => { return { sourceThreadId, targetThreadId, + secondRunId, commands, }; }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime); @@ -1189,6 +1198,12 @@ describe("orchestration V2 thread fork", () => { { type: "dispatch", command: materialized.commands[4]!, await: true }, { type: "await_thread_idle", threadId: materialized.targetThreadId }, { type: "dispatch", command: materialized.commands[5]!, await: true }, + { + type: "await_run_status", + threadId: materialized.sourceThreadId, + runId: materialized.secondRunId, + status: "rolled_back", + }, ], projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId], runtimePolicyOverride: { cwd }, diff --git a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts index 736428f9c3..9acc0baf83 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts @@ -35,7 +35,10 @@ import { } from "./fixtures/shared.ts"; import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts"; import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts"; -import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts"; +import { + decodeProviderReplayNdjson, + materializeReplayTranscriptWorkspace, +} from "./ReplayTranscriptNdjson.ts"; const CODEX_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("codex"), @@ -349,8 +352,9 @@ describe("orchestration V2 merge-back provider replay", () => { ? yield* runOrchestratorV2ProviderReplayScenario( { ...scenario, - transcript: - yield* CodexOrchestratorReplayHarness.decodeTranscript(parameterizedTranscript), + transcript: yield* CodexOrchestratorReplayHarness.decodeTranscript( + materializeReplayTranscriptWorkspace(parameterizedTranscript, cwd), + ), }, CodexOrchestratorReplayHarness, ).pipe(provideDeterministicTestRuntime) @@ -602,7 +606,9 @@ describe("orchestration V2 merge-back provider replay", () => { ? yield* runOrchestratorV2ProviderReplayScenario( { ...scenario, - transcript: yield* CodexOrchestratorReplayHarness.decodeTranscript(transcript), + transcript: yield* CodexOrchestratorReplayHarness.decodeTranscript( + materializeReplayTranscriptWorkspace(transcript, cwd), + ), }, CodexOrchestratorReplayHarness, ).pipe(provideDeterministicTestRuntime) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson index c9b76c13a2..2328008a85 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019e014d-b214-71f0-9538-23527e8247ca","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778138329,"updatedAt":1778138329,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T00-18-49-019e014d-b214-71f0-9538-23527e8247ca.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","instructionSources":["/Users/julius/.codex_p/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex_p/memories"],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"type":"managed","network":{"enabled":false},"fileSystem":{"type":"restricted","entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":null}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".git"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".agents"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".codex"}},"access":"read"},{"path":{"type":"path","path":"/Users/julius/.codex_p/memories"},"access":"write"}]}},"activePermissionProfile":{"id":":workspace","extends":null,"modifications":[]},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"threadId":"019e014d-b214-71f0-9538-23527e8247ca"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: steering fixture initial response","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019e014d-b214-71f0-9538-23527e8247ca"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019e014d-b214-71f0-9538-23527e8247ca","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778138329,"updatedAt":1778138329,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T00-18-49-019e014d-b214-71f0-9538-23527e8247ca.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019e014d-b214-71f0-9538-23527e8247ca","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /Users/julius/.codex_p/config.toml."}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson index a6a0dc4bc7..a202c381d5 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadec-c14b-7b13-b96c-92c98ccfc342","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-27-019dadec-c14b-7b13-b96c-92c98ccfc342.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadec-c14b-7b13-b96c-92c98ccfc342","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-27-019dadec-c14b-7b13-b96c-92c98ccfc342.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} @@ -29,7 +29,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1776748632},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1777335432},"credits":null,"planType":"pro"}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","turn":{"id":"019dadec-c155-74a2-8acc-f9f4ff86c15b","items":[],"status":"completed","error":null,"startedAt":1776739467,"completedAt":1776739474,"durationMs":6986}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"019dadec-dca0-7df0-9bc1-5a44135d8735","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","turn":{"id":"019dadec-dca0-7df0-9bc1-5a44135d8735","items":[],"status":"inProgress","error":null,"startedAt":1776739474,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson index e4157905f6..e3b0ff72ba 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019db22a-e824-7ac3-bbf7-994a4aa087e5","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810649,"updatedAt":1776810649,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-30-49-019db22a-e824-7ac3-bbf7-994a4aa087e5.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.3-codex","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db22a-e824-7ac3-bbf7-994a4aa087e5","collaborationMode":{"mode":"plan","settings":{"developer_instructions":"# Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `` block.\n\nSeparately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, `target/`, `.cache/`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the `request_user_input` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the `request_user_input` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n * If asking, present concrete candidates (paths/service names) + recommend one.\n * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n * These are intent or implementation preferences that cannot be derived from exploration.\n * Provide 2-4 mutually exclusive options + a recommended default.\n * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a `` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as `` and `` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n\nplan content\n\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one `` block per turn, and only when you are presenting a complete spec.\n","model":"gpt-5.4","reasoning_effort":"medium"}}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db22a-e824-7ac3-bbf7-994a4aa087e5","collaborationMode":{"mode":"plan","settings":{"developer_instructions":"# Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `` block.\n\nSeparately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, `target/`, `.cache/`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the `request_user_input` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the `request_user_input` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n * If asking, present concrete candidates (paths/service names) + recommend one.\n * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n * These are intent or implementation preferences that cannot be derived from exploration.\n * Provide 2-4 mutually exclusive options + a recommended default.\n * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a `` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as `` and `` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n\nplan content\n\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one `` block per turn, and only when you are presenting a complete spec.\n","model":"gpt-5.4","reasoning_effort":"medium"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019db22a-e824-7ac3-bbf7-994a4aa087e5","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810649,"updatedAt":1776810649,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-30-49-019db22a-e824-7ac3-bbf7-994a4aa087e5.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson index df39632263..c61abe9d93 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019db22b-08cd-7e12-b967-cf6ab32dd408","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810658,"updatedAt":1776810658,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-30-58-019db22b-08cd-7e12-b967-cf6ab32dd408.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.3-codex","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","collaborationMode":{"mode":"plan","settings":{"developer_instructions":"# Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `` block.\n\nSeparately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, `target/`, `.cache/`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the `request_user_input` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the `request_user_input` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n * If asking, present concrete candidates (paths/service names) + recommend one.\n * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n * These are intent or implementation preferences that cannot be derived from exploration.\n * Provide 2-4 mutually exclusive options + a recommended default.\n * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a `` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as `` and `` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n\nplan content\n\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one `` block per turn, and only when you are presenting a complete spec.\n","model":"gpt-5.4","reasoning_effort":"medium"}}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Create a short implementation plan for adding deterministic replay fixtures. Do not ask questions. Present the final plan in a proposed plan block.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","collaborationMode":{"mode":"plan","settings":{"developer_instructions":"# Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a `` block.\n\nSeparately, `update_plan` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use `update_plan` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, `target/`, `.cache/`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the `request_user_input` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the `request_user_input` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n * If asking, present concrete candidates (paths/service names) + recommend one.\n * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n * These are intent or implementation preferences that cannot be derived from exploration.\n * Provide 2-4 mutually exclusive options + a recommended default.\n * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a `` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as `` and `` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n\nplan content\n\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a `` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one `` block per turn, and only when you are presenting a complete spec.\n","model":"gpt-5.4","reasoning_effort":"medium"}}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019db22b-08cd-7e12-b967-cf6ab32dd408","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810658,"updatedAt":1776810658,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-30-58-019db22b-08cd-7e12-b967-cf6ab32dd408.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson index c8d19f6d07..f28e4ccf24 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/provider_thread_resume/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019db117-b50d-7a01-a6b6-65e47d749c3e","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776792614,"updatedAt":1776792614,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T10-30-14-019db117-b50d-7a01-a6b6-65e47d749c3e.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.3-codex","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":null,"input":[{"text":"Respond with exactly: provider thread resume fixture first turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019db117-b50d-7a01-a6b6-65e47d749c3e","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776792614,"updatedAt":1776792614,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T10-30-14-019db117-b50d-7a01-a6b6-65e47d749c3e.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} @@ -42,7 +42,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"thread/resume","frame":{"id":2,"result":{"thread":{"id":"019db117-b50d-7a01-a6b6-65e47d749c3e","forkedFromId":null,"preview":"Respond with exactly: provider thread resume fixture first turn complete","ephemeral":false,"modelProvider":"openai","createdAt":1776792614,"updatedAt":1776792622,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T10-30-14-019db117-b50d-7a01-a6b6-65e47d749c3e.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"7eefb2eb1d98f6b814c9fd7f43652727059c3326","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019db117-b519-7fa3-85c8-7762b26478a7","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"Respond with exactly: provider thread resume fixture first turn complete","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"provider thread resume fixture first turn complete","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1776792614,"completedAt":1776792622,"durationMs":8794}]},"model":"gpt-5.3-codex","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":null,"input":[{"text":"Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"019db117-d7ac-7462-90cf-8e244a290f78","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019db117-b50d-7a01-a6b6-65e47d749c3e","turn":{"id":"019db117-d7ac-7462-90cf-8e244a290f78","items":[],"status":"inProgress","error":null,"startedAt":1776792623,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson index d8fd90960d..1d9f4048bc 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadec-c14b-7b13-b96c-92c98ccfc342","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-27-019dadec-c14b-7b13-b96c-92c98ccfc342.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadec-c14b-7b13-b96c-92c98ccfc342","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739467,"updatedAt":1776739467,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-27-019dadec-c14b-7b13-b96c-92c98ccfc342.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} @@ -29,7 +29,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1776748632},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1777335432},"credits":null,"planType":"pro"}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","turn":{"id":"019dadec-c155-74a2-8acc-f9f4ff86c15b","items":[],"status":"completed","error":null,"startedAt":1776739467,"completedAt":1776739474,"durationMs":6986}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"019dadec-dca0-7df0-9bc1-5a44135d8735","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dadec-c14b-7b13-b96c-92c98ccfc342","turn":{"id":"019dadec-dca0-7df0-9bc1-5a44135d8735","items":[],"status":"inProgress","error":null,"startedAt":1776739474,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index 3533f8a01c..1dd8fe2d73 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -596,6 +596,11 @@ export function materializeFixtureInput(input: { } break; case "interrupt": + steps.push({ + type: "await_run_steerable", + threadId: ids.threadId, + runId: runIdFor(step.targetRunIndex), + }); if (step.waitForTurnItemType !== undefined) { steps.push({ type: "await_run_turn_item", @@ -691,6 +696,7 @@ export function assertBaseProjection(input: { assert.isAtLeast( projection.providerTurns.length, input.providerTurnCountAtLeast ?? input.runCount, + `expected provider turns; runs=${projection.runs.map((run) => `${run.id}:${run.status}`).join(",")}; sessions=${projection.providerSessions.map((session) => `${session.id}:${session.status}`).join(",")}; items=${projection.turnItems.map((item) => (item.type === "error" ? `${item.type}:${item.failure.message}` : item.type)).join(",")}`, ); assert.isAtLeast(input.result.domainEvents.length, 1); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson index adf4fc6c04..680905ccd1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadea-f49b-7012-aa03-534f1bfc3181","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739349,"updatedAt":1776739349,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-42-29-019dadea-f49b-7012-aa03-534f1bfc3181.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"threadId":"019dadea-f49b-7012-aa03-534f1bfc3181"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with the following text: fixture simple ok","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019dadea-f49b-7012-aa03-534f1bfc3181"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadea-f49b-7012-aa03-534f1bfc3181","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739349,"updatedAt":1776739349,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-42-29-019dadea-f49b-7012-aa03-534f1bfc3181.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson index f8c8355aa6..c7135aa158 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadec-4bed-7991-a1b7-1ed4fc1038b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739437,"updatedAt":1776739437,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-57-019dadec-4bed-7991-a1b7-1ed4fc1038b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"on-request","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadec-4bed-7991-a1b7-1ed4fc1038b8"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"on-request","cwd":"","input":[{"text":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadec-4bed-7991-a1b7-1ed4fc1038b8"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadec-4bed-7991-a1b7-1ed4fc1038b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739437,"updatedAt":1776739437,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-57-019dadec-4bed-7991-a1b7-1ed4fc1038b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson index f6ba3c2d4c..563cebbf2a 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_continue/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"native-root-thread","sessionId":"native-root-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1781051850,"updatedAt":1781051850,"status":{"type":"idle"},"path":"/tmp/root-thread.jsonl","cwd":"/tmp","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":null,"cwd":"/tmp","instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false},"reasoningEffort":"high"}}} -{"type":"expect_outbound","label":"turn/start/spawn","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"threadId":"native-root-thread"}}} +{"type":"expect_outbound","label":"turn/start/spawn","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-root-thread"}}} {"type":"emit_inbound","label":"turn/start/spawn","frame":{"id":3,"result":{"turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"turn/started/root-1","frame":{"method":"turn/started","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051851,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/completed/root-user-1","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-1","content":[{"type":"text","text":"Spawn one subagent and have it reply exactly: initial subagent response","text_elements":[]}]},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051851000}}} @@ -17,7 +17,7 @@ {"type":"emit_inbound","label":"item/completed/wait-1","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-1","tool":"wait","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{"native-child-thread":{"status":"completed","message":"initial subagent response"}}},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051853100}}} {"type":"emit_inbound","label":"item/completed/root-answer-1","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-answer-1","text":"Hooke says: initial subagent response","phase":"final_answer","memoryCitation":null},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051854000}}} {"type":"emit_inbound","label":"turn/completed/root-1","frame":{"method":"turn/completed","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1781051851,"completedAt":1781051854,"durationMs":3000}}}} -{"type":"expect_outbound","label":"turn/start/continue","frame":{"id":4,"method":"turn/start","params":{"input":[{"text":"@hooke have the same subagent reply exactly: continued subagent response","type":"text"}],"threadId":"native-root-thread"}}} +{"type":"expect_outbound","label":"turn/start/continue","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"@hooke have the same subagent reply exactly: continued subagent response","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-root-thread"}}} {"type":"emit_inbound","label":"turn/start/continue","frame":{"id":4,"result":{"turn":{"id":"native-root-turn-2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"turn/started/root-2","frame":{"method":"turn/started","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051860,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/completed/root-user-2","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-2","content":[{"type":"text","text":"@hooke have the same subagent reply exactly: continued subagent response","text_elements":[]}]},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051860000}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson index 7076046378..4d8dabfa4a 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start/source","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start/source","frame":{"id":2,"result":{"thread":{"id":"native-source-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739349,"updatedAt":1776739349,"status":{"type":"idle"},"path":"/tmp/source.jsonl","cwd":"/tmp/project","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/tmp/project","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start/source","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with the following text: source fork seed ok","type":"text"}],"threadId":"native-source-thread"}}} +{"type":"expect_outbound","label":"turn/start/source","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with the following text: source fork seed ok","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-source-thread"}}} {"type":"emit_inbound","label":"turn/start/source","frame":{"id":3,"result":{"turn":{"id":"native-source-turn","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"turn/started/source","frame":{"method":"turn/started","params":{"threadId":"native-source-thread","turn":{"id":"native-source-turn","items":[],"status":"inProgress","error":null,"startedAt":1776739349,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/completed/source-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"native-source-user-item","content":[{"type":"text","text":"Respond with the following text: source fork seed ok","text_elements":[]}]},"threadId":"native-source-thread","turnId":"native-source-turn"}}} @@ -12,7 +12,7 @@ {"type":"emit_inbound","label":"turn/completed/source","frame":{"method":"turn/completed","params":{"threadId":"native-source-thread","turn":{"id":"native-source-turn","items":[],"status":"completed","error":null,"startedAt":1776739349,"completedAt":1776739356,"durationMs":6434}}}} {"type":"expect_outbound","label":"thread/fork","frame":{"id":4,"method":"thread/fork","params":{"threadId":"native-source-thread"}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"native-fork-thread","forkedFromId":"native-source-thread","preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739360,"updatedAt":1776739360,"status":{"type":"idle"},"path":"/tmp/fork.jsonl","cwd":"/tmp/project","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/tmp/project","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start/fork","frame":{"id":5,"method":"turn/start","params":{"input":[{"text":"Respond with the following text: fork native ok","type":"text"}],"threadId":"native-fork-thread"}}} +{"type":"expect_outbound","label":"turn/start/fork","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with the following text: fork native ok","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-fork-thread"}}} {"type":"emit_inbound","label":"turn/start/fork","frame":{"id":5,"result":{"turn":{"id":"native-fork-turn","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"turn/started/fork","frame":{"method":"turn/started","params":{"threadId":"native-fork-thread","turn":{"id":"native-fork-turn","items":[],"status":"inProgress","error":null,"startedAt":1776739361,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"item/completed/fork-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"native-fork-user-item","content":[{"type":"text","text":"Respond with the following text: fork native ok","text_elements":[]}]},"threadId":"native-fork-thread","turnId":"native-fork-turn"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_continue/codex_transcript.ndjson index 864898bd8c..d3d4324258 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_continue/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_continue/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"Juliuss-MacBook-Pro.local","installationId":"c067a38f-79bf-4874-ba7b-c00e86012954","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019ea981-51d9-7ba2-a200-6937187e3928","sessionId":"019ea981-51d9-7ba2-a200-6937187e3928","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780960285,"updatedAt":1780960285,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-11-25-019ea981-51d9-7ba2-a200-6937187e3928.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Remember the opaque marker source-marker-7Q9V for later in this conversation. Respond with exactly: source marker stored","type":"text"}],"threadId":"019ea981-51d9-7ba2-a200-6937187e3928"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the opaque marker source-marker-7Q9V for later in this conversation. Respond with exactly: source marker stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea981-51d9-7ba2-a200-6937187e3928"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea981-51d9-7ba2-a200-6937187e3928","sessionId":"019ea981-51d9-7ba2-a200-6937187e3928","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780960285,"updatedAt":1780960285,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-11-25-019ea981-51d9-7ba2-a200-6937187e3928.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} @@ -44,7 +44,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"019ea981-64c4-76b1-9f90-866490b7dd60","sessionId":"019ea981-64c4-76b1-9f90-866490b7dd60","forkedFromId":"019ea981-51d9-7ba2-a200-6937187e3928","parentThreadId":null,"preview":"Remember the opaque marker source-marker-7Q9V for later in this conversation. Respond with exactly: source marker stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960289,"updatedAt":1780960290,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-11-30-019ea981-64c4-76b1-9f90-866490b7dd60.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea981-539b-7650-a091-e03174d8e009","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker source-marker-7Q9V for later in this conversation. Respond with exactly: source marker stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"source marker stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780960285,"completedAt":1780960289,"durationMs":4325}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"input":[{"text":"Remember the second opaque marker fork-marker-2K4M for later in this conversation. Respond with exactly: fork marker stored","type":"text"}],"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the second opaque marker fork-marker-2K4M for later in this conversation. Respond with exactly: fork marker stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60","turnId":"019ea981-539b-7650-a091-e03174d8e009","tokenUsage":{"total":{"totalTokens":18446,"inputTokens":18439,"cachedInputTokens":9088,"outputTokens":7,"reasoningOutputTokens":0},"last":{"totalTokens":18446,"inputTokens":18439,"cachedInputTokens":9088,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea981-64c4-76b1-9f90-866490b7dd60","sessionId":"019ea981-64c4-76b1-9f90-866490b7dd60","forkedFromId":"019ea981-51d9-7ba2-a200-6937187e3928","parentThreadId":null,"preview":"Remember the opaque marker source-marker-7Q9V for later in this conversation. Respond with exactly: source marker stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960289,"updatedAt":1780960290,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-11-30-019ea981-64c4-76b1-9f90-866490b7dd60.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019ea981-662f-70c3-b2e4-9357b2beb122","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} @@ -66,7 +66,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60","turn":{"id":"019ea981-662f-70c3-b2e4-9357b2beb122","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780960290,"completedAt":1780960294,"durationMs":3942}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"input":[{"text":"Return the two opaque markers previously provided in chronological order, separated by a single | character. Respond with only the markers and separator.","type":"text"}],"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Return the two opaque markers previously provided in chronological order, separated by a single | character. Respond with only the markers and separator.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"019ea981-759a-7e61-90b2-29c4a08825db","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea981-64c4-76b1-9f90-866490b7dd60","turn":{"id":"019ea981-759a-7e61-90b2-29c4a08825db","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780960294,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson index 3d37d5d21b..6acaad473e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"network":{"enabled":false},"fileSystem":{"entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"current_working_directory"}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"path","path":"/Users/julius/.codex/memories"},"access":"write"},{"path":{"type":"path","path":"/Users/julius/Development/Work/codething-mvp/.git/worktrees/t3code-c1e5e1d1"},"access":"read"},{"path":{"type":"path","path":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/.git"},"access":"read"},{"path":{"type":"path","path":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/.codex"},"access":"read"}]}},"reasoningEffort":"medium"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1777424017,"updatedAt":1777424017,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-37-019dd6ba-2681-7bf0-b051-141b0cbcbb27.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"approvalPolicy":"never","sandboxPolicy":{"type":"readOnly","networkAccess":false}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27"}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /Users/julius/.codex/config.toml."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} @@ -31,7 +31,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1777429830},"secondary":{"usedPercent":23,"windowDurationMins":10080,"resetsAt":1777959590},"credits":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"approvalPolicy":"never","sandboxPolicy":{"type":"readOnly","networkAccess":false}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta"}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","turn":{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[],"status":"inProgress","error":null,"startedAt":1777424023,"completedAt":null,"durationMs":null}}}} @@ -61,7 +61,7 @@ {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880},{"id":"019dd6ba-416d-7902-95cf-d4179c3f4738","items":[{"type":"userMessage","id":"item-3","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary beta","text_elements":[]}]},{"type":"agentMessage","id":"item-4","text":"fork boundary beta","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424023,"completedAt":1777424025,"durationMs":1596}]}}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","turnId":"019dd6ba-47e9-7ed2-ba44-374e8b74cf27","tokenUsage":{"total":{"totalTokens":53852,"inputTokens":53827,"cachedInputTokens":29952,"outputTokens":25,"reasoningOutputTokens":9},"last":{"totalTokens":10877,"inputTokens":0,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/rollback","frame":{"id":6,"result":{"thread":{"id":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","forkedFromId":null,"preview":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","ephemeral":false,"modelProvider":"openai","createdAt":1777424025,"updatedAt":1777424025,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/28/rollout-2026-04-28T17-53-45-019dd6ba-47b7-7092-8688-9cf7fe5f6498.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.124.0-alpha.3","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"969e8ea4fac1f2066ed50dd4f82b5fd0014d8a4d","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"For this fork-boundary fixture, respond with exactly: fork boundary alpha","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"fork boundary alpha","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1777424017,"completedAt":1777424023,"durationMs":6880}]}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"approvalPolicy":"never","sandboxPolicy":{"type":"readOnly","networkAccess":false}}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"type":"text","text":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"model":"gpt-5.4","sandboxPolicy":{"type":"readOnly","networkAccess":false},"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","turn":{"id":"019dd6ba-47eb-7041-ad45-5abe752c28c9","items":[],"status":"inProgress","error":null,"startedAt":1777424025,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_siblings/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_siblings/codex_transcript.ndjson index 61b9e2cfa4..164ce1e897 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_siblings/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_siblings/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"Juliuss-MacBook-Pro.local","installationId":"c067a38f-79bf-4874-ba7b-c00e86012954","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019ea989-52ea-7360-b19f-391107d1f7ea","sessionId":"019ea989-52ea-7360-b19f-391107d1f7ea","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780960810,"updatedAt":1780960810,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-09-019ea989-52ea-7360-b19f-391107d1f7ea.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","type":"text"}],"threadId":"019ea989-52ea-7360-b19f-391107d1f7ea"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea989-52ea-7360-b19f-391107d1f7ea"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea989-52ea-7360-b19f-391107d1f7ea","sessionId":"019ea989-52ea-7360-b19f-391107d1f7ea","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780960810,"updatedAt":1780960810,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-09-019ea989-52ea-7360-b19f-391107d1f7ea.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"openaiDeveloperDocs","status":"starting","error":null}}} @@ -45,7 +45,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"019ea989-6721-7b82-bc0c-de6aae7d46e2","sessionId":"019ea989-6721-7b82-bc0c-de6aae7d46e2","forkedFromId":"019ea989-52ea-7360-b19f-391107d1f7ea","parentThreadId":null,"preview":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960814,"updatedAt":1780960815,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-14-019ea989-6721-7b82-bc0c-de6aae7d46e2.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea989-5456-7383-9002-f4f035fa8cb8","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"sibling source stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780960810,"completedAt":1780960814,"durationMs":4719}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"input":[{"text":"Remember the fork-local marker sibling-first-5L2P. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.","type":"text"}],"threadId":"019ea989-6721-7b82-bc0c-de6aae7d46e2"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the fork-local marker sibling-first-5L2P. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea989-6721-7b82-bc0c-de6aae7d46e2"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea989-6721-7b82-bc0c-de6aae7d46e2","turnId":"019ea989-5456-7383-9002-f4f035fa8cb8","tokenUsage":{"total":{"totalTokens":18447,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":18447,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea989-6721-7b82-bc0c-de6aae7d46e2","sessionId":"019ea989-6721-7b82-bc0c-de6aae7d46e2","forkedFromId":"019ea989-52ea-7360-b19f-391107d1f7ea","parentThreadId":null,"preview":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960814,"updatedAt":1780960815,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-14-019ea989-6721-7b82-bc0c-de6aae7d46e2.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019ea989-6834-72b3-887d-747b22d38305","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} @@ -91,7 +91,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":6,"result":{"thread":{"id":"019ea989-79f2-7d43-ad3f-6999afbd845e","sessionId":"019ea989-79f2-7d43-ad3f-6999afbd845e","forkedFromId":"019ea989-52ea-7360-b19f-391107d1f7ea","parentThreadId":null,"preview":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960819,"updatedAt":1780960819,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-19-019ea989-79f2-7d43-ad3f-6999afbd845e.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea989-5456-7383-9002-f4f035fa8cb8","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"sibling source stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780960810,"completedAt":1780960814,"durationMs":4719}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"input":[{"text":"Remember the fork-local marker sibling-second-9N6C. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.","type":"text"}],"threadId":"019ea989-79f2-7d43-ad3f-6999afbd845e"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the fork-local marker sibling-second-9N6C. Return the source marker followed by this marker, separated by |. Respond with only the markers and separator.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea989-79f2-7d43-ad3f-6999afbd845e"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea989-79f2-7d43-ad3f-6999afbd845e","turnId":"019ea989-5456-7383-9002-f4f035fa8cb8","tokenUsage":{"total":{"totalTokens":18447,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":18447,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea989-79f2-7d43-ad3f-6999afbd845e","sessionId":"019ea989-79f2-7d43-ad3f-6999afbd845e","forkedFromId":"019ea989-52ea-7360-b19f-391107d1f7ea","parentThreadId":null,"preview":"Remember the opaque marker sibling-source-8R3D for later in this conversation. Respond with exactly: sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780960819,"updatedAt":1780960819,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-20-19-019ea989-79f2-7d43-ad3f-6999afbd845e.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019ea989-7b05-7190-9e84-b6f5e70d2312","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson index d7cb94e1f9..137b9564ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"Juliuss-MacBook-Pro.local","installationId":"c067a38f-79bf-4874-ba7b-c00e86012954","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","sessionId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780962799,"updatedAt":1780962799,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-18-019ea9a7-ac5e-74f0-a17c-75426d4c40c1.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","type":"text"}],"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","sessionId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780962799,"updatedAt":1780962799,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-18-019ea9a7-ac5e-74f0-a17c-75426d4c40c1.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"xcodebuildmcp","status":"starting","error":null}}} @@ -44,7 +44,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"openaiDeveloperDocs","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","sessionId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","forkedFromId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","parentThreadId":null,"preview":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962804,"updatedAt":1780962804,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-24-019ea9a7-c1e4-72a0-b56b-a7b751aa97e6.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea9a7-adb0-77a2-85a6-3d3b6ff5ef67","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"merge source stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780962799,"completedAt":1780962804,"durationMs":5102}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"input":[{"text":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","type":"text"}],"threadId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","turnId":"019ea9a7-adb0-77a2-85a6-3d3b6ff5ef67","tokenUsage":{"total":{"totalTokens":18446,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":7,"reasoningOutputTokens":0},"last":{"totalTokens":18446,"inputTokens":18439,"cachedInputTokens":18304,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","sessionId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","forkedFromId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","parentThreadId":null,"preview":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962804,"updatedAt":1780962804,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-24-019ea9a7-c1e4-72a0-b56b-a7b751aa97e6.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019ea9a7-c370-73a2-a906-f722f57cb683","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} @@ -66,7 +66,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea9a7-c1e4-72a0-b56b-a7b751aa97e6","turn":{"id":"019ea9a7-c370-73a2-a906-f722f57cb683","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780962804,"completedAt":1780962809,"durationMs":4675}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","type":"text"}],"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"019ea9a7-d5bd-7c13-a5ae-7479b421a677","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","turn":{"id":"019ea9a7-d5bd-7c13-a5ae-7479b421a677","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780962809,"completedAt":null,"durationMs":null}}}} @@ -81,7 +81,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","turn":{"id":"019ea9a7-d5bd-7c13-a5ae-7479b421a677","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780962809,"completedAt":1780962810,"durationMs":1414}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"input":[{"text":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.","type":"text"}],"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019ea9a7-db48-7bd3-9c20-3d806cf8a702","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea9a7-ac5e-74f0-a17c-75426d4c40c1","turn":{"id":"019ea9a7-db48-7bd3-9c20-3d806cf8a702","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780962810,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson index e2cd6f4e4f..e2141814cd 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"Juliuss-MacBook-Pro.local","installationId":"c067a38f-79bf-4874-ba7b-c00e86012954","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","sessionId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780962812,"updatedAt":1780962812,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-32-019ea9a7-e28f-7c72-96e8-9ca581f225ce.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","sessionId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1780962812,"updatedAt":1780962812,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-32-019ea9a7-e28f-7c72-96e8-9ca581f225ce.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"starting","error":null}}} @@ -45,7 +45,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a","sessionId":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a","forkedFromId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","parentThreadId":null,"preview":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962817,"updatedAt":1780962817,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-37-019ea9a7-f48f-74e2-b87e-4a7e9313b57a.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea9a7-e43a-74f2-b94e-99f168de38fd","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780962813,"completedAt":1780962817,"durationMs":4111}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"threadId":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a","turnId":"019ea9a7-e43a-74f2-b94e-99f168de38fd","tokenUsage":{"total":{"totalTokens":18450,"inputTokens":18442,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":18450,"inputTokens":18442,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a","sessionId":"019ea9a7-f48f-74e2-b87e-4a7e9313b57a","forkedFromId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","parentThreadId":null,"preview":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962817,"updatedAt":1780962817,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-37-019ea9a7-f48f-74e2-b87e-4a7e9313b57a.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"019ea9a7-f5bd-7c22-a906-5625e1d8564d","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} @@ -78,7 +78,7 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"node_repl","status":"ready","error":null}}} {"type":"emit_inbound","label":"thread/fork","frame":{"id":6,"result":{"thread":{"id":"019ea9a8-079f-7100-bbdf-74026e9c20c1","sessionId":"019ea9a8-079f-7100-bbdf-74026e9c20c1","forkedFromId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","parentThreadId":null,"preview":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962822,"updatedAt":1780962822,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-42-019ea9a8-079f-7100-bbdf-74026e9c20c1.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019ea9a7-e43a-74f2-b94e-99f168de38fd","items":[{"type":"userMessage","id":"item-1","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"merge sibling source stored","phase":"final_answer","memoryCitation":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1780962813,"completedAt":1780962817,"durationMs":4111}]},"model":"kindle-alpha","modelProvider":"openai","serviceTier":null,"cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","runtimeWorkspaceRoots":["/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server"],"instructionSources":["/Users/julius/.codex/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"threadId":"019ea9a8-079f-7100-bbdf-74026e9c20c1"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a8-079f-7100-bbdf-74026e9c20c1"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019ea9a8-079f-7100-bbdf-74026e9c20c1","turnId":"019ea9a7-e43a-74f2-b94e-99f168de38fd","tokenUsage":{"total":{"totalTokens":18450,"inputTokens":18442,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":18450,"inputTokens":18442,"cachedInputTokens":18304,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019ea9a8-079f-7100-bbdf-74026e9c20c1","sessionId":"019ea9a8-079f-7100-bbdf-74026e9c20c1","forkedFromId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","parentThreadId":null,"preview":"Remember the opaque marker merge-sibling-source-3C7K for later in this conversation. Respond with exactly: merge sibling source stored","ephemeral":false,"modelProvider":"openai","createdAt":1780962822,"updatedAt":1780962822,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/06/08/rollout-2026-06-08T16-53-42-019ea9a8-079f-7100-bbdf-74026e9c20c1.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-17b43ed6/apps/server","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"5115887f33051a4e25d2b427622a54656eeb9ab0","branch":"t3code/17b43ed6","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"019ea9a8-093e-7f11-8cd1-a38c032d4642","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} @@ -101,7 +101,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a8-079f-7100-bbdf-74026e9c20c1","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea9a8-079f-7100-bbdf-74026e9c20c1","turn":{"id":"019ea9a8-093e-7f11-8cd1-a38c032d4642","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780962822,"completedAt":1780962826,"durationMs":4114}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":8,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from first forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-first-6V2J.\n- Assistant confirmed: first merge sibling stored\n\nUser message:\nRetain the first transferred marker for later. Respond with exactly: first merge delta stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":8,"result":{"turn":{"id":"019ea9a8-1956-7183-acaa-f43d53da7a22","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","turn":{"id":"019ea9a8-1956-7183-acaa-f43d53da7a22","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780962826,"completedAt":null,"durationMs":null}}}} @@ -117,7 +117,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","turn":{"id":"019ea9a8-1956-7183-acaa-f43d53da7a22","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780962826,"completedAt":1780962828,"durationMs":1738}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":9,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from second forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-sibling-second-9X5B.\n- Assistant confirmed: second merge sibling stored\n\nUser message:\nRetain the second transferred marker for later. Respond with exactly: second merge delta stored","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":9,"result":{"turn":{"id":"019ea9a8-2025-7de2-bb4b-ecd86a568956","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","turn":{"id":"019ea9a8-2025-7de2-bb4b-ecd86a568956","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780962828,"completedAt":null,"durationMs":null}}}} @@ -133,7 +133,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1780968999},"secondary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1781296757},"credits":null,"individualLimit":null,"planType":"pro","rateLimitReachedType":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","turn":{"id":"019ea9a8-2025-7de2-bb4b-ecd86a568956","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1780962828,"completedAt":1780962829,"durationMs":1313}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":10,"method":"turn/start","params":{"input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":10,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Return the source marker followed by both transferred fork markers in merge order, separated by single | characters. Respond with only the markers and separators.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":10,"result":{"turn":{"id":"019ea9a8-254b-7e53-af1e-1066f8bc37a4","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019ea9a7-e28f-7c72-96e8-9ca581f225ce","turn":{"id":"019ea9a8-254b-7e53-af1e-1066f8bc37a4","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1780962829,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson index 0ec8b32174..02d20d69c2 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019daded-23e0-7100-87d7-12089c71339a","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739492,"updatedAt":1776739492,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-52-019daded-23e0-7100-87d7-12089c71339a.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: rollback fixture first turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019daded-23e0-7100-87d7-12089c71339a","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739492,"updatedAt":1776739492,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-52-019daded-23e0-7100-87d7-12089c71339a.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} @@ -30,7 +30,7 @@ {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1776748632},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1777335432},"credits":null,"planType":"pro"}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","status":{"type":"idle"}}}} {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","turn":{"id":"019daded-23e9-7100-8f16-28223024be18","items":[],"status":"completed","error":null,"startedAt":1776739492,"completedAt":1776739501,"durationMs":8544}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Respond with exactly: rollback fixture second turn complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"019daded-454a-70e2-acce-09a54f6192d0","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","turn":{"id":"019daded-454a-70e2-acce-09a54f6192d0","items":[],"status":"inProgress","error":null,"startedAt":1776739501,"completedAt":null,"durationMs":null}}}} @@ -53,7 +53,7 @@ {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","turnId":"019daded-515f-7642-b0db-bd62c3f7a473","tokenUsage":{"total":{"totalTokens":56503,"inputTokens":56470,"cachedInputTokens":56064,"outputTokens":33,"reasoningOutputTokens":13},"last":{"totalTokens":12317,"inputTokens":0,"cachedInputTokens":0,"outputTokens":0,"reasoningOutputTokens":0},"modelContextWindow":258400}}}} {"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":0,"windowDurationMins":300,"resetsAt":1776748632},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1777335432},"credits":null,"planType":"pro"}}}} {"type":"emit_inbound","label":"thread/rollback","frame":{"id":5,"result":{"thread":{"id":"019daded-23e0-7100-87d7-12089c71339a","forkedFromId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"modelProvider":"openai","createdAt":1776739492,"updatedAt":1776739504,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-52-019daded-23e0-7100-87d7-12089c71339a.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":{"sha":"7eefb2eb1d98f6b814c9fd7f43652727059c3326","branch":"t3code/codex-turn-mapping","originUrl":"git@github.com:pingdotgg/t3code.git"},"name":null,"turns":[{"id":"019daded-23e9-7100-8f16-28223024be18","items":[{"type":"userMessage","id":"item-1","content":[{"type":"text","text":"Respond with exactly: rollback fixture first turn complete","text_elements":[]}]},{"type":"agentMessage","id":"item-2","text":"rollback fixture first turn complete","phase":"final_answer","memoryCitation":null}],"status":"completed","error":null,"startedAt":1776739492,"completedAt":1776739501,"durationMs":8544}]}}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Repeat the conversation verbatim.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019daded-23e0-7100-87d7-12089c71339a"}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"019daded-5165-7f73-a6bc-3cf4386b542c","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","status":{"type":"active","activeFlags":[]}}}} {"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019daded-23e0-7100-87d7-12089c71339a","turn":{"id":"019daded-5165-7f73-a6bc-3cf4386b542c","items":[],"status":"inProgress","error":null,"startedAt":1776739504,"completedAt":null,"durationMs":null}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson index 02af6f8c1b..4e6d73df58 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019db229-ac7a-7923-ab72-67bfefd79a8b","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810568,"updatedAt":1776810568,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-29-28-019db229-ac7a-7923-ab72-67bfefd79a8b.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.3-codex","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db229-ac7a-7923-ab72-67bfefd79a8b"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019db229-ac7a-7923-ab72-67bfefd79a8b"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019db229-ac7a-7923-ab72-67bfefd79a8b","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776810568,"updatedAt":1776810568,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T15-29-28-019db229-ac7a-7923-ab72-67bfefd79a8b.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson index 17005a1b1c..a9915c185d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadeb-5cd0-76e1-910c-3effc0cc5e67","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739376,"updatedAt":1776739376,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-42-56-019dadeb-5cd0-76e1-910c-3effc0cc5e67.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"on-request","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadeb-5cd0-76e1-910c-3effc0cc5e67"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"on-request","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadeb-5cd0-76e1-910c-3effc0cc5e67"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadeb-5cd0-76e1-910c-3effc0cc5e67","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739376,"updatedAt":1776739376,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-42-56-019dadeb-5cd0-76e1-910c-3effc0cc5e67.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson index 4f99c9b4e0..20bf497bb1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadeb-c0d3-7331-8353-a710f2912df3","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739401,"updatedAt":1776739401,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-21-019dadeb-c0d3-7331-8353-a710f2912df3.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadeb-c0d3-7331-8353-a710f2912df3"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":{"granular":{"mcp_elicitations":true,"request_permissions":true,"rules":true,"sandbox_approval":true,"skill_approval":true}},"cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"readOnly"},"threadId":"019dadeb-c0d3-7331-8353-a710f2912df3"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadeb-c0d3-7331-8353-a710f2912df3","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739401,"updatedAt":1776739401,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-21-019dadeb-c0d3-7331-8353-a710f2912df3.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson index e989da4bbd..474498ab35 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019dadeb-9a1f-7d61-8e4b-92d487d180b4","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739392,"updatedAt":1776739392,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-12-019dadeb-9a1f-7d61-8e4b-92d487d180b4.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019dadeb-9a1f-7d61-8e4b-92d487d180b4"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019dadeb-9a1f-7d61-8e4b-92d487d180b4"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019dadeb-9a1f-7d61-8e4b-92d487d180b4","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739392,"updatedAt":1776739392,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-43-12-019dadeb-9a1f-7d61-8e4b-92d487d180b4.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson index ec87666a94..8b1f22dafa 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019daded-1d25-7df0-abf3-9ed9d31c346c","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739491,"updatedAt":1776739491,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-51-019daded-1d25-7df0-abf3-9ed9d31c346c.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019daded-1d25-7df0-abf3-9ed9d31c346c"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019daded-1d25-7df0-abf3-9ed9d31c346c"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019daded-1d25-7df0-abf3-9ed9d31c346c","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739491,"updatedAt":1776739491,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T19-44-51-019daded-1d25-7df0-abf3-9ed9d31c346c.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson index ab43808f8b..bf3036c580 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/codex_transcript.ndjson @@ -5,7 +5,7 @@ {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","environmentId":null}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778178891,"updatedAt":1778178891,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T11-34-51-019e03b8-9e5c-7b32-88ab-f742a29b75b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","instructionSources":["/Users/julius/.codex_p/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex_p/memories"],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"type":"managed","network":{"enabled":false},"fileSystem":{"type":"restricted","entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":null}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".git"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".agents"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".codex"}},"access":"read"},{"path":{"type":"path","path":"/Users/julius/.codex_p/memories"},"access":"write"}]}},"activePermissionProfile":{"id":":workspace","extends":null,"modifications":[]},"reasoningEffort":"medium"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778178891,"updatedAt":1778178891,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T11-34-51-019e03b8-9e5c-7b32-88ab-f742a29b75b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}} {"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /Users/julius/.codex_p/config.toml."}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson index 1305eaf121..f7c5f42710 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_transcript.ndjson @@ -4,7 +4,7 @@ {"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} {"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}} {"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019db20e-d982-70e9-a996-8e56a2f7968d","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776819600,"updatedAt":1776819600,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T18-00-00-019db20e-d982-70e9-a996-8e56a2f7968d.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex/memories"],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}} -{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"threadId":"019db20e-d982-70e9-a996-8e56a2f7968d"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"","input":[{"text":"Search the web for FIFA World Cup ticket pricing, then answer exactly: web search fixture complete","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"019db20e-d982-70e9-a996-8e56a2f7968d"}}} {"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019db20e-d982-70e9-a996-8e56a2f7968d","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776819600,"updatedAt":1776819600,"status":{"type":"idle"},"path":"/Users/julius/.codex/sessions/2026/04/21/rollout-2026-04-21T18-00-00-019db20e-d982-70e9-a996-8e56a2f7968d.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}} {"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"019db20e-d98f-73c1-bb7e-e5d2dd9a77cf","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019db20e-d982-70e9-a996-8e56a2f7968d","status":{"type":"active","activeFlags":[]}}}} diff --git a/apps/server/src/orchestration/Layers/ProjectEnrichmentProjection.test.ts b/apps/server/src/orchestration/Layers/ProjectEnrichmentProjection.test.ts new file mode 100644 index 0000000000..a03046e2c8 --- /dev/null +++ b/apps/server/src/orchestration/Layers/ProjectEnrichmentProjection.test.ts @@ -0,0 +1,101 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { ProjectId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import * as ProjectEnrichment from "../../project/ProjectEnrichmentService.ts"; +import * as ProjectFaviconResolver from "../../project/ProjectFaviconResolver.ts"; +import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; +import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; + +it.effect("keeps shell snapshots and later deltas moving while project enrichment is hung", () => + Effect.gen(function* () { + const repositoryStarted = yield* Deferred.make(); + const releaseRepository = yield* Deferred.make(); + const metadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + Deferred.succeed(repositoryStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRepository)), + Effect.as({ + canonicalKey: "example.test/project", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://example.test/project.git", + }, + rootPath: workspaceRoot, + }), + ), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: () => Effect.succeed(null), + }), + ); + const testLayer = OrchestrationProjectionSnapshotQueryLive.pipe( + Layer.provideMerge(ProjectEnrichment.layer), + Layer.provideMerge(metadataLayer), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "projection-snapshot-query-test-" }), + ), + Layer.provide(NodeServices.layer), + ); + + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const query = yield* ProjectionSnapshotQuery; + const projectId = ProjectId.make("project:hung-enrichment"); + const now = "2026-06-22T00:00:00.000Z"; + yield* sql` + INSERT INTO projection_projects ( + project_id, + title, + workspace_root, + default_model_selection_json, + scripts_json, + created_at, + updated_at, + deleted_at + ) VALUES ( + ${projectId}, + 'Hung enrichment', + '/work/hung-enrichment', + NULL, + '[]', + ${now}, + ${now}, + NULL + ) + `; + + const snapshotFiber = yield* query + .getShellSnapshot() + .pipe(Effect.forkChild({ startImmediately: true })); + const snapshot = yield* Fiber.join(snapshotFiber); + assert.equal(snapshot.projects[0]?.id, projectId); + assert.isNull(snapshot.projects[0]?.repositoryIdentity ?? null); + yield* Deferred.await(repositoryStarted); + + const delivered = yield* Stream.fromIterable(["project", "thread"] as const).pipe( + Stream.mapEffect((kind) => + kind === "project" + ? query.getProjectShellById(projectId).pipe(Effect.as(kind)) + : Effect.succeed(kind), + ), + Stream.runCollect, + ); + assert.deepEqual(Array.from(delivered), ["project", "thread"]); + + yield* Deferred.succeed(releaseRepository, undefined); + }).pipe(Effect.provide(testLayer)); + }), +); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 3e77f9cf87..4904abfd04 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -52,11 +52,7 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts"; import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts"; import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts"; -import { - decodeThreadDetailPageCursor, - encodeThreadDetailPageCursor, -} from "../threadDetailCursor.ts"; -import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; +import { ProjectEnrichmentService } from "../../project/ProjectEnrichmentService.ts"; import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; import { ProjectionSnapshotQuery, @@ -349,10 +345,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService; const threadPlanProgress = yield* ThreadPlanProgressService; const sql = yield* SqlClient.SqlClient; - const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const repositoryIdentityResolutionConcurrency = 4; - const resolveRepositoryIdentitiesForProjects = Effect.fn( - "ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects", + const projectEnrichment = yield* ProjectEnrichmentService; + const getAvailableRepositoryIdentities = Effect.fn( + "ProjectionSnapshotQuery.getAvailableRepositoryIdentities", )(function* ( projectRows: ReadonlyArray>, options?: { @@ -368,10 +363,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { yield* Effect.forEach( uniqueWorkspaceRoots, (workspaceRoot) => - repositoryIdentityResolver - .resolve(workspaceRoot) - .pipe(Effect.map((identity) => [workspaceRoot, identity] as const)), - { concurrency: repositoryIdentityResolutionConcurrency }, + projectEnrichment + .getAvailable(workspaceRoot) + .pipe( + Effect.map((enrichment) => [workspaceRoot, enrichment.repositoryIdentity] as const), + ), + { concurrency: 16 }, ), ); @@ -1539,10 +1536,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { }); } - const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects( - projectRows, - { includeDeleted: true }, - ); + const repositoryIdentities = yield* getAvailableRepositoryIdentities(projectRows, { + includeDeleted: true, + }); const projects: ReadonlyArray = projectRows.map((row) => ({ id: row.projectId, @@ -1810,148 +1806,152 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { }), ); - const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () => - sql - .withTransaction( - Effect.all([ - listProjectRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:listProjects:query", - "ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows", - ), - ), - ), - listActiveThreadRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:listThreads:query", - "ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows", - ), - ), - ), - listActiveThreadSessionRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query", - "ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows", - ), - ), - ), - listActiveLatestTurnRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query", - "ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows", - ), - ), - ), - listProjectionStateRows(undefined).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query", - "ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows", - ), - ), - ), - ]), - ) - .pipe( - Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) => - Effect.gen(function* () { - let updatedAt: string | null = null; - for (const row of projectRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - for (const row of threadRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - for (const row of sessionRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - for (const row of latestTurnRows) { - updatedAt = maxIso(updatedAt, row.requestedAt); - if (row.startedAt !== null) { - updatedAt = maxIso(updatedAt, row.startedAt); - } - if (row.completedAt !== null) { - updatedAt = maxIso(updatedAt, row.completedAt); - } - } - for (const row of stateRows) { - updatedAt = maxIso(updatedAt, row.updatedAt); - } - - const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows); - const latestTurnByThread = new Map( - latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const), - ); - const sessionByThread = new Map( - sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const), - ); - - const snapshot = { - snapshotSequence: computeSnapshotSequence(stateRows), - projects: Arr.filterMap(projectRows, (row) => - row.deletedAt === null - ? Result.succeed( - mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null), - ) - : Result.failVoid, - ), - threads: Arr.filterMap(threadRows, (row) => - row.deletedAt === null - ? Result.succeed({ - id: row.threadId, - projectId: row.projectId, - title: row.title, - modelSelection: row.modelSelection, - runtimeMode: row.runtimeMode, - interactionMode: row.interactionMode, - branch: row.branch, - worktreePath: row.worktreePath, - latestTurn: latestTurnByThread.get(row.threadId) ?? null, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - archivedAt: row.archivedAt, - settledOverride: row.settledOverride, - settledAt: row.settledAt, - snoozedUntil: row.snoozedUntil, - snoozedAt: row.snoozedAt, - pinnedAt: row.pinnedAt, - pinOrderKey: row.pinOrderKey ?? null, - titleRegeneration: mapTitleRegeneration(row), - session: sessionByThread.get(row.threadId) ?? null, - latestUserMessageAt: row.latestUserMessageAt, - hasPendingApprovals: row.pendingApprovalCount > 0, - hasPendingUserInput: row.pendingUserInputCount > 0, - hasActionableProposedPlan: row.hasActionableProposedPlan > 0, - backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness( - row.threadId, - ), - planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId), - } satisfies OrchestrationThreadShell) - : Result.failVoid, - ), - updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z", - }; - - return yield* decodeShellSnapshot(snapshot).pipe( + const getShellSnapshotWithoutEnrichment: ProjectionSnapshotQueryShape["getShellSnapshotWithoutEnrichment"] = + () => + sql + .withTransaction( + Effect.all([ + listProjectRows(undefined).pipe( Effect.mapError( - toPersistenceDecodeError( - "ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot", + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:listProjects:query", + "ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows", ), ), - ); + ), + listActiveThreadRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:listThreads:query", + "ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows", + ), + ), + ), + listActiveThreadSessionRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query", + "ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows", + ), + ), + ), + listActiveLatestTurnRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query", + "ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows", + ), + ), + ), + listProjectionStateRows(undefined).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query", + "ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows", + ), + ), + ), + ]), + ) + .pipe( + Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) => + Effect.gen(function* () { + let updatedAt: string | null = null; + for (const row of projectRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of threadRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of sessionRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + for (const row of latestTurnRows) { + updatedAt = maxIso(updatedAt, row.requestedAt); + if (row.startedAt !== null) { + updatedAt = maxIso(updatedAt, row.startedAt); + } + if (row.completedAt !== null) { + updatedAt = maxIso(updatedAt, row.completedAt); + } + } + for (const row of stateRows) { + updatedAt = maxIso(updatedAt, row.updatedAt); + } + + const latestTurnByThread = new Map( + latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const), + ); + const sessionByThread = new Map( + sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const), + ); + + const snapshot = { + snapshotSequence: computeSnapshotSequence(stateRows), + projects: Arr.filterMap(projectRows, (row) => + row.deletedAt === null + ? Result.succeed(mapProjectShellRow(row, null)) + : Result.failVoid, + ), + threads: Arr.filterMap(threadRows, (row) => + row.deletedAt === null + ? Result.succeed({ + id: row.threadId, + projectId: row.projectId, + title: row.title, + modelSelection: row.modelSelection, + runtimeMode: row.runtimeMode, + interactionMode: row.interactionMode, + branch: row.branch, + worktreePath: row.worktreePath, + latestTurn: latestTurnByThread.get(row.threadId) ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + archivedAt: row.archivedAt, + session: sessionByThread.get(row.threadId) ?? null, + latestUserMessageAt: row.latestUserMessageAt, + hasPendingApprovals: row.pendingApprovalCount > 0, + hasPendingUserInput: row.pendingUserInputCount > 0, + hasActionableProposedPlan: row.hasActionableProposedPlan > 0, + } satisfies OrchestrationThreadShell) + : Result.failVoid, + ), + updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z", + }; + + return yield* decodeShellSnapshot(snapshot).pipe( + Effect.mapError( + toPersistenceDecodeError( + "ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot", + ), + ), + ); + }), + ), + Effect.mapError((error) => { + if (isPersistenceError(error)) { + return error; + } + return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error); }), - ), - Effect.mapError((error) => { - if (isPersistenceError(error)) { - return error; - } - return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error); - }), - ); + ); + + const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () => + getShellSnapshotWithoutEnrichment().pipe( + Effect.flatMap((snapshot) => + Effect.forEach( + snapshot.projects, + (project) => + projectEnrichment.getAvailable(project.workspaceRoot).pipe( + Effect.map((enrichment) => ({ + ...project, + repositoryIdentity: enrichment.repositoryIdentity, + })), + ), + { concurrency: 16 }, + ).pipe(Effect.map((projects) => ({ ...snapshot, projects }))), + ), + ); const getArchivedShellSnapshot: ProjectionSnapshotQueryShape["getArchivedShellSnapshot"] = () => sql @@ -2026,7 +2026,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { } const activeProjectIds = new Set(threadRows.map((row) => row.projectId)); - const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects( + const repositoryIdentities = yield* getAvailableRepositoryIdentities( projectRows.filter((row) => activeProjectIds.has(row.projectId)), ); const latestTurnByThread = new Map( @@ -2166,13 +2166,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { Effect.flatMap((option) => Option.isNone(option) ? Effect.succeed(Option.none()) - : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe( - Effect.map((repositoryIdentity) => + : projectEnrichment.getAvailable(option.value.workspaceRoot).pipe( + Effect.map((enrichment) => Option.some({ id: option.value.projectId, title: option.value.title, workspaceRoot: option.value.workspaceRoot, - repositoryIdentity, + repositoryIdentity: enrichment.repositoryIdentity, defaultModelSelection: option.value.defaultModelSelection, defaultThreadEnvMode: option.value.defaultThreadEnvMode, faviconPath: option.value.faviconPath ?? null, @@ -2197,11 +2197,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { Effect.flatMap((option) => Option.isNone(option) ? Effect.succeed(Option.none()) - : repositoryIdentityResolver - .resolve(option.value.workspaceRoot) + : projectEnrichment + .getAvailable(option.value.workspaceRoot) .pipe( - Effect.map((repositoryIdentity) => - Option.some(mapProjectShellRow(option.value, repositoryIdentity)), + Effect.map((enrichment) => + Option.some(mapProjectShellRow(option.value, enrichment.repositoryIdentity)), ), ), ), @@ -2668,6 +2668,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { getCommandReadModel, getSnapshot, getShellSnapshot, + getShellSnapshotWithoutEnrichment, getArchivedShellSnapshot, searchThreads, getSnapshotSequence, diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 0a00253a22..014384003e 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -86,6 +86,17 @@ export interface ProjectionSnapshotQueryShape { ProjectionRepositoryError >; + /** + * Read the shell snapshot with null optional repository metadata. + * + * Transactional callers use this method and enrich the returned projects + * only after their transaction has closed. + */ + readonly getShellSnapshotWithoutEnrichment: () => Effect.Effect< + OrchestrationShellSnapshot, + ProjectionRepositoryError + >; + /** * Read archived thread shell summaries for the archive page. * diff --git a/apps/server/src/project/ProjectEnrichmentService.test.ts b/apps/server/src/project/ProjectEnrichmentService.test.ts new file mode 100644 index 0000000000..d7049cf594 --- /dev/null +++ b/apps/server/src/project/ProjectEnrichmentService.test.ts @@ -0,0 +1,239 @@ +import { assert, it } from "@effect/vitest"; +import type { RepositoryIdentity } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; + +import * as ProjectEnrichment from "./ProjectEnrichmentService.ts"; +import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; +import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; + +const identity = (workspaceRoot: string, version = 1): RepositoryIdentity => ({ + canonicalKey: `example.test/v${version}${workspaceRoot}`, + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: `https://example.test/v${version}${workspaceRoot}.git`, + }, + rootPath: workspaceRoot, +}); + +const waitForAvailable = Effect.fn("ProjectEnrichmentServiceTest.waitForAvailable")(function* ( + service: ProjectEnrichment.ProjectEnrichmentService["Service"], + workspaceRoot: string, + predicate: (value: ProjectEnrichment.ProjectEnrichment) => boolean, +) { + for (let attempt = 0; attempt < 100; attempt += 1) { + const available = yield* service.peek(workspaceRoot); + if (predicate(available)) return available; + yield* Effect.yieldNow; + } + return yield* Effect.die(`Project metadata for ${workspaceRoot} was not resolved in time.`); +}); + +const makeLayer = ( + metadataLayer: Layer.Layer< + | ProjectFaviconResolver.ProjectFaviconResolver + | RepositoryIdentityResolver.RepositoryIdentityResolver + >, + options: ProjectEnrichment.ProjectEnrichmentServiceOptions = {}, +) => + Layer.effect(ProjectEnrichment.ProjectEnrichmentService, ProjectEnrichment.make(options)).pipe( + Layer.provide(metadataLayer), + ); + +it.effect("preserves either enrichment field when the other resolver fails", () => + Effect.gen(function* () { + const metadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + workspaceRoot === "/repo-fails" + ? Effect.die("repository resolver failed") + : Effect.succeed(identity(workspaceRoot)), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => + workspaceRoot === "/favicon-fails" + ? Effect.fail( + new ProjectFaviconResolver.ProjectFaviconResolutionError({ + operation: "stat-candidate", + workspaceRoot, + cause: "favicon resolver failed", + }), + ) + : Effect.succeed(`${workspaceRoot}/favicon.svg`), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectEnrichment.ProjectEnrichmentService; + yield* service.request("/favicon-fails"); + yield* service.request("/repo-fails"); + + const faviconFailure = yield* waitForAvailable( + service, + "/favicon-fails", + (value) => value.repositoryIdentity !== null, + ); + assert.equal( + faviconFailure.repositoryIdentity?.canonicalKey, + "example.test/v1/favicon-fails", + ); + assert.isNull(faviconFailure.faviconPath); + + const repositoryFailure = yield* waitForAvailable( + service, + "/repo-fails", + (value) => value.faviconPath !== null, + ); + assert.isNull(repositoryFailure.repositoryIdentity); + assert.equal(repositoryFailure.faviconPath, "/repo-fails/favicon.svg"); + }).pipe(Effect.provide(makeLayer(metadataLayer))); + }), +); + +it.effect("publishes repository completion while favicon enrichment is still pending", () => + Effect.gen(function* () { + const releaseFavicon = yield* Deferred.make(); + const metadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => + Deferred.await(releaseFavicon).pipe(Effect.as(`${workspaceRoot}/favicon.svg`)), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectEnrichment.ProjectEnrichmentService; + const changes = yield* service.subscribeChanges; + yield* service.request("/completed"); + + const change = yield* PubSub.take(changes); + assert.equal(change.workspaceRoot, "/completed"); + assert.isTrue(change.repositoryIdentityResolved); + assert.equal(change.enrichment.repositoryIdentity?.canonicalKey, "example.test/v1/completed"); + assert.isNull(change.enrichment.faviconPath); + }).pipe(Effect.provide(makeLayer(metadataLayer))); + }), +); + +it.effect("keeps repository workers available when every favicon worker is hung", () => + Effect.gen(function* () { + const faviconWorkersStarted = yield* Deferred.make(); + const faviconStarts = yield* Ref.make(0); + const metadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: () => + Effect.gen(function* () { + const started = yield* Ref.updateAndGet(faviconStarts, (count) => count + 1); + if (started === 2) { + yield* Deferred.succeed(faviconWorkersStarted, undefined); + } + return yield* Effect.never; + }), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectEnrichment.ProjectEnrichmentService; + yield* service.request("/favicon-hung-a"); + yield* service.request("/favicon-hung-b"); + yield* Deferred.await(faviconWorkersStarted); + + yield* service.request("/repository-later"); + const available = yield* waitForAvailable( + service, + "/repository-later", + (value) => value.repositoryIdentity !== null, + ); + + assert.equal(available.repositoryIdentity?.canonicalKey, "example.test/v1/repository-later"); + assert.equal(yield* Ref.get(faviconStarts), 2); + }).pipe( + Effect.provide( + makeLayer(metadataLayer, { + cacheCapacity: 8, + maxPending: 4, + concurrency: 2, + }), + ), + ); + }), +); + +it.effect("deduplicates requests, bounds pending work, and reloads invalidated roots", () => + Effect.gen(function* () { + const firstStarted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const repositoryCalls = yield* Ref.make>([]); + const version = yield* Ref.make(1); + const metadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + Effect.gen(function* () { + yield* Ref.update(repositoryCalls, (calls) => [...calls, workspaceRoot]); + if (workspaceRoot === "/first" && (yield* Ref.get(version)) === 1) { + yield* Deferred.succeed(firstStarted, undefined); + yield* Deferred.await(releaseFirst); + } + return identity(workspaceRoot, yield* Ref.get(version)); + }), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectEnrichment.ProjectEnrichmentService; + yield* Effect.forEach(Array.from({ length: 20 }), () => service.request("/first"), { + concurrency: "unbounded", + discard: true, + }); + yield* Deferred.await(firstStarted); + yield* service.request("/second"); + yield* service.request("/dropped"); + assert.deepEqual(yield* Ref.get(repositoryCalls), ["/first"]); + + yield* Deferred.succeed(releaseFirst, undefined); + yield* waitForAvailable(service, "/second", (value) => value.repositoryIdentity !== null); + assert.deepEqual(yield* Ref.get(repositoryCalls), ["/first", "/second"]); + + yield* service.request("/dropped"); + yield* waitForAvailable(service, "/dropped", (value) => value.repositoryIdentity !== null); + assert.deepEqual(yield* Ref.get(repositoryCalls), ["/first", "/second", "/dropped"]); + + yield* Ref.set(version, 2); + yield* service.invalidate(["/first"]); + const invalidated = yield* service.getAvailable("/first"); + assert.isNull(invalidated.repositoryIdentity); + const refreshed = yield* waitForAvailable( + service, + "/first", + (value) => value.repositoryIdentity?.canonicalKey === "example.test/v2/first", + ); + assert.equal(refreshed.repositoryIdentity?.canonicalKey, "example.test/v2/first"); + assert.deepEqual(yield* Ref.get(repositoryCalls), [ + "/first", + "/second", + "/dropped", + "/first", + ]); + }).pipe( + Effect.provide( + makeLayer(metadataLayer, { + cacheCapacity: 8, + maxPending: 2, + concurrency: 1, + }), + ), + ); + }), +); diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts new file mode 100644 index 0000000000..0a7549dba9 --- /dev/null +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -0,0 +1,285 @@ +import type { RepositoryIdentity } from "@t3tools/contracts"; +import * as Cache from "effect/Cache"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import type * as Scope from "effect/Scope"; + +import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; +import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; + +const DEFAULT_CACHE_CAPACITY = 512; +const DEFAULT_MAX_PENDING = 512; +const DEFAULT_CONCURRENCY = 4; +const DEFAULT_SUCCESS_TTL = Duration.minutes(1); +const DEFAULT_FAILURE_TTL = Duration.seconds(5); + +export interface ProjectEnrichment { + readonly repositoryIdentity: RepositoryIdentity | null; + readonly faviconPath: string | null; +} + +export interface ProjectEnrichmentChange { + readonly workspaceRoot: string; + readonly enrichment: ProjectEnrichment; + readonly repositoryIdentityResolved: boolean; +} + +export interface ProjectEnrichmentServiceOptions { + readonly cacheCapacity?: number; + /** Maximum active and queued roots for each enrichment field. */ + readonly maxPending?: number; + /** Worker concurrency for each enrichment field. */ + readonly concurrency?: number; + readonly successTtl?: Duration.Input; + readonly failureTtl?: Duration.Input; +} + +export class ProjectEnrichmentService extends Context.Service< + ProjectEnrichmentService, + { + /** Read resolved metadata without starting or awaiting filesystem work. */ + readonly peek: (workspaceRoot: string) => Effect.Effect; + /** Schedule missing metadata for bounded background resolution. */ + readonly request: (workspaceRoot: string) => Effect.Effect; + /** Read immediately available metadata and schedule anything missing. */ + readonly getAvailable: (workspaceRoot: string) => Effect.Effect; + /** Invalidate workspace-derived metadata. */ + readonly invalidate: (workspaceRoots: Iterable) => Effect.Effect; + /** Subscribe to ephemeral completion notifications. */ + readonly subscribeChanges: Effect.Effect< + PubSub.Subscription, + never, + Scope.Scope + >; + } +>()("t3/project/ProjectEnrichmentService") {} + +function availableValue(cached: Option.Option>): A | null { + return Option.match(cached, { + onNone: () => null, + onSome: (exit) => + Exit.match(exit, { + onFailure: () => null, + onSuccess: (value) => value, + }), + }); +} + +interface EnrichmentWorkLane { + readonly pendingRoots: Ref.Ref>; + readonly queue: Queue.Queue; +} + +export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( + options: ProjectEnrichmentServiceOptions = {}, +) { + const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; + const cacheCapacity = Math.max(1, options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY); + const maxPending = Math.max(1, options.maxPending ?? DEFAULT_MAX_PENDING); + const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY); + const successTtl = options.successTtl ?? DEFAULT_SUCCESS_TTL; + const failureTtl = options.failureTtl ?? DEFAULT_FAILURE_TTL; + + const repositoryIdentityCache = yield* Cache.makeWith( + (workspaceRoot: string) => Effect.exit(repositoryIdentityResolver.resolve(workspaceRoot)), + { + capacity: cacheCapacity, + timeToLive: Exit.match({ + onFailure: () => failureTtl, + onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl), + }), + }, + ); + const faviconCache = yield* Cache.makeWith( + (workspaceRoot: string) => Effect.exit(faviconResolver.resolvePath(workspaceRoot)), + { + capacity: cacheCapacity, + timeToLive: Exit.match({ + onFailure: () => failureTtl, + onSuccess: (result) => (Exit.isSuccess(result) ? successTtl : failureTtl), + }), + }, + ); + const makeWorkLane = Effect.gen(function* () { + const pendingRoots = yield* Ref.make>(new Set()); + const queue = yield* Effect.acquireRelease(Queue.dropping(maxPending), (queue) => + Queue.shutdown(queue), + ); + return { pendingRoots, queue } satisfies EnrichmentWorkLane; + }); + const repositoryIdentityLane = yield* makeWorkLane; + const faviconLane = yield* makeWorkLane; + const changes = yield* Effect.acquireRelease( + PubSub.sliding(256), + (pubsub) => PubSub.shutdown(pubsub), + ); + + const removePending = (lane: EnrichmentWorkLane, workspaceRoot: string) => + Ref.update(lane.pendingRoots, (current) => { + if (!current.has(workspaceRoot)) return current; + const next = new Set(current); + next.delete(workspaceRoot); + return next; + }); + + const reservePending = (lane: EnrichmentWorkLane, workspaceRoot: string) => + Ref.modify(lane.pendingRoots, (current) => { + if (current.has(workspaceRoot) || current.size >= maxPending) { + return [false, current] as const; + } + const next = new Set(current); + next.add(workspaceRoot); + return [true, next] as const; + }); + + const logFailure = ( + workspaceRoot: string, + field: "repositoryIdentity" | "faviconPath", + result: Exit.Exit, + ) => + Exit.isFailure(result) + ? Effect.logWarning("Failed to enrich optional project metadata", { + workspaceRoot, + field, + cause: Cause.pretty(result.cause), + }) + : Effect.void; + + const resolveRepositoryIdentity = Effect.fn("ProjectEnrichmentService.resolveRepositoryIdentity")( + function* (workspaceRoot: string) { + const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot); + yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity); + const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot); + yield* PubSub.publish(changes, { + workspaceRoot, + repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity), + enrichment: { + repositoryIdentity: availableValue(Option.some(repositoryIdentity)), + faviconPath: availableValue(faviconPath), + }, + }); + }, + ); + + const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* ( + workspaceRoot: string, + ) { + const faviconPath = yield* Cache.get(faviconCache, workspaceRoot); + yield* logFailure(workspaceRoot, "faviconPath", faviconPath); + }); + + const startWorkers = ( + lane: EnrichmentWorkLane, + resolve: (workspaceRoot: string) => Effect.Effect, + ) => { + const worker = Queue.take(lane.queue).pipe( + Effect.flatMap((workspaceRoot) => + resolve(workspaceRoot).pipe(Effect.ensuring(removePending(lane, workspaceRoot))), + ), + Effect.forever, + ); + return Effect.forEach(Array.from({ length: concurrency }), () => Effect.forkScoped(worker), { + discard: true, + }); + }; + yield* Effect.all( + [ + startWorkers(repositoryIdentityLane, resolveRepositoryIdentity), + startWorkers(faviconLane, resolveFavicon), + ], + { concurrency: "unbounded", discard: true }, + ); + + const requestLane = Effect.fn("ProjectEnrichmentService.requestLane")(function* ( + lane: EnrichmentWorkLane, + workspaceRoot: string, + field: "repositoryIdentity" | "faviconPath", + ) { + if (!(yield* reservePending(lane, workspaceRoot))) return; + if (!(yield* Queue.offer(lane.queue, workspaceRoot))) { + yield* removePending(lane, workspaceRoot); + yield* Effect.logWarning("Project metadata enrichment queue is full", { + workspaceRoot, + field, + }); + } + }); + + const peek: ProjectEnrichmentService["Service"]["peek"] = Effect.fn( + "ProjectEnrichmentService.peek", + )(function* (workspaceRoot) { + const [repositoryIdentity, faviconPath] = yield* Effect.all( + [ + Cache.getSuccess(repositoryIdentityCache, workspaceRoot), + Cache.getSuccess(faviconCache, workspaceRoot), + ] as const, + { concurrency: "unbounded" }, + ); + return { + repositoryIdentity: availableValue(repositoryIdentity), + faviconPath: availableValue(faviconPath), + }; + }); + + const request: ProjectEnrichmentService["Service"]["request"] = Effect.fn( + "ProjectEnrichmentService.request", + )(function* (workspaceRoot) { + const [hasRepositoryIdentity, hasFaviconPath] = yield* Effect.all( + [Cache.has(repositoryIdentityCache, workspaceRoot), Cache.has(faviconCache, workspaceRoot)], + { concurrency: "unbounded" }, + ); + yield* Effect.all( + [ + hasRepositoryIdentity + ? Effect.void + : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"), + hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"), + ], + { concurrency: "unbounded", discard: true }, + ); + }); + + const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn( + "ProjectEnrichmentService.getAvailable", + )(function* (workspaceRoot) { + const available = yield* peek(workspaceRoot); + yield* request(workspaceRoot); + return available; + }); + + const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn( + "ProjectEnrichmentService.invalidate", + )(function* (workspaceRoots) { + yield* Effect.forEach( + new Set(workspaceRoots), + (workspaceRoot) => + Effect.all( + [ + Cache.invalidate(repositoryIdentityCache, workspaceRoot), + Cache.invalidate(faviconCache, workspaceRoot), + ], + { concurrency: "unbounded", discard: true }, + ), + { discard: true }, + ); + }); + + return ProjectEnrichmentService.of({ + peek, + request, + getAvailable, + invalidate, + subscribeChanges: PubSub.subscribe(changes), + }); +}); + +export const layer = Layer.effect(ProjectEnrichmentService, make()); diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 7ee869bcac..c4a877edc8 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -1,9 +1,12 @@ import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { CommandId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import { CommandId, type Project, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; import { TestClock } from "effect/testing"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -11,6 +14,7 @@ import { ServerConfig } from "../config.ts"; import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; +import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; import * as ProjectService from "./ProjectService.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; @@ -39,13 +43,35 @@ const metadataLayer = Layer.merge( }), ); -const TestLayer = ProjectServiceLayerLive.pipe( - Layer.provideMerge(workspacePathsLayer), - Layer.provideMerge(metadataLayer), - Layer.provideMerge(SqlitePersistenceMemory), - Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })), - Layer.provide(NodeServices.layer), -); +const makeTestLayer = ( + projectMetadataLayer: Layer.Layer< + | ProjectFaviconResolver.ProjectFaviconResolver + | RepositoryIdentityResolver.RepositoryIdentityResolver + >, +) => + ProjectServiceLayerLive.pipe( + Layer.provideMerge(ProjectEnrichmentService.layer), + Layer.provideMerge(workspacePathsLayer), + Layer.provideMerge(projectMetadataLayer), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })), + Layer.provide(NodeServices.layer), + ); + +const TestLayer = makeTestLayer(metadataLayer); + +const waitForProject = Effect.fn("ProjectServiceTest.waitForProject")(function* ( + service: ProjectService.ProjectService["Service"], + projectId: ProjectId, + predicate: (project: Project) => boolean, +) { + for (let attempt = 0; attempt < 100; attempt += 1) { + const project = Option.getOrThrow(yield* service.getById(projectId)); + if (predicate(project)) return project; + yield* Effect.yieldNow; + } + return yield* Effect.die(`Project ${projectId} was not enriched in time.`); +}); it.layer(TestLayer)("ProjectService", (it) => { it.effect("creates, updates, resolves, snapshots, and soft-deletes projects", () => @@ -75,8 +101,16 @@ it.layer(TestLayer)("ProjectService", (it) => { ], }); assert.equal(created.workspaceRoot, "/work/project"); - assert.equal(created.repositoryIdentity?.canonicalKey, "github.com/t3tools/project"); - assert.equal(created.faviconPath, "/work/project/favicon.svg"); + assert.isNull(created.repositoryIdentity); + assert.isNull(created.faviconPath); + + const hydratedCreated = yield* waitForProject( + service, + projectId, + (project) => project.repositoryIdentity !== null && project.faviconPath !== null, + ); + assert.equal(hydratedCreated?.repositoryIdentity?.canonicalKey, "github.com/t3tools/project"); + assert.equal(hydratedCreated?.faviconPath, "/work/project/favicon.svg"); const updated = yield* service.update({ commandId: CommandId.make("command:project:update"), @@ -163,3 +197,216 @@ it.layer(TestLayer)("ProjectService", (it) => { }), ); }); + +it.effect( + "returns project mutations before slow enrichment and shares the eventual result across reads", + () => + Effect.gen(function* () { + const repositoryStarted = yield* Deferred.make(); + const releaseRepository = yield* Deferred.make(); + const repositoryCalls = yield* Ref.make(0); + const faviconCalls = yield* Ref.make(0); + + const slowMetadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + Effect.gen(function* () { + yield* Ref.update(repositoryCalls, (count) => count + 1); + yield* Deferred.succeed(repositoryStarted, undefined); + yield* Deferred.await(releaseRepository); + return { + canonicalKey: "github.com/t3tools/slow-project", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:t3tools/slow-project.git", + }, + rootPath: workspaceRoot, + }; + }), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => + Ref.updateAndGet(faviconCalls, (count) => count + 1).pipe( + Effect.as(`${workspaceRoot}/favicon.svg`), + ), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const projectId = ProjectId.make("project:slow-enrichment"); + const createFiber = yield* service + .create({ + commandId: CommandId.make("command:slow-enrichment:create"), + projectId, + title: "Slow enrichment", + workspaceRoot: "/work/slow-enrichment", + }) + .pipe(Effect.forkChild({ startImmediately: true })); + + yield* Deferred.await(repositoryStarted); + yield* Effect.yieldNow; + assert.isDefined(createFiber.pollUnsafe()); + + const created = yield* Fiber.join(createFiber); + assert.isNull(created.repositoryIdentity); + assert.isNull(created.faviconPath); + + const updated = yield* service.update({ + commandId: CommandId.make("command:slow-enrichment:update"), + projectId, + title: "Updated before enrichment", + }); + assert.equal(updated.title, "Updated before enrichment"); + assert.isNull(updated.repositoryIdentity); + assert.equal(updated.faviconPath, "/work/slow-enrichment/favicon.svg"); + + const immediateReadFiber = yield* service + .getById(projectId) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + assert.isDefined(immediateReadFiber.pollUnsafe()); + const immediateRead = Option.getOrThrow(yield* Fiber.join(immediateReadFiber)); + assert.isNull(immediateRead.repositoryIdentity); + assert.equal(immediateRead.faviconPath, "/work/slow-enrichment/favicon.svg"); + + const snapshotFiber = yield* service.snapshot.pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.yieldNow; + assert.isDefined(snapshotFiber.pollUnsafe()); + const immediateSnapshot = yield* Fiber.join(snapshotFiber); + assert.isNull(immediateSnapshot.projects[0]?.repositoryIdentity ?? null); + + yield* Deferred.succeed(releaseRepository, undefined); + + const firstProject = yield* waitForProject( + service, + projectId, + (project) => project.repositoryIdentity !== null && project.faviconPath !== null, + ); + assert.isDefined(firstProject); + assert.equal( + firstProject.repositoryIdentity?.canonicalKey, + "github.com/t3tools/slow-project", + ); + assert.equal(firstProject.faviconPath, "/work/slow-enrichment/favicon.svg"); + + const byId = Option.getOrThrow(yield* service.getById(projectId)); + const secondSnapshot = yield* service.snapshot; + assert.equal(byId.repositoryIdentity?.canonicalKey, "github.com/t3tools/slow-project"); + assert.equal(secondSnapshot.projects[0]?.faviconPath, "/work/slow-enrichment/favicon.svg"); + assert.equal(yield* Ref.get(repositoryCalls), 1); + assert.equal(yield* Ref.get(faviconCalls), 1); + }).pipe(Effect.provide(makeTestLayer(slowMetadataLayer))); + }), +); + +it.effect("keeps project snapshots available when optional metadata enrichment fails", () => + Effect.gen(function* () { + const failingMetadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: () => Effect.succeed(null), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => + Effect.fail( + new ProjectFaviconResolver.ProjectFaviconResolutionError({ + operation: "stat-candidate", + workspaceRoot, + cause: "permission denied", + }), + ), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const projectId = ProjectId.make("project:failed-enrichment"); + yield* service.create({ + commandId: CommandId.make("command:failed-enrichment:create"), + projectId, + title: "Still visible", + workspaceRoot: "/work/failed-enrichment", + }); + + const snapshot = yield* service.snapshot; + assert.equal(snapshot.projects.length, 1); + assert.equal(snapshot.projects[0]?.id, projectId); + assert.equal(snapshot.projects[0]?.title, "Still visible"); + assert.isNull(snapshot.projects[0]?.repositoryIdentity ?? null); + assert.isNull(snapshot.projects[0]?.faviconPath ?? null); + }).pipe(Effect.provide(makeTestLayer(failingMetadataLayer))); + }), +); + +it.effect("invalidates workspace-derived metadata when a project moves", () => + Effect.gen(function* () { + const metadataVersion = yield* Ref.make(1); + const versionedMetadataLayer = Layer.merge( + Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { + resolve: (workspaceRoot) => + Ref.get(metadataVersion).pipe( + Effect.map((version) => ({ + canonicalKey: `example.test/v${version}${workspaceRoot}`, + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: `https://example.test/v${version}${workspaceRoot}.git`, + }, + rootPath: workspaceRoot, + })), + ), + }), + Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + resolvePath: (workspaceRoot) => + Ref.get(metadataVersion).pipe( + Effect.map((version) => `${workspaceRoot}/favicon-v${version}.svg`), + ), + }), + ); + + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const projectId = ProjectId.make("project:moved-enrichment"); + yield* service.create({ + commandId: CommandId.make("command:moved-enrichment:create"), + projectId, + title: "Moved", + workspaceRoot: "/work/original", + }); + assert.equal( + (yield* waitForProject( + service, + projectId, + (project) => project.faviconPath === "/work/original/favicon-v1.svg", + )).faviconPath, + "/work/original/favicon-v1.svg", + ); + + yield* Ref.set(metadataVersion, 2); + yield* service.update({ + commandId: CommandId.make("command:moved-enrichment:away"), + projectId, + workspaceRoot: "/work/temporary", + }); + yield* service.snapshot; + + yield* Ref.set(metadataVersion, 3); + yield* service.update({ + commandId: CommandId.make("command:moved-enrichment:return"), + projectId, + workspaceRoot: "/work/original", + }); + assert.equal( + (yield* waitForProject( + service, + projectId, + (project) => project.faviconPath === "/work/original/favicon-v3.svg", + )).faviconPath, + "/work/original/favicon-v3.svg", + ); + }).pipe(Effect.provide(makeTestLayer(versionedMetadataLayer))); + }), +); diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 1f3d9869f5..4f11d0111a 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -15,8 +15,7 @@ import * as Schema from "effect/Schema"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts"; -import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; -import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; +import { ProjectEnrichmentService, type ProjectEnrichment } from "./ProjectEnrichmentService.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; export interface ProjectCreateInput { @@ -75,7 +74,6 @@ export class ProjectOperationError extends Schema.TaggedErrorClass { - const repositoryIdentity = yield* repositoryIdentityResolver.resolve(row.workspaceRoot); - const faviconPath = yield* faviconResolver.resolvePath(row.workspaceRoot).pipe( - Effect.mapError( - (cause) => - new ProjectOperationError({ - operation: "resolve-favicon", - projectId: row.projectId, - workspaceRoot: row.workspaceRoot, - cause, - }), - ), - ); - return { - id: row.projectId, - title: row.title, - workspaceRoot: row.workspaceRoot, - repositoryIdentity, - faviconPath, - defaultModelSelection: row.defaultModelSelection, - scripts: row.scripts, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - deletedAt: row.deletedAt, - }; + enrichment: ProjectEnrichment | null, + ): Project => ({ + id: row.projectId, + title: row.title, + workspaceRoot: row.workspaceRoot, + repositoryIdentity: enrichment?.repositoryIdentity ?? null, + faviconPath: enrichment?.faviconPath ?? null, + defaultModelSelection: row.defaultModelSelection, + scripts: row.scripts, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + deletedAt: row.deletedAt, + }); + + const hydrateAvailable = Effect.fn("ProjectService.hydrateAvailable")(function* ( + row: ProjectionProjects.ProjectionProject, + ) { + const enrichment = + row.deletedAt === null + ? yield* projectEnrichment.getAvailable(row.workspaceRoot) + : yield* projectEnrichment.peek(row.workspaceRoot); + return toProject(row, enrichment); }); const readRows = Effect.fn("ProjectService.readRows")(function* () { @@ -174,7 +168,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(row) || (row.value.deletedAt !== null && !options?.includeDeleted)) { return Option.none(); } - return Option.some(yield* hydrate(row.value)); + return Option.some(yield* hydrateAvailable(row.value)); }, ); @@ -196,7 +190,7 @@ export const make = Effect.gen(function* () { candidate.workspaceRoot === normalized && (options?.includeDeleted === true || candidate.deletedAt === null), ); - return row === undefined ? Option.none() : Option.some(yield* hydrate(row)); + return row === undefined ? Option.none() : Option.some(yield* hydrateAvailable(row)); }); const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) { @@ -214,9 +208,12 @@ export const make = Effect.gen(function* () { cause: "The accepted project command did not produce a project projection.", }); } - return yield* hydrate(row.value); + return yield* hydrateAvailable(row.value); }); + const invalidateEnrichment = (...workspaceRoots: ReadonlyArray) => + projectEnrichment.invalidate(workspaceRoots); + const dispatch = ( projectId: ProjectId, command: Parameters[0], @@ -284,7 +281,7 @@ export const make = Effect.gen(function* () { scripts: [...(input.scripts ?? [])], createdAt: now, }, - readCommitted(input.projectId), + invalidateEnrichment(workspaceRoot).pipe(Effect.andThen(readCommitted(input.projectId))), ); }, ); @@ -332,7 +329,10 @@ export const make = Effect.gen(function* () { : { defaultModelSelection: input.defaultModelSelection }), ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }), }, - readCommitted(input.projectId), + (workspaceRoot === existing.value.workspaceRoot + ? Effect.void + : invalidateEnrichment(existing.value.workspaceRoot, workspaceRoot) + ).pipe(Effect.andThen(readCommitted(input.projectId))), ); }, ); @@ -365,14 +365,16 @@ export const make = Effect.gen(function* () { commandId: input.commandId, projectId, }, - readCommitted(projectId), + invalidateEnrichment(existing.value.workspaceRoot).pipe( + Effect.andThen(readCommitted(projectId)), + ), ); }, ); const snapshot = Effect.gen(function* () { const rows = (yield* readRows()).filter((row) => row.deletedAt === null); - const hydrated = yield* Effect.forEach(rows, hydrate, { concurrency: 8 }); + const hydrated = yield* Effect.forEach(rows, hydrateAvailable, { concurrency: 8 }); return { projects: hydrated, updatedAt: DateTime.formatIso(yield* DateTime.now), diff --git a/apps/server/src/provider/NativeProtocolLogging.ts b/apps/server/src/provider/NativeProtocolLogging.ts new file mode 100644 index 0000000000..a85833b0e8 --- /dev/null +++ b/apps/server/src/provider/NativeProtocolLogging.ts @@ -0,0 +1,40 @@ +import { errorTag } from "@t3tools/shared/observability"; + +export function structuralProtocolMethod(value: string): string { + return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown"; +} + +/** + * Retain only bounded structural metadata for native protocol diagnostics. + * Provider payload values may contain prompts, credentials, or arbitrarily + * large tool output and must never be copied into the observability stream. + */ +export function summarizeNativeProtocolPayload( + payload: unknown, +): Readonly> { + if (payload === null) return { valueType: "null" }; + if (typeof payload === "string") { + return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength }; + } + if (payload instanceof Uint8Array) { + return { valueType: "bytes", byteLength: payload.byteLength }; + } + if (Array.isArray(payload)) { + return { valueType: "array", itemCount: payload.length }; + } + if (typeof payload !== "object") { + return { valueType: typeof payload }; + } + + try { + const record = payload as Record; + return { + valueType: "object", + fieldCount: Object.keys(record).length, + ...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}), + ...(typeof record.tag === "string" ? { method: structuralProtocolMethod(record.tag) } : {}), + }; + } catch { + return { valueType: "object" }; + } +} diff --git a/apps/server/src/provider/acp/AcpNativeLogging.ts b/apps/server/src/provider/acp/AcpNativeLogging.ts index 06bff3aa61..79e925766c 100644 --- a/apps/server/src/provider/acp/AcpNativeLogging.ts +++ b/apps/server/src/provider/acp/AcpNativeLogging.ts @@ -1,5 +1,5 @@ import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts"; -import { causeErrorTag, errorTag } from "@t3tools/shared/observability"; +import { causeErrorTag } from "@t3tools/shared/observability"; import * as Cause from "effect/Cause"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; @@ -7,46 +7,18 @@ import * as Effect from "effect/Effect"; import type * as EffectAcpProtocol from "effect-acp/protocol"; import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts"; +import { + structuralProtocolMethod, + summarizeNativeProtocolPayload, +} from "../NativeProtocolLogging.ts"; import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts"; -function structuralMethod(value: string): string { - return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown"; -} - -function summarizePayload(payload: unknown): Readonly> { - if (payload === null) return { valueType: "null" }; - if (typeof payload === "string") { - return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength }; - } - if (payload instanceof Uint8Array) { - return { valueType: "bytes", byteLength: payload.byteLength }; - } - if (Array.isArray(payload)) { - return { valueType: "array", itemCount: payload.length }; - } - if (typeof payload !== "object") { - return { valueType: typeof payload }; - } - - try { - const record = payload as Record; - return { - valueType: "object", - fieldCount: Object.keys(record).length, - ...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}), - ...(typeof record.tag === "string" ? { method: structuralMethod(record.tag) } : {}), - }; - } catch { - return { valueType: "object" }; - } -} - function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) { return { - method: structuralMethod(event.method), + method: structuralProtocolMethod(event.method), status: event.status, - request: summarizePayload(event.payload), - ...(event.result !== undefined ? { result: summarizePayload(event.result) } : {}), + request: summarizeNativeProtocolPayload(event.payload), + ...(event.result !== undefined ? { result: summarizeNativeProtocolPayload(event.result) } : {}), ...(event.cause !== undefined ? { errorTag: causeErrorTag(event.cause), @@ -56,11 +28,11 @@ function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEv }; } -function formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) { +export function formatAcpProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) { return { direction: event.direction, stage: event.stage, - payload: summarizePayload(event.payload), + payload: summarizeNativeProtocolPayload(event.payload), }; } @@ -119,7 +91,7 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory" logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) => writeNativeAcpLog({ kind: "protocol", - payload: formatProtocolLogPayload(event), + payload: formatAcpProtocolLogPayload(event), }), } satisfies NonNullable, } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0c9c8cc5c1..ebe6cc04ed 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -36,6 +36,7 @@ import * as GitHubCli from "./sourceControl/GitHubCli.ts"; import * as GitLabCli from "./sourceControl/GitLabCli.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts"; +import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as McpHttpServer from "./mcp/McpHttpServer.ts"; import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts"; @@ -50,6 +51,7 @@ import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts"; import * as ServerSettings from "./serverSettings.ts"; +import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -354,6 +356,7 @@ const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe( ); const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( + Layer.provideMerge(ProviderEventLoggersLive), // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but // the rewritten registry reads snapshots off the instance registry and @@ -361,6 +364,7 @@ const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe( // keeps a single Live for all opencode consumers. Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), Layer.provideMerge(WorkspaceLayerLive), + Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(ProjectFaviconResolverLayerLive), Layer.provideMerge(RepositoryIdentityResolver.layer), Layer.provideMerge(ServerEnvironment.layer), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 55e4531a0c..6db5d0f22e 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -26,7 +26,6 @@ import * as ServerConfig from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; -import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; @@ -329,7 +328,6 @@ export const make = Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; const keybindings = yield* Keybindings.Keybindings; const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; - const orchestrator = yield* Orchestrator.OrchestratorV2; const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; @@ -418,10 +416,6 @@ export const make = Effect.gen(function* () { const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped); yield* Ref.set(effectWorkerFiber, workerFiber); yield* agentAwarenessRelay.start(); - const resumedQueuedRuns = yield* orchestrator.resumeQueuedRuns; - if (resumedQueuedRuns > 0) { - yield* Effect.logInfo("V2 queued runs resumed", { resumedQueuedRuns }); - } }), ), autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 895d4aeea0..4d51728ba4 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -29,7 +29,7 @@ import { OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, ORCHESTRATION_WS_METHODS, - type ProjectId, + type OrchestrationProjectShell, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, @@ -100,6 +100,7 @@ import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as ReviewService from "./review/ReviewService.ts"; +import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; import * as ProjectService from "./project/ProjectService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; @@ -423,6 +424,21 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const threadManagement = yield* ThreadManagementService.ThreadManagementService; const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( + (projects: ReadonlyArray) => + Effect.forEach( + projects, + (project) => + projectEnrichment.getAvailable(project.workspaceRoot).pipe( + Effect.map((enrichment) => ({ + ...project, + repositoryIdentity: enrichment.repositoryIdentity, + })), + ), + { concurrency: 16 }, + ), + ); const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const projectService = yield* ProjectService.ProjectService; const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; @@ -629,10 +645,11 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( function* () { - const snapshot = yield* sql - .withTransaction( + const enrichmentChanges = yield* projectEnrichment.subscribeChanges; + const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () { + const base = yield* sql.withTransaction( Effect.gen(function* () { - const projects = yield* projectionSnapshotQuery.getShellSnapshot(); + const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); const threads = yield* threadManagement.getShellSnapshot(); return { schemaVersion: threads.schemaVersion, @@ -642,16 +659,19 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => archivedThreads: threads.archivedThreads, } as const; }), - ) - .pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed to load the application shell snapshot", - cause, - }), - ), ); + const projects = yield* enrichProjectShells(base.projects); + return { ...base, projects }; + }); + const snapshot = yield* loadSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to load the application shell snapshot", + cause, + }), + ), + ); const live = applicationEvents .streamApplicationEvents({ afterSequence: snapshot.snapshotSequence }) @@ -695,7 +715,17 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ), ); - return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live).pipe( + const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe( + Stream.filter((change) => change.repositoryIdentityResolved), + Stream.debounce("25 millis"), + Stream.mapEffect(() => loadSnapshot()), + Stream.map((snapshot) => ({ kind: "snapshot" as const, snapshot })), + ); + + return Stream.merge( + Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live), + enrichmentRefreshes, + ).pipe( Stream.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ @@ -710,7 +740,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => const getOrchestrationV2ArchivedShellSnapshot = sql .withTransaction( Effect.gen(function* () { - const projects = yield* projectionSnapshotQuery.getShellSnapshot(); + const projects = yield* projectionSnapshotQuery.getShellSnapshotWithoutEnrichment(); const threads = yield* threadManagement.getShellSnapshot(); return { schemaVersion: threads.schemaVersion, @@ -721,6 +751,11 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => }), ) .pipe( + Effect.flatMap((snapshot) => + enrichProjectShells(snapshot.projects).pipe( + Effect.map((projects) => ({ ...snapshot, projects })), + ), + ), Effect.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1c6f8c95cd..6b0a47efde 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2542,8 +2542,20 @@ function ChatViewContent(props: ChatViewProps) { visibleTurnItems: serverVisibleTurnItems, optimisticMessages: optimisticUserMessages, attachmentUrlById: serverAttachmentUrlById, + ...(serverThread === null + ? {} + : { + attempts: serverThread.projection.attempts, + nodes: serverThread.projection.nodes, + }), }), - [optimisticUserMessages, serverVisibleTurnItems, serverAttachmentUrlById], + [ + optimisticUserMessages, + serverVisibleTurnItems, + serverAttachmentUrlById, + serverThread?.projection.attempts, + serverThread?.projection.nodes, + ], ); const draftTimelineEntries = useMemo( () => diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index b39efa6682..3315ba6cb1 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -672,7 +672,11 @@ export function resolveThreadStatusPill(input: { }; } - if (thread.runtime?.status === "starting" || thread.runtime?.status === "queued") { + if ( + thread.runtime?.status === "preparing" || + thread.runtime?.status === "starting" || + thread.runtime?.status === "queued" + ) { return { label: "Connecting", colorClass: "text-sky-600 dark:text-sky-300/80", diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 744186727a..8a42479eda 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -541,6 +541,143 @@ describe("deriveMessagesTimelineRows", () => { ).toBeDefined(); }); + it("collapses only output from a superseded V2 attempt within the active logical run", () => { + const runId = "run-steered" as never; + const supersededAttemptId = "attempt-1" as never; + const activeAttemptId = "attempt-2" as never; + const supersededAttempt = { + id: supersededAttemptId, + runId, + attemptOrdinal: 1, + rootNodeId: "node-attempt-1" as never, + status: "superseded" as const, + }; + const activeAttempt = { + id: activeAttemptId, + runId, + attemptOrdinal: 2, + rootNodeId: "node-attempt-2" as never, + status: "running" as const, + }; + const timelineEntries = [ + { + id: "initial-user-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:00Z", + attempt: supersededAttempt, + message: { + id: "initial-user" as never, + role: "user" as const, + text: "Build it", + runId, + inputIntent: "turn_start" as const, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + streaming: false, + }, + }, + { + id: "superseded-assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:02Z", + attempt: supersededAttempt, + message: { + id: "superseded-assistant" as never, + role: "assistant" as const, + text: "Partial old response", + runId, + createdAt: "2026-01-01T00:00:02Z", + updatedAt: "2026-01-01T00:00:03Z", + streaming: false, + }, + }, + { + id: "superseded-work-entry", + kind: "work" as const, + createdAt: "2026-01-01T00:00:04Z", + attempt: supersededAttempt, + entry: { + id: "superseded-work", + createdAt: "2026-01-01T00:00:04Z", + runId, + label: "Old command", + tone: "tool" as const, + }, + }, + { + id: "steer-user-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + attempt: activeAttempt, + message: { + id: "steer-user" as never, + role: "user" as const, + text: "Change direction", + runId, + inputIntent: "steer" as const, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:05Z", + streaming: false, + }, + }, + { + id: "active-assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:06Z", + attempt: activeAttempt, + message: { + id: "active-assistant" as never, + role: "assistant" as const, + text: "Current response", + runId, + createdAt: "2026-01-01T00:00:06Z", + updatedAt: "2026-01-01T00:00:07Z", + streaming: true, + }, + }, + ]; + const common = { + timelineEntries, + latestRun: { + runId, + status: "running" as const, + startedAt: "2026-01-01T00:00:00Z", + completedAt: null, + }, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }; + + const collapsedRows = deriveMessagesTimelineRows(common); + expect(collapsedRows.map((row) => row.id)).toEqual([ + "initial-user-entry", + `attempt-fold:${supersededAttemptId}`, + "steer-user-entry", + "active-assistant-entry", + ]); + expect(collapsedRows.find((row) => row.kind === "attempt-fold")).toMatchObject({ + attemptId: supersededAttemptId, + runId, + label: "Superseded attempt", + expanded: false, + }); + + const expandedRows = deriveMessagesTimelineRows({ + ...common, + expandedAttemptIds: new Set([supersededAttemptId]), + }); + expect(expandedRows.map((row) => row.id)).toEqual([ + "initial-user-entry", + `attempt-fold:${supersededAttemptId}`, + "superseded-assistant-entry", + "superseded-work-entry", + "steer-user-entry", + "active-assistant-entry", + ]); + }); + it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => { // A steer ends the previous turn early: its only message completes the // instant it is created, and trailing work entries land after it. The diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 92b49a4975..6eaf7344cf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -11,6 +11,7 @@ import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../.. import { type MessageId, type OrchestrationV2ProjectedTurnItem, + type RunAttemptId, type RunId, } from "@t3tools/contracts"; import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell"; @@ -189,6 +190,15 @@ export type MessagesTimelineRow = label: string; expanded: boolean; } + | { + kind: "attempt-fold"; + id: string; + createdAt: string; + runId: RunId; + attemptId: RunAttemptId; + label: string; + expanded: boolean; + } | { kind: "message"; id: string; @@ -300,6 +310,51 @@ interface TurnFold { label: string; } +interface SupersededAttemptFold { + readonly runId: RunId; + readonly attemptId: RunAttemptId; + readonly anchorEntryId: string; + readonly createdAt: string; + readonly hiddenEntryIds: ReadonlySet; +} + +/** + * Groups only provider output owned by an explicitly superseded V2 attempt. + * User messages remain visible because they are inputs to the logical run, + * including the steer message that started the replacement attempt. + */ +function deriveSupersededAttemptFolds( + timelineEntries: ReadonlyArray, +): ReadonlyMap { + const entriesByAttemptId = new Map(); + for (const entry of timelineEntries) { + if ( + entry.attempt?.status !== "superseded" || + (entry.kind === "message" && entry.message.role === "user") + ) { + continue; + } + const entries = entriesByAttemptId.get(entry.attempt.id) ?? []; + entries.push(entry); + entriesByAttemptId.set(entry.attempt.id, entries); + } + + const foldsByAnchorEntryId = new Map(); + for (const entries of entriesByAttemptId.values()) { + const firstEntry = entries[0]; + const attempt = firstEntry?.attempt; + if (firstEntry === undefined || attempt === undefined) continue; + foldsByAnchorEntryId.set(firstEntry.id, { + runId: attempt.runId, + attemptId: attempt.id, + anchorEntryId: firstEntry.id, + createdAt: firstEntry.createdAt, + hiddenEntryIds: new Set(entries.map((entry) => entry.id)), + }); + } + return foldsByAnchorEntryId; +} + /** * The session's running turn is authoritative when latestTurn briefly lags or * regresses behind it. Otherwise, the latest turn counts as unsettled while it @@ -466,6 +521,7 @@ export function deriveMessagesTimelineRows(input: { timelineEntries: ReadonlyArray; latestRun?: TimelineLatestRun | null; expandedRunIds?: ReadonlySet; + expandedAttemptIds?: ReadonlySet; isWorking: boolean; activeTurnStartedAt: string | null; turnDiffSummaryByAssistantMessageId: ReadonlyMap; @@ -477,6 +533,7 @@ export function deriveMessagesTimelineRows(input: { ); const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries); const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null); + const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds(input.timelineEntries); const foldsByAnchorEntryId = deriveTurnFolds({ timelineEntries: input.timelineEntries, terminalAssistantMessageIds, @@ -491,6 +548,14 @@ export function deriveMessagesTimelineRows(input: { } } } + const collapsedSupersededEntryIds = new Set(); + for (const fold of supersededFoldsByAnchorEntryId.values()) { + if (!input.expandedAttemptIds?.has(fold.attemptId)) { + for (const entryId of fold.hiddenEntryIds) { + collapsedSupersededEntryIds.add(entryId); + } + } + } for (let index = 0; index < input.timelineEntries.length; index += 1) { const timelineEntry = input.timelineEntries[index]; @@ -514,6 +579,23 @@ export function deriveMessagesTimelineRows(input: { continue; } + const supersededFold = supersededFoldsByAnchorEntryId.get(timelineEntry.id); + if (supersededFold) { + nextRows.push({ + kind: "attempt-fold", + id: `attempt-fold:${supersededFold.attemptId}`, + createdAt: supersededFold.createdAt, + runId: supersededFold.runId, + attemptId: supersededFold.attemptId, + label: "Superseded attempt", + expanded: input.expandedAttemptIds?.has(supersededFold.attemptId) ?? false, + }); + } + + if (collapsedSupersededEntryIds.has(timelineEntry.id)) { + continue; + } + if (timelineEntry.kind === "work") { const groupedEntries = [timelineEntry.entry]; let cursor = index + 1; @@ -523,7 +605,10 @@ export function deriveMessagesTimelineRows(input: { !nextEntry || nextEntry.kind !== "work" || collapsedEntryIds.has(nextEntry.id) || - foldsByAnchorEntryId.has(nextEntry.id) + collapsedSupersededEntryIds.has(nextEntry.id) || + foldsByAnchorEntryId.has(nextEntry.id) || + supersededFoldsByAnchorEntryId.has(nextEntry.id) || + nextEntry.attempt?.id !== timelineEntry.attempt?.id ) { break; } @@ -700,6 +785,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded; } + case "attempt-fold": { + const bf = b as typeof a; + return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded; + } + case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index d6e44f7c51..aacd6dd402 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -482,6 +482,75 @@ describe("MessagesTimeline", () => { expect(markup).toContain(">steer<"); }); + it("shows a collapsed disclosure for superseded attempt output", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const runId = RunId.make("run-steered"); + const supersededAttempt = { + id: "attempt-1" as never, + runId, + attemptOrdinal: 1, + rootNodeId: "node-attempt-1" as never, + status: "superseded" as const, + }; + const activeAttempt = { + id: "attempt-2" as never, + runId, + attemptOrdinal: 2, + rootNodeId: "node-attempt-2" as never, + status: "running" as const, + }; + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-superseded-attempt-id="attempt-1"'); + expect(markup).toContain('aria-expanded="false"'); + expect(markup).toContain("Superseded attempt"); + expect(markup).toContain("Partial output retained"); + expect(markup).toContain("Current response remains visible"); + expect(markup).not.toContain("Partial response from the old attempt"); + }); + it("exposes a per-response fork action for completed assistant items", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const projectedItem = { @@ -672,6 +741,55 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain("Structured details"); }); + it("renders V2 provider failures as standalone error rows", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-v2-item-type="error"'); + expect(markup).toContain("Provider error"); + expect(markup).toContain("Invalid reasoning effort."); + }); + it("keeps inherited V2 work provenance on the rendered row", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const item = { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index d67cfe3e26..c59846d766 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -2,6 +2,7 @@ import { type EnvironmentId, type MessageId, type OrchestrationV2TurnItem, + type RunAttemptId, type ScopedThreadRef, type ServerProviderSkill, type RunId, @@ -155,6 +156,7 @@ interface TimelineRowSharedState { readonly scopeId: string; }) => void; onToggleTurnFold: (runId: RunId) => void; + onToggleAttemptFold: (attemptId: RunAttemptId) => void; } interface TimelineRowActivityState { @@ -303,6 +305,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ loadEarlier = null, }: MessagesTimelineProps) { const [expandedRunIds, setExpandedRunIds] = useState>(new Set()); + const [expandedAttemptIds, setExpandedAttemptIds] = useState>( + new Set(), + ); // Toggling a fold inserts/removes rows between the fold row and the final // message — everything above the trigger is unchanged, so the trigger stays @@ -344,32 +349,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }); }); }, []); - - const shouldRestoreVisibleContentPosition = useCallback((row: MessagesTimelineRow) => { - const disclosureAnchorKey = disclosureAnchorKeyRef.current; - return disclosureAnchorKey === null || row.id === disclosureAnchorKey; + const onToggleAttemptFold = useCallback((attemptId: RunAttemptId) => { + setFoldToggleSettling(true); + setExpandedAttemptIds((existing) => { + const next = new Set(existing); + if (next.has(attemptId)) { + next.delete(attemptId); + } else { + next.add(attemptId); + } + return next; + }); }, []); - - const maintainVisibleContentPosition = useMemo( - () => ({ - data: true, - size: true, - shouldRestorePosition: shouldRestoreVisibleContentPosition, - }), - [shouldRestoreVisibleContentPosition], - ); - - const onToggleTurnFold = useCallback( - (turnId: TurnId) => { - suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`); - setExpandedTurnIds((existing) => { - const next = new Set(existing); - if (next.has(turnId)) { - next.delete(turnId); - } else { - next.add(turnId); - } - return next; + useEffect(() => { + if (!foldToggleSettling) { + return; + } + let secondFrameId: number | null = null; + const firstFrameId = window.requestAnimationFrame(() => { + secondFrameId = window.requestAnimationFrame(() => { + setFoldToggleSettling(false); }); }, [suspendEndScrollMaintenanceForDisclosure], @@ -425,6 +424,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ timelineEntries, latestRun, expandedRunIds, + expandedAttemptIds, isWorking, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, @@ -434,6 +434,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ timelineEntries, latestRun, expandedRunIds, + expandedAttemptIds, isWorking, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, @@ -539,9 +540,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onForkFromRun, onRollbackCheckpoint, onToggleTurnFold, - onToggleWorkGroup, - agentPanelModel, - onOpenAgents, + onToggleAttemptFold, }), [ timestampFormat, @@ -558,9 +557,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onForkFromRun, onRollbackCheckpoint, onToggleTurnFold, - onToggleWorkGroup, - agentPanelModel, - onOpenAgents, + onToggleAttemptFold, ], ); const activityState = useMemo( @@ -955,7 +952,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time // they sit closer to the work that follows them. (row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) || row.kind === "work" || - row.kind === "event" + row.kind === "event" || + row.kind === "attempt-fold" ? "pb-2" : "pb-4", row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null, @@ -968,6 +966,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "work" ? : null} {row.kind === "work-toggle" ? : null} {row.kind === "turn-fold" ? : null} + {row.kind === "attempt-fold" ? : null} {row.kind === "message" && row.message.role === "user" ? : null} {row.kind === "message" && row.message.role === "assistant" ? ( @@ -1180,6 +1179,26 @@ function TurnFoldTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const Icon = row.expanded ? ChevronDownIcon : ChevronRightIcon; + + return ( + + ); +} + function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)"); @@ -1326,6 +1345,13 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { readonly icon: typeof CircleAlertIcon; } { switch (item.type) { + case "error": + return { + label: item.title?.trim() || "Provider error", + detail: item.failure.message, + tone: "danger", + icon: CircleAlertIcon, + }; case "run_interrupt_request": return { label: "Interrupt requested", diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index efce259b78..5f697db8f6 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -37,7 +37,11 @@ export function QueuedRunsControl(props: { ); const activeRun = projection?.runs.findLast( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", ) ?? null; if (queued.length === 0) return null; diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index ff59624056..3c2435b301 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -2645,6 +2645,7 @@ function formatDurationShort(diffMs: number): string | undefined { } const ACTIVE_RUN_STATUSES: ReadonlySet = new Set([ + "preparing", "starting", "running", "waiting", @@ -3152,6 +3153,13 @@ function workLogRowContent(item: OrchestrationV2TurnItem): WorkLogRowContent { preview: item.message, tone: "red", }; + case "error": + return { + glyph: "!", + label: "Provider error", + preview: clipOneLine(item.failure.message, 160), + tone: "red", + }; case "compaction": return { glyph: "≈", diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 9636c7f946..8f97b680c7 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1,10 +1,16 @@ import { MessageId, + NodeId, PlanId, + ProviderInstanceId, + ProviderThreadId, + RunAttemptId, RunId, ThreadId, TurnItemId, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2ExecutionNode, + type OrchestrationV2RunAttempt, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -196,12 +202,24 @@ describe("V2 session presentation", () => { { id: "step-2", text: "Second", status: "pending" as const }, ], } satisfies OrchestrationV2TurnItem; + const errorItem = { + ...base("item-error", 5), + status: "failed" as const, + type: "error" as const, + failure: { + class: "validation_error" as const, + message: "Invalid reasoning effort.", + code: "invalid_request", + retryable: false, + }, + } satisfies OrchestrationV2TurnItem; const visibleTurnItems: ReadonlyArray = [ userItem, requestItem, commandItem, resultItem, todoItem, + errorItem, ].map((item, position) => ({ position, visibility: "local" as const, @@ -221,6 +239,7 @@ describe("V2 session presentation", () => { ["work", commandItem.id], ["event", resultItem.id], ["work", todoItem.id], + ["event", errorItem.id], ]); const commandEntry = entries[2]; const userEntry = entries[0]; @@ -240,6 +259,139 @@ describe("V2 session presentation", () => { expect(todoEntry.entry.label).toBe("Updated tasks"); expect(todoEntry.entry.detail).toBe("1/2 completed"); } + const errorEntry = entries[5]; + expect(errorEntry?.kind).toBe("event"); + if (errorEntry?.kind === "event") { + expect(errorEntry.projectedItem).toBe(visibleTurnItems[5]); + expect(errorEntry.projectedItem.item.type).toBe("error"); + if (errorEntry.projectedItem.item.type === "error") { + expect(errorEntry.projectedItem.item.failure.message).toBe("Invalid reasoning effort."); + } + } + }); + + it("resolves attempt identity through V2 execution nodes", () => { + const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); + const threadId = ThreadId.make("thread-attempts"); + const runId = RunId.make("run-steered"); + const supersededRootNodeId = NodeId.make("node-attempt-1-root"); + const supersededChildNodeId = NodeId.make("node-attempt-1-child"); + const activeRootNodeId = NodeId.make("node-attempt-2-root"); + const supersededAttemptId = RunAttemptId.make("attempt-1"); + const activeAttemptId = RunAttemptId.make("attempt-2"); + const providerInstanceId = ProviderInstanceId.make("codex-default"); + const providerThreadId = ProviderThreadId.make("provider-thread-attempts"); + const attempts: ReadonlyArray = [ + { + id: supersededAttemptId, + runId, + attemptOrdinal: 1, + rootNodeId: supersededRootNodeId, + providerInstanceId, + providerThreadId, + providerTurnId: null, + reason: "initial", + status: "superseded", + startedAt: now, + completedAt: now, + }, + { + id: activeAttemptId, + runId, + attemptOrdinal: 2, + rootNodeId: activeRootNodeId, + providerInstanceId, + providerThreadId, + providerTurnId: null, + reason: "steering_restart", + status: "running", + startedAt: now, + completedAt: null, + }, + ]; + const node = ( + id: OrchestrationV2ExecutionNode["id"], + rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"], + parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"], + ): OrchestrationV2ExecutionNode => ({ + id, + threadId, + runId, + parentNodeId, + rootNodeId, + kind: id === rootNodeId ? "root_turn" : "assistant_message", + status: "running", + countsForRun: true, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }); + const nodes = [ + node(supersededRootNodeId, supersededRootNodeId, null), + node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId), + node(activeRootNodeId, activeRootNodeId, null), + ]; + const assistantItem = ( + id: string, + messageId: string, + nodeId: NodeId, + text: string, + ordinal: number, + ): OrchestrationV2TurnItem => ({ + id: TurnItemId.make(id), + threadId, + runId, + nodeId, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "assistant_message", + messageId: MessageId.make(messageId), + text, + streaming: true, + }); + const items = [ + assistantItem( + "item-superseded", + "message-superseded", + supersededChildNodeId, + "Partial old response", + 0, + ), + assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1), + ]; + const visibleTurnItems: ReadonlyArray = items.map( + (item, position) => ({ + position, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: item.id, + item, + }), + ); + + const entries = deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems, + optimisticMessages: [], + attempts, + nodes, + }); + + expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([ + [supersededAttemptId, "superseded"], + [activeAttemptId, "running"], + ]); }); }); diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 3bdb31ccbf..2d47e62b2a 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1,6 +1,8 @@ import { ProviderDriverKind, + type OrchestrationV2ExecutionNode, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2RunAttempt, type OrchestrationV2TurnItem, type PlanId, type RunId, @@ -83,7 +85,12 @@ export interface LatestProposedPlanState { readonly status: ThreadProposedPlan["status"]; } -export type TimelineEntry = +export type TimelineAttempt = Pick< + OrchestrationV2RunAttempt, + "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status" +>; + +export type TimelineEntry = ( | { readonly id: string; readonly kind: "message"; @@ -108,7 +115,11 @@ export type TimelineEntry = readonly kind: "event"; readonly createdAt: string; readonly projectedItem: OrchestrationV2ProjectedTurnItem; - }; + } +) & { + /** V2 identity resolved from the item's execution node, when locally available. */ + readonly attempt?: TimelineAttempt; +}; export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { return ( @@ -169,6 +180,7 @@ export function isLatestRunSettled( ): boolean { if (latestRun === null) return false; if ( + latestRun.status === "preparing" || latestRun.status === "starting" || latestRun.status === "running" || latestRun.status === "waiting" @@ -387,6 +399,7 @@ export function deriveTimelineEntries( const STANDALONE_V2_ITEM_TYPES = new Set([ "approval_request", "compaction", + "error", "fork", "handoff", "run_interrupt_request", @@ -496,6 +509,13 @@ function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry changedFiles: item.files.map((file) => file.path), toolData: item, }; + case "error": + return { + ...common, + label: title ?? "Provider error", + detail: item.failure.message, + toolData: item, + }; case "todo_list": { const completed = item.steps.filter((step) => step.status === "completed").length; return { @@ -530,13 +550,38 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: { readonly visibleTurnItems: ReadonlyArray; readonly optimisticMessages: ReadonlyArray; readonly attachmentUrlById?: ReadonlyMap; + readonly attempts?: ReadonlyArray; + readonly nodes?: ReadonlyArray; }): TimelineEntry[] { const committedMessageIds = new Set(); const entries: TimelineEntry[] = []; + const attemptByRootNodeId = new Map( + (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const), + ); + const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const)); + + const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => { + if (item.nodeId === null || item.runId === null) return undefined; + let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId; + const visited = new Set(); + while (nodeId !== null && !visited.has(nodeId)) { + visited.add(nodeId); + const directAttempt = attemptByRootNodeId.get(nodeId); + if (directAttempt?.runId === item.runId) return directAttempt; + const node = nodeById.get(nodeId); + if (node === undefined) return undefined; + const rootAttempt = attemptByRootNodeId.get(node.rootNodeId); + if (rootAttempt?.runId === item.runId) return rootAttempt; + nodeId = node.parentNodeId; + } + return undefined; + }; for (const row of input.visibleTurnItems) { const { item } = row; const createdAt = projectedItemCreatedAt(row); + const attempt = resolveAttempt(item); + const attemptMetadata = attempt === undefined ? {} : { attempt }; if (item.type === "user_message" || item.type === "assistant_message") { const message: ChatMessage = { id: item.messageId, @@ -557,7 +602,14 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: { ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}), }; committedMessageIds.add(message.id); - entries.push({ id: message.id, kind: "message", createdAt, message, projectedItem: row }); + entries.push({ + id: message.id, + kind: "message", + createdAt, + message, + projectedItem: row, + ...attemptMetadata, + }); continue; } @@ -572,16 +624,34 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: { createdAt, updatedAt: DateTime.formatIso(item.updatedAt), }; - entries.push({ id: item.id, kind: "proposed-plan", createdAt, proposedPlan }); + entries.push({ + id: item.id, + kind: "proposed-plan", + createdAt, + proposedPlan, + ...attemptMetadata, + }); continue; } if (STANDALONE_V2_ITEM_TYPES.has(item.type)) { - entries.push({ id: item.id, kind: "event", createdAt, projectedItem: row }); + entries.push({ + id: item.id, + kind: "event", + createdAt, + projectedItem: row, + ...attemptMetadata, + }); continue; } - entries.push({ id: item.id, kind: "work", createdAt, entry: projectedWorkEntry(row) }); + entries.push({ + id: item.id, + kind: "work", + createdAt, + entry: projectedWorkEntry(row), + ...attemptMetadata, + }); } for (const message of input.optimisticMessages) { @@ -634,7 +704,12 @@ export function deriveRevertTurnCountByUserMessageId(input: { export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase { if (runtime === null) return "disconnected"; - if (runtime.status === "starting" || runtime.status === "queued") return "connecting"; + if ( + runtime.status === "preparing" || + runtime.status === "starting" || + runtime.status === "queued" + ) + return "connecting"; if (runtime.status === "running" || runtime.status === "waiting") return "running"; return "ready"; } diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 2fb9d5b601..fda9980ac5 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -450,7 +450,11 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( const projection = yield* getProjection(input.threadId); const activeRun = projection.runs.findLast( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", ); const requestedMode = input.dispatchMode ?? "auto"; const activeProviderThread = @@ -504,7 +508,11 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea input.runId ?? (input.turnId as RunId | undefined) ?? projection.runs.findLast( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", )?.id; if (runId === undefined) return { sequence: 0 }; return yield* dispatch({ diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index f37ab18f75..da0a66fb6b 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -68,7 +68,11 @@ export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | und export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean { return ( - status === "queued" || status === "starting" || status === "running" || status === "waiting" + status === "preparing" || + status === "queued" || + status === "starting" || + status === "running" || + status === "waiting" ); } @@ -347,6 +351,12 @@ function summarizeWorkItem(item: OrchestrationV2TurnItem): { return { label: title ?? "Interrupt requested", detail: item.message, toolData: item }; case "run_interrupt_result": return { label: title ?? "Run interrupted", detail: item.message, toolData: item }; + case "error": + return { + label: title ?? "Provider error", + detail: item.failure.message, + toolData: item, + }; case "compaction": return { label: title ?? "Context compacted", @@ -659,7 +669,11 @@ export function presentThread( )?.id ?? null, activeRunId: projection.runs.findLast( - (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + (run) => + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting", )?.id ?? null, status: presentLatestRun(projection)?.status ?? "idle", pendingRuntimeRequest: diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 598e7e2325..d604dbbbd9 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -245,6 +245,42 @@ describe("orchestration V2 contracts", () => { expect(dynamicTool.id).toBe(TurnItemId.make("turn-item-dynamic-1")); }); + it("decodes bounded provider failures as expected error turn items", () => { + const errorItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem)({ + id: "turn-item-error-1", + type: "error", + threadId: "thread-1", + runId: "run-1", + nodeId: "node-root-1", + providerThreadId: "provider-thread-1", + providerTurnId: "provider-turn-1", + nativeItemRef: null, + parentItemId: null, + ordinal: 199, + status: "failed", + title: "Provider error", + failure: { + class: "validation_error", + message: "Invalid reasoning effort.", + code: "invalid_request", + retryable: false, + }, + startedAt: now, + completedAt: now, + updatedAt: now, + }); + + expect(errorItem.type).toBe("error"); + if (errorItem.type !== "error") throw new Error("expected error item"); + expect(errorItem.failure.message).toBe("Invalid reasoning effort."); + expect(() => + Schema.decodeUnknownSync(OrchestrationV2TurnItem)({ + ...errorItem, + failure: { ...errorItem.failure, message: "x".repeat(4_097) }, + }), + ).toThrow(); + }); + it("decodes provider-native subagent lifecycle records and timeline items", () => { const subagent = Schema.decodeUnknownSync(OrchestrationV2Subagent)({ id: "node-subagent-1", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 43293a2c10..3770915362 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -316,6 +316,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type; export const OrchestrationV2RunStatus = Schema.Literals([ + "preparing", "queued", "starting", "running", @@ -689,6 +690,37 @@ export const OrchestrationV2TurnItemStatus = Schema.Literals([ ]); export type OrchestrationV2TurnItemStatus = typeof OrchestrationV2TurnItemStatus.Type; +export const OrchestrationV2ProviderFailureClass = Schema.Literals([ + "provider_error", + "transport_error", + "permission_error", + "validation_error", + "unknown", +]); +export type OrchestrationV2ProviderFailureClass = typeof OrchestrationV2ProviderFailureClass.Type; + +const OrchestrationV2ProviderFailureMessage = TrimmedNonEmptyString.check( + Schema.isMaxLength(4_096), +); +const OrchestrationV2ProviderFailureCode = TrimmedNonEmptyString.check(Schema.isMaxLength(128)); + +/** + * Transport-safe failure information suitable for persistence and display. + * Producers must redact credentials before constructing this value. The + * schema bounds every provider-controlled string as a second line of defense. + */ +export const OrchestrationV2ProviderFailure = Schema.Struct({ + class: OrchestrationV2ProviderFailureClass, + message: OrchestrationV2ProviderFailureMessage, + code: Schema.NullOr(OrchestrationV2ProviderFailureCode), + retryable: Schema.NullOr(Schema.Boolean), +}); +export type OrchestrationV2ProviderFailure = typeof OrchestrationV2ProviderFailure.Type; + +export const OrchestrationV2ProviderThreadDisposition = Schema.Literals(["reusable", "broken"]); +export type OrchestrationV2ProviderThreadDisposition = + typeof OrchestrationV2ProviderThreadDisposition.Type; + export const OrchestrationV2UserMessageInputIntent = Schema.Literals([ "turn_start", "queued_turn", @@ -826,6 +858,11 @@ export const OrchestrationV2TurnItem = Schema.Union([ type: Schema.Literal("run_interrupt_result"), message: Schema.String, }), + Schema.Struct({ + ...OrchestrationV2TurnItemBaseFields, + type: Schema.Literal("error"), + failure: OrchestrationV2ProviderFailure, + }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("compaction"), @@ -1406,6 +1443,11 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ type: Schema.Literal("run_interrupt_result"), message: Schema.String, }), + Schema.Struct({ + ...OrchestrationV2TurnItemJsonBaseFields, + type: Schema.Literal("error"), + failure: OrchestrationV2ProviderFailure, + }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("compaction"), @@ -1683,12 +1725,33 @@ export const OrchestrationV2Command = Schema.Union([ modelSelection: Schema.optional(ModelSelection), sourcePlanRef: Schema.optional(Schema.Struct({ threadId: ThreadId, planId: PlanId })), dispatchMode: Schema.Union([ + Schema.Struct({ type: Schema.Literal("defer_start") }), Schema.Struct({ type: Schema.Literal("steer_active"), targetRunId: RunId }), Schema.Struct({ type: Schema.Literal("restart_active"), targetRunId: RunId }), Schema.Struct({ type: Schema.Literal("queue_after_active") }), Schema.Struct({ type: Schema.Literal("start_immediately") }), ]), }), + Schema.Struct({ + type: Schema.Literal("prepared-run.release"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + }), + Schema.Struct({ + type: Schema.Literal("prepared-run.progress"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + phase: Schema.Literals(["worktree", "setup"]), + }), + Schema.Struct({ + type: Schema.Literal("prepared-run.fail"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + failure: OrchestrationV2ProviderFailure, + }), Schema.Struct({ type: Schema.Literal("run.interrupt"), commandId: CommandId, diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 5ec92d5903..4ecd357df8 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -128,6 +128,7 @@ export type OrchestratorMcpCreateThreadsInput = typeof OrchestratorMcpCreateThre export const OrchestratorMcpCreatedThreadStatus = Schema.Union([ Schema.Literal("idle"), + Schema.Literal("preparing"), Schema.Literal("starting"), OrchestratorMcpDelegatedTaskStatus, Schema.Literal("rolled_back"), diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts index eb9655d364..fcf35ac5ae 100644 --- a/packages/shared/src/agentAwareness.ts +++ b/packages/shared/src/agentAwareness.ts @@ -125,6 +125,7 @@ function resolveThreadAwarenessPhaseV2( return "waiting_for_approval"; } switch (thread.status) { + case "preparing": case "starting": return "starting"; case "running": diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts index b67c457447..5108204faf 100644 --- a/packages/shared/src/model.test.ts +++ b/packages/shared/src/model.test.ts @@ -10,7 +10,8 @@ import { getProviderOptionDescriptors, getProviderOptionBooleanSelectionValue, getProviderOptionStringSelectionValue, - normalizeCustomModelSlug, + isClaudeUltrathinkPrompt, + modelSelectionsEqual, normalizeModelSlug, } from "./model.ts"; @@ -145,6 +146,29 @@ describe("descriptor helpers", () => { expect(getModelSelectionStringOptionValue(selection, "reasoningEffort")).toBe("high"); expect(getModelSelectionBooleanOptionValue(selection, "fastMode")).toBe(true); }); + + it("compares complete model selections independent of option ordering", () => { + const left = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "reasoningEffort", value: "high" }, + { id: "fastMode", value: true }, + ]); + const reordered = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "fastMode", value: true }, + { id: "reasoningEffort", value: "high" }, + ]); + + expect(modelSelectionsEqual(left, reordered)).toBe(true); + expect( + modelSelectionsEqual(left, { + ...reordered, + options: [ + { id: "fastMode", value: true }, + { id: "reasoningEffort", value: "medium" }, + ], + }), + ).toBe(false); + expect(modelSelectionsEqual(left, { ...reordered, model: "gpt-5.5" })).toBe(false); + }); }); describe("model slug normalization", () => { diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index d8d384a43e..7a2c7973c4 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -77,6 +77,35 @@ export function getModelSelectionBooleanOptionValue( return getProviderOptionBooleanSelectionValue(modelSelection?.options, id); } +function canonicalModelSelectionOptions( + modelSelection: ModelSelection, +): ReadonlyArray { + return (modelSelection.options ?? []) + .map((selection) => [selection.id, selection.value] as const) + .toSorted(([leftId, leftValue], [rightId, rightValue]) => { + const idOrder = leftId.localeCompare(rightId); + return idOrder !== 0 ? idOrder : String(leftValue).localeCompare(String(rightValue)); + }); +} + +/** + * Compares the complete provider selection while treating option ordering and + * an omitted empty option list as presentation details. + */ +export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection): boolean { + if (left.instanceId !== right.instanceId || left.model !== right.model) { + return false; + } + const leftOptions = canonicalModelSelectionOptions(left); + const rightOptions = canonicalModelSelectionOptions(right); + return ( + leftOptions.length === rightOptions.length && + leftOptions.every( + ([id, value], index) => id === rightOptions[index]?.[0] && value === rightOptions[index]?.[1], + ) + ); +} + function resolveDescriptorChoiceValue( descriptor: Extract, raw: string | null | undefined,