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

decider.settled.test.ts

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