diff --git a/.plans/21-orchestration-v2-application-integration.md b/.plans/21-orchestration-v2-application-integration.md index b5005f69bc..152fb66f2b 100644 --- a/.plans/21-orchestration-v2-application-integration.md +++ b/.plans/21-orchestration-v2-application-integration.md @@ -486,16 +486,18 @@ Create `ProviderRuntimeRecoveryService` and run it before command readiness. It must: -- reconcile provider sessions left active by a crash -- expire or cancel orphaned runtime requests -- reclaim pending or running outbox effects -- resume provider threads where supported -- retry recoverable attempts within policy -- terminalize unrecoverable runs -- release idle sessions +- expose one idempotent durable reconciliation path used as a best-effort shutdown finalizer and as the authoritative startup repair +- stop the effect worker and close/revoke live provider sessions before shutdown reconciliation +- mark every persisted nonterminal provider session stopped without eagerly reopening provider processes on startup +- cancel the complete provider-bound active run subtree, close streaming messages/items, return active provider threads to idle, and expire or cancel orphaned runtime requests +- preserve a `waiting` run only when its pending/running replay-safe checkpoint-capture effect can still complete it; cancel a waiting run with no such durable effect as stale +- cancel pending or running process-bound effects whose outcome cannot be replayed safely: provider turn start, interrupt, steer, restart, and runtime-request response +- immediately requeue only explicitly replay-safe effects such as deterministic checkpoint capture, cleanup, detach, and checkpoint-targeted rollback +- commit each thread's durable state repair and process-bound effect cancellation in one transaction +- suppress normal terminal-event queue advancement while reconciliation is committing, then resume genuinely queued runs after startup recovery - prevent one logical effect from executing concurrently twice -Recovery decisions must be driven by capabilities and runtime policy, not provider-name checks. +Provider processes remain lazy. A later user turn, a genuinely queued turn, or an explicitly replay-safe effect may reopen a session and resume the provider-native thread then; the mere presence of persisted session or thread metadata must not spawn a process. Replay classification is effect-semantic and provider-neutral, not a provider-name check. ### 7. Portable provider fallback @@ -528,6 +530,10 @@ Direct service-level integration tests must cover: - archive, unarchive, and delete cleanup - checkpoint capture, diff, and rollback - process restart during each durable external effect +- graceful shutdown during an active effect +- idempotent startup reconciliation after a partial or missing shutdown finalizer +- no provider process spawn for idle persisted sessions +- queued turns do not start during shutdown and resume only after startup reconciliation - provider-native resume - failed native resume followed by portable fallback @@ -537,6 +543,9 @@ Direct service-level integration tests must cover: - Provider session transition decisions preserve current production model, mode, workspace, and instance-routing semantics. - External side effects are durable and idempotent. - Restart recovery leaves no permanently active run or request. +- Unknown-outcome provider effects are retired rather than blindly replayed, while explicitly replay-safe effects are reclaimed. +- Clean shutdown performs best-effort reconciliation, and startup remains correct after `SIGKILL`, a crash, or a failed finalizer. +- Idle persisted sessions do not spawn provider processes during recovery. - Portable fallback can continue a thread after native resume failure. - No WebSocket or production client cutover has occurred yet. - `vp check`, `vp run typecheck`, and `vp test` pass. @@ -871,7 +880,19 @@ Add web and mobile integration coverage for: ## Shape 4.5: V2-Native Frontend Enrichment -Implementation status: in progress. Sections 1 and 2 are implemented for web; mobile cutover and the deeper supporting-state, graph, workflow, and parity-removal sections remain. +Implementation status: in progress. The web-first pass through Sections 1, 2, 4, and 5 is implemented. Mobile remains on the Shape 4.0 presentation path; shared selector extraction and parity-facade removal are intentionally deferred until the mobile port demonstrates what is actually shared. + +Web-first implementation outcome: + +- Production web continues to render the server-authoritative `visibleTurnItems` sequence and now joins individual rows to narrowly selected V2 run, attempt, node, provider, request, checkpoint, subagent, handoff, and transfer state. +- Expandable production inspectors expose command input/output and exit state, file changes and diff navigation, search provenance, dynamic/provider-native structured payloads, checkpoint rollback, subagent/fork navigation, provider identity, attempts, and context handoff state. +- An environment-scoped, cycle-safe relationship graph combines shell lineage with projection subagent and context-transfer edges while retaining missing-node fallback. The web header exposes related-thread navigation plus capability-gated fork, merge-back, and provider-session detach actions. +- Production web exposes queued-run reordering and promotion-to-steer directly from V2 run state. Cross-provider model selection dispatches `provider.switch`; same-provider model changes retain `thread.model-selection.set`. +- Production message rows retain their original projected-item reference. User messages visibly distinguish queued, steer, and queued-then-promoted intent; completed assistant responses expose exact-run forking, including inherited source-thread provenance. +- While a run is active, an empty composer keeps the Stop action. Entering content replaces it with Send, whose current default is explicit steering; `Mod+Enter` explicitly queues. The default action is isolated behind a small policy seam for a future user setting, without adding an action menu now. +- Interrupt request/result, compaction, handoff, fork, and subagent lifecycle items use polished production-native dividers or compact rows. Todo updates remain ordinary work-log items because the Tasks right-panel surface owns rich task progress. +- Shutdown now blocks new mutations, stops the effect worker, closes provider sessions and MCP capabilities, and best-effort reconciles durable state. Startup repeats that repair authoritatively, atomically cancels the complete provider-bound in-flight execution subtree plus its non-replayable effects, allows a waiting run to finish only through its durable replay-safe checkpoint capture, leaves idle provider processes closed, and resumes genuinely queued turns after repair. A development-server restart therefore leaves the interrupted thread terminal and sendable instead of failing projection startup. +- No mobile binding or shared presentation abstraction was introduced during this pass. The existing projection reducer and command semantics remain the shared substrate. ### Goal diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index cdc763f854..7666b72109 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -91,6 +91,11 @@ export const layer: Layer.Layer< } const capturedAt = yield* DateTime.now; + const baselineCheckpoint = projection.checkpoints.some( + (candidate) => candidate.scopeId === scope.id && candidate.ordinalWithinScope === 0, + ) + ? null + : yield* checkpoints.materializeBaselineCheckpoint({ scope }); const checkpoint = yield* checkpoints.capture({ scope, runId: run.id, @@ -107,6 +112,20 @@ export const layer: Layer.Layer< acceptedAt: capturedAt, effects: [], events: [ + ...(baselineCheckpoint === null + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint.captured" as const, + threadId: input.threadId, + nodeId: baselineCheckpoint.nodeId, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: baselineCheckpoint, + }, + ]), { id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), type: "checkpoint.captured", diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 370efeea42..e11caa2143 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -131,6 +131,9 @@ export interface CheckpointServiceV2Shape { readonly scope: OrchestrationV2CheckpointScope; readonly ordinalWithinScope: number; }) => Effect.Effect; + readonly materializeBaselineCheckpoint: (input: { + readonly scope: OrchestrationV2CheckpointScope; + }) => Effect.Effect; readonly capture: (input: { readonly scope: OrchestrationV2CheckpointScope; readonly runId: RunId | null; @@ -310,6 +313,51 @@ export const layer: Layer.Layer< ), ); + const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] = + (input) => + withWorkspaceLock( + input.scope.cwd, + Effect.gen(function* () { + const ordinalWithinScope = 0; + const checkpointRef = checkpointRefForScopeOrdinal({ + scopeId: input.scope.id, + ordinalWithinScope, + }); + const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, { + scopeId: input.scope.id, + ordinalWithinScope, + }); + const checkpointable = yield* isGitCheckpointable(input.scope.cwd); + const available = checkpointable + ? yield* checkpointStore.hasCheckpointRef({ + cwd: input.scope.cwd, + checkpointRef, + }) + : false; + return makeCheckpoint({ + id: checkpointId, + scope: input.scope, + runId: null, + nodeId: input.scope.nodeId, + parentCheckpointId: null, + ordinalWithinScope, + appRunOrdinal: null, + ref: checkpointRef, + status: available ? "ready" : "missing", + files: [], + capturedAt: input.scope.createdAt, + }); + }), + ).pipe( + Effect.mapError( + (cause) => + new CheckpointCaptureError({ + scopeId: input.scope.id, + cause, + }), + ), + ); + const capture: CheckpointServiceV2Shape["capture"] = (input) => withWorkspaceLock( input.scope.cwd, @@ -319,7 +367,7 @@ export const layer: Layer.Layer< ordinalWithinScope: input.ordinalWithinScope, }); const parentCheckpointId = - input.ordinalWithinScope > 1 + input.ordinalWithinScope > 0 ? yield* checkpointIdForScopeOrdinal(idAllocator, { scopeId: input.scope.id, ordinalWithinScope: input.ordinalWithinScope - 1, @@ -507,6 +555,7 @@ export const layer: Layer.Layer< ), ensureScope, captureBaseline, + materializeBaselineCheckpoint, capture, restore, deleteStaleRefs, diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index af4f3b5bcc..cba016a53e 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -81,11 +81,28 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ ]); export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; +export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ + "provider-session.detach", + "provider-thread.rollback", + "checkpoint.capture", + "terminal.cleanup", + "attachment.cleanup", +] as const satisfies ReadonlyArray; + +export const PROCESS_BOUND_EFFECT_TYPES = [ + "provider-turn.start", + "provider-turn.interrupt", + "provider-turn.steer", + "provider-turn.restart", + "runtime-request.respond", +] as const satisfies ReadonlyArray; + export const OrchestrationEffectStatusV2 = Schema.Literals([ "pending", "running", "succeeded", "failed", + "cancelled", ]); export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type; @@ -138,7 +155,15 @@ export interface EffectOutboxV2Shape { readonly listByCommandId: ( commandId: CommandId, ) => Effect.Effect, EffectOutboxError>; - readonly reclaimRunning: Effect.Effect; + readonly cancelUnsettled: (input: { + readonly threadId: ThreadId; + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }) => Effect.Effect; + readonly reconcileAfterProcessLoss: Effect.Effect< + { readonly requeued: number; readonly cancelled: number }, + EffectOutboxError + >; readonly claimNext: (input: { readonly workerId: string; readonly leaseDurationMs: number; @@ -289,22 +314,65 @@ export const layer: Layer.Layer = La : new EffectOutboxError({ operation: "list", cause }), ), ), - reclaimRunning: Effect.gen(function* () { + cancelUnsettled: ({ threadId, effectTypes, reason }) => + Effect.gen(function* () { + if (effectTypes.length === 0) return 0; + const now = DateTime.formatIso(yield* DateTime.now); + const rows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'cancelled', + lease_owner = NULL, + lease_expires_at = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = ${reason} + WHERE thread_id = ${threadId} + AND status IN ('pending', 'running') + AND effect_type IN ${sql.in(effectTypes)} + RETURNING effect_id + `; + return rows.length; + }).pipe( + Effect.mapError( + (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }), + ), + ), + reconcileAfterProcessLoss: Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); - const rows = yield* sql<{ readonly effect_id: string }>` + const cancelledRows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'cancelled', + lease_owner = NULL, + lease_expires_at = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = 'Cancelled because the server process ended before the effect completed.' + WHERE status IN ('pending', 'running') + AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)} + RETURNING effect_id + `; + const requeuedRows = yield* sql<{ readonly effect_id: string }>` UPDATE orchestration_v2_effect_outbox SET status = 'pending', lease_owner = NULL, lease_expires_at = NULL, available_at = ${now}, - updated_at = ${now} + updated_at = ${now}, + last_error = 'Requeued after the previous server process ended.' WHERE status = 'running' + AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)} RETURNING effect_id `; - if (rows.length > 0) yield* Queue.offer(available, undefined); - return rows.length; - }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "reclaim", cause }))), + if (requeuedRows.length > 0) yield* Queue.offer(available, undefined); + return { requeued: requeuedRows.length, cancelled: cancelledRows.length }; + }).pipe( + Effect.mapError( + (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }), + ), + ), claimNext: ({ workerId, leaseDurationMs }) => Effect.gen(function* () { const now = yield* DateTime.now; diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 257b694db0..dd8ce3885a 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -21,6 +21,7 @@ import { } from "./CommandReceiptStore.ts"; import { EffectOutboxV2, + type OrchestrationEffectRequestV2, type PendingOrchestrationEffectV2, layer as effectOutboxLayer, } from "./EffectOutbox.ts"; @@ -88,11 +89,16 @@ export interface EventSinkV2Shape { readonly acceptedAt: DateTime.Utc; readonly events: ReadonlyArray; readonly effects: ReadonlyArray; + readonly cancelUnsettledEffects?: { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }; }) => Effect.Effect< { readonly receipt: CommandReceiptV2; readonly storedEvents: ReadonlyArray; readonly committed: boolean; + readonly cancelledEffectCount: number; }, EventSinkV2Error >; @@ -255,7 +261,7 @@ const baseLayer: Layer.Layer< }); if (!reserved) { const existing = yield* existingCommandResult(input.commandId); - return { ...existing, committed: false as const }; + return { ...existing, committed: false as const, cancelledEffectCount: 0 }; } const normalized = yield* normalizeEvents(input.events); @@ -281,7 +287,14 @@ const baseLayer: Layer.Layer< error: null, }; yield* commandReceipts.upsert(receipt); - return { receipt, storedEvents, committed: true as const }; + const cancelledEffectCount = + input.cancelUnsettledEffects === undefined + ? 0 + : yield* effectOutbox.cancelUnsettled({ + threadId: input.threadId, + ...input.cancelUnsettledEffects, + }); + return { receipt, storedEvents, committed: true as const, cancelledEffectCount }; }), ); if (input.effects.length > 0) { diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index c4ad8ed986..c2a8ca4151 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -13,6 +13,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + ProviderSessionId, ProviderThreadId, RunId, ThreadId, @@ -28,6 +29,7 @@ import * as Stream from "effect/Stream"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts"; import { @@ -37,11 +39,13 @@ import { } from "./EffectWorker.ts"; import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts"; import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts"; +import { layer as idAllocatorLayer } from "./IdAllocator.ts"; import { ProjectionMaintenanceV2, layer as projectionMaintenanceLayer, } from "./ProjectionMaintenance.ts"; import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts"; +import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; const databaseLayer = SqlitePersistenceMemory; const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer)); @@ -58,6 +62,7 @@ const TestLayer = Layer.mergeAll( eventSinkProvided, effectOutboxProvided, commandReceiptStoreProvided, + idAllocatorLayer, projectionMaintenanceProvided, ); @@ -184,6 +189,71 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); + it.effect("replays shared provider-session payloads across every bound thread", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const projectionStore = yield* ProjectionStoreV2; + const maintenance = yield* ProjectionMaintenanceV2; + const now = yield* DateTime.now; + const firstThreadId = ThreadId.make("thread:foundation-shared-session:first"); + const secondThreadId = ThreadId.make("thread:foundation-shared-session:second"); + const providerSessionId = ProviderSessionId.make("provider-session:foundation:shared"); + const firstSession = { + id: providerSessionId, + driver: providerDriver, + providerInstanceId, + status: "ready" as const, + cwd: "/workspace/first", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }; + const secondSession = { ...firstSession, cwd: "/workspace/second" }; + + yield* eventSink.write({ + events: [ + threadCreatedEvent({ + id: "event:foundation-shared-session:first-thread", + thread: makeThread(firstThreadId, now), + now, + }), + { + id: EventId.make("event:foundation-shared-session:first-attachment"), + type: "provider-session.attached", + threadId: firstThreadId, + driver: providerDriver, + providerInstanceId, + occurredAt: now, + payload: firstSession, + }, + threadCreatedEvent({ + id: "event:foundation-shared-session:second-thread", + thread: makeThread(secondThreadId, now), + now, + }), + { + id: EventId.make("event:foundation-shared-session:second-attachment"), + type: "provider-session.attached", + threadId: secondThreadId, + driver: providerDriver, + providerInstanceId, + occurredAt: now, + payload: secondSession, + }, + ], + }); + + assert.equal( + (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions[0]?.cwd, + secondSession.cwd, + ); + assert.isTrue((yield* maintenance.verify).valid); + assert.isTrue((yield* maintenance.rebuild).valid); + }), + ); + it.effect( "rolls back events, projections, receipts, and effects after a projection failure", () => @@ -368,33 +438,140 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { }), ); - it.effect("reclaims running effects immediately during startup recovery", () => - Effect.gen(function* () { - const outbox = yield* EffectOutboxV2; - const commandId = CommandId.make("command:foundation-reclaim-running"); - yield* outbox.enqueue([ - { - id: "effect:foundation-reclaim-running", - commandId, - threadId: ThreadId.make("thread:foundation-reclaim-running"), - request: { - type: "provider-turn.start", - runId: RunId.make("run:foundation-reclaim-running"), + it.effect( + "retires live provider effects and requeues replay-safe effects after process loss", + () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const commandId = CommandId.make("command:foundation-reclaim-running"); + yield* outbox.enqueue([ + { + id: "effect:a-foundation-cancel-provider-turn", + commandId, + threadId: ThreadId.make("thread:foundation-reclaim-running"), + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-reclaim-running"), + }, }, - }, - ]); + { + id: "effect:b-foundation-requeue-cleanup", + commandId, + threadId: ThreadId.make("thread:foundation-reclaim-running"), + request: { type: "terminal.cleanup" }, + }, + ]); + assert.isTrue( + Option.isSome( + yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }), + ), + ); + assert.isTrue( + Option.isSome( + yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }), + ), + ); + assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, { + cancelled: 1, + requeued: 1, + }); + const cancelled = yield* outbox.get("effect:a-foundation-cancel-provider-turn"); + assert.isTrue(Option.isSome(cancelled)); + if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled"); + + const reclaimed = yield* outbox.claimNext({ + workerId: "recovery-worker", + leaseDurationMs: 30_000, + }); + assert.isTrue(Option.isSome(reclaimed)); + if (Option.isSome(reclaimed)) { + assert.equal(reclaimed.value.request.type, "terminal.cleanup"); + assert.equal(reclaimed.value.attemptCount, 2); + } + }), + ); + + it.effect("atomically cancels stale runs and their process-bound effects", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const outbox = yield* EffectOutboxV2; + const projectionStore = yield* ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:foundation-process-loss"); + const runId = RunId.make("run:foundation-process-loss"); + const commandId = CommandId.make("command:foundation-process-loss"); + const thread = makeThread(threadId, now); + yield* eventSink.commitCommand({ + commandId, + threadId, + commandType: "foundation.process-loss", + acceptedAt: now, + events: [ + threadCreatedEvent({ id: "event:foundation-process-loss:thread", thread, now }), + { + id: EventId.make("event:foundation-process-loss:run"), + type: "run.created", + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message:foundation-process-loss"), + rootNodeId: null, + activeAttemptId: null, + status: "starting", + queuePosition: null, + requestedAt: now, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }, + ], + effects: [ + { + id: "effect:foundation-process-loss", + commandId, + threadId, + request: { type: "provider-turn.start", runId }, + }, + ], + }); assert.isTrue( Option.isSome( yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }), ), ); - assert.equal(yield* outbox.reclaimRunning, 1); - const reclaimed = yield* outbox.claimNext({ - workerId: "recovery-worker", - leaseDurationMs: 30_000, - }); - assert.isTrue(Option.isSome(reclaimed)); - if (Option.isSome(reclaimed)) assert.equal(reclaimed.value.attemptCount, 2); + + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provideService( + OrchestrationEffectWorkerV2, + OrchestrationEffectWorkerV2.of({ + awaitWork: Effect.void, + runOnce: Effect.succeed(false), + drain: () => Effect.succeed(0), + }), + ), + ); + const first = yield* recovery.recover; + assert.equal(first.terminalizedRuns, 1); + assert.equal(first.retiredEffects, 1); + const projection = yield* projectionStore.getThreadProjection(threadId); + assert.equal(projection.runs[0]?.status, "cancelled"); + const effect = yield* outbox.get("effect:foundation-process-loss"); + assert.isTrue(Option.isSome(effect)); + if (Option.isSome(effect)) assert.equal(effect.value.status, "cancelled"); + + const second = yield* recovery.recover; + assert.equal(second.terminalizedRuns, 0); + assert.equal(second.retiredEffects, 0); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 545c3849a4..68355093a4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -131,6 +131,7 @@ export interface OrchestratorV2DispatchResult { } export interface OrchestratorV2Shape { + readonly resumeQueuedRuns: Effect.Effect; readonly dispatch: ( command: OrchestrationV2Command, ) => Effect.Effect; @@ -637,6 +638,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* effectWorker.drain(1); }); + const resumeQueuedRuns = Effect.gen(function* () { + const shell = yield* projectionStore.getShellSnapshot(); + let resumed = 0; + for (const thread of shell.threads) { + const resumedThread = yield* Effect.gen(function* () { + const projection = yield* projectionStore.getThreadProjection(thread.id); + if (projection.runs.some(isBlockingRun) || nextQueuedRun(projection) === undefined) { + return false; + } + yield* dispatchSemaphore.withPermit(startNextQueuedRun(thread.id)); + return true; + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to resume queued V2 run after recovery", { + threadId: thread.id, + cause, + }).pipe(Effect.as(false)), + ), + ); + if (resumedThread) { + resumed += 1; + } + } + return resumed; + }).pipe( + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: CommandId.make("command:system:resume-queued-runs"), + commandType: "message.dispatch", + cause, + }), + ), + ); + const dispatchThreadCreate = Effect.fn("orchestrationV2.dispatch.threadCreate")(function* ( command: Extract, events: Ref.Ref>, @@ -4340,6 +4376,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Stream.filter( (stored) => stored.event.type === "run.updated" && + !String(stored.commandId).startsWith("command:runtime-reconcile:") && (stored.event.payload.status === "completed" || stored.event.payload.status === "interrupted" || stored.event.payload.status === "failed" || @@ -4359,6 +4396,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); return OrchestratorV2.of({ + resumeQueuedRuns, dispatch: dispatchWithReceipt, getThreadProjection: (threadId) => projectionStore @@ -4432,6 +4470,13 @@ export const layer: Layer.Layer< export const layerUnavailable: Layer.Layer = Layer.succeed( OrchestratorV2, OrchestratorV2.of({ + resumeQueuedRuns: Effect.fail( + new OrchestratorDispatchError({ + commandId: CommandId.make("command:system:resume-queued-runs"), + commandType: "message.dispatch", + cause: "Orchestration V2 live runtime is not configured.", + }), + ), dispatch: (command) => Effect.fail( new OrchestratorDispatchError({ diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts index 5ea252d58e..023d8ffd26 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -13,8 +13,8 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import { EventStoreV2 } from "./EventStore.ts"; import { - applyToProjection, - emptyProjection, + applyToProjectionReplayState, + makeProjectionReplayState, ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, ProjectionStoreV2, } from "./ProjectionStore.ts"; @@ -121,19 +121,11 @@ export const layer: Layer.Layer< }); const expectedProjections = (events: ReadonlyArray) => { - const projections = new Map(); + const state = makeProjectionReplayState(); for (const stored of events) { - const event = stored.event; - if (event.type === "thread.created") { - projections.set(event.threadId, emptyProjection(event)); - continue; - } - const current = projections.get(event.threadId); - if (current !== undefined) { - projections.set(event.threadId, applyToProjection(current, event)); - } + applyToProjectionReplayState(state, stored.event); } - return projections; + return state.projections; }; const verify = Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 0d4fcdce2e..81ec3e6582 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -7,6 +7,7 @@ import type { OrchestrationV2ThreadShell, OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, + ProviderSessionId, } from "@t3tools/contracts"; import { OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema, @@ -283,6 +284,98 @@ export function applyToProjection( } } +/** + * Replay state for entities whose persisted projection is shared across thread bindings. + * + * Provider sessions are process-scoped: one session row can be bound to several app + * threads. Updating that row changes what every bound thread reads, even though the + * application event itself belongs to one thread stream. Keeping the binding index here + * makes in-memory replay match the normalized SQL projection without scanning every + * thread for every session event. + */ +export interface ProjectionReplayState { + readonly projections: Map; + readonly providerSessionThreadIds: Map>; +} + +export function makeProjectionReplayState(): ProjectionReplayState { + return { + projections: new Map(), + providerSessionThreadIds: new Map(), + }; +} + +export function applyToProjectionReplayState( + state: ProjectionReplayState, + event: OrchestrationV2DomainEvent, +): boolean { + if (event.type === "thread.created" && !state.projections.has(event.threadId)) { + state.projections.set(event.threadId, emptyProjection(event)); + return true; + } + + const current = state.projections.get(event.threadId); + if (current === undefined) { + return false; + } + + let next = applyToProjection(current, event); + if (event.type === "provider-session.updated") { + const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id); + if (boundThreadIds?.has(event.threadId) !== true) { + // The SQL projection updates the global session row but does not implicitly + // create a thread binding for an update event. + next = { ...next, providerSessions: current.providerSessions }; + } + } + state.projections.set(event.threadId, next); + + switch (event.type) { + case "provider-session.attached": { + const boundThreadIds = new Set(state.providerSessionThreadIds.get(event.payload.id) ?? []); + boundThreadIds.add(event.threadId); + state.providerSessionThreadIds.set(event.payload.id, boundThreadIds); + for (const threadId of boundThreadIds) { + if (threadId === event.threadId) continue; + const projection = state.projections.get(threadId); + if (projection === undefined) continue; + state.projections.set(threadId, { + ...projection, + providerSessions: upsertById(projection.providerSessions, event.payload), + }); + } + break; + } + case "provider-session.updated": { + const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id) ?? []; + for (const threadId of boundThreadIds) { + if (threadId === event.threadId) continue; + const projection = state.projections.get(threadId); + if (projection === undefined) continue; + state.projections.set(threadId, { + ...projection, + providerSessions: upsertById(projection.providerSessions, event.payload), + }); + } + break; + } + case "provider-session.detached": { + const boundThreadIds = new Set( + state.providerSessionThreadIds.get(event.payload.providerSessionId) ?? [], + ); + boundThreadIds.delete(event.threadId); + if (boundThreadIds.size === 0) { + state.providerSessionThreadIds.delete(event.payload.providerSessionId); + } else { + state.providerSessionThreadIds.set(event.payload.providerSessionId, boundThreadIds); + } + break; + } + } + + return true; +} + type PayloadRow = { readonly payload_json: string; }; @@ -2110,29 +2203,23 @@ export const layer: Layer.Layer = export const layerMemory: Layer.Layer = Layer.effect( ProjectionStoreV2, Effect.gen(function* () { - const projections = yield* Ref.make(new Map()); + const replayState = yield* Ref.make(makeProjectionReplayState()); const sequence = yield* Ref.make(0); const service: ProjectionStoreV2Shape = { apply: (event) => Effect.gen(function* () { - const result = yield* Ref.modify(projections, (existing) => { - const next = new Map(existing); - - if (event.type === "thread.created" && !next.has(event.threadId)) { - next.set(event.threadId, emptyProjection(event)); - return [undefined, next] as const; - } - - const projection = next.get(event.threadId); - if (!projection) { + const result = yield* Ref.modify(replayState, (existing) => { + const next: ProjectionReplayState = { + projections: new Map(existing.projections), + providerSessionThreadIds: new Map(existing.providerSessionThreadIds), + }; + if (!applyToProjectionReplayState(next, event)) { return [ new ProjectionStoreThreadNotFoundError({ threadId: event.threadId }), existing, ] as const; } - - next.set(event.threadId, applyToProjection(projection, event)); return [undefined, next] as const; }); @@ -2143,7 +2230,7 @@ export const layerMemory: Layer.Layer = Layer.effect( }), getShellSnapshot: () => Effect.gen(function* () { - const existing = yield* Ref.get(projections); + const existing = (yield* Ref.get(replayState)).projections; const shells = yield* Effect.forEach( [...existing.keys()].toSorted((left, right) => String(left).localeCompare(String(right)), @@ -2161,7 +2248,7 @@ export const layerMemory: Layer.Layer = Layer.effect( }), getThreadProjection: (threadId) => Effect.gen(function* () { - const existing = yield* Ref.get(projections); + const existing = (yield* Ref.get(replayState)).projections; const readProjection = ( targetThreadId: ThreadId, seenThreadIds: ReadonlySet, diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index c9014b421b..d1434e2ddd 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -1,8 +1,17 @@ import { assert, it, vi } from "@effect/vitest"; import { + MessageId, NodeId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, RuntimeRequestId, ThreadId, + TurnItemId, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -15,157 +24,6 @@ import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "./IdAllocator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; -import * as ProviderSessionManager from "./ProviderSessionManager.ts"; - -const { decideProviderRuntimeRecovery } = ProviderRuntimeRecovery; - -it("retries process and transport failures only within the idempotent retry budget", () => { - assert.deepEqual( - decideProviderRuntimeRecovery({ - kind: "process_exited", - attempt: 1, - maxAttempts: 3, - idempotent: true, - online: true, - }), - { type: "retry_now" }, - ); - assert.equal( - decideProviderRuntimeRecovery({ - kind: "transport_unavailable", - attempt: 3, - maxAttempts: 3, - idempotent: true, - online: true, - }).type, - "terminalize", - ); -}); - -it("waits for connectivity and requires retry-after for rate limits", () => { - assert.deepEqual( - decideProviderRuntimeRecovery({ - kind: "network_unavailable", - attempt: 0, - maxAttempts: 3, - idempotent: true, - online: false, - }), - { type: "wait_for_connectivity" }, - ); - assert.deepEqual( - decideProviderRuntimeRecovery({ - kind: "provider_rate_limited", - attempt: 0, - maxAttempts: 3, - idempotent: true, - retryAfterMs: 250, - online: true, - }), - { type: "retry_after", delayMs: 250 }, - ); -}); - -it("terminalizes non-recoverable provider failures", () => { - for (const kind of [ - "provider_quota_exceeded", - "auth_invalid", - "permission_denied", - "invalid_request", - "unsupported_model", - ] as const) { - assert.equal( - decideProviderRuntimeRecovery({ - kind, - attempt: 0, - maxAttempts: 3, - idempotent: true, - online: true, - }).type, - "terminalize", - ); - } -}); - -it("classifies wrapped provider failures without provider-name checks", () => { - assert.deepEqual( - ProviderRuntimeRecovery.classifyProviderRuntimeFailure({ - _tag: "ProviderSessionOpenError", - cause: { code: "rate_limit_exceeded", retryAfterMs: 125 }, - }), - { kind: "provider_rate_limited", retryAfterMs: 125 }, - ); - assert.deepEqual( - ProviderRuntimeRecovery.classifyProviderRuntimeFailure({ - cause: { status: 401, message: "authentication failed" }, - }), - { kind: "auth_invalid" }, - ); -}); - -it.effect("executes bounded transport retries and returns the resumed value", () => - Effect.gen(function* () { - const attempts = yield* Ref.make(0); - const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({ - operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe( - Effect.flatMap((count) => - count < 2 ? Effect.fail("transport down") : Effect.succeed("resumed"), - ), - ), - classify: () => ({ kind: "transport_unavailable" }), - connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void }, - maxAttempts: 3, - idempotent: true, - }); - assert.equal(value, "resumed"); - assert.equal(yield* Ref.get(attempts), 3); - }), -); - -it.effect("waits for connectivity before retrying a network failure", () => - Effect.gen(function* () { - const attempts = yield* Ref.make(0); - const online = yield* Ref.make(false); - const waits = yield* Ref.make(0); - const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({ - operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe( - Effect.flatMap((count) => - count === 0 ? Effect.fail("offline") : Effect.succeed("resumed"), - ), - ), - classify: () => ({ kind: "network_unavailable" }), - connectivity: { - isOnline: Ref.get(online), - awaitOnline: Ref.set(online, true).pipe( - Effect.andThen(Ref.update(waits, (count) => count + 1)), - ), - }, - maxAttempts: 3, - idempotent: true, - }); - assert.equal(value, "resumed"); - assert.equal(yield* Ref.get(waits), 1); - }), -); - -it.effect("does not retry unrecoverable failures", () => - Effect.gen(function* () { - const attempts = yield* Ref.make(0); - const result = yield* Effect.result( - ProviderRuntimeRecovery.recoverWithPolicy({ - operation: Ref.update(attempts, (count) => count + 1).pipe( - Effect.andThen(Effect.fail("invalid credentials")), - ), - classify: () => ({ kind: "auth_invalid" }), - connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void }, - maxAttempts: 3, - idempotent: true, - }), - ); - assert.equal(result._tag, "Failure"); - assert.equal(yield* Ref.get(attempts), 1); - }), -); it.effect("drains durable effects before reporting recovery complete", () => Effect.gen(function* () { @@ -182,7 +40,6 @@ it.effect("drains durable effects before reporting recovery complete", () => archivedThreads: [], }), }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), Layer.mock(EventSink.EventSinkV2)({}), IdAllocator.layer, Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ @@ -190,15 +47,24 @@ it.effect("drains durable effects before reporting recovery complete", () => Effect.map((count) => count < 2), ), }), - Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), + }), ), ), ); const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe( - Effect.flatMap((service) => service.recover), + Effect.flatMap((recovery) => recovery.recover), Effect.provide(layer), ); - assert.deepEqual(summary, { resumedSessions: 0, terminalizedRuns: 0, executedEffects: 2 }); + assert.deepEqual(summary, { + terminalizedRuns: 0, + stoppedSessions: 0, + closedRequests: 0, + retiredEffects: 0, + requeuedEffects: 0, + executedEffects: 2, + }); }), ); @@ -209,7 +75,7 @@ it.effect("expires orphaned runtime requests before command readiness", () => { const committed = vi.fn( (input: Parameters[0]) => { committedInput = input; - return Effect.succeed({ committed: true } as never); + return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never); }, ); const projection = { @@ -223,6 +89,7 @@ it.effect("expires orphaned runtime requests before command readiness", () => { }, ], providerSessions: [], + providerThreads: [], runs: [], nodes: [], } as unknown as OrchestrationV2ThreadProjection; @@ -239,11 +106,12 @@ it.effect("expires orphaned runtime requests before command readiness", () => { } as never), getThreadProjection: () => Effect.succeed(projection), }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }), IdAllocator.layer, Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }), - Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), + }), ), ), ); @@ -259,3 +127,311 @@ it.effect("expires orphaned runtime requests before command readiness", () => { } }).pipe(Effect.provide(layer)); }); + +it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => { + const threadId = ThreadId.make("thread_shutdown_requests"); + let committedInput: Parameters[0] | null = + null; + const projection = { + thread: { id: threadId }, + runtimeRequests: [ + { + id: RuntimeRequestId.make("request_shutdown"), + nodeId: NodeId.make("node_shutdown"), + status: "pending", + responseCapability: { type: "live" }, + }, + ], + providerSessions: [], + providerThreads: [], + runs: [], + nodes: [], + } 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: 1 } 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("shutdown"); + assert.equal(summary.closedRequests, 1); + assert.equal(summary.retiredEffects, 1); + const requestEvent = committedInput?.events[0]; + assert.equal(requestEvent?.type, "runtime-request.updated"); + if (requestEvent?.type === "runtime-request.updated") { + assert.equal(requestEvent.payload.status, "cancelled"); + assert.equal(requestEvent.payload.responseCapability.type, "not_resumable"); + if (requestEvent.payload.responseCapability.type === "not_resumable") { + assert.match(requestEvent.payload.responseCapability.reason, /shut down/); + } + } + }).pipe(Effect.provide(layer)); +}); + +it.effect("preserves a waiting run while its replay-safe checkpoint capture is unsettled", () => { + const threadId = ThreadId.make("thread_waiting_checkpoint"); + const runId = RunId.make("run_waiting_checkpoint"); + const committed = vi.fn(() => Effect.succeed({ committed: true } as never)); + const projection = { + thread: { id: threadId }, + runtimeRequests: [], + providerSessions: [], + providerThreads: [], + runs: [{ id: runId, status: "waiting" }], + } 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: committed }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + listByCommandId: () => + Effect.succeed([ + { + request: { type: "checkpoint.capture", runId }, + status: "running", + }, + ] as never), + cancelUnsettled: () => Effect.succeed(0), + reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }), + }), + ), + ), + ); + + return Effect.gen(function* () { + const summary = + yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup"); + assert.equal(summary.terminalizedRuns, 0); + assert.equal(summary.requeuedEffects, 1); + assert.equal(committed.mock.calls.length, 0); + }).pipe(Effect.provide(layer)); +}); + +it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => { + const threadId = ThreadId.make("thread_stale_waiting"); + const runId = RunId.make("run_stale_waiting"); + let committedInput: Parameters[0] | null = + null; + const projection = { + thread: { id: threadId }, + runtimeRequests: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runs: [ + { + id: runId, + status: "waiting", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + ], + attempts: [], + nodes: [], + 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)({ + listByCommandId: () => Effect.succeed([]), + 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 runEvent = committedInput?.events.find((event) => event.type === "run.updated"); + assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled"); + }).pipe(Effect.provide(layer)); +}); + +it.effect( + "cancels the complete in-flight subtree and stops its persisted session without reopening it", + () => { + const threadId = ThreadId.make("thread_recovery_cancel"); + const runId = RunId.make("run_recovery_cancel"); + const attemptId = RunAttemptId.make("attempt_recovery_cancel"); + const rootNodeId = NodeId.make("node_recovery_cancel"); + const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel"); + const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel"); + const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel"); + let committedInput: Parameters[0] | null = + null; + const projection = { + thread: { id: threadId }, + runtimeRequests: [], + providerSessions: [ + { + id: providerSessionId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + status: "ready", + }, + ], + providerThreads: [ + { + id: providerThreadId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + status: "active", + }, + ], + providerTurns: [ + { + id: providerTurnId, + runAttemptId: attemptId, + nodeId: rootNodeId, + status: "running", + }, + ], + runs: [ + { + id: runId, + status: "starting", + providerThreadId, + providerInstanceId: ProviderInstanceId.make("codex"), + }, + ], + attempts: [ + { + id: attemptId, + runId, + rootNodeId, + status: "running", + }, + ], + nodes: [{ id: rootNodeId, runId, status: "running" }], + subagents: [], + messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }], + turnItems: [ + { + id: TurnItemId.make("turn_item_recovery_cancel"), + runId, + nodeId: rootNodeId, + status: "running", + }, + ], + } 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: 2 } 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) + .recover; + assert.equal(summary.terminalizedRuns, 1); + assert.equal(summary.stoppedSessions, 1); + assert.equal(summary.retiredEffects, 2); + assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [ + "provider-turn.start", + "provider-turn.interrupt", + "provider-turn.steer", + "provider-turn.restart", + "runtime-request.respond", + ]); + const events = committedInput?.events ?? []; + assert.deepEqual( + events.map((event) => [ + event.type, + "status" in event.payload ? event.payload.status : null, + ]), + [ + ["run.updated", "cancelled"], + ["run-attempt.updated", "cancelled"], + ["node.updated", "cancelled"], + ["provider-turn.updated", "cancelled"], + ["message.updated", null], + ["turn-item.updated", "cancelled"], + ["provider-thread.updated", "idle"], + ["provider-session.updated", "stopped"], + ], + ); + const messageEvent = events.find((event) => event.type === "message.updated"); + assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming); + }).pipe(Effect.provide(layer)); + }, +); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 3915802f2c..576ea35ee5 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -6,7 +6,6 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -16,17 +15,11 @@ import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "./IdAllocator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; -import * as ProviderSessionManager from "./ProviderSessionManager.ts"; export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass()( "ProviderRuntimeRecoveryError", { - operation: Schema.Literals([ - "read-projections", - "resume-session", - "terminalize", - "drain-outbox", - ]), + operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]), threadId: Schema.optional(ThreadId), cause: Schema.Defect(), }, @@ -37,209 +30,33 @@ export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass= input.maxAttempts) { - return { type: "terminalize", reason: "Provider recovery retry budget was exhausted." }; - } - switch (input.kind) { - case "process_exited": - case "transport_unavailable": - return input.idempotent - ? { type: "retry_now" } - : { type: "terminalize", reason: "The interrupted operation is not idempotent." }; - case "network_unavailable": - return input.online ? { type: "retry_now" } : { type: "wait_for_connectivity" }; - case "provider_rate_limited": - return input.idempotent && input.retryAfterMs !== undefined - ? { type: "retry_after", delayMs: Math.max(0, input.retryAfterMs) } - : { - type: "terminalize", - reason: "Rate-limit recovery requires retry-after and an idempotent operation.", - }; - case "provider_quota_exceeded": - case "auth_invalid": - case "permission_denied": - case "invalid_request": - case "unsupported_model": - return { type: "terminalize", reason: `Provider failure ${input.kind} is not recoverable.` }; - } -} - -export interface ConnectivityServiceShape { - readonly isOnline: Effect.Effect; - readonly awaitOnline: Effect.Effect; -} - -export class ConnectivityService extends Context.Reference( - "t3/orchestration-v2/ConnectivityService", - { - defaultValue: () => ({ isOnline: Effect.succeed(true), awaitOnline: Effect.void }), - }, -) {} - -export interface ClassifiedProviderRuntimeFailure { - readonly kind: ProviderRuntimeFailureKind; - readonly retryAfterMs?: number; -} - -export function classifyProviderRuntimeFailure(cause: unknown): ClassifiedProviderRuntimeFailure { - const record = - cause !== null && typeof cause === "object" - ? (cause as Record) - : ({} as Record); - const serialized = (() => { - try { - return JSON.stringify(cause); - } catch { - return ""; - } - })(); - const description = [ - record._tag, - record.code, - record.status, - record.message, - record.detail, - serialized, - ] - .filter((value) => typeof value === "string" || typeof value === "number") - .join(" ") - .toLowerCase(); - const nestedCause = - record.cause !== null && typeof record.cause === "object" - ? (record.cause as Record) - : undefined; - const retryAfter = - record.retryAfterMs ?? - record.retry_after_ms ?? - nestedCause?.retryAfterMs ?? - nestedCause?.retry_after_ms; - const retryAfterMs = typeof retryAfter === "number" ? retryAfter : undefined; - if (description.includes("rate") && description.includes("limit")) { - return { - kind: "provider_rate_limited", - ...(retryAfterMs === undefined ? {} : { retryAfterMs }), - }; - } - if (description.includes("quota")) return { kind: "provider_quota_exceeded" }; - if (description.includes("auth") || description.includes("unauthorized")) { - return { kind: "auth_invalid" }; - } - if (description.includes("permission") || description.includes("forbidden")) { - return { kind: "permission_denied" }; - } - if (description.includes("unsupported") && description.includes("model")) { - return { kind: "unsupported_model" }; - } - if (description.includes("invalid") && description.includes("request")) { - return { kind: "invalid_request" }; - } - if ( - description.includes("network") || - description.includes("offline") || - description.includes("econnreset") || - description.includes("enotfound") - ) { - return { kind: "network_unavailable" }; - } - if (description.includes("exit") || description.includes("terminated")) { - return { kind: "process_exited" }; - } - return { kind: "transport_unavailable" }; -} - -export class ProviderRuntimeFailureClassifier extends Context.Reference<{ - readonly classify: (cause: unknown) => ClassifiedProviderRuntimeFailure; -}>("t3/orchestration-v2/ProviderRuntimeFailureClassifier", { - defaultValue: () => ({ classify: classifyProviderRuntimeFailure }), -}) {} - -export class ProviderRuntimeRecoveryPolicy extends Context.Reference<{ - readonly maxAttempts: number; -}>("t3/orchestration-v2/ProviderRuntimeRecoveryPolicy", { - defaultValue: () => ({ maxAttempts: 3 }), -}) {} - -export function recoverWithPolicy(input: { - readonly operation: Effect.Effect; - readonly classify: (cause: E) => ClassifiedProviderRuntimeFailure; - readonly connectivity: ConnectivityServiceShape; - readonly maxAttempts: number; - readonly idempotent: boolean; -}): Effect.Effect { - const attempt = (attemptNumber: number): Effect.Effect => - input.operation.pipe( - Effect.catch((cause) => - Effect.gen(function* () { - const classified = input.classify(cause); - const online = yield* input.connectivity.isOnline; - const decision = decideProviderRuntimeRecovery({ - kind: classified.kind, - attempt: attemptNumber, - maxAttempts: input.maxAttempts, - idempotent: input.idempotent, - online, - ...(classified.retryAfterMs === undefined - ? {} - : { retryAfterMs: classified.retryAfterMs }), - }); - switch (decision.type) { - case "retry_now": - return yield* attempt(attemptNumber + 1); - case "retry_after": - yield* Effect.sleep(Duration.millis(decision.delayMs)); - return yield* attempt(attemptNumber + 1); - case "wait_for_connectivity": - yield* input.connectivity.awaitOnline; - return yield* attempt(attemptNumber + 1); - case "terminalize": - return yield* Effect.fail(cause); - } - }), - ), - ); - return attempt(1); +export interface ProviderRuntimeReconciliationSummary { + readonly terminalizedRuns: number; + readonly stoppedSessions: number; + readonly closedRequests: number; + readonly retiredEffects: number; + readonly requeuedEffects: number; } export class ProviderRuntimeRecoveryService extends Context.Service< ProviderRuntimeRecoveryService, { + readonly reconcile: ( + trigger: "startup" | "shutdown", + ) => Effect.Effect; readonly recover: Effect.Effect; } >()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {} -function activeRuns(projection: OrchestrationV2ThreadProjection) { +function nonterminalRuns(projection: OrchestrationV2ThreadProjection) { return projection.runs.filter( (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", ); @@ -247,249 +64,317 @@ function activeRuns(projection: OrchestrationV2ThreadProjection) { export const make = Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; - const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const eventSink = yield* EventSink.EventSinkV2; const ids = yield* IdAllocator.IdAllocatorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const outbox = yield* EffectOutbox.EffectOutboxV2; - const connectivity = yield* ConnectivityService; - const classifier = yield* ProviderRuntimeFailureClassifier; - const recoveryPolicy = yield* ProviderRuntimeRecoveryPolicy; - - const terminalize = Effect.fn("ProviderRuntimeRecoveryService.terminalize")(function* ( - projection: OrchestrationV2ThreadProjection, - detail: string, - ) { - const now = yield* DateTime.now; - const runs = activeRuns(projection); - if (runs.length === 0) return 0; - const commandId = CommandId.make(`command:recovery:terminalize:${projection.thread.id}`); - const allocateEventId = () => - ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe( - Effect.mapError( - (cause) => - new ProviderRuntimeRecoveryError({ - operation: "terminalize", - threadId: projection.thread.id, - cause, - }), - ), - ); - const events: Array = []; - for (const run of runs) { - events.push({ - id: yield* allocateEventId(), - type: "run.updated", - threadId: projection.thread.id, - runId: run.id, - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...run, status: "failed", completedAt: now }, - }); - for (const node of projection.nodes.filter( - (candidate) => - candidate.runId === run.id && - (candidate.status === "pending" || - candidate.status === "running" || - candidate.status === "waiting"), - )) { - events.push({ - id: yield* allocateEventId(), - type: "node.updated", - threadId: projection.thread.id, - runId: run.id, - nodeId: node.id, - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...node, status: "failed", completedAt: now }, - }); - } - } - yield* eventSink - .commitCommand({ - commandId, - threadId: projection.thread.id, - commandType: "provider-runtime.recovery-terminalize", - acceptedAt: now, - events, - effects: [], - }) - .pipe( - Effect.mapError( - (cause) => - new ProviderRuntimeRecoveryError({ - operation: "terminalize", - threadId: projection.thread.id, - cause: { detail, cause }, - }), - ), - ); - return runs.length; - }); - - const expireOrphanedRequests = Effect.fn("ProviderRuntimeRecoveryService.expireOrphanedRequests")( - function* (projection: OrchestrationV2ThreadProjection) { - const requests = projection.runtimeRequests.filter((request) => request.status === "pending"); - if (requests.length === 0) return; + const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")( + function* (projection: OrchestrationV2ThreadProjection, trigger: "startup" | "shutdown") { const now = yield* DateTime.now; - const commandId = CommandId.make(`command:recovery:expire-requests:${projection.thread.id}`); + const runs = [] as Array; + for (const run of nonterminalRuns(projection)) { + if (run.status === "waiting") { + const checkpointEffects = yield* outbox + .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`)) + .pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "reconcile", + threadId: projection.thread.id, + cause, + }), + ), + ); + const hasReplayableCheckpoint = checkpointEffects.some( + (effect) => + effect.request.type === "checkpoint.capture" && + effect.request.runId === run.id && + (effect.status === "pending" || effect.status === "running"), + ); + if (hasReplayableCheckpoint) continue; + } + runs.push(run); + } + const requests = projection.runtimeRequests.filter((request) => request.status === "pending"); + const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`; + const commandId = CommandId.make( + `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`, + ); + const allocateEventId = () => + ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "reconcile", + threadId: projection.thread.id, + cause, + }), + ), + ); const events: Array = []; for (const request of requests) { events.push({ - id: yield* ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe( - Effect.mapError( - (cause) => - new ProviderRuntimeRecoveryError({ - operation: "terminalize", - threadId: projection.thread.id, - cause, - }), - ), - ), + id: yield* allocateEventId(), type: "runtime-request.updated", threadId: projection.thread.id, nodeId: request.nodeId, occurredAt: now, payload: { ...request, - status: "expired", + status: trigger === "startup" ? "expired" : "cancelled", responseCapability: { type: "not_resumable", - reason: "The server restarted before this runtime request was resolved.", + reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`, }, resolvedAt: now, }, }); } - yield* eventSink - .commitCommand({ - commandId, + for (const run of runs) { + events.push({ + id: yield* allocateEventId(), + type: "run.updated", threadId: projection.thread.id, - commandType: "provider-runtime.expire-orphaned-requests", - acceptedAt: now, - events, - effects: [], - }) + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now }, + }); + for (const attempt of projection.attempts.filter( + (candidate) => + candidate.runId === run.id && + (candidate.status === "pending" || candidate.status === "running"), + )) { + events.push({ + id: yield* allocateEventId(), + type: "run-attempt.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: attempt.rootNodeId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...attempt, status: "cancelled", completedAt: now }, + }); + } + for (const node of projection.nodes.filter( + (candidate) => + candidate.runId === run.id && + (candidate.status === "pending" || + candidate.status === "running" || + candidate.status === "waiting"), + )) { + events.push({ + id: yield* allocateEventId(), + type: "node.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: node.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...node, status: "cancelled", completedAt: now }, + }); + } + for (const subagent of projection.subagents.filter( + (candidate) => + candidate.runId === run.id && + (candidate.status === "pending" || + candidate.status === "running" || + candidate.status === "waiting"), + )) { + events.push({ + id: yield* allocateEventId(), + type: "subagent.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: subagent.id, + driver: subagent.driver, + providerInstanceId: subagent.providerInstanceId, + occurredAt: now, + payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now }, + }); + } + for (const providerTurn of projection.providerTurns.filter( + (candidate) => + candidate.runAttemptId !== null && + projection.attempts.some( + (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id, + ) && + (candidate.status === "pending" || candidate.status === "running"), + )) { + events.push({ + id: yield* allocateEventId(), + type: "provider-turn.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: providerTurn.nodeId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...providerTurn, status: "cancelled", completedAt: now }, + }); + } + for (const message of projection.messages.filter( + (candidate) => candidate.runId === run.id && candidate.streaming, + )) { + events.push({ + id: yield* allocateEventId(), + type: "message.updated", + threadId: projection.thread.id, + runId: run.id, + ...(message.nodeId === null ? {} : { nodeId: message.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...message, streaming: false, updatedAt: now }, + }); + } + for (const item of projection.turnItems.filter( + (candidate) => + candidate.runId === run.id && + (candidate.status === "pending" || + candidate.status === "running" || + candidate.status === "waiting"), + )) { + events.push({ + id: yield* allocateEventId(), + type: "turn-item.updated", + threadId: projection.thread.id, + runId: run.id, + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now }, + }); + } + } + for (const providerThread of projection.providerThreads.filter( + (candidate) => candidate.status === "active", + )) { + events.push({ + id: yield* allocateEventId(), + type: "provider-thread.updated", + threadId: projection.thread.id, + driver: providerThread.driver, + providerInstanceId: providerThread.providerInstanceId, + occurredAt: now, + payload: { ...providerThread, status: "idle", updatedAt: now }, + }); + } + for (const session of projection.providerSessions.filter( + (candidate) => candidate.status !== "stopped" && candidate.status !== "error", + )) { + events.push({ + id: yield* allocateEventId(), + type: "provider-session.updated", + threadId: projection.thread.id, + driver: session.driver, + providerInstanceId: session.providerInstanceId, + occurredAt: now, + payload: { ...session, status: "stopped", updatedAt: now, lastError: null }, + }); + } + const stoppedSessions = projection.providerSessions.filter( + (candidate) => candidate.status !== "stopped" && candidate.status !== "error", + ).length; + let retiredEffects: number; + if (events.length === 0) { + retiredEffects = yield* outbox + .cancelUnsettled({ + threadId: projection.thread.id, + effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES, + reason: detail, + }) + .pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "reconcile", + threadId: projection.thread.id, + cause: { detail, cause }, + }), + ), + ); + } else { + const result = yield* eventSink + .commitCommand({ + commandId, + threadId: projection.thread.id, + commandType: "provider-runtime.reconcile", + acceptedAt: now, + events, + effects: [], + cancelUnsettledEffects: { + effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES, + reason: detail, + }, + }) + .pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "reconcile", + threadId: projection.thread.id, + cause, + }), + ), + ); + retiredEffects = result.cancelledEffectCount; + } + return { + terminalizedRuns: runs.length, + stoppedSessions, + closedRequests: requests.length, + retiredEffects, + }; + }, + ); + + const reconcile = (trigger: "startup" | "shutdown") => + Effect.gen(function* () { + const shell = yield* projections + .getShellSnapshot() .pipe( + Effect.mapError( + (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }), + ), + ); + let terminalizedRuns = 0; + let stoppedSessions = 0; + let closedRequests = 0; + let retiredEffects = 0; + for (const thread of [...shell.threads, ...shell.archivedThreads]) { + const projection = yield* projections.getThreadProjection(thread.id).pipe( Effect.mapError( (cause) => new ProviderRuntimeRecoveryError({ - operation: "terminalize", - threadId: projection.thread.id, + operation: "read-projections", + threadId: thread.id, cause, }), ), ); - }, - ); - - const recoverProjection = Effect.fn("ProviderRuntimeRecoveryService.recoverProjection")( - function* (projection: OrchestrationV2ThreadProjection) { - yield* expireOrphanedRequests(projection); - let resumedSessions = 0; - for (const session of projection.providerSessions.filter( - (candidate) => candidate.status !== "stopped" && candidate.status !== "error", - )) { - const resume = sessions - .open({ - threadId: projection.thread.id, - providerSessionId: session.id, - modelSelection: projection.thread.modelSelection, - runtimePolicy: { - runtimeMode: projection.thread.runtimeMode, - interactionMode: projection.thread.interactionMode, - cwd: session.cwd, - }, - resumeFromSession: session, - }) - .pipe( - Effect.flatMap((runtime) => - Effect.forEach( - projection.providerThreads.filter( - (providerThread) => - providerThread.providerSessionId === session.id && - providerThread.appThreadId === projection.thread.id && - providerThread.status !== "closed" && - providerThread.status !== "archived", - ), - (providerThread) => - runtime.resumeThread({ - providerThread, - threadId: projection.thread.id, - modelSelection: projection.thread.modelSelection, - runtimePolicy: { - runtimeMode: projection.thread.runtimeMode, - interactionMode: projection.thread.interactionMode, - cwd: session.cwd, - }, - }), - { discard: true }, - ), - ), - ); - const recovered = yield* Effect.result( - recoverWithPolicy({ - operation: resume, - classify: classifier.classify, - connectivity, - maxAttempts: recoveryPolicy.maxAttempts, - idempotent: true, - }), - ); - if (recovered._tag === "Failure") { - const terminalizedRuns = yield* terminalize( - projection, - `Unable to resume provider session ${session.id}.`, - ); - return { resumedSessions, terminalizedRuns }; - } - resumedSessions += 1; + const result = yield* reconcileProjection(projection, trigger); + terminalizedRuns += result.terminalizedRuns; + stoppedSessions += result.stoppedSessions; + closedRequests += result.closedRequests; + retiredEffects += result.retiredEffects; } - if ( - resumedSessions === 0 && - projection.runs.some((run) => run.status === "running" || run.status === "waiting") - ) { - const terminalizedRuns = yield* terminalize( - projection, - "No resumable provider session remained for the active run.", - ); - return { resumedSessions, terminalizedRuns }; - } - return { resumedSessions, terminalizedRuns: 0 }; - }, - ); + const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe( + Effect.mapError( + (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }), + ), + ); + return { + terminalizedRuns, + stoppedSessions, + closedRequests, + retiredEffects: retiredEffects + outboxReconciliation.cancelled, + requeuedEffects: outboxReconciliation.requeued, + } satisfies ProviderRuntimeReconciliationSummary; + }); const recover = Effect.gen(function* () { - const shell = yield* projections - .getShellSnapshot() - .pipe( - Effect.mapError( - (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }), - ), - ); - let resumedSessions = 0; - let terminalizedRuns = 0; - for (const thread of shell.threads) { - const projection = yield* projections.getThreadProjection(thread.id).pipe( - Effect.mapError( - (cause) => - new ProviderRuntimeRecoveryError({ - operation: "read-projections", - threadId: thread.id, - cause, - }), - ), - ); - const result = yield* recoverProjection(projection); - resumedSessions += result.resumedSessions; - terminalizedRuns += result.terminalizedRuns; - } + const reconciliation = yield* reconcile("startup"); let executedEffects = 0; - yield* outbox.reclaimRunning.pipe( - Effect.mapError( - (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }), - ), - ); while ( yield* worker.runOnce.pipe( Effect.mapError( @@ -499,10 +384,10 @@ export const make = Effect.gen(function* () { ) { executedEffects += 1; } - return { resumedSessions, terminalizedRuns, executedEffects }; + return { ...reconciliation, executedEffects } satisfies ProviderRuntimeRecoverySummary; }); - return ProviderRuntimeRecoveryService.of({ recover }); + return ProviderRuntimeRecoveryService.of({ reconcile, recover }); }); export const layer = Layer.effect(ProviderRuntimeRecoveryService, make); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index a5588d6538..7e36efff7d 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -509,6 +509,48 @@ it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts }), ); +it.effect("ProviderSessionManagerV2 closes event subscriptions normally on server shutdown", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + 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-shutdown-subscription"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const bufferedSubscription = yield* runtime.subscribeEvents!; + const activeSubscription = yield* runtime.subscribeEvents!; + const adapterQueue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(adapterQueue); + yield* Queue.offer(adapterQueue!, { + type: "provider_session.updated", + driver: CODEX_DRIVER, + providerSession: runtime.providerSession, + }); + assert.isTrue(Option.isSome(yield* activeSubscription.events.pipe(Stream.runHead))); + + yield* manager.shutdown; + + assert.isEmpty(yield* bufferedSubscription.events.pipe(Stream.runCollect)); + }); + + yield* effect.pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000 }))); + }), +); + it.effect( "ProviderSessionManagerV2 issues MCP credentials before opening and revokes them on close", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 377762d889..ec24038e0b 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -53,17 +53,9 @@ export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.T * ProviderSessionManager owns live session residency: open sessions, idle release, * explicit shutdown, and release-on-runtime-failure. * - * It intentionally does not decide whether a provider failure should be retried. - * The next recovery layer should classify adapter failures into canonical runtime - * failure kinds before attempting recovery: - * - * - process_exited / transport_unavailable: bounded restart + native thread resume. - * - network_unavailable: wait for ConnectivityService to report online, then resume. - * - provider_rate_limited: retry only when retry-after/idempotency/retry budget allow it. - * - provider_quota_exceeded / auth_invalid / permission_denied / invalid_request: - * terminal until user or configuration changes. - * - * This keeps lifecycle cleanup separate from policy-driven recovery. + * It intentionally does not resurrect persisted sessions. Process-loss recovery + * terminalizes provider-bound work and retires non-replayable effects; a later + * user command or durable replay-safe operation opens a session lazily. */ export class ProviderSessionOpenError extends Schema.TaggedErrorClass()( "ProviderSessionOpenError", @@ -137,6 +129,7 @@ export const ProviderSessionManagerV2Error = Schema.Union([ export type ProviderSessionManagerV2Error = typeof ProviderSessionManagerV2Error.Type; export interface ProviderSessionManagerV2Shape { + readonly shutdown: Effect.Effect; readonly open: (input: { readonly threadId: ThreadId; readonly providerSessionId: ProviderSessionId; @@ -173,7 +166,9 @@ interface LiveSessionEntry { readonly supportsMultipleProviderThreads: boolean; readonly runtime: ProviderAdapterV2SessionRuntime; readonly exposedRuntime: ProviderAdapterV2SessionRuntime; - readonly eventSubscribers: Ref.Ref>>; + readonly eventSubscribers: Ref.Ref< + ReadonlyMap> + >; readonly scope: Scope.Closeable; readonly idleGeneration: number; readonly busyCount: number; @@ -276,7 +271,9 @@ export const layerWithOptions = ( ); const publishToSubscribers = ( - subscribers: Ref.Ref>>, + subscribers: Ref.Ref< + ReadonlyMap> + >, signal: ProviderSessionEventSignal, ) => Ref.get(subscribers).pipe( @@ -294,11 +291,26 @@ export const layerWithOptions = ( providerSessionId: entry.runtime.providerSessionId, cause: detail, }); - yield* publishToSubscribers(entry.eventSubscribers, { - type: "failure", - cause: Cause.fail(error), - }); - yield* Ref.set(entry.eventSubscribers, new Map()); + const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map()); + yield* Effect.forEach( + subscribers.values(), + (queue) => + Queue.offer(queue, { + type: "failure", + cause: Cause.fail(error), + }), + { discard: true }, + ); + }); + + const closeSubscribers = (entry: LiveSessionEntry) => + Effect.gen(function* () { + const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map()); + yield* Effect.forEach( + subscribers.values(), + (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue))), + { discard: true }, + ); }); const cancelIdleFiber = (fiber: Fiber.Fiber | null) => @@ -479,10 +491,14 @@ export const layerWithOptions = ( if (input.cancelIdleFiber !== false) { yield* cancelIdleFiber(entry.idleFiber); } - yield* failSubscribers( - entry, - input.detail ?? `Provider session released: ${input.reason}.`, - ); + if (input.reason === "server_shutdown") { + yield* closeSubscribers(entry); + } else { + yield* failSubscribers( + entry, + input.detail ?? `Provider session released: ${input.reason}.`, + ); + } const closeExit = yield* Effect.exit(Scope.close(entry.scope, Exit.void)); yield* writeReleasedSessionEvents({ entry, @@ -779,10 +795,12 @@ export const layerWithOptions = ( ); const makeEventSubscription = ( - subscribers: Ref.Ref>>, + subscribers: Ref.Ref< + ReadonlyMap> + >, ): Effect.Effect => Effect.gen(function* () { - const queue = yield* Queue.unbounded(); + const queue = yield* Queue.unbounded(); const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1); yield* Ref.update(subscribers, (current) => { const updated = new Map(current); @@ -796,7 +814,13 @@ export const layerWithOptions = ( const updated = new Map(current); updated.delete(subscriberId); return [true, updated] as const; - }).pipe(Effect.flatMap((removed) => (removed ? Queue.shutdown(queue) : Effect.void))); + }).pipe( + Effect.flatMap((removed) => + removed + ? Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue)), Effect.asVoid) + : Effect.void, + ), + ); const events = Stream.fromQueue(queue).pipe( Stream.mapEffect((signal) => signal.type === "event" @@ -810,7 +834,9 @@ export const layerWithOptions = ( const decorateRuntime = ( runtime: ProviderAdapterV2SessionRuntime, - eventSubscribers: Ref.Ref>>, + eventSubscribers: Ref.Ref< + ReadonlyMap> + >, ): ProviderAdapterV2SessionRuntime => { const providerSessionId = runtime.providerSessionId; const subscribeEvents = makeEventSubscription(eventSubscribers); @@ -1021,29 +1047,29 @@ export const layerWithOptions = ( Effect.forkIn(layerScope), ); - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - const activeSessions = [...(yield* Ref.get(sessions)).values()]; - yield* Effect.forEach( - activeSessions, - (entry) => - releaseEntry({ - providerSessionId: entry.runtime.providerSessionId, - reason: "server_shutdown", - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", { - providerSessionId: entry.runtime.providerSessionId, - cause, - }), - ), + const shutdown = Effect.gen(function* () { + const activeSessions = [...(yield* Ref.get(sessions)).values()]; + yield* Effect.forEach( + activeSessions, + (entry) => + releaseEntry({ + providerSessionId: entry.runtime.providerSessionId, + reason: "server_shutdown", + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", { + providerSessionId: entry.runtime.providerSessionId, + cause, + }), ), - { discard: true }, - ); - }), - ); + ), + { discard: true }, + ); + }); + yield* Effect.addFinalizer(() => shutdown); return ProviderSessionManagerV2.of({ + shutdown, open: (input) => openSemaphore.withPermit( Effect.gen(function* () { @@ -1109,7 +1135,7 @@ export const layerWithOptions = ( ), ); const eventSubscribers = yield* Ref.make< - ReadonlyMap> + ReadonlyMap> >(new Map()); const exposedRuntime = decorateRuntime(runtime, eventSubscribers); const now = yield* Clock.currentTimeMillis; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 0e66987b64..b395a6ac0e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -403,11 +403,13 @@ export const layer: Layer.Layer< ) + 1, shouldFinalizeRun: () => projectionStore.getThreadProjection(projection.thread.id).pipe( - Effect.map( - (current) => - current.runs.find((candidate) => candidate.id === run.id)?.activeAttemptId === - attempt.id, - ), + Effect.map((current) => { + const currentRun = current.runs.find((candidate) => candidate.id === run.id); + return ( + currentRun?.activeAttemptId === attempt.id && + (currentRun.status === "starting" || currentRun.status === "running") + ); + }), Effect.catchCause(() => Effect.succeed(false)), ), message: { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 0f56f6d0ab..689a7f20c3 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -178,7 +178,6 @@ const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe( eventSinkProvided, idAllocatorLayer, projectionStoreLayer, - providerSessionManagerProvided, ), ), ); @@ -229,6 +228,7 @@ export const OrchestrationV2LayerLive = Layer.mergeAll( orchestratorProvided, threadManagementProvided, effectWorkerProvided, + providerSessionManagerProvided, providerRuntimeRecoveryProvided, projectionMaintenanceProvided, ); 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 a0c1a4dd76..447c40a5f8 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -96,6 +96,16 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < assert.isDefined(projection); const latestRun = projection.runs.at(-1); assert.deepEqual(latestRun?.modelSelection, input.driver.modelSelection); + if (projection.runs.some((run) => run.status === "completed")) { + const threadStartCheckpoint = projection.checkpoints.find( + (checkpoint) => checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null, + ); + assert.isDefined( + threadStartCheckpoint, + "completed threads must retain an addressable thread-start checkpoint", + ); + assert.equal(threadStartCheckpoint.status, "ready"); + } return result; }); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 0a23560ce1..fd3bbf15a6 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -51,6 +51,7 @@ import Migration0035 from "./Migrations/035_OrchestrationV2Foundation.ts"; import Migration0036 from "./Migrations/036_OrchestrationV2ProviderSessionBindings.ts"; import Migration0037 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts"; import Migration0038 from "./Migrations/038_ApplicationEventSource.ts"; +import Migration0039 from "./Migrations/039_OrchestrationV2EffectCancellation.ts"; /** * Migration loader with all migrations defined inline. @@ -101,6 +102,7 @@ export const migrationEntries = [ [36, "OrchestrationV2ProviderSessionBindings", Migration0036], [37, "OrchestrationV2ThreadLaunchWorkflows", Migration0037], [38, "ApplicationEventSource", Migration0038], + [39, "OrchestrationV2EffectCancellation", Migration0039], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.test.ts b/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.test.ts new file mode 100644 index 0000000000..20c389ac55 --- /dev/null +++ b/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.test.ts @@ -0,0 +1,80 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +layer("039_OrchestrationV2EffectCancellation", (it) => { + it.effect("preserves existing effects and adds the cancelled terminal status", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 38 }); + yield* sql` + INSERT INTO orchestration_v2_effect_outbox ( + effect_id, + command_id, + thread_id, + effect_type, + payload_json, + status, + attempt_count, + available_at, + lease_owner, + lease_expires_at, + created_at, + updated_at, + completed_at, + last_error + ) VALUES ( + 'effect:existing', + 'command:existing', + 'thread:existing', + 'provider-turn.start', + '{"type":"provider-turn.start","runId":"run:existing"}', + 'running', + 1, + '2026-06-20T00:00:00.000Z', + 'worker:old', + '2026-06-20T00:00:30.000Z', + '2026-06-20T00:00:00.000Z', + '2026-06-20T00:00:00.000Z', + NULL, + NULL + ) + `; + + yield* runMigrations({ toMigrationInclusive: 39 }); + yield* sql` + UPDATE orchestration_v2_effect_outbox + SET + status = 'cancelled', + lease_owner = NULL, + lease_expires_at = NULL, + completed_at = '2026-06-20T00:01:00.000Z' + WHERE effect_id = 'effect:existing' + `; + + const rows = yield* sql<{ + readonly effect_id: string; + readonly status: string; + readonly attempt_count: number; + readonly lease_owner: string | null; + }>` + SELECT effect_id, status, attempt_count, lease_owner + FROM orchestration_v2_effect_outbox + `; + assert.deepStrictEqual(rows, [ + { + effect_id: "effect:existing", + status: "cancelled", + attempt_count: 1, + lease_owner: null, + }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.ts b/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.ts new file mode 100644 index 0000000000..eb2512b013 --- /dev/null +++ b/apps/server/src/persistence/Migrations/039_OrchestrationV2EffectCancellation.ts @@ -0,0 +1,78 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE orchestration_v2_effect_outbox_next ( + effect_id TEXT PRIMARY KEY, + command_id TEXT NOT NULL, + thread_id TEXT NOT NULL, + effect_type TEXT NOT NULL, + payload_json TEXT NOT NULL, + status TEXT NOT NULL CHECK ( + status IN ('pending', 'running', 'succeeded', 'failed', 'cancelled') + ), + attempt_count INTEGER NOT NULL DEFAULT 0, + available_at TEXT NOT NULL, + lease_owner TEXT, + lease_expires_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + completed_at TEXT, + last_error TEXT + ) + `; + yield* sql` + INSERT INTO orchestration_v2_effect_outbox_next ( + effect_id, + command_id, + thread_id, + effect_type, + payload_json, + status, + attempt_count, + available_at, + lease_owner, + lease_expires_at, + created_at, + updated_at, + completed_at, + last_error + ) + SELECT + effect_id, + command_id, + thread_id, + effect_type, + payload_json, + status, + attempt_count, + available_at, + lease_owner, + lease_expires_at, + created_at, + updated_at, + completed_at, + last_error + FROM orchestration_v2_effect_outbox + `; + yield* sql`DROP TABLE orchestration_v2_effect_outbox`; + yield* sql` + ALTER TABLE orchestration_v2_effect_outbox_next + RENAME TO orchestration_v2_effect_outbox + `; + yield* sql` + CREATE INDEX orchestration_v2_effect_outbox_claim_idx + ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at) + `; + yield* sql` + CREATE INDEX orchestration_v2_effect_outbox_command_idx + ON orchestration_v2_effect_outbox(command_id, effect_id) + `; + yield* sql` + CREATE INDEX orchestration_v2_effect_outbox_thread_status_idx + ON orchestration_v2_effect_outbox(thread_id, status, effect_type) + `; +}); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index c3731023e3..a584cf8cfa 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -21,7 +21,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({ verify: record("verify").pipe(Effect.as({ valid: false })), rebuild: record("rebuild").pipe(Effect.as({ valid: true })), - recover: record("recover").pipe(Effect.as({ resumedSessions: 2 })), + recover: record("recover").pipe(Effect.as({ closedRequests: 2 })), startEffectWorker: record("worker"), autoBootstrap: record("bootstrap").pipe(Effect.as({ projectId: "project-1" })), }); @@ -34,7 +34,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or "bootstrap", ]); assert.deepEqual(result, { - recovery: { resumedSessions: 2 }, + recovery: { closedRequests: 2 }, bootstrap: { projectId: "project-1" }, }); }), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 3bb3b1bbe7..55e4531a0c 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -8,12 +8,14 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Console from "effect/Console"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; 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 Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; @@ -24,8 +26,10 @@ 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"; import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "./project/ProjectService.ts"; @@ -325,7 +329,9 @@ 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; const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -334,6 +340,33 @@ export const make = Effect.gen(function* () { const commandGate = yield* makeCommandGate; const httpListening = yield* Deferred.make(); + const effectWorkerFiber = yield* Ref.make | null>(null); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* commandGate.failCommandReady( + new ServerRuntimeStartupError({ + mode: serverConfig.mode, + host: serverConfig.host ?? null, + port: serverConfig.port, + cause: "Server runtime is shutting down.", + }), + ); + const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null); + if (workerFiber !== null) { + yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); + } + yield* providerSessions.shutdown; + const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); + yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("V2 orchestration shutdown reconciliation failed", { + cause: Cause.pretty(cause), + }), + ), + ), + ); yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void)); @@ -382,8 +415,13 @@ export const make = Effect.gen(function* () { startEffectWorker: runStartupPhase( "orchestration-v2.effect-worker.start", Effect.gen(function* () { - yield* EffectWorker.runDaemon.pipe(Effect.forkScoped); + 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 @@ -427,72 +465,21 @@ export const make = Effect.gen(function* () { Effect.withSpan("server.startup", { kind: "server", root: true }), ); - yield* Effect.logDebug("startup phase: starting server settings runtime"); - yield* runStartupPhase( - "settings.start", - serverSettings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start server settings runtime", { - path: error.settingsPath, - operation: error.operation, - providerInstanceId: error.providerInstanceId, - environmentVariable: error.environmentVariable, - cause: error.cause, - }), - ), - ), - ); - - yield* Effect.logDebug("startup phase: parking orchestration roots at activation"); - yield* runStartupPhase( - "reactors.start", - Effect.gen(function* () { - yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope)); - yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope)); - }), - ); - - const welcomeBase = yield* resolveWelcomeBase; - const environment = yield* serverEnvironment.getDescriptor; - yield* Effect.logDebug("startup phase: preparing welcome payload"); - - if (serverConfig.autoBootstrapProjectFromCwd) { - yield* forkParked( - runStartupPhase( - "welcome.autobootstrap", - Effect.gen(function* () { - const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe( - Effect.provideService(Crypto.Crypto, crypto), - ); - if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) { - return; - } - - yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", { - environmentId: environment.environmentId, - cwd: welcomeBase.cwd, - projectName: welcomeBase.projectName, - bootstrapProjectId: bootstrapTargets.bootstrapProjectId, - bootstrapThreadId: bootstrapTargets.bootstrapThreadId, - }); - yield* lifecycleEvents.publish({ - version: 1, - type: "welcome", - payload: { - environment, - ...welcomeBase, - ...bootstrapTargets, - }, - }); - }).pipe( - Effect.catch((cause) => - Effect.logWarning("startup auto-bootstrap welcome failed", { - cause, - }), - ), - ), - ), - ); + yield* Effect.forkScoped( + Effect.gen(function* () { + const startupExit = yield* Effect.exit(startup); + if (Exit.isFailure(startupExit)) { + const error = new ServerRuntimeStartupError({ + mode: serverConfig.mode, + host: serverConfig.host ?? null, + port: serverConfig.port, + cause: startupExit.cause, + }); + yield* Effect.logError("server runtime startup failed", { + cause: Cause.pretty(startupExit.cause), + }); + yield* commandGate.failCommandReady(error); + return; } yield* Effect.logDebug("startup phase: waiting for http listener"); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index edb4dcc491..febd3ba1dd 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -79,6 +79,7 @@ import { derivePhase, deriveTimelineEntries, deriveTimelineEntriesFromVisibleTurnItems, + deriveRevertTurnCountByUserMessageId, deriveActiveWorkStartedAt, deriveActivePlanState, findSidebarProposedPlan, @@ -177,7 +178,7 @@ import { deriveLogicalProjectKeyFromSettings, selectProjectGroupingSettings, } from "../logicalProject"; -import { buildDraftThreadRouteParams } from "../threadRoutes"; +import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRoutes"; import { type ComposerImageAttachment, type DraftThreadEnvMode, @@ -239,15 +240,8 @@ import { import { ThreadErrorBanner } from "./chat/ThreadErrorBanner"; import { resolveThreadPr } from "./ThreadStatusIndicators"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; -import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill"; -import { - DRAFT_HERO_TRANSITION_ANIMATION_ID, - DRAFT_HERO_TRANSITION_DURATION_MS, - DRAFT_HERO_TRANSITION_EASING, - MOBILE_COMPOSER_VIEW_TRANSITION_NAME, - MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME, - runMobileComposerTransition, -} from "./chat/draftHeroTransition"; +import { QueuedRunsControl } from "./chat/QueuedRunsControl"; +import type { ComposerDispatchMode } from "./chat/composerDispatch"; import { MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, branchMismatchKey, @@ -1191,6 +1185,9 @@ function ChatViewContent(props: ChatViewProps) { const revertThreadCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, { reportFailure: false, }); + const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, { + reportFailure: false, + }); const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const closePreview = useAtomCommand(previewEnvironment.close, "preview close"); const { environments } = useEnvironments(); @@ -2398,8 +2395,7 @@ function ChatViewContent(props: ChatViewProps) { [activeThread?.proposedPlans, timelineMessages, workLogEntries], ); const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; - const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = - useTurnDiffSummaries(activeThread); + const { turnDiffSummaries } = useTurnDiffSummaries(activeThread); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); for (const summary of turnDiffSummaries) { @@ -2408,38 +2404,14 @@ function ChatViewContent(props: ChatViewProps) { } return byMessageId; }, [turnDiffSummaries]); - const revertTurnCountByUserMessageId = useMemo(() => { - const byUserMessageId = new Map(); - for (let index = 0; index < timelineEntries.length; index += 1) { - const entry = timelineEntries[index]; - if (!entry || entry.kind !== "message" || entry.message.role !== "user") { - continue; - } - - for (let nextIndex = index + 1; nextIndex < timelineEntries.length; nextIndex += 1) { - const nextEntry = timelineEntries[nextIndex]; - if (!nextEntry || nextEntry.kind !== "message") { - continue; - } - if (nextEntry.message.role === "user") { - break; - } - const summary = turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id); - if (!summary) { - continue; - } - const turnCount = - summary.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[summary.runId]; - if (typeof turnCount !== "number") { - break; - } - byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1)); - break; - } - } - - return byUserMessageId; - }, [inferredCheckpointTurnCountByRunId, timelineEntries, turnDiffSummaryByAssistantMessageId]); + const revertTurnCountByUserMessageId = useMemo( + () => + deriveRevertTurnCountByUserMessageId({ + timelineEntries, + checkpoints: turnDiffSummaries, + }), + [timelineEntries, turnDiffSummaries], + ); const gitCwd = activeProject ? projectScriptCwd({ @@ -4556,7 +4528,114 @@ function ChatViewContent(props: ChatViewProps) { ], ); - const onSend = async (e?: { preventDefault: () => void }) => { + const onRollbackCheckpoint = useCallback( + async (input: { readonly checkpointId: string; readonly scopeId: string }) => { + if (!activeThread || isRevertingCheckpoint) return; + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { + setThreadError( + activeThread.id, + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + ); + return; + } + if (phase === "running" || isSendBusy || isConnecting) { + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); + return; + } + const localApi = readLocalApi(); + const confirmed = + localApi == null + ? window.confirm("Roll back this thread to the selected checkpoint?") + : await localApi.dialogs.confirm( + "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.", + ); + if (!confirmed) return; + + setIsRevertingCheckpoint(true); + setThreadError(activeThread.id, null); + const result = await revertThreadCheckpoint({ + environmentId, + input: { + threadId: activeThread.id, + checkpointId: input.checkpointId, + scopeId: input.scopeId, + }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThread.id, + error instanceof Error ? error.message : "Failed to revert thread state.", + ); + } + setIsRevertingCheckpoint(false); + }, + [ + activeEnvironmentUnavailable, + activeEnvironmentUnavailableLabel, + activeThread, + environmentId, + isConnecting, + isRevertingCheckpoint, + isSendBusy, + phase, + revertThreadCheckpoint, + setThreadError, + ], + ); + + const onOpenRelatedThread = useCallback( + (threadId: ThreadId) => { + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)), + }); + }, + [environmentId, navigate], + ); + + const onForkFromRun = useCallback( + async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => { + if (!activeThread || activeEnvironmentUnavailable) return; + const targetThreadId = newThreadId(); + const result = await forkThreadFromRun({ + environmentId, + input: { + sourceThreadId: input.sourceThreadId, + targetThreadId, + runId: input.runId, + title: `${activeThread.title} fork`, + }, + }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThread.id, + error instanceof Error ? error.message : "Failed to fork this response.", + ); + } + return; + } + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(environmentId, targetThreadId)), + }); + }, + [ + activeEnvironmentUnavailable, + activeThread, + environmentId, + forkThreadFromRun, + navigate, + setThreadError, + ], + ); + + const onSend = async ( + e?: { preventDefault: () => void }, + dispatchMode: ComposerDispatchMode = "auto", + ) => { e?.preventDefault(); if ( !activeThread || @@ -4757,6 +4836,11 @@ function ChatViewContent(props: ChatViewProps) { createdAt: messageCreatedAt, updatedAt: messageCreatedAt, streaming: false, + ...(phase === "running" && dispatchMode === "queue" + ? { inputIntent: "queued_turn" as const } + : phase === "running" && dispatchMode === "steer" + ? { inputIntent: "steer" as const } + : {}), }, ]); setThreadError(threadIdForSend, null); @@ -4886,6 +4970,7 @@ function ChatViewContent(props: ChatViewProps) { titleSeed: title, runtimeMode, interactionMode, + dispatchMode, ...(bootstrap ? { bootstrap } : {}), createdAt: messageCreatedAt, }, @@ -5823,6 +5908,9 @@ function ChatViewContent(props: ChatViewProps) { activeThreadEnvironmentId={activeThread.environmentId} routeThreadKey={routeThreadKey} onOpenTurnDiff={onOpenTurnDiff} + onOpenThread={onOpenRelatedThread} + onForkFromRun={onForkFromRun} + onRollbackCheckpoint={(input) => void onRollbackCheckpoint(input)} revertTurnCountByUserMessageId={revertTurnCountByUserMessageId} onRevertUserMessage={onRevertUserMessage} isRevertingCheckpoint={isRevertingCheckpoint} @@ -5882,6 +5970,12 @@ function ChatViewContent(props: ChatViewProps) {
+ {isServerThread && activeThread ? ( + + ) : null}
void; onInterrupt: () => void; @@ -438,6 +440,11 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( {props.isPreparingWorktree ? ( Preparing worktree... ) : null} + {props.isRunning && props.hasSendableContent ? ( + + {props.queueShortcutLabel} to queue + + ) : null} void; // Callbacks - onSend: (e?: { preventDefault: () => void }) => void; + onSend: (e?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode) => void; onInterrupt: () => void; onImplementPlanInNewThread: () => void; onRespondToApproval: ( @@ -1843,37 +1850,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ]); const submitComposer = useCallback( - (event?: { preventDefault: () => void }) => { - if (noProviderAvailable || isSendDisabled) { - event?.preventDefault(); - return; - } - // A send while a pasted image is still compressing would strand that - // image: the turn snapshot wouldn't include it, and it would surface - // in the *next* draft instead. Only oversized images hit this — small - // files clear the pending counter within a microtask. - if (activeThreadId && (pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) { - event?.preventDefault(); - toastManager.add({ - type: "info", - title: "Still compressing a pasted image.", - description: "Send again once its thumbnail appears.", - }); - return; - } - onSend(event); + (event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode) => { + onSend(event, dispatchMode ?? resolveComposerDispatchMode({ phase, queueModifier: false })); if (shouldBlurMobileComposerOnSubmit()) { blurMobileComposerAfterSend(); } }, - [ - activeThreadId, - blurMobileComposerAfterSend, - isSendDisabled, - noProviderAvailable, - onSend, - shouldBlurMobileComposerOnSubmit, - ], + [blurMobileComposerAfterSend, onSend, phase, shouldBlurMobileComposerOnSubmit], ); const expandMobileComposer = useCallback(() => { if (composerBlurFrameRef.current !== null) { @@ -1927,11 +1910,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return true; } } - if ( - key === "Enter" && - shouldSubmitComposerOnEnter({ isMobileViewport, shiftKey: event.shiftKey }) - ) { - submitComposer(); + if (key === "Enter" && !event.shiftKey) { + submitComposer( + undefined, + resolveComposerDispatchMode({ + phase, + queueModifier: event.metaKey || event.ctrlKey, + }), + ); return true; } return false; @@ -3248,6 +3234,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } isPreparingWorktree={isPreparingWorktree} hasSendableContent={composerSendState.hasSendableContent} + queueShortcutLabel={isMacPlatform(navigator.platform) ? "⌘↵" : "Ctrl+Enter"} preserveComposerFocusOnPointerDown={isMobileViewport} onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} onInterrupt={handleInterruptPrimaryAction} diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 0adeed6ffa..27e08b3430 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -19,6 +19,7 @@ import { usePrimaryEnvironmentId } from "../../state/environments"; import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts"; import { ProjectFavicon } from "../ProjectFavicon"; import { cn } from "~/lib/utils"; +import { ThreadRelationshipsControl } from "./ThreadRelationshipsControl"; interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; @@ -152,6 +153,12 @@ export const ChatHeader = memo(function ChatHeader({ onDeleteScript={onDeleteProjectScript} /> )} + {!draftId ? ( + + ) : null} {showOpenInPicker && ( {}, + onInterrupt: () => {}, + onImplementPlanInNewThread: () => {}, +} as const; describe("formatPendingPrimaryActionLabel", () => { it("returns 'Submitting...' while responding", () => { @@ -91,3 +108,31 @@ describe("formatPendingPrimaryActionLabel", () => { ).toBe("Submit answers"); }); }); + +describe("active-turn primary action", () => { + it("shows stop while the active composer is empty", () => { + const markup = renderToStaticMarkup( + createElement(ComposerPrimaryActions, { + ...activeTurnProps, + isRunning: true, + hasSendableContent: false, + }), + ); + + expect(markup).toContain('aria-label="Stop generation"'); + expect(markup).not.toContain("steer active turn"); + }); + + it("replaces stop with send while the active composer has content", () => { + const markup = renderToStaticMarkup( + createElement(ComposerPrimaryActions, { + ...activeTurnProps, + isRunning: true, + hasSendableContent: true, + }), + ); + + expect(markup).toContain('aria-label="Send message to steer active turn"'); + expect(markup).not.toContain('aria-label="Stop generation"'); + }); +}); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 504b7e1cc4..9f46864034 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -6,6 +6,7 @@ import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../Sideb import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Spinner } from "../ui/spinner"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; interface PendingActionState { questionIndex: number; @@ -132,7 +133,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ ); } - if (isRunning) { + if (isRunning && !hasSendableContent) { return ( ); + + if (!isRunning) return sendButton; + + return ( + + + Send now to steer the active turn + + ); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index edf3b01adc..a80986ec9b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -167,6 +167,7 @@ export type MessagesTimelineRow = id: string; createdAt: string; message: ChatMessage; + projectedItem?: OrchestrationV2ProjectedTurnItem; durationStart: string; showAssistantMeta: boolean; showAssistantCopyButton: boolean; @@ -572,6 +573,9 @@ export function deriveMessagesTimelineRows(input: { id: timelineEntry.id, createdAt: timelineEntry.createdAt, message: timelineEntry.message, + ...(timelineEntry.projectedItem === undefined + ? {} + : { projectedItem: timelineEntry.projectedItem }), durationStart, showAssistantMeta, showAssistantCopyButton: showAssistantMeta, @@ -655,6 +659,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean const bm = b as typeof a; return ( a.message === bm.message && + a.projectedItem === bm.projectedItem && a.durationStart === bm.durationStart && a.showAssistantMeta === bm.showAssistantMeta && a.showAssistantCopyButton === bm.showAssistantCopyButton && diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index e4028f03a7..5482e1d4be 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1,4 +1,4 @@ -import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts"; +import { EnvironmentId, MessageId, RunId } from "@t3tools/contracts"; import { createRef, type ReactNode, type Ref } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; @@ -180,6 +180,9 @@ function buildProps() { turnDiffSummaryByAssistantMessageId: new Map(), routeThreadKey: "environment-local:thread-1", onOpenTurnDiff: () => {}, + onOpenThread: () => {}, + onForkFromRun: async () => {}, + onRollbackCheckpoint: () => {}, revertTurnCountByUserMessageId: new Map(), onRevertUserMessage: () => {}, isRevertingCheckpoint: false, @@ -436,7 +439,78 @@ describe("MessagesTimeline", () => { expect(markup).toContain("rounded-2xl bg-accent p-3"); }); - it("renders inline terminal labels with the composer chip UI", () => { + it("keeps steer intent visible on committed user messages", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const entry = buildUserTimelineEntry("Adjust the current turn"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Steered the active turn"); + expect(markup).toContain(">steer<"); + }); + + it("exposes a per-response fork action for completed assistant items", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const projectedItem = { + position: 0, + visibility: "local", + sourceThreadId: "thread-1", + sourceItemId: "assistant-item-1", + item: { + id: "assistant-item-1", + threadId: "thread-1", + runId: "run-1", + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: null, + completedAt: null, + updatedAt: {}, + type: "assistant_message", + messageId: "assistant-message-1", + text: "Done", + streaming: false, + }, + } as never; + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('aria-label="Fork from this response"'); + }); + + it("renders inline terminal labels with the composer chip UI", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { expect(markup).toContain('data-v2-item-type="run_interrupt_request"'); expect(markup).toContain("Interrupt requested"); expect(markup).toContain("Waiting for the provider to stop."); - expect(markup).toContain('data-v2-structured-details="true"'); - expect(markup).toContain("Structured details"); - expect(markup).toContain(""type": "run_interrupt_request""); + expect(markup).not.toContain("Structured details"); }); it("keeps inherited V2 work provenance on the rendered row", async () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 7e71e09880..a7ffea7ed3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -5,6 +5,7 @@ import { type ScopedThreadRef, type ServerProviderSkill, type RunId, + type ThreadId, } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; @@ -46,6 +47,7 @@ import { ChevronRightIcon, CircleAlertIcon, EyeIcon, + GitForkIcon, GlobeIcon, HammerIcon, MessageCircleIcon, @@ -99,6 +101,9 @@ import { cn } from "~/lib/utils"; import { useUiStateStore } from "~/uiStateStore"; import { type TimestampFormat } from "@t3tools/contracts/settings"; import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat"; +import { V2ItemInspector } from "./V2ItemInspector"; +import { useV2ItemSupport } from "../../state/v2ItemSupport"; +import { isV2LifecycleItem, V2LifecycleRow } from "./V2LifecycleRow"; import { buildInlineTerminalContextText, @@ -133,6 +138,15 @@ interface TimelineRowSharedState { onRevertUserMessage: (messageId: MessageId) => void; onImageExpand: (preview: ExpandedImagePreview) => void; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; + onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; + onForkFromRun: (input: { + readonly sourceThreadId: ThreadId; + readonly runId: RunId; + }) => Promise; + onRollbackCheckpoint: (input: { + readonly checkpointId: string; + readonly scopeId: string; + }) => void; onToggleTurnFold: (runId: RunId) => void; } @@ -164,6 +178,15 @@ interface MessagesTimelineProps { turnDiffSummaryByAssistantMessageId: Map; routeThreadKey: string; onOpenTurnDiff: (runId: RunId, filePath?: string) => void; + onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void; + onForkFromRun: (input: { + readonly sourceThreadId: ThreadId; + readonly runId: RunId; + }) => Promise; + onRollbackCheckpoint: (input: { + readonly checkpointId: string; + readonly scopeId: string; + }) => void; revertTurnCountByUserMessageId: Map; onRevertUserMessage: (messageId: MessageId) => void; isRevertingCheckpoint: boolean; @@ -198,6 +221,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ turnDiffSummaryByAssistantMessageId, routeThreadKey, onOpenTurnDiff, + onOpenThread, + onForkFromRun, + onRollbackCheckpoint, revertTurnCountByUserMessageId, onRevertUserMessage, isRevertingCheckpoint, @@ -427,6 +453,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onOpenThread, + onForkFromRun, + onRollbackCheckpoint, onToggleTurnFold, onToggleWorkGroup, }), @@ -441,6 +470,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRevertUserMessage, onImageExpand, onOpenTurnDiff, + onOpenThread, + onForkFromRun, + onRollbackCheckpoint, onToggleTurnFold, onToggleWorkGroup, ], @@ -948,6 +980,25 @@ function UserTimelineRow({ row }: { row: Extract
+ {(row.message.inputIntent && row.message.inputIntent !== "turn_start") || + (row.projectedItem && + row.projectedItem.item.status !== "completed" && + row.projectedItem.item.status !== "pending" && + row.projectedItem.item.status !== "waiting") ? ( +
+ {row.message.inputIntent && row.message.inputIntent !== "turn_start" ? ( + + ) : null} + {row.projectedItem && + row.projectedItem.item.status !== "completed" && + row.projectedItem.item.status !== "pending" && + row.projectedItem.item.status !== "waiting" ? ( + + {row.projectedItem.item.status} + + ) : null} +
+ ) : null}
@@ -970,6 +1021,39 @@ function UserTimelineRow({ row }: { row: Extract; +}) { + const presentation = + intent === "queued_turn" + ? { label: "queued", className: "border-amber-500/25 bg-amber-500/8 text-amber-700" } + : intent === "promoted_queued_to_steer" + ? { + label: "queued → steer", + className: "border-sky-500/25 bg-sky-500/8 text-sky-700", + } + : { label: "steer", className: "border-sky-500/25 bg-sky-500/8 text-sky-700" }; + return ( + + {presentation.label} + + ); +} + function RevertUserMessageButton({ messageId }: { messageId: MessageId }) { const ctx = use(TimelineRowCtx); const activity = use(TimelineRowActivityCtx); @@ -1036,8 +1120,16 @@ function AssistantTimelineRow({ row }: { row: Extract {row.showAssistantMeta ? ( -
+
+ {row.projectedItem?.item.type === "assistant_message" ? ( + + ) : null} + {row.projectedItem && row.projectedItem.item.status !== "completed" ? ( + + {row.projectedItem.item.status} + + ) : null} {!row.message.streaming && ( ["projectedItem"]>; +}) { + const ctx = use(TimelineRowCtx); + const [busy, setBusy] = useState(false); + const support = useV2ItemSupport({ + environmentId: ctx.activeThreadEnvironmentId, + sourceThreadId: projectedItem.sourceThreadId, + sourceItemId: projectedItem.sourceItemId, + }); + const capabilities = support.providerSession?.capabilities; + const canForkNatively = + capabilities?.threads.canForkThread === true && + capabilities.threads.canForkFromTurn === true && + capabilities.identity.nativeThreadIds === "strong"; + const canFork = + projectedItem.item.runId !== null && + projectedItem.item.status === "completed" && + (capabilities === undefined || + canForkNatively || + capabilities.context.supportsFullThreadHandoff === true); + + if (!canFork || projectedItem.item.runId === null) return null; + const runId = projectedItem.item.runId; + + return ( + + { + setBusy(true); + void ctx + .onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }) + .finally(() => setBusy(false)); + }} + aria-label="Fork from this response" + /> + } + > + + + Fork from this response + + ); +} + function AssistantCopyButton({ row }: { row: Extract }) { const assistantCopyState = resolveAssistantMessageCopyState({ text: row.message.text ?? null, @@ -1186,6 +1331,16 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { function V2EventTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const { item, visibility, sourceThreadId } = row.projectedItem; + if (isV2LifecycleItem(item)) { + return ( + + ); + } const presentation = v2EventPresentation(item); const Icon = presentation.icon; return ( @@ -1240,18 +1395,17 @@ function V2EventTimelineRow({ row }: { row: Extract ) : null} -
- - - Structured details - -
-              {JSON.stringify(item, null, 2)}
-            
-
+
+ +
@@ -2129,6 +2283,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { }) { const { workEntry, workspaceRoot } = props; const activity = use(TimelineRowActivityCtx); + const ctx = use(TimelineRowCtx); const [expanded, setExpanded] = useState(false); const iconConfig = workToneIcon(workEntry.tone); const showWarningIndicator = false; @@ -2143,7 +2298,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { : rawPreview; const displayText = preview ? `${heading} - ${preview}` : heading; const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot); - const canExpand = expandedBody !== null; + const canExpand = expandedBody !== null || workEntry.projectedItem !== undefined; const showFailedIndicator = workEntryIndicatesToolFailure(workEntry); const showDestructiveRowStyle = showFailedIndicator && !workLogEntryIsToolLike(workEntry); const iconWrapperClass = cn( @@ -2273,15 +2428,27 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
- {expanded && canExpand && expandedBody ? ( + {expanded && canExpand ? (
-
-            {expandedBody}
-          
+ {workEntry.projectedItem ? ( + + ) : expandedBody ? ( +
+              {expandedBody}
+            
+ ) : null}
) : null}
diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx new file mode 100644 index 0000000000..efce259b78 --- /dev/null +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -0,0 +1,111 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { ArrowDownIcon, ArrowUpIcon, CornerUpRightIcon, ListOrderedIcon } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { threadEnvironment } from "../../state/threads"; +import { useThreadProjection } from "../../state/entities"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; + +export function QueuedRunsControl(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const projection = useThreadProjection( + scopeThreadRef(props.environmentId, props.threadId), + )?.projection; + const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun); + const promote = useAtomCommand(threadEnvironment.promoteQueuedRun); + const [busyRunId, setBusyRunId] = useState(null); + const queued = useMemo( + () => + (projection?.runs ?? []) + .filter((run) => run.status === "queued") + .toSorted( + (left, right) => + (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) || + left.ordinal - right.ordinal, + ) + .map((run) => ({ + run, + text: + projection?.messages.find((message) => message.id === run.userMessageId)?.text ?? + "Queued message", + })), + [projection], + ); + const activeRun = + projection?.runs.findLast( + (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + ) ?? null; + + if (queued.length === 0) return null; + + const move = async (runId: RunId, beforeRunId: RunId | null) => { + setBusyRunId(runId); + await reorder({ + environmentId: props.environmentId, + input: { threadId: props.threadId, runId, beforeRunId }, + }); + setBusyRunId(null); + }; + + const steer = async (queuedRunId: RunId) => { + if (activeRun === null) return; + setBusyRunId(queuedRunId); + await promote({ + environmentId: props.environmentId, + input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, + }); + setBusyRunId(null); + }; + + return ( +
+
+ + Queue + {queued.length} +
+
    + {queued.map(({ run, text }, index) => ( +
  1. + + {index + 1} + + {text} + + + +
  2. + ))} +
+
+ ); +} diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx new file mode 100644 index 0000000000..58e495007e --- /dev/null +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -0,0 +1,243 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { ArrowRightIcon, GitBranchIcon, GitForkIcon, NetworkIcon, UnplugIcon } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; +import { + deriveThreadRelationshipGraph, + walkThreadRelationships, +} from "../../lib/threadRelationships"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { newThreadId } from "../../lib/utils"; +import { threadEnvironment } from "../../state/threads"; +import { useThreadProjection, useThreadShells } from "../../state/entities"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; + +function relationshipLabel( + edge: ReturnType[number]["edge"], + currentThreadId: ThreadId, +) { + if (edge.kind === "transfer") return "context transfer"; + if (edge.kind === "subagent") { + return edge.sourceThreadId === currentThreadId ? "subagent" : "parent agent"; + } + return edge.sourceThreadId === currentThreadId ? "fork" : "source"; +} + +export function ThreadRelationshipsControl(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const ref = scopeThreadRef(props.environmentId, props.threadId); + const projection = useThreadProjection(ref)?.projection ?? null; + const activeShells = useThreadShells().filter( + (thread) => thread.environmentId === props.environmentId, + ); + const archived = useArchivedThreadSnapshots([props.environmentId]); + const archivedShells = + archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot + .threads ?? []; + const shells = useMemo>( + () => [...activeShells.map((thread) => thread.source), ...archivedShells], + [activeShells, archivedShells], + ); + const graph = useMemo( + () => deriveThreadRelationshipGraph({ threads: shells, projection }), + [projection, shells], + ); + const relationshipRows = useMemo( + () => walkThreadRelationships(graph, props.threadId), + [graph, props.threadId], + ); + const navigate = useNavigate(); + const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun); + const mergeBack = useAtomCommand(threadEnvironment.mergeBack); + const stopSession = useAtomCommand(threadEnvironment.stopSession); + const [busyAction, setBusyAction] = useState<"fork" | "merge" | "detach" | null>(null); + const latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null; + const sourceProviderThread = + latestCompletedRun?.providerThreadId == null + ? null + : (projection?.providerThreads.find( + (thread) => thread.id === latestCompletedRun.providerThreadId, + ) ?? null); + const capabilities = + (sourceProviderThread === null + ? null + : projection?.providerSessions.find( + (session) => session.id === sourceProviderThread.providerSessionId, + )?.capabilities) ?? null; + const canForkNatively = + capabilities?.threads.canForkThread === true && + capabilities.threads.canForkFromTurn === true && + capabilities.identity.nativeThreadIds === "strong"; + const canFork = + latestCompletedRun !== null && + (canForkNatively || capabilities?.context.supportsFullThreadHandoff === true); + const parentThreadId = + projection?.thread.forkedFrom?.type === "run" + ? projection.thread.forkedFrom.threadId + : (projection?.thread.lineage.parentThreadId ?? null); + const canMerge = + parentThreadId !== null && + projection?.thread.lineage.relationshipToParent === "fork" && + latestCompletedRun !== null; + const canDetach = + projection?.providerSessions.some( + (session) => session.status !== "stopped" && session.status !== "error", + ) ?? false; + + const openThread = (threadId: ThreadId) => { + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)), + }); + }; + + const fork = async () => { + if (!latestCompletedRun || busyAction !== null) return; + setBusyAction("fork"); + const targetThreadId = newThreadId(); + const result = await forkFromRun({ + environmentId: props.environmentId, + input: { + sourceThreadId: props.threadId, + targetThreadId, + runId: latestCompletedRun.id, + title: `${projection?.thread.title ?? "Thread"} fork`, + }, + }); + setBusyAction(null); + if (result._tag === "Success") openThread(targetThreadId); + }; + + const merge = async () => { + if (!latestCompletedRun || parentThreadId === null || busyAction !== null) return; + setBusyAction("merge"); + const result = await mergeBack({ + environmentId: props.environmentId, + input: { + sourceThreadId: props.threadId, + targetThreadId: parentThreadId, + runId: latestCompletedRun.id, + }, + }); + setBusyAction(null); + if (result._tag === "Success") openThread(parentThreadId); + }; + + const detach = async () => { + if (!canDetach || busyAction !== null) return; + setBusyAction("detach"); + await stopSession({ + environmentId: props.environmentId, + input: { threadId: props.threadId }, + }); + setBusyAction(null); + }; + + return ( + + + + } + > + + {relationshipRows.length > 0 ? {relationshipRows.length} : null} + + } + /> + Thread relationships + + +
+

Thread relationships

+

+ Forks, subagents, and context transfers in this environment. +

+
+
+ {relationshipRows.length === 0 ? ( +

+ This thread has no related threads yet. +

+ ) : ( +
    + {relationshipRows.map(({ threadId, fromThreadId, depth, edge }) => { + const node = graph.nodes.get(threadId); + return ( +
  • + +
  • + ); + })} +
+ )} +
+
+ + + +
+
+
+ ); +} diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx new file mode 100644 index 0000000000..25463bb620 --- /dev/null +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -0,0 +1,298 @@ +import type { + EnvironmentId, + OrchestrationV2ProjectedTurnItem, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import { ExternalLinkIcon, GitBranchIcon, RotateCcwIcon } from "lucide-react"; +import { memo, type ReactNode } from "react"; + +import { useV2ItemSupport } from "../../state/v2ItemSupport"; +import { formatWorkspaceRelativePath } from "../../filePathDisplay"; +import { Button } from "../ui/button"; +import ChatMarkdown from "../ChatMarkdown"; + +interface V2ItemInspectorProps { + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + readonly environmentId: EnvironmentId; + readonly cwd?: string | undefined; + readonly workspaceRoot?: string | undefined; + readonly onOpenThread: (threadId: ThreadId) => void; + readonly onOpenTurnDiff: (runId: RunId, filePath?: string) => void; + readonly onRollbackCheckpoint?: (input: { + readonly checkpointId: string; + readonly scopeId: string; + }) => void; +} + +function durationLabel(startedAt: unknown, completedAt: unknown): string | null { + if (startedAt == null) return null; + const start = Date.parse(String(startedAt)); + const end = completedAt == null ? Date.now() : Date.parse(String(completedAt)); + if (!Number.isFinite(start) || !Number.isFinite(end)) return null; + const milliseconds = Math.max(0, end - start); + if (milliseconds < 1_000) return `${milliseconds}ms`; + if (milliseconds < 60_000) return `${(milliseconds / 1_000).toFixed(1)}s`; + return `${Math.floor(milliseconds / 60_000)}m ${Math.floor((milliseconds % 60_000) / 1_000)}s`; +} + +function DataField(props: { readonly label: string; readonly children: ReactNode }) { + return ( +
+
+ {props.label} +
+
+ {props.children} +
+
+ ); +} + +function StructuredValue({ value }: { readonly value: unknown }) { + const text = typeof value === "string" ? value : JSON.stringify(value, null, 2); + if (!text) return null; + return ( +
+      {text}
+    
+ ); +} + +export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) { + const { item } = props.projectedItem; + const support = useV2ItemSupport({ + environmentId: props.environmentId, + sourceThreadId: props.projectedItem.sourceThreadId, + sourceItemId: props.projectedItem.sourceItemId, + }); + const duration = durationLabel(item.startedAt, item.completedAt); + const latestAttempt = support.attempts.at(-1) ?? null; + const runtimeRequest = support.runtimeRequest; + + return ( +
+
+ {item.type} + {item.status} + {duration ? {duration} : null} + {support.run ? {support.run.status} : null} + {latestAttempt ? ( + + {latestAttempt.attemptOrdinal} · {latestAttempt.status} · {latestAttempt.reason} + + ) : null} + {support.node ? ( + + {support.node.kind} · {support.node.status} + + ) : null} + {support.providerThread ? ( + + {support.providerThread.providerInstanceId} · {support.providerThread.status} + + ) : null} + {support.providerTurn ? ( + {support.providerTurn.status} + ) : null} + {support.providerSession ? ( + + {support.providerSession.status} · {support.providerSession.model ?? "default model"} + + ) : null} + {support.providerSession ? ( + {support.providerSession.cwd} + ) : null} + {runtimeRequest ? ( + + {runtimeRequest.status} · {runtimeRequest.responseCapability.type} + + ) : null} +
+ + {support.attempts.length > 1 ? ( +
+ + Attempt history · {support.attempts.length} + +
    + {support.attempts.map((attempt) => ( +
  1. + + Attempt {attempt.attemptOrdinal} · {attempt.reason.replaceAll("_", " ")} + + {attempt.status} +
  2. + ))} +
+
+ ) : null} + + {item.type === "reasoning" && item.text ? ( +
+ +
+ ) : null} + + {item.type === "command_execution" ? ( +
+ + {item.output !== undefined ? : null} + {item.exitCode !== undefined ? ( +

+ Process exited with code {item.exitCode} +

+ ) : null} +
+ ) : null} + + {item.type === "file_change" ? ( +
+ + {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)} + + {item.additions !== undefined || item.deletions !== undefined ? ( + + +{item.additions ?? 0}{" "} + -{item.deletions ?? 0} + + ) : null} + {item.runId !== null ? ( + + ) : null} + {item.diffStr ? : null} +
+ ) : null} + + {item.type === "file_search" && item.results ? ( +
    + {item.results.map((result) => ( +
  • + + {formatWorkspaceRelativePath(result.fileName, props.workspaceRoot)} + {result.line === undefined ? "" : `:${result.line}`} + {result.column === undefined ? "" : `:${result.column}`} + + {result.preview ? ( +

    {result.preview}

    + ) : null} +
  • + ))} +
+ ) : null} + + {item.type === "web_search" && item.results ? ( +
    + {item.results.map((result) => ( +
  • + {result.url ? ( + + {result.title ?? result.url} + + + ) : ( +

    {result.title ?? "Search result"}

    + )} + {result.snippet ?

    {result.snippet}

    : null} +
  • + ))} +
+ ) : null} + + {item.type === "dynamic_tool" ? ( +
+
+

+ Input +

+ +
+ {item.output !== undefined ? ( +
+

+ Output +

+ +
+ ) : null} +
+ ) : null} + + {item.type === "checkpoint" ? ( +
+ + {support.checkpoint?.status ?? item.status} · {item.files.length} files + + {props.onRollbackCheckpoint && support.checkpoint?.status === "ready" ? ( + + ) : null} +
+ ) : null} + + {item.type === "fork" ? ( + + ) : null} + + {item.type === "subagent" && item.childThreadId !== null ? ( + + ) : null} + + {item.type === "handoff" ? ( +
+

+ {item.fromProviderInstanceIds.join(", ")} → {item.toProviderInstanceId} +

+

+ {item.strategy.replaceAll("_", " ")} · {support.contextHandoff?.status ?? item.status} +

+ {support.contextTransfer ? ( +

+ Transfer {support.contextTransfer.type.replaceAll("_", " ")} ·{" "} + {support.contextTransfer.status} +

+ ) : null} +
+ ) : null} + +
+ + Structured details + +
+ +
+
+
+ ); +}); diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx new file mode 100644 index 0000000000..652143dd59 --- /dev/null +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -0,0 +1,160 @@ +import type { OrchestrationV2TurnItem, ThreadId } from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import { GitForkIcon, HammerIcon, MinusIcon, XIcon, ZapIcon } from "lucide-react"; + +import { cn } from "~/lib/utils"; +import { formatShortTimestamp } from "../../timestampFormat"; + +const LIFECYCLE_TYPES = new Set([ + "run_interrupt_request", + "run_interrupt_result", + "compaction", + "handoff", + "fork", + "subagent", +]); + +export function isV2LifecycleItem(item: OrchestrationV2TurnItem): boolean { + return LIFECYCLE_TYPES.has(item.type); +} + +export function V2LifecycleRow(props: { + readonly item: OrchestrationV2TurnItem; + readonly createdAt: string; + readonly timestampFormat: TimestampFormat; + readonly onOpenThread: (threadId: ThreadId) => void; +}) { + const { item } = props; + if (item.type === "run_interrupt_request") { + return ( +
+
+ + Interrupt requested + + {item.message} + + {formatShortTimestamp(props.createdAt, props.timestampFormat)} + +
+
+ ); + } + if (item.type === "run_interrupt_result") { + return ( + + ); + } + if (item.type === "compaction") { + const tokenDetail = + item.beforeTokenCount === undefined && item.afterTokenCount === undefined + ? null + : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`; + return ( + + ); + } + if (item.type === "handoff") { + return ( + + ); + } + if (item.type === "fork") { + const relatedThreadId = item.source.type === "run" ? item.source.threadId : item.targetThreadId; + return ( + props.onOpenThread(relatedThreadId)} + /> + ); + } + if (item.type === "subagent") { + const content = ( + <> + + + {item.title ?? "Subagent"} + + + {item.result ?? item.prompt} + + + {item.status} + + + ); + return item.childThreadId === null ? ( +
+ {content} +
+ ) : ( + + ); + } + return null; +} + +function SystemDivider(props: { + readonly label: string; + readonly detail?: string | null; + readonly tone?: "neutral" | "danger"; + readonly icon?: typeof GitForkIcon; + readonly actionLabel?: string; + readonly onAction?: () => void; +}) { + const Icon = props.icon; + const content = ( + <> + {Icon ? : null} + {props.label} + {props.detail ? · {props.detail} : null} + + ); + return ( +
+
+ ); +} diff --git a/apps/web/src/components/chat/composerDispatch.test.ts b/apps/web/src/components/chat/composerDispatch.test.ts new file mode 100644 index 0000000000..630b3f15d3 --- /dev/null +++ b/apps/web/src/components/chat/composerDispatch.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveComposerDispatchMode } from "./composerDispatch"; + +describe("resolveComposerDispatchMode", () => { + it("starts an ordinary turn while idle", () => { + expect(resolveComposerDispatchMode({ phase: "ready", queueModifier: false })).toBe("auto"); + }); + + it("steers by default and reserves Mod+Enter for queueing while running", () => { + expect(resolveComposerDispatchMode({ phase: "running", queueModifier: false })).toBe("steer"); + expect(resolveComposerDispatchMode({ phase: "running", queueModifier: true })).toBe("queue"); + }); + + it("accepts a configured default without changing the queue shortcut", () => { + expect( + resolveComposerDispatchMode({ + phase: "running", + queueModifier: false, + activeTurnDefault: "restart", + }), + ).toBe("restart"); + expect( + resolveComposerDispatchMode({ + phase: "running", + queueModifier: true, + activeTurnDefault: "restart", + }), + ).toBe("queue"); + }); +}); diff --git a/apps/web/src/components/chat/composerDispatch.ts b/apps/web/src/components/chat/composerDispatch.ts new file mode 100644 index 0000000000..d6dd6de422 --- /dev/null +++ b/apps/web/src/components/chat/composerDispatch.ts @@ -0,0 +1,15 @@ +import type { SessionPhase } from "../../types"; + +export type ComposerDispatchMode = "auto" | "queue" | "steer" | "restart"; +export type ActiveTurnComposerAction = Exclude; + +/** One policy seam for the future configurable active-turn default action. */ +export function resolveComposerDispatchMode(input: { + readonly phase: SessionPhase; + readonly queueModifier: boolean; + readonly activeTurnDefault?: ActiveTurnComposerAction; +}): ComposerDispatchMode { + if (input.phase !== "running") return "auto"; + if (input.queueModifier) return "queue"; + return input.activeTurnDefault ?? "steer"; +} diff --git a/apps/web/src/lib/threadRelationships.test.ts b/apps/web/src/lib/threadRelationships.test.ts new file mode 100644 index 0000000000..f00c37def1 --- /dev/null +++ b/apps/web/src/lib/threadRelationships.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vite-plus/test"; +import { ThreadId } from "@t3tools/contracts"; + +import { + deriveThreadRelationshipGraph, + relatedThreadIds, + walkThreadRelationships, +} from "./threadRelationships"; + +describe("thread relationships", () => { + it("keeps missing parents and cycles navigable without recursive traversal", () => { + const root = ThreadId.make("thread-root"); + const child = ThreadId.make("thread-child"); + const missing = ThreadId.make("thread-missing"); + const graph = deriveThreadRelationshipGraph({ + threads: [ + { + id: root, + title: "Root", + status: "completed", + forkedFrom: { type: "run", threadId: child, runId: "run-cycle" }, + lineage: { rootThreadId: root, parentThreadId: child, relationshipToParent: "fork" }, + }, + { + id: child, + title: "Child", + status: "completed", + forkedFrom: { type: "run", threadId: missing, runId: "run-missing" }, + lineage: { rootThreadId: root, parentThreadId: missing, relationshipToParent: "fork" }, + }, + ] as never, + projection: null, + }); + + expect(graph.nodes.get(missing)?.missing).toBe(true); + expect(relatedThreadIds(graph, root)).toEqual([child]); + expect(relatedThreadIds(graph, child)).toEqual([root, missing]); + expect( + walkThreadRelationships(graph, root).map(({ threadId, depth }) => [threadId, depth]), + ).toEqual([ + [child, 1], + [missing, 2], + ]); + }); +}); diff --git a/apps/web/src/lib/threadRelationships.ts b/apps/web/src/lib/threadRelationships.ts new file mode 100644 index 0000000000..c126389c9b --- /dev/null +++ b/apps/web/src/lib/threadRelationships.ts @@ -0,0 +1,139 @@ +import type { + OrchestrationV2ThreadProjection, + OrchestrationV2ThreadShell, + ThreadId, +} from "@t3tools/contracts"; + +export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer"; + +export interface ThreadRelationshipNode { + readonly threadId: ThreadId; + readonly thread: OrchestrationV2ThreadShell | null; + readonly missing: boolean; +} + +export interface ThreadRelationshipEdge { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly kind: ThreadRelationshipKind; + readonly status: string | null; +} + +export interface ThreadRelationshipGraph { + readonly nodes: ReadonlyMap; + readonly edges: ReadonlyArray; +} + +export interface ThreadRelationshipWalkRow { + readonly threadId: ThreadId; + readonly fromThreadId: ThreadId; + readonly depth: number; + readonly edge: ThreadRelationshipEdge; +} + +function edgeKey(edge: ThreadRelationshipEdge): string { + return `${edge.sourceThreadId}\u001f${edge.targetThreadId}\u001f${edge.kind}`; +} + +export function deriveThreadRelationshipGraph(input: { + readonly threads: ReadonlyArray; + readonly projection: OrchestrationV2ThreadProjection | null; +}): ThreadRelationshipGraph { + const nodes = new Map( + input.threads.map( + (thread) => [thread.id, { threadId: thread.id, thread, missing: false }] as const, + ), + ); + const edgesByKey = new Map(); + const ensureNode = (threadId: ThreadId) => { + if (!nodes.has(threadId)) { + nodes.set(threadId, { threadId, thread: null, missing: true }); + } + }; + const addEdge = (edge: ThreadRelationshipEdge) => { + ensureNode(edge.sourceThreadId); + ensureNode(edge.targetThreadId); + edgesByKey.set(edgeKey(edge), edge); + }; + + for (const thread of input.threads) { + const parentThreadId = + thread.forkedFrom?.type === "run" + ? thread.forkedFrom.threadId + : thread.lineage.parentThreadId; + if (parentThreadId === null) continue; + addEdge({ + sourceThreadId: parentThreadId, + targetThreadId: thread.id, + kind: thread.lineage.relationshipToParent === "subagent" ? "subagent" : "fork", + status: thread.status, + }); + } + + if (input.projection !== null) { + const ownerThreadId = input.projection.thread.id; + for (const subagent of input.projection.subagents) { + if (subagent.childThreadId === null) continue; + addEdge({ + sourceThreadId: ownerThreadId, + targetThreadId: subagent.childThreadId, + kind: "subagent", + status: subagent.status, + }); + } + for (const transfer of input.projection.contextTransfers) { + if (transfer.sourceThreadId === transfer.targetThreadId) continue; + addEdge({ + sourceThreadId: transfer.sourceThreadId, + targetThreadId: transfer.targetThreadId, + kind: "transfer", + status: transfer.status, + }); + } + } + + return { nodes, edges: [...edgesByKey.values()] }; +} + +export function relatedThreadIds( + graph: ThreadRelationshipGraph, + threadId: ThreadId, +): ReadonlyArray { + const ids = new Set(); + for (const edge of graph.edges) { + if (edge.sourceThreadId === threadId) ids.add(edge.targetThreadId); + if (edge.targetThreadId === threadId) ids.add(edge.sourceThreadId); + } + return [...ids]; +} + +export function walkThreadRelationships( + graph: ThreadRelationshipGraph, + threadId: ThreadId, +): ReadonlyArray { + const visited = new Set([threadId]); + const pending: Array<{ readonly threadId: ThreadId; readonly depth: number }> = [ + { threadId, depth: 0 }, + ]; + const rows: ThreadRelationshipWalkRow[] = []; + + for (let index = 0; index < pending.length; index += 1) { + const current = pending[index]; + if (current === undefined) continue; + for (const edge of graph.edges) { + const relatedId = + edge.sourceThreadId === current.threadId + ? edge.targetThreadId + : edge.targetThreadId === current.threadId + ? edge.sourceThreadId + : null; + if (relatedId === null || visited.has(relatedId)) continue; + visited.add(relatedId); + const depth = current.depth + 1; + rows.push({ threadId: relatedId, fromThreadId: current.threadId, depth, edge }); + pending.push({ threadId: relatedId, depth }); + } + } + + return rows; +} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index c7e5293cfc..5e0580b8c6 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -13,6 +13,7 @@ import { describe, expect, it } from "vite-plus/test"; import { deriveTimelineEntries, deriveTimelineEntriesFromVisibleTurnItems, + deriveRevertTurnCountByUserMessageId, findLatestProposedPlan, isLatestRunSettled, } from "./session-logic"; @@ -78,6 +79,66 @@ describe("V2 session presentation", () => { expect(entries.map((entry) => entry.kind)).toEqual(["message"]); }); + it("assigns run rollback to the turn-start message instead of a later steer", () => { + const runId = RunId.make("run-steered"); + const turnStartMessageId = MessageId.make("message-turn-start"); + const steerMessageId = MessageId.make("message-steer"); + const assistantMessageId = MessageId.make("message-assistant"); + const timelineEntries = deriveTimelineEntries( + [ + { + id: turnStartMessageId, + role: "user", + text: "Start", + runId, + inputIntent: "turn_start", + streaming: false, + createdAt: "2026-06-20T00:00:00.000Z", + updatedAt: "2026-06-20T00:00:00.000Z", + }, + { + id: steerMessageId, + role: "user", + text: "Steer", + runId, + inputIntent: "steer", + streaming: false, + createdAt: "2026-06-20T00:00:01.000Z", + updatedAt: "2026-06-20T00:00:01.000Z", + }, + { + id: assistantMessageId, + role: "assistant", + text: "Done", + runId, + streaming: false, + createdAt: "2026-06-20T00:00:02.000Z", + updatedAt: "2026-06-20T00:00:02.000Z", + }, + ], + [], + [], + ); + + const targets = deriveRevertTurnCountByUserMessageId({ + timelineEntries, + checkpoints: [ + { + runId, + checkpointTurnCount: 1, + checkpointRef: "checkpoint-run-1" as never, + status: "ready", + files: [], + assistantMessageId, + completedAt: "2026-06-20T00:00:03.000Z", + }, + ], + }); + + expect([...targets]).toEqual([[turnStartMessageId, 0]]); + expect(targets.has(steerMessageId)).toBe(false); + }); + it("uses visible turn item order and keeps interruption lifecycle entries standalone", () => { const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); const threadId = ThreadId.make("thread-visible"); @@ -125,11 +186,22 @@ describe("V2 session presentation", () => { type: "run_interrupt_result" as const, message: "Stopped", } satisfies OrchestrationV2TurnItem; + const todoItem = { + ...base("item-todo", 4), + type: "todo_list" as const, + planId: PlanId.make("plan-visible"), + explanation: "Keep task detail in the Tasks panel", + steps: [ + { id: "step-1", text: "First", status: "completed" as const }, + { id: "step-2", text: "Second", status: "pending" as const }, + ], + } satisfies OrchestrationV2TurnItem; const visibleTurnItems: ReadonlyArray = [ userItem, requestItem, commandItem, resultItem, + todoItem, ].map((item, position) => ({ position, visibility: "local" as const, @@ -148,12 +220,25 @@ describe("V2 session presentation", () => { ["event", requestItem.id], ["work", commandItem.id], ["event", resultItem.id], + ["work", todoItem.id], ]); const commandEntry = entries[2]; + const userEntry = entries[0]; + expect(userEntry?.kind).toBe("message"); + if (userEntry?.kind === "message") { + expect(userEntry.projectedItem).toBe(visibleTurnItems[0]); + expect(userEntry.message.inputIntent).toBe("turn_start"); + } expect(commandEntry?.kind).toBe("work"); if (commandEntry?.kind === "work") { expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]); expect(commandEntry.entry.structuredPayload).toBe(commandItem); } + const todoEntry = entries[4]; + expect(todoEntry?.kind).toBe("work"); + if (todoEntry?.kind === "work") { + expect(todoEntry.entry.label).toBe("Updated tasks"); + expect(todoEntry.entry.detail).toBe("1/2 completed"); + } }); }); diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 65a0c66e26..9bbb2d52a1 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -89,6 +89,7 @@ export type TimelineEntry = readonly kind: "message"; readonly createdAt: string; readonly message: ChatMessage; + readonly projectedItem?: OrchestrationV2ProjectedTurnItem; } | { readonly id: string; @@ -324,7 +325,6 @@ const STANDALONE_V2_ITEM_TYPES = new Set file.path), toolData: item, }; + case "todo_list": { + const completed = item.steps.filter((step) => step.status === "completed").length; + return { + ...common, + label: title ?? "Updated tasks", + detail: `${completed}/${item.steps.length} completed`, + toolData: item, + }; + } case "dynamic_tool": return { ...common, @@ -478,9 +487,10 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: { streaming: item.type === "assistant_message" && item.streaming, createdAt, updatedAt: DateTime.formatIso(item.updatedAt), + ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}), }; committedMessageIds.add(message.id); - entries.push({ id: message.id, kind: "message", createdAt, message }); + entries.push({ id: message.id, kind: "message", createdAt, message, projectedItem: row }); continue; } @@ -531,6 +541,30 @@ export function inferCheckpointTurnCountByRunId( ); } +export function deriveRevertTurnCountByUserMessageId(input: { + readonly timelineEntries: ReadonlyArray; + readonly checkpoints: ReadonlyArray; +}): Map { + const readyCheckpointByRunId = new Map(); + for (const checkpoint of input.checkpoints) { + if (checkpoint.status === "ready") { + readyCheckpointByRunId.set(checkpoint.runId, checkpoint); + } + } + const byUserMessageId = new Map(); + for (const entry of input.timelineEntries) { + if (entry.kind !== "message" || entry.message.role !== "user") continue; + if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") { + continue; + } + if (entry.message.runId === null) continue; + const checkpoint = readyCheckpointByRunId.get(entry.message.runId); + if (checkpoint === undefined) continue; + byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1)); + } + return byUserMessageId; +} + export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase { if (runtime === null) return "disconnected"; if (runtime.status === "starting" || runtime.status === "queued") return "connecting"; diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 91a72a8def..f8ac362c7e 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -3,6 +3,7 @@ import type { EnvironmentProject, EnvironmentThread, EnvironmentThreadShell, + ScopedThreadProjection, ThreadConversationMessage, ThreadProposedPlan, ThreadRuntimeSummary, @@ -41,8 +42,8 @@ const EMPTY_THREAD_SHELL_ATOM = Atom.make(null).p const EMPTY_THREAD_DETAIL_ATOM = Atom.make(null).pipe( Atom.withLabel("web-thread-detail:empty"), ); -const EMPTY_THREAD_STATUS_ATOM = Atom.make("empty").pipe( - Atom.withLabel("web-thread-status:empty"), +const EMPTY_SCOPED_THREAD_PROJECTION_ATOM = Atom.make(null).pipe( + Atom.withLabel("web-scoped-thread-projection:empty"), ); const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe( Atom.withLabel("web-thread-messages:empty"), @@ -143,22 +144,12 @@ export function useThreadDetail(ref: ScopedThreadRef | null): EnvironmentThread ); } -export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus { +export function useThreadProjection(ref: ScopedThreadRef | null): ScopedThreadProjection | null { return useAtomValue( - ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref), + ref === null ? EMPTY_SCOPED_THREAD_PROJECTION_ATOM : environmentThreadDetails.threadAtom(ref), ); } -export function resolveThreadDetailRef( - ref: ScopedThreadRef | null, - options: { - shellExists: boolean; - waitForShell: boolean; - }, -): ScopedThreadRef | null { - return ref !== null && (!options.waitForShell || options.shellExists) ? ref : null; -} - /** Detail collections composed with shell-authoritative thread/workspace metadata. */ export function useThread( ref: ScopedThreadRef | null, diff --git a/apps/web/src/state/v2ItemSupport.ts b/apps/web/src/state/v2ItemSupport.ts new file mode 100644 index 0000000000..1c985bdfd6 --- /dev/null +++ b/apps/web/src/state/v2ItemSupport.ts @@ -0,0 +1,189 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { + EnvironmentId, + OrchestrationV2ThreadProjection, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { Atom } from "effect/unstable/reactivity"; + +import { environmentThreadDetails } from "./threads"; + +type Projection = OrchestrationV2ThreadProjection; + +export interface V2ItemSupport { + readonly item: Projection["turnItems"][number] | null; + readonly run: Projection["runs"][number] | null; + readonly attempts: ReadonlyArray; + readonly node: Projection["nodes"][number] | null; + readonly providerSession: Projection["providerSessions"][number] | null; + readonly providerThread: Projection["providerThreads"][number] | null; + readonly providerTurn: Projection["providerTurns"][number] | null; + readonly runtimeRequest: Projection["runtimeRequests"][number] | null; + readonly checkpoint: Projection["checkpoints"][number] | null; + readonly subagent: Projection["subagents"][number] | null; + readonly contextHandoff: Projection["contextHandoffs"][number] | null; + readonly contextTransfer: Projection["contextTransfers"][number] | null; +} + +const EMPTY_SUPPORT: V2ItemSupport = Object.freeze({ + item: null, + run: null, + attempts: Object.freeze([]), + node: null, + providerSession: null, + providerThread: null, + providerTurn: null, + runtimeRequest: null, + checkpoint: null, + subagent: null, + contextHandoff: null, + contextTransfer: null, +}); + +function supportKey(input: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; +}): string { + return JSON.stringify(input); +} + +function parseSupportKey(key: string): { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; +} { + return JSON.parse(key) as { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; + }; +} + +function sameEntities(left: ReadonlyArray, right: ReadonlyArray): boolean { + return left.length === right.length && left.every((value, index) => value === right[index]); +} + +function sameSupport(left: V2ItemSupport, right: V2ItemSupport): boolean { + return ( + left.item === right.item && + left.run === right.run && + sameEntities(left.attempts, right.attempts) && + left.node === right.node && + left.providerSession === right.providerSession && + left.providerThread === right.providerThread && + left.providerTurn === right.providerTurn && + left.runtimeRequest === right.runtimeRequest && + left.checkpoint === right.checkpoint && + left.subagent === right.subagent && + left.contextHandoff === right.contextHandoff && + left.contextTransfer === right.contextTransfer + ); +} + +const itemSupportAtomFamily = Atom.family((key: string) => { + const target = parseSupportKey(key); + const ref = scopeThreadRef(target.environmentId, target.threadId); + let previous = EMPTY_SUPPORT; + return Atom.make((get): V2ItemSupport => { + const scoped = get(environmentThreadDetails.threadAtom(ref)); + if (scoped === null) return EMPTY_SUPPORT; + const projection = scoped.projection; + const item = + projection.turnItems.find((candidate) => candidate.id === target.itemId) ?? + projection.visibleTurnItems.find((candidate) => candidate.sourceItemId === target.itemId) + ?.item ?? + null; + if (item === null) return EMPTY_SUPPORT; + const run = + item.runId === null + ? null + : (projection.runs.find((candidate) => candidate.id === item.runId) ?? null); + const attempts = + item.runId === null + ? EMPTY_SUPPORT.attempts + : projection.attempts.filter((candidate) => candidate.runId === item.runId); + const node = + item.nodeId === null + ? null + : (projection.nodes.find((candidate) => candidate.id === item.nodeId) ?? null); + const providerThread = + item.providerThreadId === null + ? null + : (projection.providerThreads.find((candidate) => candidate.id === item.providerThreadId) ?? + null); + const providerSession = + providerThread?.providerSessionId == null + ? null + : (projection.providerSessions.find( + (candidate) => candidate.id === providerThread.providerSessionId, + ) ?? null); + const providerTurn = + item.providerTurnId === null + ? null + : (projection.providerTurns.find((candidate) => candidate.id === item.providerTurnId) ?? + null); + const requestId = + item.type === "approval_request" || item.type === "user_input_request" + ? item.requestId + : node?.runtimeRequestId; + const runtimeRequest = + requestId == null + ? null + : (projection.runtimeRequests.find((candidate) => candidate.id === requestId) ?? null); + const checkpoint = + item.type === "checkpoint" + ? (projection.checkpoints.find((candidate) => candidate.id === item.checkpointId) ?? null) + : null; + const subagent = + item.type === "subagent" + ? (projection.subagents.find((candidate) => candidate.id === item.subagentId) ?? null) + : null; + const contextHandoff = + item.type === "handoff" + ? (projection.contextHandoffs.find((candidate) => candidate.id === item.contextHandoffId) ?? + null) + : null; + const contextTransfer = + contextHandoff?.transferId == null + ? null + : (projection.contextTransfers.find( + (candidate) => candidate.id === contextHandoff.transferId, + ) ?? null); + const next: V2ItemSupport = { + item, + run, + attempts, + node, + providerSession, + providerThread, + providerTurn, + runtimeRequest, + checkpoint, + subagent, + contextHandoff, + contextTransfer, + }; + if (sameSupport(previous, next)) return previous; + previous = next; + return next; + }).pipe(Atom.withLabel(`web-v2-item-support:${key}`)); +}); + +export function useV2ItemSupport(input: { + readonly environmentId: EnvironmentId; + readonly sourceThreadId: ThreadId; + readonly sourceItemId: TurnItemId; +}): V2ItemSupport { + return useAtomValue( + itemSupportAtomFamily( + supportKey({ + environmentId: input.environmentId, + threadId: input.sourceThreadId, + itemId: input.sourceItemId, + }), + ), + ); +} diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index 20af209a7b..f918b3f99f 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -1,5 +1,6 @@ import type { ChatImageAttachment as ContractChatImageAttachment, + OrchestrationV2UserMessageInputIntent, ProjectScript as ContractProjectScript, ProviderInteractionMode, RuntimeMode, @@ -38,6 +39,7 @@ export type ChatAttachment = ChatImageAttachment; export interface ChatMessage extends Omit { readonly attachments?: ReadonlyArray | undefined; + readonly inputIntent?: OrchestrationV2UserMessageInputIntent | undefined; } export type ProposedPlan = ThreadProposedPlan; diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index 50b57124ab..be5950e427 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -1,7 +1,11 @@ import { + CheckpointId, + CheckpointRef, + CheckpointScopeId, CommandId, EnvironmentId, MessageId, + NodeId, ORCHESTRATION_V2_WS_METHODS, PlanId, ProjectId, @@ -30,8 +34,18 @@ import { import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as RpcSession from "../rpc/session.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; -import { v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts"; -import { archiveThread, createProject, startThreadTurn } from "./commands.ts"; +import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts"; +import { + archiveThread, + createProject, + forkThreadFromRun, + mergeThreadBack, + promoteQueuedRun, + reorderQueuedRun, + revertThreadCheckpoint, + startThreadTurn, + updateThreadMetadata, +} from "./commands.ts"; const TEST_CRYPTO_LAYER = Layer.succeed( Crypto.Crypto, @@ -149,6 +163,50 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), ); + it.effect("resolves run ordinal zero to the persisted thread-start checkpoint", () => + Effect.gen(function* () { + const scopeId = CheckpointScopeId.make("checkpoint-scope-root"); + const checkpointId = CheckpointId.make("checkpoint-thread-start"); + const projection: OrchestrationV2ThreadProjection = { + ...v2Projection, + checkpoints: [ + { + id: checkpointId, + threadId: v2ThreadId, + scopeId, + runId: null, + nodeId: NodeId.make("node-run-1"), + parentCheckpointId: null, + ordinalWithinScope: 0, + appRunOrdinal: null, + ref: CheckpointRef.make("refs/t3/thread-start"), + status: "ready", + files: [], + capturedAt: v2Now, + }, + ], + }; + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [], projection }); + + yield* revertThreadCheckpoint({ + commandId: CommandId.make("rollback-thread-start"), + threadId: v2ThreadId, + turnCount: 0, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(commands).toEqual([ + { + type: "checkpoint.rollback", + commandId: "rollback-thread-start", + threadId: v2ThreadId, + scopeId, + checkpointId, + }, + ]); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + it.effect("preserves plan implementation provenance on V2 runs", () => Effect.gen(function* () { const commands: OrchestrationV2Command[] = []; @@ -325,4 +383,78 @@ describe("V2 environment commands", () => { } }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), ); + + it.effect( + "dispatches V2-native relationship and queue commands without compatibility shaping", + () => + Effect.gen(function* () { + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [] }); + const provide = Effect.provideService( + EnvironmentSupervisor.EnvironmentSupervisor, + supervisor, + ); + + yield* forkThreadFromRun({ + commandId: CommandId.make("fork"), + sourceThreadId: v2ThreadId, + targetThreadId: ThreadId.make("thread-fork"), + runId: RunId.make("run-1"), + }).pipe(provide); + yield* mergeThreadBack({ + commandId: CommandId.make("merge"), + sourceThreadId: ThreadId.make("thread-fork"), + targetThreadId: v2ThreadId, + runId: RunId.make("run-2"), + }).pipe(provide); + yield* reorderQueuedRun({ + commandId: CommandId.make("reorder"), + threadId: v2ThreadId, + runId: RunId.make("run-3"), + beforeRunId: RunId.make("run-4"), + }).pipe(provide); + yield* promoteQueuedRun({ + commandId: CommandId.make("promote"), + threadId: v2ThreadId, + queuedRunId: RunId.make("run-3"), + targetRunId: RunId.make("run-active"), + }).pipe(provide); + + expect(commands).toMatchObject([ + { type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } }, + { type: "thread.merge_back", sourcePoint: { type: "run", runId: "run-2" } }, + { type: "queued-run.reorder", runId: "run-3", beforeRunId: "run-4" }, + { + type: "queued-message.promote-to-steer", + queuedRunId: "run-3", + targetRunId: "run-active", + }, + ]); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + + it.effect("uses provider.switch when model selection changes provider instance", () => + Effect.gen(function* () { + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [] }); + + yield* updateThreadMetadata({ + commandId: CommandId.make("switch-provider"), + threadId: v2ThreadId, + modelSelection: { + instanceId: ProviderInstanceId.make("claude"), + model: "claude-sonnet-4-6", + }, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(commands).toEqual([ + { + type: "provider.switch", + commandId: "switch-provider", + threadId: v2ThreadId, + modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" }, + }, + ]); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); }); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index e660ac44db..2fb9d5b601 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1,6 +1,7 @@ import { CommandId, ORCHESTRATION_V2_WS_METHODS, + OrchestrationV2CheckpointUnavailableError, WS_METHODS, type ChatAttachment, type MessageId, @@ -146,6 +147,29 @@ export interface RevertThreadCheckpointInput extends ThreadCommandInput { export type StopThreadSessionInput = ThreadCommandInput; +export interface ForkThreadFromRunInput extends CommandMetadata { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly runId: RunId; + readonly title?: string; +} + +export interface MergeThreadBackInput extends CommandMetadata { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly runId: RunId; +} + +export interface ReorderQueuedRunInput extends ThreadCommandInput { + readonly runId: RunId; + readonly beforeRunId: RunId | null; +} + +export interface PromoteQueuedRunInput extends ThreadCommandInput { + readonly queuedRunId: RunId; + readonly targetRunId: RunId; +} + const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* ( input: CommandMetadata, ) { @@ -330,8 +354,13 @@ export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadM }); } if (input.modelSelection !== undefined) { + const projection = yield* getProjection(input.threadId); + const type = + projection.thread.providerInstanceId === input.modelSelection.instanceId + ? ("thread.model-selection.set" as const) + : ("provider.switch" as const); result = yield* dispatch({ - type: "thread.model-selection.set", + type, commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`), threadId: input.threadId, modelSelection: input.modelSelection, @@ -517,8 +546,21 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea projection.checkpoints.find( (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId, ) ?? - projection.checkpoints.findLast((candidate) => candidate.appRunOrdinal === input.turnCount); - if (checkpoint === undefined) return { sequence: 0 }; + projection.checkpoints.findLast((candidate) => + input.turnCount === 0 + ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null + : candidate.appRunOrdinal === input.turnCount, + ); + if (checkpoint === undefined || checkpoint.status !== "ready") { + const target = + input.checkpointId === undefined + ? `run ordinal ${input.turnCount ?? "unknown"}` + : `checkpoint ${input.checkpointId}`; + return yield* new OrchestrationV2CheckpointUnavailableError({ + threadId: input.threadId, + target, + }); + } return yield* dispatch({ type: "checkpoint.rollback", commandId: yield* allocateCommandId(input), @@ -546,3 +588,56 @@ export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSessio } return result; }); + +export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* ( + input: ForkThreadFromRunInput, +) { + return yield* dispatch({ + type: "thread.fork", + commandId: yield* allocateCommandId(input), + createdBy: "user", + creationSource: input.creationSource ?? "web", + sourceThreadId: input.sourceThreadId, + targetThreadId: input.targetThreadId, + sourcePoint: { type: "run", runId: input.runId }, + ...(input.title === undefined ? {} : { title: input.title }), + }); +}); + +export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* ( + input: MergeThreadBackInput, +) { + return yield* dispatch({ + type: "thread.merge_back", + commandId: yield* allocateCommandId(input), + createdBy: "user", + creationSource: input.creationSource ?? "web", + sourceThreadId: input.sourceThreadId, + targetThreadId: input.targetThreadId, + sourcePoint: { type: "run", runId: input.runId }, + }); +}); + +export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* ( + input: ReorderQueuedRunInput, +) { + return yield* dispatch({ + type: "queued-run.reorder", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + runId: input.runId, + beforeRunId: input.beforeRunId, + }); +}); + +export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( + input: PromoteQueuedRunInput, +) { + return yield* dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }); +}); diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index def79fa417..412f51a62d 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -7,6 +7,10 @@ import { type CreateThreadInput, type DeleteThreadInput, type InterruptThreadTurnInput, + type ForkThreadFromRunInput, + type MergeThreadBackInput, + type PromoteQueuedRunInput, + type ReorderQueuedRunInput, type RespondToThreadApprovalInput, type RespondToThreadUserInputInput, type RevertThreadCheckpointInput, @@ -24,6 +28,10 @@ import { createThread, deleteThread, interruptThreadTurn, + forkThreadFromRun, + mergeThreadBack, + promoteQueuedRun, + reorderQueuedRun, respondToThreadApproval, respondToThreadUserInput, revertThreadCheckpoint, @@ -45,6 +53,10 @@ export type { CreateThreadInput, DeleteThreadInput, InterruptThreadTurnInput, + ForkThreadFromRunInput, + MergeThreadBackInput, + PromoteQueuedRunInput, + ReorderQueuedRunInput, RespondToThreadApprovalInput, RespondToThreadUserInputInput, RevertThreadCheckpointInput, @@ -173,5 +185,36 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency, }), + forkFromRun: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:fork-from-run", + execute: (input: ForkThreadFromRunInput) => forkThreadFromRun(input), + scheduler, + concurrency: { + mode: "serial", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]), + }, + }), + mergeBack: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:merge-back", + execute: (input: MergeThreadBackInput) => mergeThreadBack(input), + scheduler, + concurrency: { + mode: "serial", + key: ({ environmentId, input }) => + JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]), + }, + }), + reorderQueuedRun: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:reorder-queued-run", + execute: (input: ReorderQueuedRunInput) => reorderQueuedRun(input), + scheduler, + concurrency, + }), + promoteQueuedRun: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:promote-queued-run", + execute: (input: PromoteQueuedRunInput) => promoteQueuedRun(input), + scheduler, + concurrency, + }), }; } diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index abbd120486..43293a2c10 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -649,7 +649,7 @@ export const OrchestrationV2Checkpoint = Schema.Struct({ runId: Schema.NullOr(RunId), nodeId: NodeId, parentCheckpointId: Schema.NullOr(CheckpointId), - ordinalWithinScope: PositiveInt, + ordinalWithinScope: NonNegativeInt, appRunOrdinal: Schema.NullOr(PositiveInt), ref: CheckpointRef, status: Schema.Literals(["ready", "missing", "error", "stale"]), @@ -666,6 +666,18 @@ export const OrchestrationV2CheckpointRollbackRequest = Schema.Struct({ export type OrchestrationV2CheckpointRollbackRequest = typeof OrchestrationV2CheckpointRollbackRequest.Type; +export class OrchestrationV2CheckpointUnavailableError extends Schema.TaggedErrorClass()( + "OrchestrationV2CheckpointUnavailableError", + { + threadId: ThreadId, + target: Schema.String, + }, +) { + override get message(): string { + return `Rollback target ${this.target} is unavailable for thread ${this.threadId}.`; + } +} + export const OrchestrationV2TurnItemStatus = Schema.Literals([ "pending", "running",