Repository navigation
Expand file tree
/
Copy pathThread.tsx
More file actions
3958 lines (3870 loc) · 203 KB
/
Copy pathThread.tsx
File metadata and controls
3958 lines (3870 loc) · 203 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Viewer, type ViewerHandle } from '@plannotator/ui/components/Viewer';
import type { Annotation, Block } from '@plannotator/ui/types';
import { annotationOwnsHighlight } from '@plannotator/ui/utils/annotationOwnsHighlight';
import { ImageLightbox } from '@plannotator/ui/components/ImageLightbox';
import { parseMarkdownToBlocks } from '@plannotator/ui/utils/parser';
import type { InboxListRow, InboxMessageWire, InboxProjectRepo, InboxQuestion, InboxSentRecipient, InboxThread, InboxUpload } from '@plannotator/core/inbox-types';
import { capQuestionPrompt, emptyQuestionAnswer, indexQuestionBlocks, isQuestionAnswerEmpty, type IndexedQuestion, type QuestionAnswer, type QuestionStatus } from '@plannotator/core/question-block';
import { INBOX_AUTO_SEND_ACK_NOTES, inboxAskingMessage, wholeMinutes, isInboxNote, isInboxTextKind, readInboxAttachmentKind, type InboxAnnotationRecord, type InboxAttachment, type InboxAttachmentState, type InboxInlineImage, type InboxQuestionState } from '@plannotator/core/inbox-types';
import type { LocalLinkResolver } from '@plannotator/ui/components/LocalLinkContext';
import { NOT_ATTACHED_TITLE, attachmentDeepLink, attachmentDisplayPath, attachmentForLink, openAttachmentTitle, useRefRepo } from '../links';
import { InboxApiError, inboxApi, type AttachmentsModel } from '../api';
import { annotationOf, attachmentFeedback, isFileComment } from '../attachments';
import { AttachmentTiles, AttachmentsCount, changedCount } from './AttachmentTiles';
import { AttachmentPane, type AttachmentPaneHandle } from './AttachmentPane';
import type { OpenInSurface } from './OpenIn';
import { stepsOf } from '../stepping';
import { artifactKey, artifactOfFile, threadArtifacts } from '../artifacts';
import { ArtifactsView } from './ArtifactsView';
import { fileViewFor, openingView, parseFileView, readFileViewChoice, writeFileViewChoice, type FileView } from '../fileView';
import type { InboxToastModel } from './Toast';
import { AnnotationsChip } from './AnnotationsChip';
import { agentName, clockTime, dayWords, fullTime, plural, whenTime } from '../format';
import { foldSnippet, holdingsOf, isDelivered, isPersonLook, isPersonReply, lastNonNote, lookBoundary, newSinceLook, planFolds, snippetText, type FoldSnippet, type Holding } from '../folding';
import { highlightSearchHits } from '../search/highlight';
import { AuthorMark, Icon } from '../icons';
import { PILL_BAND_PX, atEnd, followBy, lookThrough, measureFirstLines, unseenArrivals, useSeenOnSight } from '../seenOnSight';
import { GuideCard } from './GuideCard';
import { inboxMessageImageBase, inlineImageRefFromSrc, markTallImage } from '../images';
import { reportUnsentReply } from '../unsent';
import { useReplyDraft } from '../replyDraft';
import { conflictText, DraftHead, DraftFootNote } from './DraftLabel';
import { canToggleRead } from '../markRead';
import { NewMessageButton, NewMessageComposer, NewMessagePopover, hostName, useLiveSessions, type NewMessageMode } from './NewMessage';
import { autoAfterText, deliveryLine, restartNote, TURN_ENDED_TEXT, waitInputs, type DeliveryLine, type RecipientConnection } from '../deliveryLine';
import { RestartLine } from './RestartNote';
import { UndeliveredBand, UndeliveredText, useMinuteClock } from './Undelivered';
import { SendToAnotherSession } from '../compose/SendToAnotherSession';
import { ComposeFileTiles, attachedAnnouncement, useComposeFiles } from '../compose/ComposeFiles';
import {
AskerEndedNote,
CLOSED_ROUTE,
LEAVE,
RouteChoice,
SessionEndedMark,
askerCanEnd,
askerHasEnded,
isRedirected,
mergeRouteRows,
othersLive,
redirectedName,
routeRace,
type AskingSession,
type RouteState,
} from './ReplyRoute';
import { ReaskNote } from './ReaskNote';
import { reaskedIn, reaskNoteAgent, reaskOffered, reaskTargets, reaskTooltip } from '../reask';
import { ChangedNotice, ReplacedQuestionCard, ReplacesLine, StaleGuard, replacedBy, replacementOf, type JumpTarget } from './ReplacedQuestion';
import { InboxComposerField } from './ComposerField';
import { ReplyAnswers, SentAnswers, draftAnswerWords, type DraftAnswer } from './ReplyAnswers';
import { sentAnswersOf, sentReplyParts, type SentAnswerGroup } from '../sentReply';
import { SkillsLine } from './SkillsLine';
import { paintSkillReferences } from '../skillHighlight';
import { paintTagReferences, type TagMarkPlace } from '../tagHighlight';
import { TagNotes, TagStack, useTagConnections, useTaggable } from './TagPicker';
import { messageTags, participantsWords, sendTagsByTarget, tagDeliveryLine, tagName, tagOptions, tagPeople, threadParticipants, type TagOption } from '../tags';
import type { MentionSource } from '@plannotator/ui/utils/mentions';
import { TAG_TOKEN_CLASS } from './ComposerField';
import { HostMark } from '../icons';
import { INBOX_REPLY_SKILL_AUDIENCE, annotationSkillTexts, inboxSkillsBlock, withSkillsBlock } from '../skills';
import { ActionChecklist, type ActionMark } from './ActionChecklist';
import { actionForBlock } from '../actions';
import { splitInboxSkillsBlock } from '@plannotator/core/skill-reference-block';
import { Tip } from './Tip';
import { OpenQuestionsButton } from './OpenQuestions';
import { laidOutChildren, pillHitsButtons } from '../footFit';
import { openQuestionsShown, placeOf, reaskItemLabel, skipToggledAnswer, threadOpenQuestions, type OpenQuestion, type OpenQuestionPlace } from '../openQuestions';
import { selectionToolbarShowing } from '../selectionToolbar';
import { replyKeysToRenew, routeSendAnnotations, sendTargetAnswerIds, sendTargetsOf, type SendTarget, type SentContents } from '../sendTargets';
export { routeSendAnnotations, sendTargetsOf, type SendTarget };
const noop = () => {};
/** The agent superseded the question this call named (`422 question_superseded`). */
const isSuperseded = (cause: unknown): boolean => cause instanceof InboxApiError && cause.code === 'question_superseded';
const NO_ANNOTATIONS: never[] = [];
/** An unsent pick's tag on its card (MessageBody's statusLabel). */
// A pick saved and not sent is part of the person's draft (approval "inbox-reply-drafts": "Draft" replaces "Not sent").
const NOT_SENT_STATUS = { label: 'Draft', tone: 'open' } as const;
const NO_IDS: ReadonlySet<string> = new Set();
/** The reply box starts with no files: they come only from a paste (compose's tiles and upload path). */
const NO_UPLOADS: InboxUpload[] = [];
/** The fold state of one open thread: in memory only, decided once when the thread opens. */
interface FoldState {
threadId: string;
/** Messages shown as one line. A message that arrives later is not in it, so it shows open. */
folded: Set<string>;
/** The middle of each long read run ("N earlier messages"), by run. */
hidden: string[][];
/** The runs whose "N earlier messages" was opened. */
revealed: Set<number>;
}
/** "Today, 9:12 AM": a moment in the thread's meta line. */
function momentWords(iso: string): string {
const day = dayWords(iso);
return day ? `${day.charAt(0).toUpperCase()}${day.slice(1)}, ${clockTime(iso)}` : '';
}
/** "Today, 9:12 AM to 5:48 PM", both days when they differ, one moment when the times are the same. */
function spanWords(from: string, to: string): string {
if (dayWords(from) === dayWords(to)) return clockTime(from) === clockTime(to) ? momentWords(from) : `${momentWords(from)} to ${clockTime(to)}`;
return `${momentWords(from)} to ${momentWords(to)}`;
}
const reducedMotion = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
/**
* What the "↓ N new" pill counts and goes to, in thread order, of the
* messages whose top is below the view (under the pill's band): the arrivals
* not yet seen on sight (`data-arrival`, design record
* "inbox-new-in-open-thread": the pill counts only unseen arrivals below);
* only when none waits there, the messages that were new when the thread
* opened (`data-new`). An arrival already seen (`data-sighted`) never counts,
* and neither does a message the person has had on screen this visit
* (`passed`): once its top was in the view, or the view went past it, it is
* read as far as the pill is concerned, so scrolling back up never brings it
* back. `mark` (the tab visible and nothing over the thread) adds what is on
* screen now to `passed`; scrolled to the end, everything is on screen.
*/
function newBelow(body: HTMLElement, passed: Set<string>, mark: boolean): HTMLElement[] {
const bottom = body.getBoundingClientRect().bottom - PILL_BAND_PX;
const end = mark && body.scrollHeight > 0 && atEnd(body);
const below = (selector: string) =>
[...body.querySelectorAll<HTMLElement>(selector)].filter((a) => {
const id = a.getAttribute('data-message-article') ?? '';
if (passed.has(id)) return false;
if (end || a.getBoundingClientRect().top <= bottom) {
if (mark) passed.add(id);
return false;
}
return true;
});
const arrivals = below('[data-message-article][data-arrival]:not([data-sighted])');
const atOpen = below('[data-message-article][data-new]:not([data-arrival]):not([data-sighted])');
return arrivals.length > 0 ? arrivals : atOpen;
}
/** A folded line's snippet: the message's first words, or the person's answers. */
function SnippetText({ snippet }: { snippet: FoldSnippet }) {
if (snippet.kind === 'words') return <>{snippet.text}</>;
return (
<>
{snippet.parts.map((part, index) => (
<span key={index} className="ib-fl-ans">
{index > 0 && <span className="ib-fl-sep"> · </span>}
{part.prompt} <span className="ib-fl-arr">→</span> <b>{part.answer}</b>
</span>
))}
</>
);
}
/** What a folded line says a message holds. */
function HoldingChips({ holdings }: { holdings: Holding[] }) {
if (holdings.length === 0) return <span className="ib-fl-chips" />;
return (
<span className="ib-fl-chips" data-holdings="">
{holdings.map((h) => (
<span key={h.kind} className={`ib-fl-chip${h.kind === 'open' || h.kind === 'todo' ? ' ib-fl-open' : h.kind === 'picks' ? ' ib-fl-pick' : ''}`} data-holding={h.kind}>
{h.kind === 'answered' || h.kind === 'delivered' ? <Icon name="check" size={14} /> : null}
{h.kind === 'files' ? <Icon name="clip" size={14} /> : null}
{h.kind === 'annotations' ? <Icon name="doc" size={14} /> : null}
{h.kind === 'guide' ? <Icon name="book" size={14} /> : null}
{h.text}
</span>
))}
</span>
);
}
/** A wire message's question states, for the shared asking rule. */
const questionStatesOf = (message: InboxMessageWire): InboxQuestionState[] => (message.questions ?? []).map((q) => q.state);
/**
* A question's empty answer as its card builds it (ui's QuestionBlock:
* `emptyQuestionAnswer` of the question Viewer indexes from the same body),
* so a Skip from the open-questions list saves what the card's Skip saves.
*/
function emptyAnswerFor(message: InboxMessageWire, q: { key: string; prompt: string; question: InboxQuestion }): QuestionAnswer {
const indexed = indexQuestionBlocks(parseMarkdownToBlocks(message.body, { frontmatter: false }), { decisionLines: false }).find(
(i) => i.question.key === q.key,
);
if (indexed) return emptyQuestionAnswer(indexed);
const kind = q.question.kind === 'multi' || q.question.kind === 'text' ? q.question.kind : 'single';
return { v: 1, key: q.key, kind, prompt: capQuestionPrompt(q.prompt), selected: [] };
}
/**
* The session a Send reaches, when its message names one: the last target's
* when words or annotations ride on it (`carries`; the latest agent message,
* or the last pick or skip when the same session wrote both), otherwise the
* last message a pick or a skip answers (a message that only would have
* carried words receives nothing, so its session is not asked about). With
* nothing to send, the latest agent message's.
*/
function askingSessionOf(thread: InboxThread, options: { skip: ReadonlySet<string>; carries: boolean }): AskingSession | null {
// Nothing rides on the latest message: the shared rule the list row's delivery uses too (core
// inbox-delivery), plus the questions the person chose to skip, when any.
const message = options.carries
? sendTargetsOf(thread, options.skip).at(-1)!.message
: (lastSkipOrPick(thread, options.skip) ?? inboxAskingMessage(thread.messages, questionStatesOf, false));
if (!message) return null;
if (message.author.kind !== 'agent' || !message.author.session) return null;
return { message, session: message.author.session, host: message.author.host ?? '', name: agentName(message.author) };
}
/** The last agent message a pick or a chosen skip answers (null when the person chose no skip: the shared rule decides). */
function lastSkipOrPick(thread: InboxThread, skip: ReadonlySet<string>): InboxMessageWire | null {
if (skip.size === 0) return null;
let found: InboxMessageWire | null = null;
for (const m of thread.messages) {
if (m.author.kind !== 'agent') continue;
if ((m.questions ?? []).some((q) => q.state === 'picked' || (q.state === 'open' && skip.has(`${m.id}/${q.key}`)))) found = m;
}
return found;
}
/** The key a reply of a Send keeps across retries: one per session (a message with no session is its own). */
function replyKeyOf(message: InboxMessageWire): string {
return message.author.kind === 'agent' && message.author.session ? `s:${message.author.host ?? ''}\u0000${message.author.session}` : `m:${message.id}`;
}
/** The sessions a comment tags with `@` (ui's `Annotation.mentions`): a tag there sends the whole reply to them. */
export function commentTags(record: InboxAnnotationRecord): string[] {
const mentions = annotationOf(record)?.mentions;
return Array.isArray(mentions) ? mentions.filter((id): id is string => typeof id === 'string') : [];
}
const NO_SENT_ANSWERS: readonly SentAnswerGroup[] = [];
/** One message's text, with its question cards (exported for its DOM test). */
export function MessageBody({
message,
projectRoot,
repo,
onOpenAttachment,
onOpenInlineImage,
readOnly,
answers,
onPick,
footerFor,
renderReplacedCard,
renderReplacesLine,
renderActions,
comments,
sentAnswers,
onJumpQuestion,
imageBase,
onImage,
pictureBadge,
}: {
message: InboxMessageWire;
/** The thread's project root: relative links start there or at the message's own folder. */
projectRoot: string;
/** The project's git `origin` (the thread payload's `project.repo`): bare `#123` refs link into it. */
repo?: InboxProjectRepo | null;
/** A link in the body to one of this message's attachments was followed. */
onOpenAttachment: (attachment: InboxAttachment) => void;
/** An image the body shows was clicked (or pressed): its captured file (`inline_images`) opens in the viewer. */
onOpenInlineImage?: (image: InboxInlineImage) => void;
readOnly: boolean;
answers: ReadonlyMap<string, QuestionAnswer>;
onPick: (key: string, answer: QuestionAnswer | null) => void;
footerFor: (key: string) => string | null;
/** A superseded question's card in place of its answer card (the question's key and number), or undefined to keep it. */
renderReplacedCard?: (key: string, number: number) => React.ReactNode | undefined;
/** The "Replaces …" line under a question's prompt, or null. */
renderReplacesLine?: (key: string) => React.ReactNode;
/**
* Action items (approval "action-items-checklist"): each run of adjacent
* `:::action` blocks (blank lines between them only) is drawn as one card
* in place of the run's first block; the run's other blocks draw nothing.
* `recordFor` names the record a block draws (null: the block stays text
* and ends the run); `render` draws a run's records, in body order.
*/
renderActions?: {
recordFor: (block: { startLine: number; content: string }) => InboxQuestion | null;
render: (records: InboxQuestion[]) => React.ReactNode;
};
/**
* Comments on the text (an agent's message that can still be answered;
* approval "inbox-message-comments"): the person's comments on this message
* waiting for a Send, drawn as highlights, and a selection opens the
* comment-only toolbar. `onSave` stores a new one (false: it was refused,
* and its highlight goes). `onUnanchored` hears which could not be found by
* their words; `onPainted` that highlights were drawn (the DOM changed).
* Absent: the text takes no comments.
*/
comments?: {
annotations: readonly Annotation[];
onSave: (annotation: Annotation) => Promise<boolean>;
onUnanchored?: (report: { attempted: readonly string[]; unanchored: readonly string[] }) => void;
onPainted?: () => void;
};
/**
* The person's own sent reply (sentReply.ts): the answers it carried, read
* from the thread's questions. The reply is then drawn in the person's
* words, these answers as a short list, then its comments and files; the
* agent-facing parts of the body ("Answered N questions.", the still-open
* line, "## Answers to your questions") are left out. Display only: the
* stored body and what agents get are unchanged.
*/
sentAnswers?: readonly SentAnswerGroup[];
/** A row of `sentAnswers` was pressed: show its question. */
onJumpQuestion?: (target: JumpTarget) => void;
/**
* Where the body's images load from, in place of the message's own image
* route (`inboxMessageImageBase`): the onboarding tour's assets
* (`inbox-tour:`, images.ts). Absent: the message's route.
*/
imageBase?: string;
/** An image the body shows (a picture choice's zoom included) was opened: the host shows it. Absent: the thread's viewer. */
onImage?: (src: string, alt: string) => void;
/** A label over each picture choice's picture (ui QuestionBlock `pictureBadge`); absent: none. */
pictureBadge?: (choice: { label: string; image: { alt: string; src: string } }) => string | null;
}) {
// A person's message ends with the skills block the window pasted when it
// was sent: folded behind one quiet line (SkillsLine). An agent's message
// is shown whole, whatever it says.
const skills = useMemo(() => (message.author.kind === 'person' ? splitInboxSkillsBlock(message.body) : null), [message.author.kind, message.body]);
const sent = skills ? skills.before : message.body;
const replyParts = useMemo(() => sentReplyParts(message, sent, sentAnswers ?? []), [message, sent, sentAnswers]);
const shown = replyParts ? replyParts.words : sent;
const restShown = replyParts ? replyParts.rest : '';
const blocks = useMemo(() => parseMarkdownToBlocks(shown, { frontmatter: false }), [shown]);
const restBlocks = useMemo(() => (restShown ? parseMarkdownToBlocks(restShown, { frontmatter: false }) : []), [restShown]);
const refRepo = useRefRepo(repo);
// A tall screenshot in the body shows its top, cropped like the gallery's
// (inbox.css); a click still opens it whole.
const bodyRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
const onLoad = (event: Event) => {
if (event.target instanceof HTMLImageElement) markTallImage(event.target);
};
for (const img of body.querySelectorAll('img')) if (img.complete) markTallImage(img);
// Load does not bubble: a capture listener on the body hears every image in it.
body.addEventListener('load', onLoad, true);
return () => body.removeEventListener('load', onLoad, true);
}, []);
// Images the body shows open in the thread's one viewer (approval "inbox-image-viewer"): a
// click, or Enter / Space on one (every image the window loads from the message is a button).
// Until the store has captured it (a later read of the thread does, in the background), the
// plain lightbox shows it, so a click always opens something.
const inlineRef = useRef<readonly InboxInlineImage[]>(message.inline_images ?? []);
inlineRef.current = message.inline_images ?? [];
const openImageRef = useRef(onOpenInlineImage);
openImageRef.current = onOpenInlineImage;
const [fallback, setFallback] = useState<{ src: string; alt: string } | null>(null);
const imageOf = useCallback(
(src: string | null) => {
const ref = src ? inlineImageRefFromSrc(src, message.id) : null;
return ref === null ? null : (inlineRef.current.find((image) => image.ref === ref) ?? null);
},
[message.id],
);
/** Open one of the body's images: its captured file in the viewer, else the lightbox. False: not one of them. */
const openImage = useCallback(
(src: string | null, alt: string): boolean => {
if (!src || inlineImageRefFromSrc(src, message.id) === null) return false;
// An image that failed to load (outside the project, gone) opens nothing: an empty lightbox helps no one.
if ([...(bodyRef.current?.querySelectorAll<HTMLImageElement>('img[data-ib-broken]') ?? [])].some((img) => img.getAttribute('src') === src)) return true;
const image = imageOf(src);
if (image && openImageRef.current) openImageRef.current(image);
else setFallback({ src, alt });
return true;
},
[imageOf, message.id],
);
const onImageRef = useRef(onImage);
onImageRef.current = onImage;
const onImageClick = useCallback((src: string, alt: string) => (onImageRef.current ? onImageRef.current(src, alt) : void openImage(src, alt)), [openImage]);
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
for (const img of body.querySelectorAll<HTMLImageElement>('img')) {
// A question card's picture (a picture choice, `Shows:`): the card makes it pick, or opens it with its own button.
if (img.hasAttribute('data-question-picture')) continue;
const src = img.getAttribute('src');
const ref = src ? inlineImageRefFromSrc(src, message.id) : null;
if (ref === null || img.hasAttribute('data-ib-broken')) continue;
const image = imageOf(src);
const name = image?.name ?? ref.split(/[\\/]/).pop() ?? 'image';
img.setAttribute('role', 'button');
img.tabIndex = 0;
img.setAttribute('aria-label', `Open ${name}${img.alt ? `, ${img.alt}` : ''}`);
if (image) img.setAttribute('data-inline-image', image.id);
else img.removeAttribute('data-inline-image');
img.style.cursor = 'zoom-in';
}
});
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
// Markdown images reach openImage through Viewer's onImageClick; an image in a raw-HTML block has no handler of its own.
const onClick = (event: MouseEvent) => {
const img = event.target instanceof HTMLImageElement ? event.target : null;
if (!img || img.classList.contains('cursor-zoom-in') || img.hasAttribute('data-question-picture')) return;
if (openImage(img.getAttribute('src'), img.alt)) event.preventDefault();
};
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
if (event.metaKey || event.ctrlKey || event.altKey || event.isComposing) return;
const img = event.target instanceof HTMLImageElement ? event.target : null;
if (img && !img.hasAttribute('data-question-picture') && openImage(img.getAttribute('src'), img.alt)) event.preventDefault();
};
body.addEventListener('click', onClick);
body.addEventListener('keydown', onKey);
// An image that fails to load is not a button (error does not bubble: a capture listener hears it).
const onError = (event: Event) => {
const img = event.target instanceof HTMLImageElement ? event.target : null;
if (!img) return;
img.setAttribute('data-ib-broken', '');
img.removeAttribute('role');
img.removeAttribute('tabindex');
img.removeAttribute('aria-label');
img.style.cursor = '';
};
body.addEventListener('error', onError, true);
return () => {
body.removeEventListener('click', onClick);
body.removeEventListener('keydown', onKey);
body.removeEventListener('error', onError, true);
};
}, [openImage]);
// The skills the block names are painted in the person's words, as the composer painted them.
useEffect(() => {
const body = bodyRef.current;
if (!body || !skills) return;
return paintSkillReferences(message.id, body, skills.skills);
}, [message.id, skills]);
// The agents the reply tags are painted too (approval "inbox-tag-agents"), from the labels it carries.
const sentTags = message.author.kind === 'person' ? (message.tags ?? []) : [];
const tagLabels = sentTags.map((t) => t.label ?? '').filter(Boolean).join('\u0000');
// Each token's chip carries its agent's mark over the `@` (the approved shot 5), drawn in a layer of our own.
const tagHosts = new Map(sentTags.filter((t) => t.label).map((t) => [t.label!, t.host]));
const tagLayerRef = useRef<HTMLDivElement>(null);
const [tagMarks, setTagMarks] = useState<TagMarkPlace[]>([]);
useEffect(() => {
const body = bodyRef.current;
if (!body || !tagLabels) return;
return paintTagReferences(`${message.id}:tags`, body, tagLabels.split('\u0000'), {
layer: tagLayerRef.current,
onMarks: (next) => setTagMarks((current) => (JSON.stringify(current) === JSON.stringify(next) ? current : next)),
});
}, [message.id, tagLabels]);
// A link to a file this message attached opens it beside the thread; any
// other local link is inert text (links.ts). Kept stable across renders,
// so raw-HTML blocks do not redraw their links on every pick.
const openRef = useRef(onOpenAttachment);
openRef.current = onOpenAttachment;
const resolveLocalLink = useCallback<LocalLinkResolver>(
(href) => {
const attachment = attachmentForLink(href, { attachments: message.attachments ?? [], root: projectRoot, base: message.base_path ?? null });
if (!attachment) return { kind: 'unavailable', title: NOT_ATTACHED_TITLE };
return {
kind: 'open',
title: openAttachmentTitle(attachmentDisplayPath(attachment, projectRoot)),
href: attachmentDeepLink(message.thread_id, attachment.id),
open: () => openRef.current(attachment),
};
},
[message.attachments, message.base_path, message.thread_id, projectRoot],
);
const renderFooter = useCallback(
(question: IndexedQuestion) => {
const text = footerFor(question.question.key);
return text ? <span className="ib-qfoot-st">{text}</span> : null;
},
[footerFor],
);
// Replaced questions: the host's Quiet card in place of the answer card, and
// the newer card's "Replaces …" line. Kept stable across renders.
const replacedRef = useRef(renderReplacedCard);
replacedRef.current = renderReplacedCard;
const replacesRef = useRef(renderReplacesLine);
replacesRef.current = renderReplacesLine;
const questionCard = useCallback(
(question: IndexedQuestion) => replacedRef.current?.(question.question.key, question.number),
// A new identity when the questions change, so a card that was just replaced redraws.
[message.questions],
);
const belowPrompt = useCallback(
(question: IndexedQuestion) => replacesRef.current?.(question.question.key) ?? null,
[message.questions],
);
// Action items: one checklist card per run of adjacent `:::action` blocks, in place of
// the run's first block; the run's other blocks draw nothing (inbox.css hides their empty
// wrapper). Prose between two blocks ends a run, so each stays where the agent put it.
const actionsRef = useRef(renderActions);
actionsRef.current = renderActions;
const actionRuns = useMemo(() => {
const runs = new Map<string, { first: boolean; records: InboxQuestion[] }>();
const draw = actionsRef.current;
if (!draw) return runs;
let run: InboxQuestion[] | null = null;
for (const block of blocks) {
const record = block.type === 'directive' && block.directiveKind === 'action' ? draw.recordFor(block) : null;
if (!record) {
run = null;
continue;
}
const first = run === null;
if (run === null) run = [];
run.push(record);
runs.set(block.id, { first, records: run });
}
return runs;
}, [blocks, message.actions, renderActions !== undefined]);
const directiveBlock = useCallback(
(block: Block) => {
if (block.directiveKind !== 'action') return undefined;
const run = actionRuns.get(block.id);
if (!run) return undefined;
return run.first ? actionsRef.current?.render(run.records) : null;
},
[actionRuns],
);
// ── Comments on the text (approval "inbox-message-comments") ──────────────
// The highlights are drawn once per mount for the comments already saved;
// a new comment paints itself (the selection becomes its mark), and one the
// person removes elsewhere (the reply box's list) leaves the text.
const viewerRef = useRef<ViewerHandle>(null);
const commentList = useMemo<Annotation[]>(() => (comments ? [...comments.annotations] : NO_ANNOTATIONS), [comments?.annotations]);
const commentsRef = useRef(comments);
commentsRef.current = comments;
const painted = useRef<Set<string>>(new Set());
const [selectedComment, setSelectedComment] = useState<string | null>(null);
const selectComment = useCallback((id: string | null) => setSelectedComment((current) => (current === id ? null : id)), []);
const addComment = useCallback((annotation: Annotation) => {
painted.current.add(annotation.id);
void commentsRef.current?.onSave(annotation).then((saved) => {
if (saved) return;
painted.current.delete(annotation.id);
viewerRef.current?.removeHighlight(annotation.id);
});
}, []);
const restoreReport = useCallback((report: { attempted: readonly string[]; unanchored: readonly string[] }) => commentsRef.current?.onUnanchored?.(report), []);
useEffect(() => {
if (!comments) return;
const ids = new Set(commentList.map((a) => a.id));
for (const id of [...painted.current]) {
if (ids.has(id)) continue;
painted.current.delete(id);
viewerRef.current?.removeHighlight(id);
}
const fresh = commentList.filter((a) => !painted.current.has(a.id) && annotationOwnsHighlight(a));
if (fresh.length === 0) return;
for (const a of fresh) painted.current.add(a.id);
// After the Viewer's highlighter is ready (the attachment pane's rule).
let done = false;
const frame = requestAnimationFrame(() => {
done = true;
viewerRef.current?.applySharedAnnotations(fresh);
commentsRef.current?.onPainted?.();
});
return () => {
if (done) return;
cancelAnimationFrame(frame);
for (const a of fresh) painted.current.delete(a.id);
};
}, [comments !== undefined, commentList]);
// The whole card, per question: only an open or picked question can be
// answered. A sent one, one a Mark read or the archive closed, and a
// replaced one draw read-only (no ticks, no Accept recommended, no Skip),
// even while another question in the same message is still open. The store
// would take a new pick on a sent question (it goes back to picked), but the
// window does not offer it (adr/implementation/inbox-thread-state.md, Pick).
const answerLocked = useCallback(
(question: IndexedQuestion) => {
// A message whose questions take no answers now (all sent, none, or closed): every card locked.
if (readOnly) return true;
const wire = message.questions?.find((q) => q.key === question.question.key);
return wire !== undefined && wire.state !== 'open' && wire.state !== 'picked';
},
[message.questions, readOnly],
);
// A pick not sent yet tags its card "Draft", not "Answered" (the footer says when it was picked);
// a sent answer, and a question a Mark read closed, keep the card's own tag.
const statusLabel = useCallback(
(question: IndexedQuestion, status: QuestionStatus) => {
if (status !== 'answered' && status !== 'skipped') return undefined;
const wire = message.questions?.find((q) => q.key === question.question.key);
return wire && (wire.state === 'open' || wire.state === 'picked') ? NOT_SENT_STATUS : undefined;
},
[message.questions],
);
return (
<div className="ib-body" data-message-id={message.id} data-text-comments={comments ? '' : undefined} data-sent-reply={replyParts ? '' : undefined} ref={bodyRef}>
{(!replyParts || shown !== '') && (
<Viewer
ref={viewerRef}
blocks={blocks}
markdown={shown}
annotations={commentList}
onAddAnnotation={comments ? addComment : noop}
onSelectAnnotation={comments ? selectComment : noop}
selectedAnnotationId={comments ? selectedComment : null}
textComments={comments !== undefined}
allowImages={false}
onRestoreReport={comments ? restoreReport : undefined}
mode="selection"
taterMode={false}
maxWidth={null}
stickyActions={false}
disableCodePathValidation
imageBaseDir={imageBase ?? inboxMessageImageBase(message.id)}
onImageClick={onImageClick}
resolveLocalLink={resolveLocalLink}
refRepo={refRepo}
answerOnly
// `readOnly` is about the question cards (answerLocked locks them); with comments on, the text still takes them.
readOnly={readOnly && !comments}
questionAnswers={answers}
onAnswerQuestion={(_blockId, answer, key) => onPick(key, answer)}
renderQuestionFooter={renderFooter}
// The Inbox records no decisions: a `Decision:` line an older agent wrote is context.
questionDecisionLines={false}
// The Inbox draws the contract lines (Stakes, Shows, Why, Can't be undone), approval "inbox-decision-mode".
questionContractLines
questionReadOnly={answerLocked}
questionStatusLabel={statusLabel}
questionPictureBadge={pictureBadge}
renderQuestionCard={renderReplacedCard ? questionCard : undefined}
renderQuestionBelowPrompt={renderReplacesLine ? belowPrompt : undefined}
renderDirectiveBlock={renderActions ? directiveBlock : undefined}
/>
)}
{replyParts && sentAnswers && sentAnswers.length > 0 && <SentAnswers groups={sentAnswers} onJump={onJumpQuestion} />}
{replyParts && restShown && (
<div data-sent-rest="">
<Viewer
blocks={restBlocks}
markdown={restShown}
annotations={NO_ANNOTATIONS}
onAddAnnotation={noop}
onSelectAnnotation={noop}
selectedAnnotationId={null}
allowImages={false}
mode="selection"
taterMode={false}
maxWidth={null}
stickyActions={false}
disableCodePathValidation
imageBaseDir={imageBase ?? inboxMessageImageBase(message.id)}
onImageClick={onImageClick}
resolveLocalLink={resolveLocalLink}
refRepo={refRepo}
answerOnly
readOnly
questionDecisionLines={false}
/>
</div>
)}
{skills && <SkillsLine split={skills} />}
{tagLabels && (
<div className="ib-tg-marks" ref={tagLayerRef} aria-hidden="true" data-tag-marks="">
{tagMarks.map((mark, index) => (
<span key={index} className="ib-tg-mark" style={{ left: mark.left, top: mark.top, width: mark.size, height: mark.size }}>
<HostMark host={tagHosts.get(mark.label) ?? null} />
</span>
))}
</div>
)}
{fallback && createPortal(<ImageLightbox src={fallback.src} alt={fallback.alt} onClose={() => setFallback(null)} />, document.body)}
</div>
);
}
export interface ThreadPaneProps {
/** A line under the subject, from the window (the tour's notifications ask, once more, in the first real thread). */
notice?: React.ReactNode;
thread: InboxThread;
/**
* The thread's list row's `sent`: the person's reply is the last message
* (the Inbox's own notes read past), and when the agent read it (by the
* store's seq, so a reply the agent was not given still reads as unread),
* or null.
*/
sent: { at: string; checked_at: string | null; recipients?: InboxSentRecipient[] } | null;
/** The thread's questions changed through a pick (the response's questions for that message). */
onQuestions: (messageId: string, questions: InboxQuestion[]) => void;
/** Something was written (a Send, resolve): read the thread and the list again. */
onChanged: () => Promise<void>;
/** Raised each time the Inbox says this thread's reply draft changed (`event: drafts`): the draft is read again. */
draftChanged?: number;
onClose: () => void;
/** The attachment open beside the thread (`#…&file=att_…`), its version, and an annotation to show. */
file: { id: string; version: 'current' | 'sent'; focus: string | null; linked?: string | null; view?: 'full' | 'side' | null } | null;
/** `replace`: swap the history entry (stepping between files), so Back returns to the thread in one press. */
/** `back`: the browser's Back when the entry on screen was opened from `file` (a linked page's Back), else a new entry. */
onOpenFile: (file: { id: string; version: 'current' | 'sent'; focus: string | null; linked?: string | null; view?: 'full' | 'side' | null } | null, options?: { replace?: boolean; back?: boolean }) => void;
/** Open the guided review a message carries (the record's 4.2). */
onOpenGuide: (messageId: string) => void;
/**
* Where "new since you looked" starts (folding.ts `lookBoundary`), read
* from the thread BEFORE the window recorded this look and kept until the
* person leaves the thread. The window takes it from its own first read,
* which lands before it records the look. Absent: the pane takes it from
* the first thread it is given.
*/
lookSeq?: number | null;
/**
* Seen on sight (design record "inbox-new-in-open-thread", approved
* 2026-10-12): the seq the window's looks this visit covered (the look
* recorded when the thread opened, raised as arrivals are seen). An agent
* message after it arrived while the thread was open; once its first lines
* have been on screen for a second (window in front, nothing over the
* thread) the pane calls `onSeen` with the seq the look may now cover.
* Null: the thread carries no seqs (an older Inbox). Absent `onSeen`: off.
*/
seenThrough?: number | null;
onSeen?: (throughSeq: number) => void;
/** Something over the thread from outside the pane (a guided review, a dialog): nothing counts as seen. */
covered?: boolean;
/**
* Whether this thread is visible: called with its id and whether anything
* covers it (from outside, or a file over it), and with null when the pane
* goes. Notifications skip a question in the thread on screen (notify.ts).
*/
onScreenChange?: (state: { threadId: string; covered: boolean } | null) => void;
/** The thread's list row as it is now: Mark read's state and whether it is offered. Null until the list has it. */
row?: InboxListRow | null;
/** Mark read, or move it back (the pressed button). Absent: no Mark read button. */
onMarkRead?: (read: boolean) => void;
/**
* 👍 Looks good on the agent's latest message (`on`), or take it back:
* silent, nothing is sent; the thread is marked read. `agent` names the
* agent for the toast. Absent: no Looks good button.
*/
onAck?: (messageId: string, on: boolean, agent: string) => void;
/**
* An action item's Done or Can't do it (`mark`), or its Undo (`null`), approval
* "inbox-next-actions": the window writes it and shows the toast with
* Undo. Resolves false when it was refused. Absent: the pane writes it
* itself and reads the thread again.
*/
onAction?: (messageId: string, key: string, mark: ActionMark | null, info: { agent: string; prompt: string }) => Promise<boolean>;
/** Archive (`true`) or Unarchive. Absent: the pane calls the resolve route itself. */
onArchive?: (archived: boolean) => void;
/**
* The thread is pinned to the sidebar (approval "inbox-pinned-threads"), and
* the header's pin toggle. Absent (an older Inbox keeps no pins): no toggle.
*/
pinned?: boolean;
/** Resolves once the pin is written and the list read again (the header waits on it before the next click's request). */
onPin?: (pinned: boolean) => void | Promise<unknown>;
/** The thread whose reply box should open (the warning toast's Reply); the pane calls `onReplyOpened` once it has. */
replyRequest?: string | null;
onReplyOpened?: () => void;
/** On a phone the header leads with a Back button named for the screen under the thread ("Inbox", a project). */
backLabel?: string;
/** A phone: one screen at a time, so an open file takes the whole window (phone.ts). */
phone?: boolean;
/**
* A window too narrow for the list beside the thread (stack.ts): the thread
* covers the list, and its header leads with the way back to it.
*/
stacked?: boolean;
/** A window too narrow for a file beside the thread (stack.ts): an open file takes the whole window. */
fileStacked?: boolean;
/**
* This page came through the tailnet ("Over your tailnet"): "Open in" is a
* new tab only, never an app on the computer. Null until the settings say
* where the page is: no "Open in" yet, so a tailnet page never asks for the
* local app list.
*/
remote?: boolean | null;
/**
* A file open beside the thread on a desktop hides the list and the
* sidebar: the header then leads with `‹ Inbox` (`backLabel`), which closes
* the file (through the pane's unsaved-comment question, as the file's ×
* does) and calls this with the file's name, so the window can bring the
* list back and put focus on this thread's row. Absent: no such button.
*/
onBackToList?: (fileName: string | null) => void;
/** The window's one toast: "Files open side by side now" with Undo, when a picked view becomes the remembered one. */
onToast?: (toast: Omit<InboxToastModel, 'id'>) => void;
/**
* A search result to land on (`#thread=…&msg=…`): the message is unfolded
* if folded or hidden in the middle fold, scrolled to the centre, focused
* and ringed (a question's card when the match was in a question), and the
* query's words are highlighted in it until the first click or key in the
* thread. `onLanded` then drops `msg=` from the hash.
*/
landing?: { messageId: string; terms: readonly string[]; questionKey: string | null } | null;
onLanded?: () => void;
/**
* The Artifacts view is on (approval "inbox-thread-artifacts", `#thread=…&artifacts`):
* the thread's body is swapped for a grid of every artifact across its messages.
*/
artifacts?: boolean;
/** Turn the Artifacts view on or off (the header's button, "Back to the thread"). Absent: no Artifacts button. */
onArtifacts?: (open: boolean) => void;
}
/** The thread's attachments as they are now and the annotations waiting for a Send, kept fresh. */
function useThreadAttachments(threadId: string, revision: unknown) {
const [model, setModel] = useState<AttachmentsModel | null>(null);
const load = useCallback(async () => {
try {
const next = await inboxApi.attachments(threadId);
setModel((current) => (current === null || current.serverSession === next.serverSession ? next : current));
} catch {
// The thread went away; the pane closes with it.
}
}, [threadId]);
useEffect(() => {
setModel(null);
}, [threadId]);
useEffect(() => {
void load();
}, [load, revision]);
// A file edited on disk shows as changed when the person comes back to the window.
useEffect(() => {
const onFocus = () => void load();
window.addEventListener('focus', onFocus);
return () => window.removeEventListener('focus', onFocus);
}, [load]);
const patch = useCallback((update: (records: InboxAnnotationRecord[]) => InboxAnnotationRecord[]) => {
setModel((current) => (current ? { ...current, annotations: update(current.annotations) } : current));
}, []);
return { model, load, patch };
}
/**
* The in-thread New message button (record 5.1 to 5.3) is off since 👍 Looks
* good (approval "inbox-acknowledge", 2026-10-15). Its route, phone door row
* and code paths stay, so it comes back by turning this on.
*/
const SHOW_NEW_MESSAGE_BUTTON = false;
/** Where a 👍 Looks good is on its way to the agent (amended 2026-10-16: it is sent through). */
export type AckPillState = 'pending' | 'queued' | 'sending' | 'saved' | 'delivered' | 'not-sent';
/**
* The line under a 👍: the toast's Undo window still runs (`pending`), the
* Inbox sent it and a connection wakes the agent with it (`queued`, or
* `sending` while that session is idle: the same honest words as a reply's
* line, from the session's connection now, `deliveryLine`), it waits for an
* agent that only reads the thread (`saved`), or it reached the agent
* (`delivered`: its turn was delivered, or the agent read it). No Send now: a
* 👍 asks nothing of the agent, so it never goes into a running turn; it
* waits for the turn to end. Pure, for the tests.
*/
export function ackPillLine(
ack: NonNullable<InboxMessageWire['ack']>,
agent: string,
wakes: boolean,
time: (iso: string) => string = whenTime,
connection?: RecipientConnection | null,
now: number = Date.now(),
): { state: AckPillState; text: string } {
if (ack.delivered_at) {
// Marked by the Inbox to go in by itself: say how it went in (into the running turn, or when it ended).
const marked = ack.deliver_now_by === 'auto' && ack.deliver_now_at && ack.wait_started_at;
const auto = !marked
? ''
: ack.delivered_into_turn === false
? ` · ${TURN_ENDED_TEXT}`
: ` · ${autoAfterText(wholeMinutes(ack.wait_started_at!, ack.deliver_now_at!))}`;
return { state: 'delivered', text: `Delivered to ${agent}, ${time(ack.delivered_at)}${auto}` };
}
// The window ended after the person replied, or the agent wrote again: it was not sent.
if (ack.not_sent === 'replied') return { state: 'not-sent', text: 'not sent: you replied' };
if (ack.not_sent === 'wrote_again') return { state: 'not-sent', text: `not sent: ${agent} wrote again` };
const you = `You, ${time(ack.at)} · `;
if (ack.settled_seq == null) return { state: 'pending', text: `${you}goes to ${agent} in a few seconds` };
// A 👍 settled before it was sent through (no note) never reaches a wake: it waits for a read.
if (wakes && ack.note_id) {
const line = deliveryLine({
name: agent,
deliveredAt: null,
time,
wakes: true,
sendingNow: !!ack.deliver_now_at,
connection,
// It waits on a busy session: "Undelivered N min"; a 👍 waits for the turn to end (INBOX_AUTO_SEND_ACK_NOTES), no countdown.
...waitInputs(connection, ack.note_id, { wait_started_at: ack.wait_started_at, deliver_now_by: ack.deliver_now_by, deliver_now_at: ack.deliver_now_at }),
...(INBOX_AUTO_SEND_ACK_NOTES ? {} : { autoSendAfterMs: null }),
now,
});
return { state: line.state === 'sending' ? 'sending' : 'queued', text: `${you}${line.text}` };
}
return { state: 'saved', text: `${you}Saved for ${agent}. It sees it when it next reads this thread.` };
}
/** Under a message the person marked 👍 Looks good: when, and where it is on its way to the agent. */
export function AckPill({
ack,
agent,
wakes = false,
connection,
}: {
ack: NonNullable<InboxMessageWire['ack']>;
agent: string;
wakes?: boolean;
/** How the agent's session is connected now (the sessions route's `asker.connection`); undefined while unknown. */
connection?: RecipientConnection | null;
}) {
// The wait on a busy session is written in whole minutes: its own clock, while the 👍 waits.
const now = useMinuteClock(!ack.delivered_at && !!ack.note_id);
const line = ackPillLine(ack, agent, wakes, whenTime, connection, now);
return (
<p className="ib-ackpill" data-ack-pill={line.state}>
<span className="ib-ackchip">
<span aria-hidden="true">👍</span> {ack.label}
</span>
<Tip content={line.state === 'delivered' && ack.delivered_at ? `You marked it ${fullTime(ack.at)}; delivered ${fullTime(ack.delivered_at)}` : fullTime(ack.at)}>
<span className="ib-ackwhen">{line.text}</span>
</Tip>
</p>
);
}
/**
* Per thread, a Send whose reply carrying the words went out but could not be
* confirmed (its answer was lost and the thread could not be read: the Inbox
* may be down): its key, and what it carried. It holds only while the box
* keeps exactly those unsent words: it goes when any thread read shows the
* reply landed (the Send is then finished), when the words change or the box
* empties, when the person leaves the thread, and after 10 minutes. The next
* Send of those words first reads the thread for that reply: there, the Send
* is finished and nothing goes again; not there, it is an ordinary new Send.
*/
interface UnconfirmedSend {
key: string;
words: string;
uploads: string[];
comments: string[];
picks: string[];
at: number;
}
const unconfirmed = new Map<string, UnconfirmedSend>();
const UNCONFIRMED_MS = 10 * 60_000;
/**
* Whether a reply with this idempotency key is in the thread: 'unknown' when
* the thread could not be read, 'gone' when the thread no longer exists.
*/
async function replyLanded(threadId: string, key: string): Promise<'yes' | 'no' | 'unknown' | 'gone'> {
try {
const read = await inboxApi.thread(threadId);
return read.thread.messages.some((m) => m.author.kind === 'person' && m.idempotency_key === key) ? 'yes' : 'no';
} catch (cause) {
return cause instanceof InboxApiError && cause.status === 404 ? 'gone' : 'unknown';
}
}
const THREAD_GONE_TEXT = 'This thread was deleted, so nothing was sent.';
export function ThreadPane({ notice, thread, sent, onQuestions, onChanged, draftChanged = 0, onClose, file, onOpenFile, onOpenGuide, lookSeq, seenThrough = null, onSeen, covered = false, onScreenChange, row, onMarkRead, onAck, onAction, onArchive, pinned = false, onPin, replyRequest, onReplyOpened, backLabel = 'Inbox', phone = false, stacked = false, fileStacked = false, remote = false, onBackToList, onToast, landing = null, onLanded, artifacts: artifactsRoute = false, onArtifacts }: ThreadPaneProps) {
// "Open in" (OpenIn.tsx): apps on this computer; a new tab only through the tailnet or on a phone.
const openIn: OpenInSurface | undefined = phone || remote === true ? 'tab' : remote === null ? undefined : 'apps';
const root = thread.messages[0]!;
// A thread the person started (compose) is about the agent it is addressed to, never the person.
const startedTo = root.started_by_person && root.to ? root.to : null;
const asker = startedTo ? hostName(startedTo.host) : agentName(root.author);
// Archived (resolved). What an agent wrote after the archive line behaves as
// an open thread's: its questions are live, Reply goes to it, its files take
// comments; the thread stays archived. `resolved` is the thread with nothing
// after the archive: read only, as before.
const archived = thread.resolved_at !== null;
const archiveSeq = thread.archive_seq ?? null;
const afterArchive = (message: InboxMessageWire) => archived && archiveSeq !== null && (message.seq ?? 0) > archiveSeq;
const liveMessage = (message: InboxMessageWire) => !archived || afterArchive(message);
const cameBack = archived && thread.messages.some((m) => m.author.kind === 'agent' && afterArchive(m));
const resolved = archived && !cameBack;
const agentMessages = thread.messages.filter((m) => m.author.kind === 'agent');
const lastAgent = agentMessages[agentMessages.length - 1] ?? root;
// 👍 Looks good (design record "inbox-acknowledge"): on the agent's latest
// message, offered only while no question in the thread waits on the person
// (open or picked) and the thread is not archived.
const ackTarget = agentMessages.at(-1) ?? null;
// An action item counts like a question here (approval "inbox-next-actions"): the store refuses a 👍 while one waits.
const questionWaits = agentMessages.some((m) => [...(m.questions ?? []), ...(m.actions ?? [])].some((q) => q.state === 'open' || q.state === 'picked'));
// Nor once the person wrote back after it (their reply is the answer; its Sent / Delivered line stays).
const personWroteLast = lastNonNote(thread.messages)?.author.kind === 'person';
const ackOffered = onAck !== undefined && ackTarget !== null && !archived && !questionWaits && !personWroteLast;
const ackOn = ackTarget?.ack != null;
// Action items: Done / Can't do it / Undo, through the window (its toast and Undo) or, without it, straight to the server.