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