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

decider.settled.test.ts

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