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

threadActivity.test.ts

841 lines25.0 KB

1import {
2 MessageId,
3 NodeId,
4 ProviderInstanceId,
5 ProviderThreadId,
6 RunId,
7 RunAttemptId,
8 ThreadId,
9 TurnItemId,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2ProjectedTurnItem,
12 type OrchestrationV2TurnItem,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import { describe, expect, it } from "vite-plus/test";
16​
17import {
18 buildThreadFeed,
19 deriveThreadFeedPresentation,
20 threadFeedActivityIsVisible,
21 threadFeedRunIsUnsettled,
22 type ThreadFeedActivity,
23 type ThreadFeedEntry,
24 togglePendingUserInputOptionSelection,
25 setPendingUserInputCustomAnswer,
26 isPendingUserInputOptionSelected,
27 buildPendingUserInputAnswers,
28} from "./threadActivity";
29​
30const threadId = ThreadId.make("thread-1");
31const sourceThreadId = ThreadId.make("thread-source");
32const runId = RunId.make("run-1");
33​
34it("keeps historical plan detail accessible from its paged turn item", () => {
35 const item = {
36 ...base("historical-plan", "2026-08-29T00:00:00.000Z", 1),
37 type: "proposed_plan",
38 planId: "plan-historical",
39 markdown: "Full historical plan text",
40 streaming: false,
41 } as OrchestrationV2TurnItem;
42​
43 const entries = buildThreadFeed([projected(item, 0)]);
44 const activity = entries.flatMap((entry) =>
45 entry.type === "activity-group" ? entry.activities : [],
46 )[0];
47 expect(activity?.detail).toBe("Full historical plan text");
48 expect(activity?.getFullDetail()).toContain("Full historical plan text");
49});
50​
51function base(id: string, updatedAt: string, ordinal: number) {
52 const timestamp = DateTime.makeUnsafe(updatedAt);
53 return {
54 id: TurnItemId.make(id),
55 threadId,
56 runId,
57 nodeId: null,
58 providerThreadId: null,
59 providerTurnId: null,
60 nativeItemRef: null,
61 parentItemId: null,
62 ordinal,
63 status: "completed" as const,
64 title: null,
65 startedAt: timestamp,
66 completedAt: timestamp,
67 updatedAt: timestamp,
68 };
70​
71function projected(
72 item: OrchestrationV2TurnItem,
73 position: number,
74 visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
75): OrchestrationV2ProjectedTurnItem {
76 return {
77 position,
78 visibility,
79 sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
80 sourceItemId: item.id,
81 item,
82 };
84​
85function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
86 return {
87 ...base("item-user", updatedAt, 0),
88 type: "user_message" as const,
89 messageId: MessageId.make("message-user"),
90 createdBy: "user" as const,
91 creationSource: "mobile" as const,
92 inputIntent: "turn_start" as const,
93 text: "Run checks",
94 attachments: [],
95 };
97​
98function command(updatedAt = "2026-06-20T00:00:02.000Z") {
99 return {
100 ...base("item-command", updatedAt, 1),
101 type: "command_execution" as const,
102 input: "vp check",
103 output: "ok",
104 exitCode: 0,
105 };
107​
108function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
109 return {
110 ...base("item-assistant", updatedAt, 2),
111 type: "assistant_message" as const,
112 messageId: MessageId.make("message-assistant"),
113 text: "Done",
114 streaming: false,
115 };
117​
118describe("buildThreadFeed", () => {
119 it("adds local feedback messages to an otherwise server-authored feed", () => {
120 const feed = buildThreadFeed([], {
121 localMessages: [
122 {
123 id: MessageId.make("feedback-local"),
124 role: "assistant",
125 text: "Feedback sent to OpenAI.\n\nThread ID: `codex-thread-1`",
126 turnId: null,
127 streaming: false,
128 createdAt: "2026-08-29T00:00:00.000Z",
129 updatedAt: "2026-08-29T00:00:00.000Z",
130 },
131 ],
132 });
133​
134 expect(feed).toHaveLength(1);
135 expect(feed[0]).toMatchObject({
136 type: "message",
137 message: {
138 id: "feedback-local",
139 role: "assistant",
140 text: expect.stringContaining("codex-thread-1"),
141 },
142 });
143 });
144​
145 it("anchors feedback before later committed turns and appends true optimistic messages", () => {
146 const laterUser = {
147 ...userMessage("2026-08-29T00:00:05.000Z"),
148 id: TurnItemId.make("item-later-user"),
149 messageId: MessageId.make("message-later-user"),
150 ordinal: 2,
151 text: "Later user turn",
152 };
153 const laterAssistant = {
154 ...assistantMessage("2026-08-29T00:00:04.000Z"),
155 id: TurnItemId.make("item-later-assistant"),
156 messageId: MessageId.make("message-later-assistant"),
157 ordinal: 3,
158 text: "Later assistant turn",
159 };
160 const localMessage = (id: string, role: "user" | "assistant") => ({
161 id: MessageId.make(id),
162 role,
163 text: id,
164 turnId: null,
165 streaming: false,
166 createdAt: "2026-08-29T00:00:03.000Z",
167 updatedAt: "2026-08-29T00:00:03.000Z",
168 });
169 const feed = buildThreadFeed(
170 [
171 projected(userMessage("2026-08-29T00:00:01.000Z"), 0),
172 projected(laterUser, 1),
173 projected(laterAssistant, 2),
174 ],
175 {
176 anchoredMessages: [
177 localMessage("feedback-user", "user"),
178 localMessage("feedback-assistant", "assistant"),
179 localMessage("message-later-user", "user"),
180 ],
181 localMessages: [
182 {
183 ...localMessage("optimistic-user", "user"),
184 createdAt: "2026-08-29T00:00:00.000Z",
185 },
186 ],
187 },
188 );
189 const messages = feed.filter((entry) => entry.type === "message");
190​
191 expect(messages.map((entry) => entry.id)).toEqual([
192 "message-user",
193 "feedback-user",
194 "feedback-assistant",
195 "message-later-user",
196 "message-later-assistant",
197 "optimistic-user",
198 ]);
199 expect(
200 messages
201 .filter((entry) => entry.id.startsWith("feedback-"))
202 .every((entry) => entry.message.projectedItem === undefined),
203 ).toBe(true);
204 });
205​
206 it("keeps prominent activity visible while it is running", () => {
207 expect(
208 threadFeedActivityIsVisible({ prominent: true, status: "neutral", toolLike: true }),
209 ).toBe(true);
210 expect(
211 threadFeedActivityIsVisible({ prominent: false, status: "neutral", toolLike: true }),
212 ).toBe(false);
213 });
214​
215 it("presents provider retries as visible work-log activity", () => {
216 const retryBase = {
217 ...base("item-provider-retry", "2026-06-20T00:00:02.000Z", 1),
218 type: "error" as const,
219 failure: {
220 class: "transport_error" as const,
221 message: "The response stream disconnected.",
222 code: "responseStreamDisconnected",
223 retryable: true,
224 },
225 retry: {
226 attempt: 2,
227 maxAttempts: 5,
228 retryDelayMs: null,
229 },
230 };
231 const runningFeed = buildThreadFeed([
232 projected(
233 {
234 ...retryBase,
235 status: "running",
236 title: "Provider retry",
237 completedAt: null,
238 },
239 0,
240 ),
241 ]);
242 const recoveredFeed = buildThreadFeed([
243 projected(
244 {
245 ...retryBase,
246 status: "completed",
247 title: "Provider recovered",
248 },
249 0,
250 ),
251 ]);
252 const failedFeed = buildThreadFeed([
253 projected(
254 {
255 ...retryBase,
256 status: "failed",
257 title: "Provider retry failed",
258 },
259 0,
260 ),
261 projected(command("2026-06-20T00:00:03.000Z"), 1),
262 ]);
263 const runningActivity = runningFeed.find((entry) => entry.type === "activity-group")
264 ?.activities[0];
265 const recoveredActivity = recoveredFeed.find((entry) => entry.type === "activity-group")
266 ?.activities[0];
267 if (runningActivity === undefined || recoveredActivity === undefined) {
268 throw new Error("Expected provider retry work-log activities.");
269 }
270​
271 expect(runningActivity).toMatchObject({
272 summary: "Provider retry",
273 status: "neutral",
274 toolLike: false,
275 });
276 expect(threadFeedActivityIsVisible(runningActivity)).toBe(true);
277 expect(recoveredActivity).toMatchObject({
278 summary: "Provider recovered",
279 status: "success",
280 toolLike: false,
281 });
282 const failedPresentation = deriveThreadFeedPresentation(
283 failedFeed,
284 { runId, status: "running", startedAt: null, completedAt: null },
285 new Set(),
286 );
287 expect(failedPresentation.map((entry) => entry.type)).toEqual([
288 "activity-group",
289 "work-toggle",
290 ]);
291 expect(
292 failedPresentation[0]?.type === "activity-group"
293 ? failedPresentation[0].activities[0]?.summary
294 : null,
295 ).toBe("Provider retry failed");
296 });
297​
298 it("hides synthetic workspace preparation activity", () => {
299 const workspacePreparation = projected(
300 {
301 ...command(),
302 title: "Workspace ready",
303 input: "Preparing workspace",
304 output: "Workspace preparation completed.",
305 },
306 0,
307 );
308​
309 expect(buildThreadFeed([workspacePreparation])).toEqual([]);
310 });
311​
312 it("does not treat a queued-only run as live feed activity", () => {
313 expect(
314 threadFeedRunIsUnsettled({
315 runId,
316 status: "queued",
317 startedAt: null,
318 completedAt: null,
319 }),
320 ).toBe(false);
321 expect(
322 threadFeedRunIsUnsettled({
323 runId,
324 status: "running",
325 startedAt: "2026-06-20T00:00:01.000Z",
326 completedAt: null,
327 }),
328 ).toBe(true);
329 expect(
330 threadFeedRunIsUnsettled({
331 runId,
332 status: "completed",
333 startedAt: "2026-06-20T00:00:01.000Z",
334 completedAt: null,
335 }),
336 ).toBe(true);
337 expect(
338 threadFeedRunIsUnsettled({
339 runId,
340 status: "waiting",
341 startedAt: "2026-06-20T00:00:01.000Z",
342 completedAt: null,
343 }),
344 ).toBe(true);
345 });
346​
347 it("adds queued input only after dispatch creates its turn item", () => {
348 const dispatchedRunId = RunId.make("run-dispatched-queued");
349 const dispatchedMessageId = MessageId.make("message-dispatched-queued");
350 expect(buildThreadFeed([])).toEqual([]);
351​
352 const promotedEntries = buildThreadFeed([
353 projected(
354 {
355 ...userMessage(),
356 id: TurnItemId.make("item-dispatched-queued"),
357 runId: dispatchedRunId,
358 messageId: dispatchedMessageId,
359 inputIntent: "turn_start",
360 },
361 0,
362 ),
363 ]);
364 expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
365 expect(
366 promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
367 ).toBe("turn_start");
368 });
369​
370 it("hides the interruption request and keeps the terminal result", () => {
371 const request = projected(
372 {
373 ...base("item-interrupt-request", "2026-06-20T00:00:02.000Z", 1),
374 type: "run_interrupt_request",
375 message: "Interrupt requested",
376 },
377 0,
378 );
379 const result = projected(
380 {
381 ...base("item-interrupt-result", "2026-06-20T00:00:03.000Z", 2),
382 type: "run_interrupt_result",
383 message: "Run interrupted before provider start",
384 },
385 1,
386 );
387​
388 const activities = buildThreadFeed([request, result]).flatMap((entry) =>
389 entry.type === "activity-group" ? entry.activities : [],
390 );
391​
392 expect(activities).toHaveLength(1);
393 expect(activities[0]?.summary).toBe("Run interrupted");
394 expect(activities[0]?.detail).toBe("Run interrupted before provider start");
395 expect(
396 deriveThreadFeedPresentation(
397 buildThreadFeed([request, result]),
398 {
399 runId,
400 status: "interrupted",
401 startedAt: "2026-06-20T00:00:01.000Z",
402 completedAt: "2026-06-20T00:00:03.000Z",
403 },
404 new Set(),
405 ).some((entry) => entry.type === "run-fold"),
406 ).toBe(false);
407 });
408​
409 it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
410 const rows = [
411 projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
412 projected(command("2026-06-20T00:00:01.000Z"), 1),
413 projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
414 ];
415​
416 const feed = buildThreadFeed(rows);
417 expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
418 expect(feed.map((entry) => entry.id)).toEqual([
419 "message-user",
420 "local:thread-1:item-command",
421 "message-assistant",
422 ]);
423 const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
424 expect(activity?.projectedItem).toBe(rows[1]);
425 expect(activity?.getFullDetail()).toContain('"input": "vp check"');
426 });
427​
428 it("keeps adjacent work from different V2 attempts in separate groups", () => {
429 const firstRootNodeId = NodeId.make("node-attempt-1");
430 const secondRootNodeId = NodeId.make("node-attempt-2");
431 const firstCommand = { ...command(), nodeId: firstRootNodeId };
432 const secondCommand = {
433 ...command("2026-06-20T00:00:03.000Z"),
434 id: TurnItemId.make("item-command-retry"),
435 ordinal: 2,
436 nodeId: secondRootNodeId,
437 };
438 const attempts = [
439 {
440 id: RunAttemptId.make("attempt-1"),
441 runId,
442 attemptOrdinal: 1,
443 rootNodeId: firstRootNodeId,
444 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
445 providerThreadId: ProviderThreadId.make("provider-thread-1"),
446 providerTurnId: null,
447 reason: "initial",
448 status: "completed",
449 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"),
450 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
451 },
452 {
453 id: RunAttemptId.make("attempt-2"),
454 runId,
455 attemptOrdinal: 2,
456 rootNodeId: secondRootNodeId,
457 providerInstanceId: ProviderInstanceId.make("provider-instance-1"),
458 providerThreadId: ProviderThreadId.make("provider-thread-1"),
459 providerTurnId: null,
460 reason: "retry",
461 status: "completed",
462 startedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
463 completedAt: DateTime.makeUnsafe("2026-06-20T00:00:03.000Z"),
464 },
465 ] satisfies ReadonlyArray<OrchestrationV2RunAttempt>;
466​
467 const feed = buildThreadFeed([projected(firstCommand, 0), projected(secondCommand, 1)], {
468 attempts,
469 });
470​
471 expect(feed).toHaveLength(2);
472 expect(
473 feed.map((entry) =>
474 entry.type === "activity-group" ? entry.activities[0]?.attemptId : null,
475 ),
476 ).toEqual(["attempt-1", "attempt-2"]);
477 });
478​
479 it("retains inherited and synthetic rows with their original projected identity", () => {
480 const inherited = projected(command(), 0, "inherited");
481 const { providerThreadId: _providerThreadId, ...forkBase } = base(
482 "item-fork",
483 "2026-06-20T00:00:03.000Z",
484 2,
485 );
486 const synthetic = projected(
487 {
488 ...forkBase,
489 type: "fork",
490 source: { type: "run", threadId: sourceThreadId, runId },
491 targetThreadId: threadId,
492 },
493 1,
494 "synthetic",
495 );
496​
497 const feed = buildThreadFeed([inherited, synthetic]);
498 const activities = feed.flatMap((entry) =>
499 entry.type === "activity-group" ? entry.activities : [],
500 );
501 expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
502 expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
503 "inherited",
504 "synthetic",
505 ]);
506 expect(activities.at(-1)?.prominent).toBe(true);
507 });
508​
509 it("keeps orchestration relationship cards visible when a completed run is folded", () => {
510 const { providerThreadId: _providerThreadId, ...forkBase } = base(
511 "item-fork",
512 "2026-06-20T00:00:02.500Z",
513 2,
514 );
515 const feed = buildThreadFeed([
516 projected(userMessage(), 0),
517 projected(command(), 1),
518 projected(
519 {
520 ...forkBase,
521 type: "fork",
522 source: { type: "run", threadId, runId },
523 targetThreadId: sourceThreadId,
524 },
525 2,
526 ),
527 projected(assistantMessage(), 3),
528 ]);
529​
530 const collapsed = deriveThreadFeedPresentation(
531 feed,
532 {
533 runId,
534 status: "completed",
535 startedAt: "2026-06-20T00:00:01.000Z",
536 completedAt: "2026-06-20T00:00:03.000Z",
537 },
538 new Set(),
539 );
540​
541 expect(
542 collapsed.some(
543 (entry) =>
544 entry.type === "activity-group" &&
545 entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
546 ),
547 ).toBe(true);
548 expect(
549 collapsed.some(
550 (entry) =>
551 entry.type === "activity-group" &&
552 entry.activities.some(
553 (activity) => activity.projectedItem.item.type === "command_execution",
554 ),
555 ),
556 ).toBe(false);
557 });
558​
559 it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
560 const feed = buildThreadFeed([
561 projected(userMessage(), 0),
562 projected(command(), 1),
563 projected(assistantMessage(), 2),
564 ]);
565 const latestRun = {
566 runId,
567 status: "completed" as const,
568 startedAt: "2026-06-20T00:00:01.000Z",
569 completedAt: "2026-06-20T00:00:03.000Z",
570 };
571​
572 const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
573 expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
574​
575 const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
576 expect(expanded.map((entry) => entry.type)).toEqual([
577 "message",
578 "run-fold",
579 "work-toggle",
580 "message",
581 ]);
582 });
583​
584 it("keeps an active run expanded and detects failures from completed command output", () => {
585 const failedCommand: OrchestrationV2TurnItem = {
586 ...command(),
587 output: "sh: missing-command: command not found",
588 };
589 const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
590 const presented = deriveThreadFeedPresentation(
591 feed,
592 {
593 runId,
594 status: "running",
595 startedAt: "2026-06-20T00:00:01.000Z",
596 completedAt: null,
597 },
598 new Set(),
599 );
600​
601 expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
602 expect(presented.find((entry) => entry.type === "work-toggle")).toMatchObject({
603 summary: "Ran 1 command",
604 hiddenCount: 1,
605 hasFailure: true,
606 live: false,
607 });
608 });
609​
610 it("does not append synthetic timeline work without a projected item", () => {
611 const startedAt = "2026-04-01T00:00:01.000Z";
612 const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
613​
614 expect(presented).toEqual([]);
615 });
616​
617 it("models work-log overflow as list rows", () => {
618 const activity = (
619 id: string,
620 createdAt: string,
621 status: ThreadFeedActivity["status"] = "success",
622 ): ThreadFeedActivity => ({
623 id,
624 createdAt,
625 runId: null,
626 attemptId: null,
627 summary: `Tool ${id}`,
628 detail: null,
629 canExpand: false,
630 getFullDetail: () => null,
631 getCopyText: () => id,
632 icon: "command",
633 logo: null,
634 toolLike: true,
635 prominent: false,
636 status,
637 lifecycleStatus: status === "neutral" ? "inProgress" : "completed",
638 workEntry: {
639 id,
640 createdAt,
641 label: `Tool ${id}`,
642 tone: "tool",
643 command: "vp check",
644 itemType: "command_execution",
645 toolLifecycleStatus: status === "neutral" ? "inProgress" : "completed",
646 },
647 projectedItem: projected(command(createdAt), 0),
648 });
649 const feed: ThreadFeedEntry[] = [
650 {
651 type: "activity-group",
652 id: "work-group-1",
653 createdAt: "2026-04-01T00:00:01.000Z",
654 runId: null,
655 activities: [
656 activity("activity-neutral", "2026-04-01T00:00:01.000Z", "neutral"),
657 activity("activity-1", "2026-04-01T00:00:02.000Z"),
658 activity("activity-2", "2026-04-01T00:00:03.000Z"),
659 activity("activity-3", "2026-04-01T00:00:04.000Z"),
660 ],
661 },
662 ];
663​
664 const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
665 expect(collapsed.map((entry) => entry.id)).toEqual(["work-toggle:work-group:activity-neutral"]);
666 expect(collapsed[0]).toMatchObject({
667 type: "work-toggle",
668 groupId: "work-group:activity-neutral",
669 hiddenCount: 3,
670 expanded: false,
671 summary: "Ran 3 commands",
672 });
673​
674 const expanded = deriveThreadFeedPresentation(
675 feed,
676 null,
677 new Set(),
678 new Set(["work-group:activity-neutral"]),
679 );
680 expect(expanded.map((entry) => entry.id)).toEqual([
681 "work-toggle:work-group:activity-neutral",
682 "activity-1",
683 "activity-2",
684 "activity-3",
685 ]);
686 expect(expanded[0]).toMatchObject({
687 type: "work-toggle",
688 expanded: true,
689 });
690 });
691​
692 it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => {
693 const toolItem: OrchestrationV2TurnItem = {
694 ...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3),
695 type: "dynamic_tool",
696 toolName: "mcp__t3-code__t3_thread_read",
697 input: { threadId: "thread-child" },
698 output: { messages: [] },
699 };
700​
701 const feed = buildThreadFeed([projected(toolItem, 0)]);
702 const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null;
703​
704 expect(activity?.summary).toBe("Read a T3 thread");
705 expect(activity?.logo).toBe("t3-code");
706 expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread");
707 });
708​
709 it("uses canonical T3 orchestration summaries in compact work groups", () => {
710 const rows = [
711 projected(command("2026-06-20T00:00:01.000Z"), 0),
712 ...["mcp__t3-code__t3_thread_send", "t3_code.t3_thread_send", "t3_thread_send"].map(
713 (toolName, index) =>
714 projected(
715 {
716 ...base(`item-send-${index}`, `2026-06-20T00:00:0${index + 2}.000Z`, index + 2),
717 type: "dynamic_tool" as const,
718 toolName,
719 input: { threadId: `thread-${index}`, message: "Continue" },
720 output: { threadId: `thread-${index}`, messageId: `message-${index}` },
721 },
722 index + 1,
723 ),
724 ),
725 projected(
726 {
727 ...command("2026-06-20T00:00:06.000Z"),
728 id: TurnItemId.make("item-command-2"),
729 ordinal: 6,
730 },
731 4,
732 ),
733 ];
734​
735 const presented = deriveThreadFeedPresentation(
736 buildThreadFeed(rows),
737 { runId, status: "running", startedAt: null, completedAt: null },
738 new Set(),
739 );
740​
741 expect(presented).toMatchObject([
742 {
743 type: "work-toggle",
744 summary: "Ran 2 commands and sent messages to 3 threads",
745 hiddenCount: 5,
746 hasFailure: false,
747 },
748 ]);
749 });
750});
751​
752const singleSelectQuestion = {
753 id: "runtime",
754 header: "Runtime",
755 question: "Which runtime should be used?",
756 options: [
757 { label: "Go", description: "One binary" },
758 { label: "Node.js", description: "Reuse TypeScript" },
759 ],
760 multiSelect: false,
761} as const;
762​
763const multiSelectQuestion = {
764 id: "scope",
765 header: "Scope",
766 question: "Which data should be collected?",
767 options: [
768 { label: "Orders", description: "Receipts" },
769 { label: "Listings", description: "Inventory" },
770 ],
771 multiSelect: true,
772} as const;
773​
774describe("pending user input answers", () => {
775 it("replaces single-select options and toggles multi-select options", () => {
776 expect(
777 togglePendingUserInputOptionSelection(
778 singleSelectQuestion,
779 { selectedOptionLabels: ["Go"] },
780 "Node.js",
781 ),
782 ).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
783​
784 const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
785 const ordersAndListings = togglePendingUserInputOptionSelection(
786 multiSelectQuestion,
787 orders,
788 "Listings",
789 );
790 expect(ordersAndListings).toEqual({
791 customAnswer: "",
792 selectedOptionLabels: ["Orders", "Listings"],
793 });
794 expect(
795 togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
796 ).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
797​
798 const paddedOrders = togglePendingUserInputOptionSelection(
799 multiSelectQuestion,
800 undefined,
801 " Orders ",
802 );
803 expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
804 expect(
805 togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
806 ).toEqual({ customAnswer: "" });
807 });
808​
809 it("builds array answers for multi-select questions", () => {
810 expect(
811 buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
812 runtime: { selectedOptionLabels: ["Go"] },
813 scope: { selectedOptionLabels: ["Orders", "Listings"] },
814 }),
815 ).toEqual({
816 runtime: "Go",
817 scope: ["Orders", "Listings"],
818 });
819 });
820​
821 it("clears selected options while a custom answer is active", () => {
822 expect(
823 setPendingUserInputCustomAnswer(
824 { selectedOptionLabels: ["Orders", "Listings"] },
825 "Orders first",
826 ),
827 ).toEqual({ customAnswer: "Orders first" });
828 });
829​
830 it("matches selected chips against normalized option labels", () => {
831 expect(
832 isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
833 ).toBe(true);
834 expect(
835 isPendingUserInputOptionSelected(
836 { selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
837 " Orders ",
838 ),
839 ).toBe(false);
840 });
841});