Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

decider.settled.test.ts

687 lines25.8 KB

1import {
2 CommandId,
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationEvent,
9 type OrchestrationReadModel,
10 type OrchestrationSession,
11 type OrchestrationThread,
12} from "@t3tools/contracts";
13import * as NodeServices from "@effect/platform-node/NodeServices";
14import { expect, it } from "@effect/vitest";
15import * as Effect from "effect/Effect";
16​
17import { decideOrchestrationCommand } from "./decider.ts";
18import { projectEvent } from "./projector.ts";
19​
20const NOW = "2026-01-01T00:00:00.000Z";
21const SETTLED_AT = "2025-12-30T00:00:00.000Z";
22​
23function makeReadModel(
24 settledOverride: OrchestrationThread["settledOverride"],
25 archivedAt: string | null = null,
26 session: OrchestrationSession | null = null,
27 activities: OrchestrationThread["activities"] = [],
28 messages: OrchestrationThread["messages"] = [],
29 lifecycle: {
30 readonly pinnedAt?: string | null;
31 readonly snoozedUntil?: string | null;
32 readonly snoozedAt?: string | null;
33 } = {},
34): OrchestrationReadModel {
35 return {
36 snapshotSequence: 0,
37 projects: [],
38 threads: [
39 {
40 id: ThreadId.make("thread-1"),
41 projectId: ProjectId.make("project-1"),
42 title: "Thread",
43 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
44 runtimeMode: "full-access",
45 interactionMode: "default",
46 branch: null,
47 worktreePath: null,
48 latestTurn: null,
49 createdAt: NOW,
50 updatedAt: NOW,
51 archivedAt,
52 settledOverride,
53 settledAt: settledOverride === "settled" ? SETTLED_AT : null,
54 snoozedUntil: lifecycle.snoozedUntil ?? null,
55 snoozedAt: lifecycle.snoozedAt ?? (lifecycle.snoozedUntil != null ? SETTLED_AT : null),
56 pinnedAt: lifecycle.pinnedAt ?? null,
57 deletedAt: null,
58 messages,
59 proposedPlans: [],
60 activities,
61 checkpoints: [],
62 session,
63 },
64 ],
65 updatedAt: NOW,
66 };
68​
69function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
70 return {
71 threadId: ThreadId.make("thread-1"),
72 status,
73 providerName: "Codex",
74 runtimeMode: "full-access",
75 activeTurnId: null,
76 lastError: null,
77 updatedAt: NOW,
78 };
80​
81it.layer(NodeServices.layer)("settled thread decider", (it) => {
82 it.effect("settles awake threads without a redundant wake and re-emits idempotently", () =>
83 Effect.gen(function* () {
84 const event = yield* decideOrchestrationCommand({
85 command: {
86 type: "thread.settle",
87 commandId: CommandId.make("cmd-settle"),
88 threadId: ThreadId.make("thread-1"),
89 },
90 readModel: makeReadModel(null),
91 });
92 const events = Array.isArray(event) ? event : [event];
93 expect(events).toHaveLength(1);
94 expect(events[0]?.type).toBe("thread.settled");
95 if (events[0]?.type === "thread.settled") {
96 expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
97 }
98​
99 // Already settled: the engine rejects zero-event commands, so idempotency
100 // is by re-emission — preserving the original settledAt.
101 const reEmit = yield* decideOrchestrationCommand({
102 command: {
103 type: "thread.settle",
104 commandId: CommandId.make("cmd-settle-again"),
105 threadId: ThreadId.make("thread-1"),
106 },
107 readModel: makeReadModel("settled"),
108 });
109 const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
110 expect(reEmitEvents).toHaveLength(1);
111 expect(reEmitEvents[0]?.type).toBe("thread.settled");
112 if (reEmitEvents[0]?.type === "thread.settled") {
113 expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
114 // updatedAt must NOT rewind to the historical settledAt: sorting and
115 // relative-time labels key on it.
116 expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
117 }
118 }),
119 );
120​
121 it.effect("settling a snoozed thread also wakes it", () =>
122 Effect.gen(function* () {
123 const result = yield* decideOrchestrationCommand({
124 command: {
125 type: "thread.settle",
126 commandId: CommandId.make("cmd-settle-snoozed"),
127 threadId: ThreadId.make("thread-1"),
128 },
129 readModel: makeReadModel(null, null, null, [], [], {
130 snoozedUntil: "1970-01-02T09:00:00.000Z",
131 }),
132 });
133 const events = Array.isArray(result) ? result : [result];
134 expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unsnoozed"]);
135 const settled = events.find((entry) => entry.type === "thread.settled");
136 const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
137 if (settled?.type === "thread.settled" && unsnoozed?.type === "thread.unsnoozed") {
138 expect(unsnoozed.payload.reason).toBe("user");
139 expect(unsnoozed.payload.updatedAt).toBe(settled.payload.updatedAt);
140 }
141 }),
142 );
143​
144 it.effect("repeated settle repairs legacy settled and snoozed state", () =>
145 Effect.gen(function* () {
146 const result = yield* decideOrchestrationCommand({
147 command: {
148 type: "thread.settle",
149 commandId: CommandId.make("cmd-settle-snoozed-again"),
150 threadId: ThreadId.make("thread-1"),
151 },
152 readModel: makeReadModel("settled", null, null, [], [], {
153 snoozedUntil: "1970-01-02T09:00:00.000Z",
154 }),
155 });
156 const events = Array.isArray(result) ? result : [result];
157 expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unsnoozed"]);
158 const settled = events.find((entry) => entry.type === "thread.settled");
159 const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
160 if (settled?.type === "thread.settled" && unsnoozed?.type === "thread.unsnoozed") {
161 expect(settled.payload.settledAt).toBe(SETTLED_AT);
162 expect(settled.payload.updatedAt).toBe(NOW);
163 expect(unsnoozed.payload.updatedAt).not.toBe(NOW);
164 }
165 }),
166 );
167​
168 it.effect("settling a pinned and snoozed thread clears the pin and snooze", () =>
169 Effect.gen(function* () {
170 const result = yield* decideOrchestrationCommand({
171 command: {
172 type: "thread.settle",
173 commandId: CommandId.make("cmd-settle-pinned-snoozed"),
174 threadId: ThreadId.make("thread-1"),
175 },
176 readModel: makeReadModel(null, null, null, [], [], {
177 pinnedAt: SETTLED_AT,
178 snoozedUntil: "1970-01-02T09:00:00.000Z",
179 }),
180 });
181 const events = Array.isArray(result) ? result : [result];
182 expect(events.map((entry) => entry.type)).toEqual([
183 "thread.settled",
184 "thread.unpinned",
185 "thread.unsnoozed",
186 ]);
187 }),
188 );
189​
190 it.effect("rejects settling a thread with a live session", () =>
191 Effect.gen(function* () {
192 for (const status of ["starting", "running"] as const) {
193 const error = yield* decideOrchestrationCommand({
194 command: {
195 type: "thread.settle",
196 commandId: CommandId.make(`cmd-settle-live-${status}`),
197 threadId: ThreadId.make("thread-1"),
198 },
199 readModel: makeReadModel(null, null, makeSession(status)),
200 }).pipe(Effect.flip);
201 expect(error._tag).toBe("OrchestrationCommandInvariantError");
202 }
203 // Stopped/error sessions are settleable — only live work is protected.
204 const settled = yield* decideOrchestrationCommand({
205 command: {
206 type: "thread.settle",
207 commandId: CommandId.make("cmd-settle-stopped"),
208 threadId: ThreadId.make("thread-1"),
209 },
210 readModel: makeReadModel(null, null, makeSession("stopped")),
211 });
212 const settledEvents = Array.isArray(settled) ? settled : [settled];
213 expect(settledEvents[0]?.type).toBe("thread.settled");
214 }),
215 );
216​
217 it.effect("rejects settling a thread with an open approval or user-input request", () =>
218 Effect.gen(function* () {
219 const requestActivity = (kind: string, requestId: string, at: string) =>
220 ({
221 id: EventId.make(`activity-${requestId}-${kind}`),
222 tone: "approval" as const,
223 kind,
224 summary: kind,
225 payload: { requestId },
226 turnId: null,
227 createdAt: at,
228 }) as OrchestrationThread["activities"][number];
229​
230 // Open approval request: settle rejected.
231 const openError = yield* decideOrchestrationCommand({
232 command: {
233 type: "thread.settle",
234 commandId: CommandId.make("cmd-settle-pending"),
235 threadId: ThreadId.make("thread-1"),
236 },
237 readModel: makeReadModel(null, null, null, [
238 requestActivity("approval.requested", "req-1", NOW),
239 ]),
240 }).pipe(Effect.flip);
241 expect(openError._tag).toBe("OrchestrationCommandInvariantError");
242​
243 // Same request later resolved: settleable again.
244 const settled = yield* decideOrchestrationCommand({
245 command: {
246 type: "thread.settle",
247 commandId: CommandId.make("cmd-settle-resolved"),
248 threadId: ThreadId.make("thread-1"),
249 },
250 readModel: makeReadModel(null, null, null, [
251 requestActivity("approval.requested", "req-1", NOW),
252 requestActivity("approval.resolved", "req-1", NOW),
253 ]),
254 });
255 const settledEvents = Array.isArray(settled) ? settled : [settled];
256 expect(settledEvents[0]?.type).toBe("thread.settled");
257​
258 // Open user-input request: also rejected.
259 const inputError = yield* decideOrchestrationCommand({
260 command: {
261 type: "thread.settle",
262 commandId: CommandId.make("cmd-settle-pending-input"),
263 threadId: ThreadId.make("thread-1"),
264 },
265 readModel: makeReadModel(null, null, null, [
266 requestActivity("user-input.requested", "req-2", NOW),
267 ]),
268 }).pipe(Effect.flip);
269 expect(inputError._tag).toBe("OrchestrationCommandInvariantError");
270 }),
271 );
272​
273 it.effect("clears an open request when its respond failure marks it stale", () =>
274 Effect.gen(function* () {
275 const activity = (
276 kind: string,
277 requestId: string,
278 payload: Record<string, unknown>,
279 ): OrchestrationThread["activities"][number] =>
280 ({
281 id: EventId.make(`activity-${requestId}-${kind}`),
282 tone: "approval" as const,
283 kind,
284 summary: kind,
285 payload: { requestId, ...payload },
286 turnId: null,
287 createdAt: NOW,
288 }) as OrchestrationThread["activities"][number];
289​
290 // Stale-failure detail clears the request — mirrors the projection's
291 // pending accounting, which is what the client's canSettle sees.
292 const settled = yield* decideOrchestrationCommand({
293 command: {
294 type: "thread.settle",
295 commandId: CommandId.make("cmd-settle-stale-failed"),
296 threadId: ThreadId.make("thread-1"),
297 },
298 readModel: makeReadModel(null, null, null, [
299 activity("approval.requested", "req-1", {}),
300 activity("provider.approval.respond.failed", "req-1", {
301 detail: "Unknown pending approval request req-1",
302 }),
303 activity("user-input.requested", "req-2", {}),
304 activity("provider.user-input.respond.failed", "req-2", {
305 detail: "stale pending user-input request req-2",
306 }),
307 ]),
308 });
309 const settledEvents = Array.isArray(settled) ? settled : [settled];
310 expect(settledEvents[0]?.type).toBe("thread.settled");
311​
312 // A non-stale respond failure (transient provider error) keeps the
313 // request open: the user can retry, so it is still blocked-on-you.
314 const stillOpen = yield* decideOrchestrationCommand({
315 command: {
316 type: "thread.settle",
317 commandId: CommandId.make("cmd-settle-transient-failed"),
318 threadId: ThreadId.make("thread-1"),
319 },
320 readModel: makeReadModel(null, null, null, [
321 activity("approval.requested", "req-3", {}),
322 activity("provider.approval.respond.failed", "req-3", {
323 detail: "provider connection reset",
324 }),
325 ]),
326 }).pipe(Effect.flip);
327 expect(stillOpen._tag).toBe("OrchestrationCommandInvariantError");
328 }),
329 );
330​
331 it.effect("bounds the queued-turn grace window against client clock skew", () =>
332 Effect.gen(function* () {
333 const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
334 id: MessageId.make("message-queued"),
335 role: "user",
336 text: "Continue",
337 turnId: null,
338 streaming: false,
339 createdAt,
340 updatedAt: createdAt,
341 });
342​
343 // The decider's clock is the Effect test clock, pinned to the epoch:
344 // timestamps here are relative to 1970-01-01T00:00:00.000Z.
345​
346 // Within the grace window: genuinely queued, settle rejected.
347 const queuedError = yield* decideOrchestrationCommand({
348 command: {
349 type: "thread.settle",
350 commandId: CommandId.make("cmd-settle-queued"),
351 threadId: ThreadId.make("thread-1"),
352 },
353 readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
354 }).pipe(Effect.flip);
355 expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
356​
357 // Message timestamp far in the FUTURE (client clock ahead of server):
358 // a negative age must not read as queued forever — past the grace
359 // bound in either direction the thread is settleable.
360 const skewed = yield* decideOrchestrationCommand({
361 command: {
362 type: "thread.settle",
363 commandId: CommandId.make("cmd-settle-skewed"),
364 threadId: ThreadId.make("thread-1"),
365 },
366 readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
367 });
368 const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
369 expect(skewedEvents[0]?.type).toBe("thread.settled");
370 }),
371 );
372​
373 it.effect("rejects settling and unsettling archived threads", () =>
374 Effect.gen(function* () {
375 const settleError = yield* decideOrchestrationCommand({
376 command: {
377 type: "thread.settle",
378 commandId: CommandId.make("cmd-settle-archived"),
379 threadId: ThreadId.make("thread-1"),
380 },
381 readModel: makeReadModel(null, NOW),
382 }).pipe(Effect.flip);
383 expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
384​
385 const unsettleError = yield* decideOrchestrationCommand({
386 command: {
387 type: "thread.unsettle",
388 commandId: CommandId.make("cmd-unsettle-archived"),
389 threadId: ThreadId.make("thread-1"),
390 reason: "user",
391 },
392 readModel: makeReadModel("settled", NOW),
393 }).pipe(Effect.flip);
394 expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
395 }),
396 );
397​
398 it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
399 Effect.gen(function* () {
400 const userEvent = yield* decideOrchestrationCommand({
401 command: {
402 type: "thread.unsettle",
403 commandId: CommandId.make("cmd-unsettle-user"),
404 threadId: ThreadId.make("thread-1"),
405 reason: "user",
406 },
407 readModel: makeReadModel("settled"),
408 });
409 const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
410 expect(userEvents).toHaveLength(1);
411 expect(userEvents[0]?.type).toBe("thread.unsettled");
412 if (userEvents[0]?.type === "thread.unsettled") {
413 expect(userEvents[0].payload.reason).toBe("user");
414 }
415​
416 // Re-dispatching against the already-reached state re-emits rather than
417 // producing zero events (the engine rejects empty commands).
418 const userAgain = yield* decideOrchestrationCommand({
419 command: {
420 type: "thread.unsettle",
421 commandId: CommandId.make("cmd-unsettle-user-again"),
422 threadId: ThreadId.make("thread-1"),
423 reason: "user",
424 },
425 readModel: makeReadModel("active"),
426 });
427 const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
428 expect(userAgainEvents).toHaveLength(1);
429 expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
430 }),
431 );
432​
433 // Command-to-projection: an accepted un-settle must land as the re-entry
434 // stamp clients sort by (max of createdAt and unsettledAt, see
435 // activeThreadAnchorTimestampMs in client-runtime), so the thread surfaces
436 // above threads created after it. The projector tests feed events directly;
437 // this one proves the decider actually emits what they consume.
438 it.effect("an accepted un-settle re-anchors the thread for the active list", () =>
439 Effect.gen(function* () {
440 const readModel = makeReadModel("settled");
441 const result = yield* decideOrchestrationCommand({
442 command: {
443 type: "thread.unsettle",
444 commandId: CommandId.make("cmd-unsettle-anchor"),
445 threadId: ThreadId.make("thread-1"),
446 reason: "user",
447 },
448 readModel,
449 });
450 const events = Array.isArray(result) ? result : [result];
451 const unsettled = events[0]!;
452 expect(unsettled.type).toBe("thread.unsettled");
453​
454 const projected = yield* projectEvent(readModel, {
455 ...unsettled,
456 sequence: readModel.snapshotSequence + 1,
457 } as OrchestrationEvent);
458 const thread = projected.threads[0]!;
459 expect(thread.settledOverride).toBe("active");
460 // The stamp is the decider's accept time: every thread created before
461 // the un-settle anchors below it.
462 expect(thread.unsettledAt).toBe(unsettled.occurredAt);
463 if (unsettled.type === "thread.unsettled") {
464 expect(thread.unsettledAt).toBe(unsettled.payload.updatedAt);
465 }
466 }),
467 );
468​
469 it.effect("prepends activity unsets for turn starts and live session updates", () =>
470 Effect.gen(function* () {
471 const turnResult = yield* decideOrchestrationCommand({
472 command: {
473 type: "thread.turn.start",
474 commandId: CommandId.make("cmd-turn-start"),
475 threadId: ThreadId.make("thread-1"),
476 message: {
477 messageId: MessageId.make("message-1"),
478 role: "user",
479 text: "Continue",
480 attachments: [],
481 },
482 runtimeMode: "full-access",
483 interactionMode: "default",
484 createdAt: NOW,
485 },
486 readModel: makeReadModel("settled"),
487 });
488 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
489 expect(turnEvents.map((event) => event.type)).toEqual([
490 "thread.unsettled",
491 "thread.message-sent",
492 "thread.turn-start-requested",
493 ]);
494​
495 const sessionResult = yield* decideOrchestrationCommand({
496 command: {
497 type: "thread.session.set",
498 commandId: CommandId.make("cmd-session-set"),
499 threadId: ThreadId.make("thread-1"),
500 session: makeSession("running"),
501 createdAt: NOW,
502 },
503 // A keep-active pin is also an override: real activity clears it
504 // back to neutral so auto-settle can apply again later.
505 readModel: makeReadModel("active"),
506 });
507 const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
508 expect(sessionEvents.map((event) => event.type)).toEqual([
509 "thread.unsettled",
510 "thread.session-set",
511 ]);
512 }),
513 );
514​
515 it.effect("clears a keep-active pin on real activity", () =>
516 Effect.gen(function* () {
517 const turnResult = yield* decideOrchestrationCommand({
518 command: {
519 type: "thread.turn.start",
520 commandId: CommandId.make("cmd-active-turn-start"),
521 threadId: ThreadId.make("thread-1"),
522 message: {
523 messageId: MessageId.make("message-active"),
524 role: "user",
525 text: "Continue",
526 attachments: [],
527 },
528 runtimeMode: "full-access",
529 interactionMode: "default",
530 createdAt: NOW,
531 },
532 readModel: makeReadModel("active"),
533 });
534 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
535 // The pin exists to suppress AUTO-settle, not to survive real work:
536 // activity resets it to neutral, restoring the default lifecycle.
537 expect(turnEvents.map((event) => event.type)).toEqual([
538 "thread.unsettled",
539 "thread.message-sent",
540 "thread.turn-start-requested",
541 ]);
542​
543 const activityResult = yield* decideOrchestrationCommand({
544 command: {
545 type: "thread.activity.append",
546 commandId: CommandId.make("cmd-active-approval"),
547 threadId: ThreadId.make("thread-1"),
548 activity: {
549 id: EventId.make("activity-active"),
550 tone: "approval",
551 kind: "approval.requested",
552 summary: "Command approval requested",
553 payload: null,
554 turnId: null,
555 createdAt: NOW,
556 },
557 createdAt: NOW,
558 },
559 readModel: makeReadModel("active"),
560 });
561 const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
562 expect(activityEvents.map((event) => event.type)).toEqual([
563 "thread.unsettled",
564 "thread.activity-appended",
565 ]);
566 }),
567 );
568​
569 it.effect("does not unsettle for session stop/error status writes", () =>
570 Effect.gen(function* () {
571 for (const status of ["stopped", "error", "ready", "idle"] as const) {
572 const result = yield* decideOrchestrationCommand({
573 command: {
574 type: "thread.session.set",
575 commandId: CommandId.make(`cmd-session-${status}`),
576 threadId: ThreadId.make("thread-1"),
577 session: makeSession(status),
578 createdAt: NOW,
579 },
580 readModel: makeReadModel("settled"),
581 });
582 const events = Array.isArray(result) ? result : [result];
583 expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
584 }
585 }),
586 );
587​
588 it.effect("unsettles for approval and user-input activities but not others", () =>
589 Effect.gen(function* () {
590 const approvalResult = yield* decideOrchestrationCommand({
591 command: {
592 type: "thread.activity.append",
593 commandId: CommandId.make("cmd-activity-approval"),
594 threadId: ThreadId.make("thread-1"),
595 activity: {
596 id: EventId.make("activity-1"),
597 tone: "approval",
598 kind: "approval.requested",
599 summary: "Command approval requested",
600 payload: null,
601 turnId: null,
602 createdAt: NOW,
603 },
604 createdAt: NOW,
605 },
606 readModel: makeReadModel("settled"),
607 });
608 const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
609 expect(approvalEvents.map((event) => event.type)).toEqual([
610 "thread.unsettled",
611 "thread.activity-appended",
612 ]);
613​
614 const routineResult = yield* decideOrchestrationCommand({
615 command: {
616 type: "thread.activity.append",
617 commandId: CommandId.make("cmd-activity-routine"),
618 threadId: ThreadId.make("thread-1"),
619 activity: {
620 id: EventId.make("activity-2"),
621 tone: "info",
622 kind: "tool.completed",
623 summary: "Tool completed",
624 payload: null,
625 turnId: null,
626 createdAt: NOW,
627 },
628 createdAt: NOW,
629 },
630 readModel: makeReadModel("settled"),
631 });
632 const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
633 expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
634 }),
635 );
636​
637 it.effect("drops an onlyIfSettled session stop when the thread was re-engaged", () =>
638 Effect.gen(function* () {
639 const stopCommand = (commandId: string) =>
640 ({
641 type: "thread.session.stop",
642 commandId: CommandId.make(commandId),
643 threadId: ThreadId.make("thread-1"),
644 createdAt: NOW,
645 onlyIfSettled: true,
646 }) as const;
647​
648 // Still settled with an idle session: the cleanup stop goes through.
649 const stopped = yield* decideOrchestrationCommand({
650 command: stopCommand("cmd-stop-settled-idle"),
651 readModel: makeReadModel("settled", null, makeSession("ready")),
652 });
653 const stoppedEvents = Array.isArray(stopped) ? stopped : [stopped];
654 expect(stoppedEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
655​
656 // Re-engaged before the stop was decided (a turn start unsettles the
657 // thread): the stale cleanup stop must not kill the new session.
658 const unsettledError = yield* decideOrchestrationCommand({
659 command: stopCommand("cmd-stop-unsettled"),
660 readModel: makeReadModel(null, null, makeSession("starting")),
661 }).pipe(Effect.flip);
662 expect(unsettledError._tag).toBe("OrchestrationCommandInvariantError");
663​
664 // Still settled but the session is already coming alive: same drop.
665 const aliveError = yield* decideOrchestrationCommand({
666 command: stopCommand("cmd-stop-session-alive"),
667 readModel: makeReadModel("settled", null, makeSession("starting")),
668 }).pipe(Effect.flip);
669 expect(aliveError._tag).toBe("OrchestrationCommandInvariantError");
670​
671 // Without the flag the stop stays unconditional (archive, stop button).
672 const unconditional = yield* decideOrchestrationCommand({
673 command: {
674 type: "thread.session.stop",
675 commandId: CommandId.make("cmd-stop-unconditional"),
676 threadId: ThreadId.make("thread-1"),
677 createdAt: NOW,
678 },
679 readModel: makeReadModel(null, null, makeSession("starting")),
680 });
681 const unconditionalEvents = Array.isArray(unconditional) ? unconditional : [unconditional];
682 expect(unconditionalEvents.map((event) => event.type)).toEqual([
683 "thread.session-stop-requested",
684 ]);
685 }),
686 );
687});