Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
80 changes: 80 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ import {
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderUserInputAnswers,
type MessageId,
type ProviderThreadId,
type RunId,
type ThreadId,
Expand Down Expand Up @@ -5203,6 +5204,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
);
const interruptedTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
const steeredTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
// 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<ClaudeLiveQueryContext | null>(null);
// Wake buffers replay result frames, so ledger growth is measured once on arrival.
const resultLedgerUsage = new WeakMap<SDKMessage, ClaudeLedgerUsage>();
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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, () => {
Expand All @@ -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(
Expand Down
8 changes: 8 additions & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down
103 changes: 103 additions & 0 deletions apps/server/src/t4/T4UnreadSteerReactor.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) =>
({
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<OrchestrationV2DomainEvent>,
thread: { archivedAt: string | null } = { archivedAt: null },
) =>
Effect.gen(function* () {
const dispatched: Array<Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[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);
}),
);
Loading
Loading