14
type OrchestrationV2ProviderTurn,
15
type OrchestrationV2Run,
16
type OrchestrationV2RunAttempt,
17
+ type OrchestrationV2StoredEvent,
18
type OrchestrationV2Subagent,
19
type OrchestrationV2TurnItem,
20
ProviderDriverKind,
29
TurnItemId,
30
} from "@t3tools/contracts";
31
import * as Cause from "effect/Cause";
32
+import * as Clock from "effect/Clock";
33
import * as Exit from "effect/Exit";
34
+import * as Fiber from "effect/Fiber";
35
import * as DateTime from "effect/DateTime";
36
import * as Deferred from "effect/Deferred";
37
+import * as Duration from "effect/Duration";
38
import * as Effect from "effect/Effect";
39
import * as Layer from "effect/Layer";
40
import * as Option from "effect/Option";
41
+import * as Queue from "effect/Queue";
42
import * as Ref from "effect/Ref";
43
import * as Stream from "effect/Stream";
44
+import * as TestClock from "effect/testing/TestClock";
45
import { CodexAppServerRequestError } from "effect-codex-app-server/errors";
46
import { SqlError, classifySqliteError } from "effect/sql/SqlError";
47
53
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
54
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
55
import * as ProjectionStore from "./ProjectionStore.ts";
56
+import * as ProviderCommitBatch from "./ProviderCommitBatch.ts";
57
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
58
import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";
59
import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
1892
}),
1893
);
1894
1895
+it.effect("keeps ingesting while the last stored root snapshot reports pending work", () =>
1896
+ Effect.gen(function* () {
1897
+ // The live probe is already idle, as when it reads adapter state ahead of the queued events.
1898
+ const consumed = yield* Deferred.make<void>();
1899
+ const result = yield* Effect.raceFirst(
1900
+ runBackgroundItemScenario(
1901
+ "root-snapshot-pending-work",
1902
+ (ids) => {
1903
+ const snapshot = (pendingBackgroundWork: boolean) =>
1904
+ ({
1905
+ type: "provider_thread.updated",
1906
+ driver,
1907
+ providerThread: { id: ids.providerThreadId, appThreadId: ids.threadId },
1908
+ pendingBackgroundWork,
1909
+ }) as ProviderAdapter.ProviderAdapterV2Event;
1910
+ return [
1911
+ snapshot(true),
1912
+ rootTerminalEvent(ids, "completed"),
1913
+ backgroundTurnItemEvent(ids, "dynamic_tool", "completed", 1),
1914
+ snapshot(false),
1915
+ ];
1916
+ },
1917
+ {
1918
+ keepEventStreamOpen: true,
1919
+ hasPendingBackgroundWorkForThread: () => Effect.succeed(false),
1920
+ onEventsConsumed: Deferred.succeed(consumed, undefined).pipe(Effect.asVoid),
1921
+ },
1922
+ ).pipe(Effect.asSome),
1923
+ Deferred.await(consumed).pipe(Effect.as(Option.none())),
1924
+ );
1925
+ assert.deepEqual(result, Option.some(["root-finalized", "turn_item:completed"]));
1926
+ }),
1927
+);
1928
+
1929
it.effect("keeps ingesting a child thread's late background item completion", () =>
1930
Effect.gen(function* () {
1931
const observed = yield* runBackgroundItemScenario("bg-child-item", (ids) => [
3733
3734
function runBackgroundItemScenario(
3735
key: string,
3695
- makeEvents: (ids: BackgroundScenarioIds) => ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
3736
+ makeEvents: (
3737
+ ids: BackgroundScenarioIds,
3738
+ ) =>
3739
+ | ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>
3740
+ | Stream.Stream<ProviderAdapter.ProviderAdapterV2Event>,
3741
options?: {
3742
+ readonly onIngest?: (
3743
+ event: ProviderAdapter.ProviderAdapterV2Event,
3744
+ write: { readonly inSharedCommit: boolean },
3745
+ ) => Effect.Effect<void>;
3746
+ // Consumes through the real commit coordinator, as the event sink does.
3747
+ readonly batched?: boolean;
3748
readonly keepEventStreamOpen?: boolean;
3749
readonly hasPendingBackgroundWorkForThread?: (
3750
providerThread: OrchestrationV2ProviderThread,
3770
const previewActivity = yield* PreviewAgentActivity.PreviewAgentActivity.pipe(
3771
Effect.provide(PreviewAgentActivity.layer),
3772
);
3773
+ let inSharedCommit = false;
3774
+ const coordinator =
3775
+ options?.batched === true
3776
+ ? yield* ProviderCommitBatch.make(
3777
+ (work) =>
3778
+ Effect.suspend(() => {
3779
+ inSharedCommit = true;
3780
+ return work;
3781
+ }).pipe(
3782
+ Effect.ensuring(
3783
+ Effect.sync(() => {
3784
+ inSharedCommit = false;
3785
+ }),
3786
+ ),
3787
+ ),
3788
+ true,
3789
+ )
3790
+ : undefined;
3791
const layerTest = RunExecutionService.layer.pipe(
3792
Layer.provide(
3793
Layer.mergeAll(
3796
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
3797
layerTurnItemPositionsTest,
3798
mockEventSink({
3799
+ ...(coordinator === undefined ? {} : { consumeProviderEvents: coordinator.consume }),
3800
write: () => Effect.succeed([]),
3801
writeWithEffects: (input) =>
3802
Effect.gen(function* () {
3814
}),
3815
IdAllocator.layer,
3816
Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
3747
- ingestNormalized: (input) =>
3748
- Effect.gen(function* () {
3817
+ ingestNormalized: (input) => {
3818
+ const write = Effect.gen(function* () {
3819
const event = input.event;
3820
+ yield* options?.onIngest?.(event, { inSharedCommit }) ?? Effect.void;
3821
if (event.type === "turn_item.updated") {
3822
yield* Ref.update(observed, (current) => [
3823
...current,
3830
`subagent:${event.subagent.status}`,
3831
]);
3832
}
3762
- return [];
3763
- }),
3833
+ // Only the count of stored events matters to the run.
3834
+ return event.type === "provider_thread.updated"
3835
+ ? [{} as OrchestrationV2StoredEvent]
3836
+ : [];
3837
+ });
3838
+ // A write outside a batch waits for queued snapshots, as the event sink's does.
3839
+ return coordinator === undefined ? write : coordinator.barrier(write);
3840
+ },
3841
}),
3842
ServerSettings.layerTest(),
3843
),
3857
: { hasPendingBackgroundWorkForThread: options.hasPendingBackgroundWorkForThread }),
3858
subscribeEvents: Effect.gen(function* () {
3859
yield* options?.onSubscribe ?? Effect.void;
3783
- const events = Stream.fromIterable(makeEvents(ids)).pipe(
3860
+ const source = makeEvents(ids);
3861
+ const events = (Stream.isStream(source) ? source : Stream.fromIterable(source)).pipe(
3862
Stream.concat(
3863
Stream.fromEffect(
3864
Effect.andThen(
3925
});
3926
}).pipe(Effect.provide(layerTest));
3927
3850
- const closed = yield* Deferred.await(ingestionDone).pipe(Effect.timeoutOption("2 seconds"));
3851
- assert.isTrue(Option.isSome(closed), "event ingestion fiber did not finish");
3928
+ // No timeout: tests advance the TestClock, which would fire it early.
3929
+ yield* Deferred.await(ingestionDone);
3930
+
3931
return yield* Ref.get(observed);
3932
});
3933
}
3979
);
3980
}),
3981
);
3982
+
3983
+it.effect.each([
3984
+ { name: "on time", wakesEarly: false },
3985
+ // Timers run on the monotonic clock, so one can fire while the wall clock still reads a
3986
+ // millisecond before its deadline.
3987
+ { name: "before the wall clock reaches the deadline", wakesEarly: true },
3988
+])("delivers held text while an open-prompt provider idles, waking $name", ({ wakesEarly }) =>
3989
+ Effect.gen(function* () {
3990
+ const key = `idle-paragraph-${wakesEarly}`;
3991
+ const ids = backgroundScenarioIds(key);
3992
+ const now = yield* DateTime.now;
3993
+ const providerEvents = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3994
+ const delivered = yield* Ref.make<ReadonlyArray<string>>([]);
3995
+ const paragraphDelivered = yield* Deferred.make<void>();
3996
+ const nextParagraphDelivered = yield* Deferred.make<void>();
3997
+ const clock = yield* Clock.Clock;
3998
+ const assistantText = (text: string, streaming: boolean) =>
3999
+ [
4000
+ {
4001
+ type: "message.updated",
4002
+ driver,
4003
+ message: {
4004
+ createdBy: "agent",
4005
+ creationSource: "provider",
4006
+ id: MessageId.make(`message:${key}`),
4007
+ threadId: ids.threadId,
4008
+ runId: ids.runId,
4009
+ nodeId: ids.rootNodeId,
4010
+ role: "assistant",
4011
+ text,
4012
+ attachments: [],
4013
+ streaming,
4014
+ createdAt: now,
4015
+ updatedAt: now,
4016
+ },
4017
+ },
4018
+ {
4019
+ type: "turn_item.updated",
4020
+ driver,
4021
+ turnItem: {
4022
+ ...makeLinkedChildTurnItemFixture({ ids, driver, type: "assistant_message" }),
4023
+ id: ids.itemId,
4024
+ threadId: ids.threadId,
4025
+ runId: ids.runId,
4026
+ nodeId: ids.rootNodeId,
4027
+ providerTurnId: ids.rootProviderTurnId,
4028
+ text,
4029
+ streaming,
4030
+ },
4031
+ },
4032
+ ] as ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>;
4033
+
4034
+ const blockerStarted = yield* Deferred.make<void>();
4035
+ const releaseBlocker = yield* Deferred.make<void>();
4036
+ const blocker = streamedMessageEvent({
4037
+ id: `message:${key}:blocker`,
4038
+ threadId: ids.threadId,
4039
+ runId: ids.runId,
4040
+ role: "assistant",
4041
+ text: "Other",
4042
+ streaming: false,
4043
+ });
4044
+ const scenario = yield* runBackgroundItemScenario(key, () => Stream.fromQueue(providerEvents), {
4045
+ batched: true,
4046
+ onIngest: (event, write) =>
4047
+ event.type === "message.updated" && event.message.text === "Other"
4048
+ ? Deferred.succeed(blockerStarted, undefined).pipe(
4049
+ Effect.andThen(Deferred.await(releaseBlocker)),
4050
+ )
4051
+ : event.type === "message.updated" || event.type === "turn_item.updated"
4052
+ ? Effect.gen(function* () {
4053
+ const message = event.type === "message.updated" ? event.message : event.turnItem;
4054
+ const text = "text" in message ? message.text : "";
4055
+ const streaming = "streaming" in message && message.streaming;
4056
+ yield* Ref.update(delivered, (current) => [
4057
+ ...current,
4058
+ `${event.type}:${streaming ? "streaming" : "final"}:${JSON.stringify(text)}${
4059
+ write.inSharedCommit ? " in commit" : ""
4060
+ }`,
4061
+ ]);
4062
+ if (event.type === "turn_item.updated") {
4063
+ yield* Deferred.succeed(paragraphDelivered, undefined);
4064
+ if (text === "First.\n\nWaiting on the build.\n\n")
4065
+ yield* Deferred.succeed(nextParagraphDelivered, undefined);
4066
+ }
4067
+ })
4068
+ : Effect.void,
4069
+ }).pipe(
4070
+ Effect.provideService(Clock.Clock, {
4071
+ ...clock,
4072
+ sleep: (duration) =>
4073
+ clock.sleep(wakesEarly ? Duration.subtract(duration, Duration.millis(1)) : duration),
4074
+ }),
4075
+ Effect.forkChild,
4076
+ );
4077
+ // Waking a sleep runs ingestion until it suspends, so an idle write has landed by now.
4078
+ const lastShown = Ref.get(delivered).pipe(Effect.map((shown) => shown.at(-1)));
4079
+
4080
+ yield* Queue.offerAll(providerEvents, assistantText("First.\n\nWaiting on the build", true));
4081
+ yield* Deferred.await(paragraphDelivered);
4082
+ // The provider keeps its prompt open while a backgrounded command runs.
4083
+ yield* TestClock.adjust("2 seconds");
4084
+ assert.strictEqual(
4085
+ yield* lastShown,
4086
+ 'turn_item.updated:streaming:"First.\\n\\nWaiting on the build"',
4087
+ );
4088
+ // The next paragraph's tail still flushes on a later pause.
4089
+ yield* Queue.offerAll(
4090
+ providerEvents,
4091
+ assistantText("First.\n\nWaiting on the build.\n\nRunning", true),
4092
+ );
4093
+ yield* Deferred.await(nextParagraphDelivered);
4094
+ yield* TestClock.adjust("1 second");
4095
+ assert.strictEqual(
4096
+ yield* lastShown,
4097
+ 'turn_item.updated:streaming:"First.\\n\\nWaiting on the build.\\n\\nRunning"',
4098
+ );
4099
+ yield* Queue.offerAll(providerEvents, [
4100
+ ...assistantText("First.\n\nWaiting on the build.\n\nRunning tests", true),
4101
+ blocker,
4102
+ ...assistantText("First.\n\nWaiting on the build.\n\nRunning tests passed.", false),
4103
+ ]);
4104
+ yield* Deferred.await(blockerStarted);
4105
+ // The appended text comes due while its final snapshots wait behind the blocked write.
4106
+ yield* TestClock.adjust("1 second");
4107
+ yield* Deferred.succeed(releaseBlocker, undefined);
4108
+ yield* Queue.offer(providerEvents, rootTerminalEvent(ids, "completed"));
4109
+ yield* Fiber.join(scenario);
4110
+
4111
+ // Snapshots share the batch commit; the idle write commits alone, before it counts as shown.
4112
+ // The final snapshots win over the stale append that came due behind them.
4113
+ assert.deepEqual(yield* Ref.get(delivered), [
4114
+ `message.updated:streaming:"First.\\n\\n" in commit`,
4115
+ `turn_item.updated:streaming:"First.\\n\\n" in commit`,
4116
+ 'message.updated:streaming:"First.\\n\\nWaiting on the build"',
4117
+ 'turn_item.updated:streaming:"First.\\n\\nWaiting on the build"',
4118
+ `message.updated:streaming:"First.\\n\\nWaiting on the build.\\n\\n" in commit`,
4119
+ `turn_item.updated:streaming:"First.\\n\\nWaiting on the build.\\n\\n" in commit`,
4120
+ 'message.updated:streaming:"First.\\n\\nWaiting on the build.\\n\\nRunning"',
4121
+ 'turn_item.updated:streaming:"First.\\n\\nWaiting on the build.\\n\\nRunning"',
4122
+ `message.updated:final:"First.\\n\\nWaiting on the build.\\n\\nRunning tests passed." in commit`,
4123
+ `turn_item.updated:final:"First.\\n\\nWaiting on the build.\\n\\nRunning tests passed." in commit`,
4124
+ ]);
4125
+ }),
4126
+);
4127
+
4128
+const heldChildText = "partial response";
4129
+
4130
+function childAssistantSnapshot(
4131
+ ids: BackgroundScenarioIds,
4132
+): ProviderAdapter.ProviderAdapterV2Event {
4133
+ return {
4134
+ type: "turn_item.updated",
4135
+ driver,
4136
+ turnItem: {
4137
+ ...makeLinkedChildTurnItemFixture({ ids, driver, type: "assistant_message" }),
4138
+ text: heldChildText,
4139
+ },
4140
+ } as ProviderAdapter.ProviderAdapterV2Event;
4141
+}
4142
+
4143
+function linkedSubagentEvent(
4144
+ ids: BackgroundScenarioIds,
4145
+ status: "running" | "completed",
4146
+): ProviderAdapter.ProviderAdapterV2Event {
4147
+ return {
4148
+ type: "subagent.updated",
4149
+ driver,
4150
+ subagent: {
4151
+ ...makeRunOwnedSubagentFixture({
4152
+ ids,
4153
+ providerInstanceId: ProviderInstanceId.make("codex"),
4154
+ childThreadId: ids.childThreadId,
4155
+ driver,
4156
+ status: "running",
4157
+ }),
4158
+ status,
4159
+ },
4160
+ };
4161
+}
4162
+
4163
+const isHeldChildSnapshot = (event: ProviderAdapter.ProviderAdapterV2Event) =>
4164
+ event.type === "turn_item.updated" &&
4165
+ "text" in event.turnItem &&
4166
+ event.turnItem.text === heldChildText;
4167
+
4168
+// Feeds a held child snapshot, then waits until ingestion has read past it.
4169
+const holdChildSnapshot = Effect.fn(function* (
4170
+ ids: BackgroundScenarioIds,
4171
+ events: Queue.Enqueue<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>,
4172
+ subagentIngested: Deferred.Deferred<void>,
4173
+) {
4174
+ yield* Queue.offerAll(events, [
4175
+ childThreadCreatedEvent(ids),
4176
+ childAssistantSnapshot(ids),
4177
+ linkedSubagentEvent(ids, "running"),
4178
+ ]);
4179
+ yield* Deferred.await(subagentIngested);
4180
+});
4181
+
4182
+it.effect("settles a child message only an idle flush wrote when the root is interrupted", () =>
4183
+ Effect.gen(function* () {
4184
+ const ids = backgroundScenarioIds("idle-child-interrupt");
4185
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
4186
+ const subagentIngested = yield* Deferred.make<void>();
4187
+ const flushed = yield* Deferred.make<void>();
4188
+ const finalized = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
4189
+ const scenario = yield* runBackgroundItemScenario(
4190
+ "idle-child-interrupt",
4191
+ () => Stream.fromQueue(events),
4192
+ {
4193
+ onIngest: (event) =>
4194
+ event.type === "subagent.updated"
4195
+ ? Deferred.succeed(subagentIngested, undefined)
4196
+ : isHeldChildSnapshot(event)
4197
+ ? Deferred.succeed(flushed, undefined)
4198
+ : Effect.void,
4199
+ onFinalized: (written) => Ref.set(finalized, written),
4200
+ },
4201
+ ).pipe(Effect.forkChild);
4202
+
4203
+ yield* holdChildSnapshot(ids, events, subagentIngested);
4204
+ yield* TestClock.adjust("1 second");
4205
+ yield* Deferred.await(flushed);
4206
+ yield* Queue.offer(events, rootTerminalEvent(ids, "interrupted"));
4207
+ yield* Fiber.join(scenario);
4208
+
4209
+ const settled = (yield* Ref.get(finalized)).flatMap((event) =>
4210
+ event.type === "turn-item.updated" && event.payload.id === ids.childItemId
4211
+ ? [event.payload]
4212
+ : [],
4213
+ );
4214
+ assert.equal(settled.length, 1);
4215
+ assert.equal(settled[0]?.status, "interrupted");
4216
+ assert.equal("text" in settled[0]! ? settled[0].text : null, heldChildText);
4217
+ assert.isFalse("streaming" in settled[0]! && settled[0].streaming);
4218
+ }),
4219
+);
4220
+
4221
+it.effect.each([
4222
+ { name: "completed", terminalStatus: "completed" as const },
4223
+ { name: "failed with its children continuing", terminalStatus: "failed" as const },
4224
+])("idle-flushes a continuing child's text after the root $name", ({ terminalStatus }) =>
4225
+ Effect.gen(function* () {
4226
+ const key = `idle-child-after-${terminalStatus}`;
4227
+ const ids = backgroundScenarioIds(key);
4228
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
4229
+ const subagentIngested = yield* Deferred.make<void>();
4230
+ const rootFinalized = yield* Deferred.make<void>();
4231
+ const flushed = yield* Deferred.make<void>();
4232
+ const rootWrites = yield* Ref.make<ReadonlyArray<string>>([]);
4233
+ const scenario = yield* runBackgroundItemScenario(key, () => Stream.fromQueue(events), {
4234
+ onIngest: (event) =>
4235
+ event.type === "subagent.updated"
4236
+ ? Deferred.succeed(subagentIngested, undefined)
4237
+ : isHeldChildSnapshot(event)
4238
+ ? Deferred.succeed(flushed, undefined)
4239
+ : event.type === "message.updated" && event.message.threadId === ids.threadId
4240
+ ? Ref.update(rootWrites, (current) => [...current, event.message.text])
4241
+ : Effect.void,
4242
+ onFinalized: () => Deferred.succeed(rootFinalized, undefined),
4243
+ }).pipe(Effect.forkChild);
4244
+
4245
+ yield* holdChildSnapshot(ids, events, subagentIngested);
4246
+ // The root ends mid-paragraph: its tail is held, and the run settles without it.
4247
+ yield* Queue.offer(
4248
+ events,
4249
+ streamedMessageEvent({
4250
+ id: `message:${key}:root`,
4251
+ threadId: ids.threadId,
4252
+ runId: ids.runId,
4253
+ role: "assistant",
4254
+ text: "Root.\n\nhalf",
4255
+ streaming: true,
4256
+ }),
4257
+ );
4258
+ const terminal = rootTerminalEvent(ids, terminalStatus);
4259
+ yield* Queue.offer(
4260
+ events,
4261
+ terminalStatus === "failed"
4262
+ ? ({ ...terminal, childTurnsContinue: true } as ProviderAdapter.ProviderAdapterV2Event)
4263
+ : terminal,
4264
+ );
4265
+ yield* Deferred.await(rootFinalized);
4266
+ yield* TestClock.adjust("1 second");
4267
+ yield* Deferred.await(flushed);
4268
+ yield* Queue.offer(events, linkedSubagentEvent(ids, "completed"));
4269
+ const observed = yield* Fiber.join(scenario);
4270
+
4271
+ assert.deepEqual(observed.slice(-3), [
4272
+ "root-finalized",
4273
+ "turn_item:running",
4274
+ "subagent:completed",
4275
+ ]);
4276
+ // A streaming write after the run settled would reopen the root's message.
4277
+ assert.deepEqual(yield* Ref.get(rootWrites), ["Root.\n\n"]);
4278
+ }),
4279
+);
4280
+
4281
+function streamedMessageEvent(input: {
4282
+ readonly id: string;
4283
+ readonly threadId: ThreadId;
4284
+ readonly runId: RunId | null;
4285
+ readonly role: "assistant" | "user";
4286
+ readonly text: string;
4287
+ readonly streaming: boolean;
4288
+}): ProviderAdapter.ProviderAdapterV2Event {
4289
+ const now = DateTime.makeUnsafe("2026-07-21T12:00:00.000Z");
4290
+ return {
4291
+ type: "message.updated",
4292
+ driver,
4293
+ message: {
4294
+ createdBy: input.role === "user" ? "user" : "agent",
4295
+ creationSource: "provider",
4296
+ id: MessageId.make(input.id),
4297
+ threadId: input.threadId,
4298
+ runId: input.runId,
4299
+ nodeId: null,
4300
+ role: input.role,
4301
+ text: input.text,
4302
+ attachments: [],
4303
+ streaming: input.streaming,
4304
+ createdAt: now,
4305
+ updatedAt: now,
4306
+ },
4307
+ } as ProviderAdapter.ProviderAdapterV2Event;
4308
+}
4309
+
4310
+it.effect("drops a child's held text once the child is handed to another run", () =>
4311
+ Effect.gen(function* () {
4312
+ const key = "idle-child-handoff";
4313
+ const ids = backgroundScenarioIds(key);
4314
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
4315
+ const subagentIngested = yield* Deferred.make<void>();
4316
+ const handoffRead = yield* Deferred.make<void>();
4317
+ const rootFlushed = yield* Deferred.make<void>();
4318
+ const staleWrites = yield* Ref.make<ReadonlyArray<string>>([]);
4319
+ const scenario = yield* runBackgroundItemScenario(key, () => Stream.fromQueue(events), {
4320
+ onIngest: (event) => {
4321
+ if (event.type === "subagent.updated") return Deferred.succeed(subagentIngested, undefined);
4322
+ if (event.type !== "message.updated" && event.type !== "turn_item.updated")
4323
+ return Effect.void;
4324
+ const message = event.type === "message.updated" ? event.message : event.turnItem;
4325
+ if (message.threadId === ids.childThreadId)
4326
+ return Ref.update(staleWrites, (current) => [...current, event.type]);
4327
+ if (event.type === "message.updated" && event.message.role === "user")
4328
+ return Deferred.succeed(handoffRead, undefined);
4329
+ return Deferred.succeed(rootFlushed, undefined);
4330
+ },
4331
+ }).pipe(Effect.forkChild);
4332
+
4333
+ yield* holdChildSnapshot(ids, events, subagentIngested);
4334
+ const handoff = linkedSubagentEvent(ids, "running");
4335
+ yield* Queue.offerAll(events, [
4336
+ streamedMessageEvent({
4337
+ id: `message:${key}:child`,
4338
+ threadId: ids.childThreadId,
4339
+ runId: null,
4340
+ role: "assistant",
4341
+ text: heldChildText,
4342
+ streaming: true,
4343
+ }),
4344
+ handoff.type === "subagent.updated"
4345
+ ? { ...handoff, subagent: { ...handoff.subagent, runId: RunId.make(`run:${key}:next`) } }
4346
+ : handoff,
4347
+ // Due in the same flush as the child's text, after it.
4348
+ streamedMessageEvent({
4349
+ id: `message:${key}:root`,
4350
+ threadId: ids.threadId,
4351
+ runId: ids.runId,
4352
+ role: "assistant",
4353
+ text: "Root partial",
4354
+ streaming: true,
4355
+ }),
4356
+ streamedMessageEvent({
4357
+ id: `message:${key}:marker`,
4358
+ threadId: ids.threadId,
4359
+ runId: ids.runId,
4360
+ role: "user",
4361
+ text: "marker",
4362
+ streaming: false,
4363
+ }),
4364
+ ]);
4365
+ yield* Deferred.await(handoffRead);
4366
+ yield* TestClock.adjust("1 second");
4367
+ yield* Deferred.await(rootFlushed);
4368
+ yield* Queue.end(events);
4369
+ yield* Fiber.join(scenario);
4370
+
4371
+ assert.deepEqual(yield* Ref.get(staleWrites), []);
4372
+ }),
4373
+);