diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 7469d8a672255..1d97c6c6cae4c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -7088,6 +7088,84 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // t4 fork (AI-96): AI-85 on 2026-11-12 typed two messages while a command ran, then pressed + // Stop; Claude still held them queued and the closed CLI dropped them. + it.effect("Stop marks steers Claude never started as dropped and the rest as read", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + freshQueueOnReopen: true, + }); + const now = yield* DateTime.now; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-stop-unread-steer"), + text: "Run the ARM build check.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }); + const steer = (messageId: string, text: string) => + harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(messageId), + text, + attachments: [], + }, + }); + yield* steer("message-read-steer", "Commands that need files outside the worktree?"); + yield* steer("message-unread-steer", "I've decided against arm if it's that heavy"); + const [readUuid, unreadUuid] = harness.offeredMessages.slice(1).map((m) => m.uuid); + assert.isDefined(readUuid); + assert.isDefined(unreadUuid); + assert.notEqual(readUuid, unreadUuid); + const lifecycle = (commandUuid: string, state: string) => + harness.offerAndWait({ + type: "command_lifecycle", + command_uuid: commandUuid, + state, + uuid: `${commandUuid.slice(0, -4)}ffff`, + session_id: "session-claude-stop-unread-steer", + } as never); + yield* lifecycle(readUuid!, "queued"); + yield* lifecycle(unreadUuid!, "queued"); + yield* lifecycle(readUuid!, "started"); + + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, + }); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + + const steerStatuses = (messageId: string) => + harness.events.flatMap((event) => + event.type === "steer.updated" && event.messageId === messageId ? [event.status] : [], + ); + assert.deepEqual(steerStatuses("message-read-steer"), ["pending", "completed"]); + assert.deepEqual(steerStatuses("message-unread-steer"), ["pending", "cancelled"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("an interrupted turn with no assistant output keeps the rolled-back head", () => Effect.gen(function* () { const harness = yield* makeWakeHarnessWithOptions({ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5bf5ba1e230dc..5472b55bb067a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -125,6 +125,7 @@ import { type ProviderInstanceId, type ProviderRequestKind, type ProviderUserInputAnswers, + type MessageId, type ProviderThreadId, type RunId, type ThreadId, @@ -5203,6 +5204,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); const interruptedTurns = yield* Ref.make(new Set()); const steeredTurns = yield* Ref.make(new Set()); + // t4 fork (AI-96): steers Claude has queued and not started, by prompt uuid. Claude + // holds a steer until the command it runs returns; Stop closes the CLI and drops it. + const unreadSteers = new Map< + string, + { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly messageId: MessageId; + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; + } + >(); const queryContext = yield* Ref.make(null); // Wake buffers replay result frames, so ledger growth is measured once on arrival. const resultLedgerUsage = new WeakMap(); @@ -8024,6 +8036,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); } input.context.compaction = null; + // t4 fork (AI-96): a turn that ends normally runs what Claude still holds; one that + // is stopped or fails drops it, and T4UnreadSteerReactor sends it again. + for (const [uuid, steer] of unreadSteers) { + if (steer.providerTurnId !== input.context.providerTurnId) continue; + unreadSteers.delete(uuid); + yield* emitProviderEvent({ + type: "steer.updated", + driver: CLAUDE_PROVIDER, + threadId: steer.threadId, + runId: steer.runId, + messageId: steer.messageId, + status: input.status === "completed" ? "completed" : "cancelled", + }); + } if (input.status !== "completed") { const liveQuery = yield* Ref.get(queryContext); for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) { @@ -10319,6 +10345,30 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const message = input.message; const context = yield* Ref.get(activeTurn); const liveQuery = yield* Ref.get(queryContext); + // t4 fork (AI-96): Claude took a queued steer. + if (unreadSteers.size > 0) { + const lifecycle = claudePromptLifecycle(message); + const read = [ + ...claudeEchoedPromptUuids(message), + ...(lifecycle !== null && lifecycle.state !== "queued" ? [lifecycle.uuid] : []), + ]; + for (const uuid of read) { + const steer = unreadSteers.get(uuid); + if (steer === undefined) continue; + unreadSteers.delete(uuid); + yield* emitProviderEvent({ + type: "steer.updated", + driver: CLAUDE_PROVIDER, + threadId: steer.threadId, + runId: steer.runId, + messageId: steer.messageId, + status: + lifecycle?.uuid === uuid && lifecycle.state === "cancelled" + ? "cancelled" + : "completed", + }); + } + } if ( context?.promptUuid === null && liveQuery?.query === input.query && @@ -11899,6 +11949,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), persistAttachmentBudget(existing.nativeThreadId), ); + // t4 fork (AI-96): a uuid lets Claude's lifecycle frames say when it reads the steer. + const steerUuid = yield* random + .uuidV4() + .pipe(Effect.filterOrFail(isClaudePromptUuid), Effect.option); const userMessage = yield* makeClaudeUserMessageWithAttachments({ text: applyClaudePromptEffortPrefix( turnInput.message.text, @@ -11907,6 +11961,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), attachments: turnInput.message.attachments, priority: "now", + ...(Option.isSome(steerUuid) ? { uuid: steerUuid.value } : {}), attachmentsDir, fileSystem, pdfReservation, @@ -11933,6 +11988,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.add(turnInput.providerTurnId); return next; }); + // Recorded before the offer: Claude can report reading it before the offer returns. + if (Option.isSome(steerUuid)) { + unreadSteers.set(steerUuid.value, { + threadId: turnInput.threadId, + runId: turnInput.runId, + messageId: turnInput.message.messageId, + providerTurnId: turnInput.providerTurnId, + }); + } yield* Effect.uninterruptibleMask((restore) => restore( existing.query.offer(userMessage, () => { @@ -11945,7 +12009,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), ), ), + ).pipe( + Effect.onError(() => + Effect.sync(() => { + if (Option.isSome(steerUuid)) unreadSteers.delete(steerUuid.value); + }), + ), ); + if (Option.isSome(steerUuid) && unreadSteers.has(steerUuid.value)) { + yield* emitProviderEvent({ + type: "steer.updated", + driver: CLAUDE_PROVIDER, + threadId: turnInput.threadId, + runId: turnInput.runId, + messageId: turnInput.message.messageId, + status: "pending", + }); + } }, (effect, turnInput) => effect.pipe( diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index feed4de75e2ed..9b162282df256 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,6 +8,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as T4UnreadSteerReactor from "./t4/T4UnreadSteerReactor.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -683,6 +684,13 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + // t4 fork (AI-96): a steer Stop dropped unread is sent again as the next turn. + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* T4UnreadSteerReactor.T4UnreadSteerReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(T4UnreadSteerReactor.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, diff --git a/apps/server/src/t4/T4UnreadSteerReactor.test.ts b/apps/server/src/t4/T4UnreadSteerReactor.test.ts new file mode 100644 index 0000000000000..a0067b67dd0c0 --- /dev/null +++ b/apps/server/src/t4/T4UnreadSteerReactor.test.ts @@ -0,0 +1,103 @@ +import { assert, it } from "@effect/vitest"; +import { + MessageId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { T4UnreadSteerReactor, UNREAD_STEER_NOTE, layer } from "./T4UnreadSteerReactor.ts"; + +const threadId = ThreadId.make("thread:unread-steer"); +const messageId = MessageId.make("message:typed-mid-turn"); +const typed = "I've decided against arm if it's that heavy"; + +const steerEvent = (payload: Record) => + ({ + type: "turn-item.updated", + threadId, + runId: RunId.make("run:stopped"), + payload: { + id: TurnItemId.make(`turn-item:message:${messageId}`), + threadId, + runId: RunId.make("run:stopped"), + type: "user_message", + messageId, + inputIntent: "steer", + status: "cancelled", + ...payload, + }, + }) as unknown as OrchestrationV2DomainEvent; + +const run = ( + events: ReadonlyArray, + thread: { archivedAt: string | null } = { archivedAt: null }, +) => + Effect.gen(function* () { + const dispatched: Array[0]> = []; + const reactor = yield* T4UnreadSteerReactor.pipe( + Effect.provide( + layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: (command) => { + dispatched.push(command); + return Effect.succeed({} as never); + }, + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThread: () => + Effect.succeed({ id: threadId, deletedAt: null, ...thread } as never), + getMessagesById: (_threadId, ids) => + Effect.succeed( + new Map( + ids.map((id) => [id, { id, text: typed, attachments: [] }] as const), + ) as never, + ), + }), + ), + ), + ), + ), + ); + for (const event of events) yield* reactor.handle(event); + return dispatched; + }); + +// AI-85, 2026-11-12: two messages typed while a command ran, then Stop. +it.effect("sends a steer Stop dropped unread as the next turn", () => + Effect.gen(function* () { + const [command, ...rest] = yield* run([steerEvent({})]); + assert.lengthOf(rest, 0); + assert.equal(command?.type, "message.dispatch"); + if (command?.type !== "message.dispatch") return; + assert.equal(command.threadId, threadId); + assert.equal(command.text, `${UNREAD_STEER_NOTE}\n\n${typed}`); + assert.deepEqual(command.dispatchMode, { type: "queue_after_active" }); + // Derived ids: a replayed event dispatches the same command, which T3 dedupes. + assert.equal(command.commandId, `server:t4-unread-steer:${messageId}`); + assert.equal(command.messageId, `message:t4-unread-steer:${messageId}`); + }), +); + +it.effect("leaves read steers, other messages and closed threads alone", () => + Effect.gen(function* () { + assert.lengthOf( + yield* run([ + steerEvent({ status: "completed" }), + steerEvent({ status: "pending" }), + steerEvent({ inputIntent: "turn_start" }), + steerEvent({ type: "assistant_message" }), + ]), + 0, + ); + assert.lengthOf(yield* run([steerEvent({})], { archivedAt: "2026-11-13T00:00:00.000Z" }), 0); + assert.lengthOf(yield* run([steerEvent({ inputIntent: "promoted_queued_to_steer" })]), 1); + }), +); diff --git a/apps/server/src/t4/T4UnreadSteerReactor.ts b/apps/server/src/t4/T4UnreadSteerReactor.ts new file mode 100644 index 0000000000000..80bd6a20de6a7 --- /dev/null +++ b/apps/server/src/t4/T4UnreadSteerReactor.ts @@ -0,0 +1,83 @@ +// t4 fork (AI-96): a steer that Stop dropped unread (`steer.updated` cancelled) is sent +// again as the next turn; Claude holds a steer until its running command returns. +import { CommandId, MessageId, type OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; + +export const UNREAD_STEER_NOTE = + "You were stopped before you read this message, which arrived while your last turn ran:"; + +export class T4UnreadSteerReactor extends Context.Service< + T4UnreadSteerReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/t4/T4UnreadSteerReactor") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + + // Runs for every domain event; all but a dropped steer return at once. + const handle: T4UnreadSteerReactor["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + if (event.type !== "turn-item.updated") return; + const item = event.payload; + if ( + item.type !== "user_message" || + item.status !== "cancelled" || + (item.inputIntent !== "steer" && item.inputIntent !== "promoted_queued_to_steer") + ) { + return; + } + const thread = yield* projections.getThread(item.threadId); + if (thread.archivedAt !== null || thread.deletedAt !== null) return; + const message = (yield* projections.getMessagesById(item.threadId, [item.messageId])).get( + item.messageId, + ); + if (message === undefined) return; + // Ids derive from the dropped message, so a replayed event sends it once. + yield* engine.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:t4-unread-steer:${item.messageId}`), + threadId: item.threadId, + messageId: MessageId.make(`message:t4-unread-steer:${item.messageId}`), + text: `${UNREAD_STEER_NOTE}\n\n${message.text}`, + attachments: message.attachments, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("t4: sending an unread steer again failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ); + + const start: T4UnreadSteerReactor["Service"]["start"] = () => + forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("t4: unread steer event stream failed", { cause }), + ), + ), + ); + + return { start, handle } satisfies T4UnreadSteerReactor["Service"]; +}); + +export const layer = Layer.effect(T4UnreadSteerReactor, make); diff --git a/docs/t4/DESIGN.md b/docs/t4/DESIGN.md index 6f3e5101e2c1e..d0726b5d93a26 100644 --- a/docs/t4/DESIGN.md +++ b/docs/t4/DESIGN.md @@ -120,16 +120,17 @@ Claude adapter switches (environment, set in t4's compose): ## 4. Server jobs -| Job | From | Notes | -| ---------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Wake delivery | `tick_wakes` | T3's `Scheduler`. | -| Settle cancel rule | `tick_settles` | On message dispatch. | -| Release-manager model | `deliver` (`RM_MODEL`) | Every turn delivered to a release manager by these tools runs on `releaseManager.model` within its provider. | -| Stall recovery | `tick_stalled_turns` | 15 min silence (no output, no tool call executing, not waiting on the user) → interrupt + restart note; a second stall within 6 h → stop + push. | -| Orphaned questions | `tick_orphan_questions` | Ported only where V2's own restart handling of pending requests doesn't already cover it (verified first). | -| Interrupted background | `tick_interrupted_background` | Same: V2 already reports background work killed by a restart; ours fills gaps only. | -| Unstarted runs | (new, AI-88) | A run a restart catches before Claude took its prompt (no provider turn) gets `provider-runtime.continue`; it sends that run's own message again, not "continue". Upstream cancelled it and the message (a wake, a handoff) was lost. | -| Limited-thread resume | `cmd_resume` | Operator action: probe one thread, then 3 at a time 60 s apart, release managers first, skipping threads already moving. | +| Job | From | Notes | +| ------------------------ | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Wake delivery | `tick_wakes` | T3's `Scheduler`. | +| Settle cancel rule | `tick_settles` | On message dispatch. | +| Release-manager model | `deliver` (`RM_MODEL`) | Every turn delivered to a release manager by these tools runs on `releaseManager.model` within its provider. | +| Stall recovery | `tick_stalled_turns` | 15 min silence (no output, no tool call executing, not waiting on the user) → interrupt + restart note; a second stall within 6 h → stop + push. | +| Orphaned questions | `tick_orphan_questions` | Ported only where V2's own restart handling of pending requests doesn't already cover it (verified first). | +| Interrupted background | `tick_interrupted_background` | Same: V2 already reports background work killed by a restart; ours fills gaps only. | +| Unstarted runs | (new, AI-88) | A run a restart catches before Claude took its prompt (no provider turn) gets `provider-runtime.continue`; it sends that run's own message again, not "continue". Upstream cancelled it and the message (a wake, a handoff) was lost. | +| Unread steers after Stop | (new, AI-96) | The Claude adapter stamps each steer with a uuid and follows Claude's `command_lifecycle` frames; a steer Claude never started when the turn is stopped or fails is `steer.updated` cancelled, and `T4UnreadSteerReactor` sends it again as the next turn (`queue_after_active`). Claude holds a steer until its running command returns, and Stop closes the CLI with the queue. | +| Limited-thread resume | `cmd_resume` | Operator action: probe one thread, then 3 at a time 60 s apart, release managers first, skipping threads already moving. | ## 5. State