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

decider.settled.test.ts

852 lines31.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("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("manual settlement dismisses async questions without starting a turn", () =>
326 Effect.gen(function* () {
327 const question = (requestId: string): OrchestrationThread["activities"][number] => ({
328 id: EventId.make(requestId),
329 kind: "user-input.requested",
330 summary: "Question",
331 tone: "approval",
332 turnId: null,
333 createdAt: "1969-12-31T00:00:00.000Z",
334 payload: { requestId, responseMode: "message" },
335 });
336 const readModel = makeReadModel(null, null, makeSession("ready"), [
337 question("first"),
338 question("second"),
339 question("answered"),
340 {
341 ...question("answered"),
342 id: EventId.make("answer"),
343 createdAt: "1969-12-31T01:00:00.000Z",
344 kind: "user-input.resolved",
345 },
346 ]);
347 const command = {
348 type: "thread.settle" as const,
349 commandId: CommandId.make("settle-async"),
350 threadId: ThreadId.make("thread-1"),
351 };
352 const result = yield* decideOrchestrationCommand({ command, readModel });
353 const events = Array.isArray(result) ? result : [result];
354 expect(events.map((event) => event.type)).toEqual([
355 "thread.settled",
356 "thread.activity-appended",
357 "thread.activity-appended",
358 ]);
359 expect(events.slice(1).map((event) => event.payload)).toEqual(
360 ["first", "second"].map((requestId) => ({
361 threadId: command.threadId,
362 activity: expect.objectContaining({
363 kind: "user-input.resolved",
364 summary: "User input dismissed",
365 payload: { requestId, responseMode: "message" },
366 }),
367 })),
368 );
369 let projected = readModel;
370 for (const [index, event] of events.entries()) {
371 projected = yield* projectEvent(projected, { ...event, sequence: index + 1 });
372 }
373 expect(projected.threads[0]?.settledOverride).toBe("settled");
374 expect(projected.threads[0]?.messages).toEqual([]);
375 const repeated = yield* decideOrchestrationCommand({ command, readModel: projected });
376 expect(repeated).toMatchObject({ type: "thread.settled" });
377 }),
378 );
379​
380 it.effect("async questions do not bypass automatic settlement or other blockers", () =>
381 Effect.gen(function* () {
382 const question: OrchestrationThread["activities"][number] = {
383 id: EventId.make("async-question"),
384 kind: "user-input.requested",
385 summary: "Question",
386 tone: "approval",
387 turnId: null,
388 createdAt: NOW,
389 payload: { requestId: "async-question", responseMode: "message" },
390 };
391 for (const blocker of ["auto", "running", "starting", "approval", "native"] as const) {
392 const error = yield* decideOrchestrationCommand({
393 command:
394 blocker === "auto"
395 ? {
396 type: "thread.auto-settle",
397 commandId: CommandId.make(`settle-${blocker}`),
398 threadId: ThreadId.make("thread-1"),
399 snapshotSequence: 0,
400 settledAt: NOW,
401 }
402 : {
403 type: "thread.settle",
404 commandId: CommandId.make(`settle-${blocker}`),
405 threadId: ThreadId.make("thread-1"),
406 },
407 readModel: makeReadModel(
408 null,
409 null,
410 makeSession(blocker === "running" || blocker === "starting" ? blocker : "ready"),
411 [
412 question,
413 ...(blocker === "approval" || blocker === "native"
414 ? [
415 {
416 ...question,
417 id: EventId.make("blocking-request"),
418 kind: blocker === "approval" ? "approval.requested" : "user-input.requested",
419 payload: { requestId: "blocking-request" },
420 },
421 ]
422 : []),
423 ],
424 ),
425 }).pipe(Effect.flip);
426 expect(error).toMatchObject({ _tag: "OrchestrationThreadSettleBlockedError" });
427 }
428 }),
429 );
430​
431 it.effect("clears an open request when its respond failure marks it stale", () =>
432 Effect.gen(function* () {
433 const activity = (
434 kind: string,
435 requestId: string,
436 payload: Record<string, unknown>,
437 ): OrchestrationThread["activities"][number] =>
438 ({
439 id: EventId.make(`activity-${requestId}-${kind}`),
440 tone: "approval" as const,
441 kind,
442 summary: kind,
443 payload: { requestId, ...payload },
444 turnId: null,
445 createdAt: NOW,
446 }) as OrchestrationThread["activities"][number];
447​
448 // Stale-failure details clear the request, matching the projection flags.
449 const settled = yield* decideOrchestrationCommand({
450 command: {
451 type: "thread.settle",
452 commandId: CommandId.make("cmd-settle-stale-failed"),
453 threadId: ThreadId.make("thread-1"),
454 },
455 readModel: makeReadModel(null, null, null, [
456 activity("approval.requested", "req-1", {}),
457 activity("provider.approval.respond.failed", "req-1", {
458 detail: "Unknown pending approval request req-1",
459 }),
460 activity("user-input.requested", "req-2", {}),
461 activity("provider.user-input.respond.failed", "req-2", {
462 detail: "stale pending user-input request req-2",
463 }),
464 ]),
465 });
466 const settledEvents = Array.isArray(settled) ? settled : [settled];
467 expect(settledEvents[0]?.type).toBe("thread.settled");
468​
469 // A non-stale respond failure (transient provider error) keeps the
470 // request open: the user can retry, so it is still blocked-on-you.
471 const stillOpen = yield* decideOrchestrationCommand({
472 command: {
473 type: "thread.settle",
474 commandId: CommandId.make("cmd-settle-transient-failed"),
475 threadId: ThreadId.make("thread-1"),
476 },
477 readModel: makeReadModel(null, null, null, [
478 activity("approval.requested", "req-3", {}),
479 activity("provider.approval.respond.failed", "req-3", {
480 detail: "provider connection reset",
481 }),
482 ]),
483 }).pipe(Effect.flip);
484 expect(stillOpen).toMatchObject({
485 _tag: "OrchestrationThreadSettleBlockedError",
486 threadId: ThreadId.make("thread-1"),
487 message: SETTLE_BLOCKED_MESSAGE,
488 });
489 }),
490 );
491​
492 it.effect("bounds the queued-turn grace window against client clock skew", () =>
493 Effect.gen(function* () {
494 const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
495 id: MessageId.make("message-queued"),
496 role: "user",
497 text: "Continue",
498 turnId: null,
499 streaming: false,
500 createdAt,
501 updatedAt: createdAt,
502 });
503​
504 // The decider's clock is the Effect test clock, pinned to the epoch:
505 // timestamps here are relative to 1970-01-01T00:00:00.000Z.
506​
507 // Within the grace window: genuinely queued, settle rejected.
508 const queuedError = yield* decideOrchestrationCommand({
509 command: {
510 type: "thread.settle",
511 commandId: CommandId.make("cmd-settle-queued"),
512 threadId: ThreadId.make("thread-1"),
513 },
514 readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
515 }).pipe(Effect.flip);
516 expect(queuedError).toMatchObject({
517 _tag: "OrchestrationThreadSettleBlockedError",
518 threadId: ThreadId.make("thread-1"),
519 message: SETTLE_BLOCKED_MESSAGE,
520 });
521​
522 // Message timestamp far in the FUTURE (client clock ahead of server):
523 // a negative age must not read as queued forever — past the grace
524 // bound in either direction the thread is settleable.
525 const skewed = yield* decideOrchestrationCommand({
526 command: {
527 type: "thread.settle",
528 commandId: CommandId.make("cmd-settle-skewed"),
529 threadId: ThreadId.make("thread-1"),
530 },
531 readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
532 });
533 const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
534 expect(skewedEvents[0]?.type).toBe("thread.settled");
535 }),
536 );
537​
538 it.effect("rejects settling and unsettling archived threads", () =>
539 Effect.gen(function* () {
540 const settleError = yield* decideOrchestrationCommand({
541 command: {
542 type: "thread.settle",
543 commandId: CommandId.make("cmd-settle-archived"),
544 threadId: ThreadId.make("thread-1"),
545 },
546 readModel: makeReadModel(null, NOW),
547 }).pipe(Effect.flip);
548 expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
549​
550 const unsettleError = yield* decideOrchestrationCommand({
551 command: {
552 type: "thread.unsettle",
553 commandId: CommandId.make("cmd-unsettle-archived"),
554 threadId: ThreadId.make("thread-1"),
555 reason: "user",
556 },
557 readModel: makeReadModel("settled", NOW),
558 }).pipe(Effect.flip);
559 expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
560 }),
561 );
562​
563 it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
564 Effect.gen(function* () {
565 const userEvent = yield* decideOrchestrationCommand({
566 command: {
567 type: "thread.unsettle",
568 commandId: CommandId.make("cmd-unsettle-user"),
569 threadId: ThreadId.make("thread-1"),
570 reason: "user",
571 },
572 readModel: makeReadModel("settled"),
573 });
574 const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
575 expect(userEvents).toHaveLength(1);
576 expect(userEvents[0]?.type).toBe("thread.unsettled");
577 if (userEvents[0]?.type === "thread.unsettled") {
578 expect(userEvents[0].payload.reason).toBe("user");
579 }
580​
581 // Re-dispatching against the already-reached state re-emits rather than
582 // producing zero events (the engine rejects empty commands).
583 const userAgain = yield* decideOrchestrationCommand({
584 command: {
585 type: "thread.unsettle",
586 commandId: CommandId.make("cmd-unsettle-user-again"),
587 threadId: ThreadId.make("thread-1"),
588 reason: "user",
589 },
590 readModel: makeReadModel("active"),
591 });
592 const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
593 expect(userAgainEvents).toHaveLength(1);
594 expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
595 }),
596 );
597​
598 // Command-to-projection: an accepted un-settle must land as the re-entry
599 // stamp clients sort by (max of createdAt and unsettledAt, see
600 // activeThreadAnchorTimestampMs in client-runtime), so the thread surfaces
601 // above threads created after it. The projector tests feed events directly;
602 // this one proves the decider actually emits what they consume.
603 it.effect("an accepted un-settle re-anchors the thread for the active list", () =>
604 Effect.gen(function* () {
605 const readModel = makeReadModel("settled");
606 const result = yield* decideOrchestrationCommand({
607 command: {
608 type: "thread.unsettle",
609 commandId: CommandId.make("cmd-unsettle-anchor"),
610 threadId: ThreadId.make("thread-1"),
611 reason: "user",
612 },
613 readModel,
614 });
615 const events = Array.isArray(result) ? result : [result];
616 const unsettled = events[0]!;
617 expect(unsettled.type).toBe("thread.unsettled");
618​
619 const projected = yield* projectEvent(readModel, {
620 ...unsettled,
621 sequence: readModel.snapshotSequence + 1,
622 } as OrchestrationEvent);
623 const thread = projected.threads[0]!;
624 expect(thread.settledOverride).toBe("active");
625 // The stamp is the decider's accept time: every thread created before
626 // the un-settle anchors below it.
627 expect(thread.unsettledAt).toBe(unsettled.occurredAt);
628 if (unsettled.type === "thread.unsettled") {
629 expect(thread.unsettledAt).toBe(unsettled.payload.updatedAt);
630 }
631 }),
632 );
633​
634 it.effect("prepends activity unsets for turn starts and live session updates", () =>
635 Effect.gen(function* () {
636 const turnResult = yield* decideOrchestrationCommand({
637 command: {
638 type: "thread.turn.start",
639 commandId: CommandId.make("cmd-turn-start"),
640 threadId: ThreadId.make("thread-1"),
641 message: {
642 messageId: MessageId.make("message-1"),
643 role: "user",
644 text: "Continue",
645 attachments: [],
646 },
647 runtimeMode: "full-access",
648 interactionMode: "default",
649 createdAt: NOW,
650 },
651 readModel: makeReadModel("settled"),
652 });
653 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
654 expect(turnEvents.map((event) => event.type)).toEqual([
655 "thread.unsettled",
656 "thread.message-sent",
657 "thread.turn-start-requested",
658 ]);
659​
660 const sessionResult = yield* decideOrchestrationCommand({
661 command: {
662 type: "thread.session.set",
663 commandId: CommandId.make("cmd-session-set"),
664 threadId: ThreadId.make("thread-1"),
665 session: makeSession("running"),
666 createdAt: NOW,
667 },
668 // A keep-active pin is also an override: real activity clears it
669 // back to neutral so auto-settle can apply again later.
670 readModel: makeReadModel("active"),
671 });
672 const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
673 expect(sessionEvents.map((event) => event.type)).toEqual([
674 "thread.unsettled",
675 "thread.session-set",
676 ]);
677 }),
678 );
679​
680 it.effect("clears a keep-active pin on real activity", () =>
681 Effect.gen(function* () {
682 const turnResult = yield* decideOrchestrationCommand({
683 command: {
684 type: "thread.turn.start",
685 commandId: CommandId.make("cmd-active-turn-start"),
686 threadId: ThreadId.make("thread-1"),
687 message: {
688 messageId: MessageId.make("message-active"),
689 role: "user",
690 text: "Continue",
691 attachments: [],
692 },
693 runtimeMode: "full-access",
694 interactionMode: "default",
695 createdAt: NOW,
696 },
697 readModel: makeReadModel("active"),
698 });
699 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
700 // The pin exists to suppress AUTO-settle, not to survive real work:
701 // activity resets it to neutral, restoring the default lifecycle.
702 expect(turnEvents.map((event) => event.type)).toEqual([
703 "thread.unsettled",
704 "thread.message-sent",
705 "thread.turn-start-requested",
706 ]);
707​
708 const activityResult = yield* decideOrchestrationCommand({
709 command: {
710 type: "thread.activity.append",
711 commandId: CommandId.make("cmd-active-approval"),
712 threadId: ThreadId.make("thread-1"),
713 activity: {
714 id: EventId.make("activity-active"),
715 tone: "approval",
716 kind: "approval.requested",
717 summary: "Command approval requested",
718 payload: null,
719 turnId: null,
720 createdAt: NOW,
721 },
722 createdAt: NOW,
723 },
724 readModel: makeReadModel("active"),
725 });
726 const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
727 expect(activityEvents.map((event) => event.type)).toEqual([
728 "thread.unsettled",
729 "thread.activity-appended",
730 ]);
731 }),
732 );
733​
734 it.effect("does not unsettle for session stop/error status writes", () =>
735 Effect.gen(function* () {
736 for (const status of ["stopped", "error", "ready", "idle"] as const) {
737 const result = yield* decideOrchestrationCommand({
738 command: {
739 type: "thread.session.set",
740 commandId: CommandId.make(`cmd-session-${status}`),
741 threadId: ThreadId.make("thread-1"),
742 session: makeSession(status),
743 createdAt: NOW,
744 },
745 readModel: makeReadModel("settled"),
746 });
747 const events = Array.isArray(result) ? result : [result];
748 expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
749 }
750 }),
751 );
752​
753 it.effect("unsettles for approval and user-input activities but not others", () =>
754 Effect.gen(function* () {
755 const approvalResult = yield* decideOrchestrationCommand({
756 command: {
757 type: "thread.activity.append",
758 commandId: CommandId.make("cmd-activity-approval"),
759 threadId: ThreadId.make("thread-1"),
760 activity: {
761 id: EventId.make("activity-1"),
762 tone: "approval",
763 kind: "approval.requested",
764 summary: "Command approval requested",
765 payload: null,
766 turnId: null,
767 createdAt: NOW,
768 },
769 createdAt: NOW,
770 },
771 readModel: makeReadModel("settled"),
772 });
773 const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
774 expect(approvalEvents.map((event) => event.type)).toEqual([
775 "thread.unsettled",
776 "thread.activity-appended",
777 ]);
778​
779 const routineResult = yield* decideOrchestrationCommand({
780 command: {
781 type: "thread.activity.append",
782 commandId: CommandId.make("cmd-activity-routine"),
783 threadId: ThreadId.make("thread-1"),
784 activity: {
785 id: EventId.make("activity-2"),
786 tone: "info",
787 kind: "tool.completed",
788 summary: "Tool completed",
789 payload: null,
790 turnId: null,
791 createdAt: NOW,
792 },
793 createdAt: NOW,
794 },
795 readModel: makeReadModel("settled"),
796 });
797 const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
798 expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
799 }),
800 );
801​
802 it.effect("drops an onlyIfSettled session stop when the thread was re-engaged", () =>
803 Effect.gen(function* () {
804 const stopCommand = (commandId: string) =>
805 ({
806 type: "thread.session.stop",
807 commandId: CommandId.make(commandId),
808 threadId: ThreadId.make("thread-1"),
809 createdAt: NOW,
810 onlyIfSettled: true,
811 }) as const;
812​
813 // Still settled with an idle session: the cleanup stop goes through.
814 const stopped = yield* decideOrchestrationCommand({
815 command: stopCommand("cmd-stop-settled-idle"),
816 readModel: makeReadModel("settled", null, makeSession("ready")),
817 });
818 const stoppedEvents = Array.isArray(stopped) ? stopped : [stopped];
819 expect(stoppedEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
820​
821 // Re-engaged before the stop was decided (a turn start unsettles the
822 // thread): the stale cleanup stop must not kill the new session.
823 const unsettledError = yield* decideOrchestrationCommand({
824 command: stopCommand("cmd-stop-unsettled"),
825 readModel: makeReadModel(null, null, makeSession("starting")),
826 }).pipe(Effect.flip);
827 expect(unsettledError._tag).toBe("OrchestrationCommandInvariantError");
828​
829 // Still settled but the session is already coming alive: same drop.
830 const aliveError = yield* decideOrchestrationCommand({
831 command: stopCommand("cmd-stop-session-alive"),
832 readModel: makeReadModel("settled", null, makeSession("starting")),
833 }).pipe(Effect.flip);
834 expect(aliveError._tag).toBe("OrchestrationCommandInvariantError");
835​
836 // Without the flag the stop stays unconditional (archive, stop button).
837 const unconditional = yield* decideOrchestrationCommand({
838 command: {
839 type: "thread.session.stop",
840 commandId: CommandId.make("cmd-stop-unconditional"),
841 threadId: ThreadId.make("thread-1"),
842 createdAt: NOW,
843 },
844 readModel: makeReadModel(null, null, makeSession("starting")),
845 });
846 const unconditionalEvents = Array.isArray(unconditional) ? unconditional : [unconditional];
847 expect(unconditionalEvents.map((event) => event.type)).toEqual([
848 "thread.session-stop-requested",
849 ]);
850 }),
851 );
852});