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

threadRequests.ts

664 lines25.1 KB

1import type {
2 EnvironmentId,
3 ScopedThreadRef,
4 ThreadId,
5 OrchestrationV2ThreadProjection,
6 OrchestrationV2RuntimeRequest,
7 OrchestrationV2UserInputQuestion,
8 ProviderApprovalFullAccessOverride,
9 ProviderApprovalOption,
10 ProviderApprovalPushHooks,
11 ProviderApprovalDecision,
12 ProviderRequestKind,
13 RuntimeRequestId,
14} from "@t3tools/contracts";
15import { Atom } from "effect/reactivity";
16import { parseThreadKey, threadKey } from "./entities.ts";
17import { getProjectionArrayReplacementIndex } from "./orchestrationV2Projection.ts";
18import type { EnvironmentThreadShell } from "./models.ts";
19import * as DateTime from "effect/DateTime";
20import type { AtomCommandResult } from "./runtime.ts";
21import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.ts";
22import { mFallback, msg } from "gt-i18n";
23import type { MFunctionType } from "gt-i18n/types";
24​
25export type ApprovalResponder = (
26 requestId: RuntimeRequestId,
27 decision: ProviderApprovalDecision,
28 feedback?: string,
29) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
30​
31/** Feedback belongs to the displayed request, which may be a native child's tool call. */
32export async function sendApprovalFeedback(
33 approval: ThreadPendingApproval,
34 feedback: string,
35 respond: ApprovalResponder,
36): Promise<boolean> {
37 if (!approval.supportsFeedback || approval.responseCapability !== "live" || !feedback.trim())
38 return false;
39 return (await respond(approval.requestId, "decline", feedback.trim()))?._tag === "Success";
41​
42/** Declines every approval a redirect replaces; any one still pending would block the agent. */
43export async function declinePendingApprovals(
44 approvals: ReadonlyArray<ThreadPendingApproval>,
45 respond: ApprovalResponder,
46): Promise<boolean> {
47 for (const approval of approvals) {
48 // A request the provider can no longer answer has nothing to decline.
49 if (approval.responseCapability !== "live") continue;
50 if ((await respond(approval.requestId, "decline"))?._tag !== "Success") return false;
51 }
52 return true;
54​
55export interface ThreadPendingApproval {
56 readonly requestId: RuntimeRequestId;
57 readonly requestKind: ProviderRequestKind;
58 readonly createdAt: string;
59 readonly detail?: string;
60 readonly reason?: string;
61 readonly fullAccessOverride?: ProviderApprovalFullAccessOverride;
62 readonly appName?: string;
63 /** Set when T3 Code itself asks to run a repository's push hooks; `detail` is the same in one sentence. */
64 readonly pushHooks?: ProviderApprovalPushHooks;
65 readonly options?: ReadonlyArray<ProviderApprovalOption>;
66 readonly responseCapability: "live" | "not_resumable";
67 readonly supportsFeedback?: boolean;
69​
70export interface ApprovalTextPart {
71 readonly text: string;
72 /** Set when `text` names a character a screen would not draw. */
73 readonly named?: true;
75​
76// Control, format, separator and ignorable characters draw as nothing or as a blank box, and some
77// reorder the text beside them. A line feed and a tab draw as themselves and are not in the set.
78const UNDRAWN = /[\0-\x08\x0B-\x1F\x7F-\x9F\p{Zl}\p{Zp}\p{Cf}\p{Default_Ignorable_Code_Point}]/gu;
79const UNDRAWN_NAMES: Readonly<Record<string, string>> = {
80 "\r": "\\r",
81 "\b": "\\b",
82 "\u001B": "\\e",
83};
84const PICTOGRAPH = /^\p{Extended_Pictographic}$/u;
85// The pictographic range also holds code points reserved for emoji that do not exist yet.
86const EMOJI = /^\p{Emoji}$/u;
87const SKIN_TONE_BASE = /^\p{Emoji_Modifier_Base}$/u;
88const JOINER = 0x200d;
89const TEXT_SELECTOR = 0xfe0e;
90const EMOJI_SELECTOR = 0xfe0f;
91const KEYCAP = 0x20e3;
92​
93const isSkinTone = (codePoint: number) => codePoint >= 0x1f3fb && codePoint <= 0x1f3ff;
94// An emoji that is not a skin tone, which only colours the emoji before it.
95const isPicture = (codePoint: number) => {
96 if (codePoint < 0 || isSkinTone(codePoint)) return false;
97 const character = String.fromCodePoint(codePoint);
98 return PICTOGRAPH.test(character) && EMOJI.test(character);
99};
100// A digit, # or *.
101const isKeycapBase = (codePoint: number) =>
102 (codePoint >= 0x30 && codePoint <= 0x39) || codePoint === 0x23 || codePoint === 0x2a;
103​
104/** The code point that ends at `end`, or -1 at the start of the text. */
105function codePointBefore(text: string, end: number): number {
106 if (end <= 0) return -1;
107 const unit = text.charCodeAt(end - 1);
108 if (unit >= 0xdc00 && unit <= 0xdfff && end >= 2) {
109 const lead = text.charCodeAt(end - 2);
110 if (lead >= 0xd800 && lead <= 0xdbff) return text.codePointAt(end - 2) ?? unit;
111 }
112 return unit;
114​
115/**
116 * Whether the undrawn character at `index` is part of an emoji: a joiner directly between two
117 * emoji, or a presentation selector directly after an emoji or in a keycap. It reads at most two
118 * code points before the character and one after it.
119 */
120function isInsideEmoji(text: string, index: number, codePoint: number): boolean {
121 if (codePoint !== JOINER && codePoint !== EMOJI_SELECTOR && codePoint !== TEXT_SELECTOR) {
122 return false;
123 }
124 const before = codePointBefore(text, index);
125 const after = text.codePointAt(index + 1) ?? -1;
126 if (codePoint !== JOINER) {
127 return (
128 isPicture(before) ||
129 (codePoint === EMOJI_SELECTOR && isKeycapBase(before) && after === KEYCAP)
130 );
131 }
132 if (!isPicture(after)) return false;
133 if (isPicture(before)) return true;
134 // The emoji before the joiner may end in its emoji selector or its skin tone.
135 const base = codePointBefore(text, index - (before > 0xffff ? 2 : 1));
136 if (before === EMOJI_SELECTOR) return isPicture(base);
137 return isSkinTone(before) && base >= 0 && SKIN_TONE_BASE.test(String.fromCodePoint(base));
139​
140export interface ApprovalTextLimit {
141 /** UTF-16 units of the text a card shows at most, its beginning and its end together. */
142 readonly length: number;
143 /** Runs of named characters, each one element in a card, shown at most in the beginning. */
144 readonly namedRuns: number;
145 /** UTF-16 units of the end of the text shown at most when the text is cut. */
146 readonly tailLength: number;
147 /** Runs of named characters shown at most in the end. */
148 readonly tailNamedRuns: number;
150​
151// A card draws one element per run of named characters and lays the whole text out at once, so
152// both are bounded: measured in Chromium, the web card at these limits renders in about 100 ms,
153// and past them the time grows in step with the text. The end comes out of the same 100,000
154// units (some 1,250 full lines, 50 of them the end) and adds at most a tenth to the elements.
155export const APPROVAL_TEXT_LIMIT: ApprovalTextLimit = {
156 length: 100_000,
157 namedRuns: 2_000,
158 tailLength: 4_000,
159 tailNamedRuns: 200,
160};
161​
162export interface ApprovalTextScan {
163 /** The text, or its shown beginning when it is cut. A run of named characters is one part. */
164 readonly parts: ReadonlyArray<ApprovalTextPart>;
165 /** The shown end of a cut text. Empty when the text is not cut. */
166 readonly tail: ReadonlyArray<ApprovalTextPart>;
167 /** UTF-16 units of the text that `parts` covers. */
168 readonly shownLength: number;
169 /** UTF-16 units between the beginning and the end that no part covers. 0 when not cut. */
170 readonly hiddenLength: number;
171 /** UTF-16 units of the whole text. */
172 readonly length: number;
174​
175const isLowSurrogate = (unit: number) => unit >= 0xdc00 && unit <= 0xdfff;
176const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
177/** Whether `index` is between the two halves of one code point. */
178const splitsCodePoint = (text: string, index: number) =>
179 index > 0 &&
180 index < text.length &&
181 isLowSurrogate(text.charCodeAt(index)) &&
182 isHighSurrogate(text.charCodeAt(index - 1));
183​
184/**
185 * `shown` in parts, each character a screen would not draw replaced by its name, up to
186 * `namedRuns` runs. `starts[i]` is where part `i` begins in `shown` and `stop` where the parts
187 * end. One pass: the work per character does not depend on what surrounds it.
188 */
189function scanApprovalText(shown: string, namedRuns: number) {
190 const parts: ApprovalTextPart[] = [];
191 const starts: number[] = [];
192 let stop = shown.length;
193 let end = 0;
194 let names = "";
195 let namesStart = 0;
196 let runs = 0;
197 for (const match of shown.matchAll(UNDRAWN)) {
198 const [character] = match;
199 const codePoint = character.codePointAt(0) ?? 0;
200 if (isInsideEmoji(shown, match.index, codePoint)) continue;
201 if (match.index > end || names === "") {
202 if (runs === namedRuns) {
203 stop = match.index;
204 break;
205 }
206 if (names !== "") {
207 parts.push({ text: names, named: true });
208 starts.push(namesStart);
209 }
210 if (match.index > end) {
211 parts.push({ text: shown.slice(end, match.index) });
212 starts.push(end);
213 }
214 names = "";
215 namesStart = match.index;
216 runs += 1;
217 }
218 names +=
219 UNDRAWN_NAMES[character] ?? `U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
220 end = match.index + character.length;
221 }
222 if (names !== "") {
223 parts.push({ text: names, named: true });
224 starts.push(namesStart);
225 }
226 if (end < stop) {
227 parts.push({ text: shown.slice(end, stop) });
228 starts.push(end);
229 }
230 return { parts, starts, stop };
232​
233/**
234 * Approval text in parts, each character a screen would not draw replaced by its name. Text that
235 * passes `limit` is cut in the middle: `parts` is its beginning and `tail` its end, so what the
236 * text ends with is always shown. Only the shown text is read, in one pass, and a cut never falls
237 * inside a code point.
238 */
239export function approvalTextParts(
240 text: string,
241 limit: ApprovalTextLimit = APPROVAL_TEXT_LIMIT,
242): ApprovalTextScan {
243 const { length } = text;
244 const tailLength = Math.max(0, Math.min(limit.tailLength, limit.length));
245 let headEnd = length > limit.length ? Math.max(0, limit.length - tailLength) : length;
246 if (splitsCodePoint(text, headEnd)) headEnd -= 1;
247 const head = scanApprovalText(headEnd < length ? text.slice(0, headEnd) : text, limit.namedRuns);
248 if (head.stop === length) {
249 return { parts: head.parts, tail: [], shownLength: length, hiddenLength: 0, length };
250 }
251​
252 let tailStart = Math.max(head.stop, length - tailLength);
253 if (splitsCodePoint(text, tailStart)) tailStart += 1;
254 const end = scanApprovalText(text.slice(tailStart), Number.POSITIVE_INFINITY);
255 // Past its runs the end keeps the last of them: it starts after the run before those.
256 let first = 0;
257 for (let index = end.parts.length - 1, runs = 0; index >= 0; index -= 1) {
258 if (!end.parts[index]?.named) continue;
259 if (runs === limit.tailNamedRuns) {
260 first = index + 1;
261 break;
262 }
263 runs += 1;
264 }
265 const tail = first === 0 ? end.parts : end.parts.slice(first);
266 tailStart += end.starts[first] ?? end.stop;
267​
268 // The end begins where the beginning stopped: nothing is hidden, so the text is not cut.
269 if (tailStart === head.stop) {
270 return {
271 parts: [...head.parts, ...tail],
272 tail: [],
273 shownLength: length,
274 hiddenLength: 0,
275 length,
276 };
277 }
278 return {
279 parts: head.parts,
280 tail,
281 shownLength: head.stop,
282 hiddenLength: tailStart - head.stop,
283 length,
284 };
286​
287export const PUSH_HOOKS_APPROVAL_LABEL = msg("Push hooks approval");
288export const PUSH_HOOKS_APPROVAL_QUESTION = msg("Run this repository's push hooks?");
289​
290export interface ApprovalDetailRow {
291 readonly label: string;
292 /** Plain text ahead of the code: a configured hook's name. */
293 readonly name?: string;
294 /** A branch, file path or command. */
295 readonly code: string;
297​
298/** What a push hooks approval names: the branch, then each hook the push would run. */
299export function pushHooksApprovalRows(
300 pushHooks: ProviderApprovalPushHooks,
301 resolve: MFunctionType = mFallback,
302): ReadonlyArray<ApprovalDetailRow> {
303 return [
304 { label: resolve(msg("Branch", { $context: "field label" })), code: pushHooks.branch },
305 ...pushHooks.files.map((file) => ({ label: resolve(msg("Hook file")), code: file })),
306 ...pushHooks.commands.map(({ name, command }) => ({
307 label: resolve(msg("Configured hook", { $context: "a hook Git's configuration defines" })),
308 name,
309 code: command,
310 })),
311 ];
313​
314export const FULL_ACCESS_OVERRIDE_QUESTION = msg("Why am I being asked this?");
315​
316export function fullAccessOverrideExplanation(
317 override: ProviderApprovalFullAccessOverride,
318 resolve: MFunctionType = mFallback,
319): string {
320 return override === "ask_rule"
321 ? resolve(
322 msg(
323 "Full access skips approvals, but an ask rule in the agent's own settings matches this action, so it still asks. Remove or narrow that rule to stop these prompts.",
324 ),
325 )
326 : resolve(
327 msg(
328 "Full access skips approvals, but the agent still stops for a few safety checks of its own that no setting can skip, such as a delete whose path it can't verify. T3 Code can't turn these off, so check the request and approve it if it's what you expect.",
329 ),
330 );
332​
333export interface ThreadUserInputQuestion extends Omit<
334 OrchestrationV2UserInputQuestion,
335 "multiSelect"
336> {
337 readonly multiSelect: boolean;
339​
340export interface ThreadPendingUserInput {
341 readonly requestId: RuntimeRequestId;
342 readonly createdAt: string;
343 readonly questions: ReadonlyArray<ThreadUserInputQuestion>;
344 readonly responseCapability: OrchestrationV2RuntimeRequest["responseCapability"]["type"];
345 readonly responseMode?: "message";
346 readonly dismissible: boolean;
348​
349export interface PendingThreadRequests {
350 readonly approvals: ReadonlyArray<ThreadPendingApproval>;
351 readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
353​
354export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?: string }>(
355 questions: ReadonlyArray<
356 Pick<OrchestrationV2UserInputQuestion, "id" | "allowCustomAnswer" | "initialAnswer">
357 >,
358 drafts: Record<string, Draft>,
359): Record<string, Draft | { customAnswer: string }> {
360 // Entries, not assignment, so an id such as `__proto__` becomes an own draft.
361 const seeds = questions.flatMap((question) =>
362 question.initialAnswer === undefined ||
363 question.allowCustomAnswer === false ||
364 Object.hasOwn(drafts, question.id)
365 ? []
366 : [[question.id, { customAnswer: question.initialAnswer }] as const],
367 );
368 return seeds.length === 0 ? drafts : { ...drafts, ...Object.fromEntries(seeds) };
370​
371/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */
372export function userInputDraftKey(
373 environmentId: string,
374 threadId: string | null,
375 requestId: string | undefined,
376): string {
377 return JSON.stringify([environmentId, threadId, requestId]);
379​
380/**
381 * Drops the thread's drafts for requests outside `pendingRequestIds`, leaving
382 * other threads alone. Returns the input itself when nothing is dropped.
383 */
384export function pruneResolvedUserInputDrafts<T>(
385 draftsByRequestKey: Record<string, T>,
386 environmentId: string,
387 threadId: string,
388 pendingRequestIds: ReadonlyArray<string>,
389): Record<string, T> {
390 const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
391 const pendingKeys = new Set(
392 pendingRequestIds.map((requestId) => userInputDraftKey(environmentId, threadId, requestId)),
393 );
394 const retained = Object.entries(draftsByRequestKey).filter(
395 ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
396 );
397 return retained.length === Object.keys(draftsByRequestKey).length
398 ? draftsByRequestKey
399 : Object.fromEntries(retained);
401​
402/**
403 * Question attachment drafts are keyed `<thread prefix><encoded [requestId, questionId]>`.
404 * Returns the keys under `threadPrefix` whose request is outside `pendingRequestIds`.
405 */
406export function resolvedQuestionDraftKeys(
407 keys: Iterable<string>,
408 threadPrefix: string,
409 pendingRequestIds: ReadonlyArray<string>,
410): string[] {
411 // encodeURIComponent is per character, so an encoded JSON prefix prefixes the encoded key.
412 const pendingPrefixes = pendingRequestIds.map(
413 (requestId) =>
414 `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,
415 );
416 const resolved: string[] = [];
417 for (const key of keys) {
418 if (key.startsWith(threadPrefix) && !pendingPrefixes.some((prefix) => key.startsWith(prefix)))
419 resolved.push(key);
420 }
421 return resolved;
423​
424export interface ThreadRequestsResolved {
425 readonly environmentId: EnvironmentId;
426 readonly threadId: ThreadId;
427 /** Every request the thread still waits on; drafts for any other request are stale. */
428 readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
429 /** Requests that closed without an answer (cancelled or expired), so typed drafts were never sent. */
430 readonly unansweredRequestIds: ReadonlyArray<RuntimeRequestId>;
432​
433const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
434​
435/**
436 * Clients register draft pruners once at module level. Thread state announces
437 * when its synchronized projection first lands and whenever a request leaves
438 * pending, wherever the resolution came from (another device, interrupt, turn end).
439 */
440export function onThreadRequestsResolved(
441 listener: (event: ThreadRequestsResolved) => void,
442): () => void {
443 threadRequestsResolvedListeners.add(listener);
444 return () => threadRequestsResolvedListeners.delete(listener);
446​
447function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
448 for (const listener of threadRequestsResolvedListeners) {
449 try {
450 listener(event);
451 } catch (error) {
452 // A failing pruner must neither stop the others nor break thread sync.
453 queueMicrotask(() => {
454 throw error;
455 });
456 }
457 }
459​
460/**
461 * Tracks one thread's announced pending requests. Feed it the runtime requests
462 * of each authoritative projection; it notifies on the first one and whenever an
463 * announced request is no longer pending. New requests alone stay quiet.
464 */
465export function makeThreadRequestsResolvedAnnouncer(
466 environmentId: EnvironmentId,
467 threadId: ThreadId,
468) {
469 let announced: ReadonlySet<RuntimeRequestId> | null = null;
470 return (
471 runtimeRequests: ReadonlyArray<
472 Pick<OrchestrationV2ThreadProjection["runtimeRequests"][number], "id" | "status">
473 >,
474 ) => {
475 const pendingRequestIds = runtimeRequests.flatMap((request) =>
476 request.status === "pending" ? [request.id] : [],
477 );
478 const pending = new Set(pendingRequestIds);
479 const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
480 announced = pending;
481 if (!resolvedSome) return;
482 const unansweredRequestIds = runtimeRequests.flatMap((request) =>
483 request.status === "cancelled" || request.status === "expired" ? [request.id] : [],
484 );
485 notifyThreadRequestsResolved({
486 environmentId,
487 threadId,
488 pendingRequestIds,
489 unansweredRequestIds,
490 });
491 };
493​
494export function derivePendingThreadRequests(
495 projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
496): PendingThreadRequests {
497 const approvals: ThreadPendingApproval[] = [];
498 const userInputs: ThreadPendingUserInput[] = [];
499​
500 for (const request of projection.runtimeRequests) {
501 if (request.status !== "pending") continue;
502 const responseCapability = request.responseCapability.type;
503 if (request.kind === "user_input") {
504 const item = projection.turnItems.findLast(
505 (candidate) =>
506 candidate.type === "user_input_request" && candidate.requestId === request.id,
507 );
508 if (item === undefined || item.type !== "user_input_request") continue;
509 userInputs.push({
510 requestId: request.id,
511 createdAt: DateTime.formatIso(request.createdAt),
512 questions: item.questions.map((question) => ({
513 ...question,
514 multiSelect: question.multiSelect ?? false,
515 })),
516 responseCapability,
517 dismissible: item.responseMode === "message" || responseCapability === "message",
518 ...(item.responseMode === "message" || responseCapability === "message"
519 ? { responseMode: "message" as const }
520 : {}),
521 });
522 continue;
523 }
524​
525 if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
526 const item = projection.turnItems.findLast(
527 (candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
528 );
529 approvals.push({
530 requestId: request.id,
531 requestKind: request.kind,
532 createdAt: DateTime.formatIso(request.createdAt),
533 ...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
534 ...(item?.type === "approval_request" && item.reason ? { reason: item.reason } : {}),
535 ...(item?.type === "approval_request" && item.fullAccessOverride
536 ? { fullAccessOverride: item.fullAccessOverride }
537 : {}),
538 ...(item?.type === "approval_request" && item.appName ? { appName: item.appName } : {}),
539 ...(item?.type === "approval_request" && item.pushHooks ? { pushHooks: item.pushHooks } : {}),
540 ...(item?.type === "approval_request" && item.options !== undefined
541 ? { options: item.options }
542 : {}),
543 responseCapability: responseCapability === "live" ? "live" : "not_resumable",
544 ...(request.responseCapability.type === "live" && request.responseCapability.supportsFeedback
545 ? { supportsFeedback: true }
546 : {}),
547 });
548 }
549​
550 return { approvals, userInputs };
552​
553export function createQuestionHistoryProjector<
554 Row extends ThreadStructureVisibleTurnItem =
555 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
556>() {
557 type Rows = ReadonlyArray<Row>;
558 type Requests = OrchestrationV2ThreadProjection["runtimeRequests"];
559 let previousRows: Rows | undefined;
560 let previousRequests: Requests | undefined;
561 let previousResult: Rows | undefined;
562 let byId = new Map<RuntimeRequestId, Requests[number]>();
563 const cache = new WeakMap<Row, { request: Requests[number]; row: Row }>();
564 const projectRow = (row: Row): Row => {
565 const item = row.item;
566 if (item.type !== "user_input_request" || item.questionAnswer) return row;
567 const request = byId.get(item.requestId);
568 if (request?.status !== "resolved" || request.answers === undefined) return row;
569 const cached = cache.get(row);
570 const next: Row =
571 cached?.request === request
572 ? cached.row
573 : {
574 ...row,
575 item: {
576 ...item,
577 questionAnswer: {
578 requestId: request.id,
579 answers: request.answers,
580 attachmentsByQuestionId: {},
581 questionTextById: Object.fromEntries(
582 item.questions.map((question) => [question.id, question.question]),
583 ),
584 },
585 },
586 };
587 cache.set(row, { request, row: next });
588 return next;
589 };
590 const projectRows = (rows: Rows): Rows => {
591 let result: Row[] | undefined;
592 for (const [index, row] of rows.entries()) {
593 const next = projectRow(row);
594 if (next !== row) result ??= rows.slice(0, index);
595 result?.push(next);
596 }
597 return result ?? rows;
598 };
599 return (projection: {
600 readonly visibleTurnItems: Rows;
601 readonly runtimeRequests: Requests;
602 }): Rows => {
603 const { visibleTurnItems: rows, runtimeRequests: requests } = projection;
604 const sameRequests = requests === previousRequests;
605 if (rows === previousRows && sameRequests && previousResult) return previousResult;
606 if (!sameRequests) byId = new Map(requests.map((request) => [request.id, request]));
607 // Nothing was overlaid and requests are unchanged, so only an exactly replaced row can differ.
608 const replacedIndex =
609 sameRequests && previousRows !== undefined && previousResult === previousRows
610 ? getProjectionArrayReplacementIndex(previousRows, rows)
611 : undefined;
612 const unchanged =
613 replacedIndex !== undefined && projectRow(rows[replacedIndex]!) === rows[replacedIndex];
614 previousRows = rows;
615 previousRequests = requests;
616 previousResult = unchanged ? rows : projectRows(rows);
617 return previousResult;
618 };
620​
621export interface ChildThreadApproval {
622 readonly thread: ScopedThreadRef;
623 readonly title: string;
624 readonly approval: ThreadPendingApproval;
626​
627export function createChildThreadApprovalsAtom(input: {
628 readonly childThreadInputsAtom: (
629 ref: ScopedThreadRef,
630 ) => Atom.Atom<ReadonlyArray<EnvironmentThreadShell>>;
631 readonly pendingRequestsAtom: (ref: ScopedThreadRef) => Atom.Atom<PendingThreadRequests | null>;
632}) {
633 const family = Atom.family((key: string) => {
634 let previous: ReadonlyArray<ChildThreadApproval> = [];
635 return Atom.make((get) => {
636 const next = get(input.childThreadInputsAtom(parseThreadKey(key))).flatMap((child) => {
637 if (!child.hasPendingApprovals) return [];
638 const thread = { environmentId: child.environmentId, threadId: child.id };
639 // Only children asking for approval need a detail subscription.
640 return (get(input.pendingRequestsAtom(thread))?.approvals ?? []).map((approval) => ({
641 thread,
642 title: child.title,
643 approval,
644 }));
645 });
646 if (
647 next.length === previous.length &&
648 next.every((entry, index) => {
649 const old = previous[index]!;
650 return (
651 old.approval === entry.approval &&
652 old.title === entry.title &&
653 threadKey(old.thread) === threadKey(entry.thread)
654 );
655 })
656 )
657 return previous;
658 previous = next;
659 return next;
660 });
661 });
662 const empty = Atom.make<ReadonlyArray<ChildThreadApproval>>([]);
663 return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref)));