The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 1,796 lines 64.6 KB
Raw
1 import * as Dialog from "../../components/ui/Dialog";
2 import type { ThreadRowProviderInstance } from "./thread-provider-instance";
3 import {
4 THREAD_LIST_V2_MONO_FONT as MONO_FONT,
5 THREAD_LIST_V2_ROW_CONTENT_CLASS_NAME,
6 THREAD_LIST_V2_ROW_DIVIDERS,
7 selectedThreadRowColors,
8 getThreadListV2NewBranchMenuTitle,
9 getThreadListV2RowAppearance,
10 } from "./thread-list-v2-row-appearance";
11 import { RowPressable } from "../../components/ui/RowPressable";
12 import { CustomSnoozeSheet } from "./CustomSnoozeSheet";
13 import { appAtomRegistry } from "../../state/atom-registry";
14 import { threadArrangementOpenAtom } from "../../state/thread-order";
15 import { threadEnvironment } from "../../state/threads";
16 import { useAtomCommand } from "../../state/use-atom-command";
17 import { useVisibleSecondClock } from "./use-visible-second-clock";
18 import type { ThreadMoveDestination } from "./threadOrder";
19 import type {
20 EnvironmentProject,
21 EnvironmentThreadShell,
22 } from "@t3tools/client-runtime/state/shell";
23 import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
24 import {
25 formatWorkingDurationLabel,
26 resolveThreadWorkingStartedAt,
27 } from "@t3tools/client-runtime/state/models";
28 import {
29 AuthOrchestrationOperateScope,
30 type EnvironmentId,
31 type EnvironmentMachineKind,
32 } from "@t3tools/contracts";
33 import { toServerClock } from "@t3tools/client-runtime/clock";
34 import type { SnoozePresetSetting } from "@t3tools/contracts/settings";
35 import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
36 import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
37 import type { MenuAction } from "@react-native-menu/menu";
38 import { useNavigation } from "@react-navigation/native";
39 import { msg, T, useGT, useMessages } from "gt-react-native";
40 import { memo, useCallback, useMemo, useState, type ComponentProps } from "react";
41 import { Platform, Pressable, Text as RNText, useWindowDimensions, View } from "react-native";
42 import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
43
44 import type { ThreadListProvider } from "../../state/thread-list-environments";
45 import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
46 import { AppText as Text } from "../../components/ui/AppText";
47 import { Menu } from "../../components/ui/Menu";
48 import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
49 import { ProjectFavicon } from "../../components/ProjectFavicon";
50 import {
51 ProviderIcon,
52 ProviderInstanceIcon,
53 providerInstanceNameLabel,
54 } from "../../components/ProviderIcon";
55 import { useNowAfter } from "../../lib/clock";
56 import { cn } from "../../lib/cn";
57 import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
58 import { copyThreadReference } from "../../lib/copyThreadReference";
59 import { useUniwindTheme } from "../../lib/useUniwindTheme";
60 import { useEnvironmentScope } from "../../state/session";
61 import type { PendingNewTask } from "../../state/use-pending-new-tasks";
62 import {
63 pendingDraftBranchNeedsRefs,
64 resolvePendingDraftBranch,
65 } from "../../state/pending-new-tasks-model";
66 import { useBranches } from "../../state/queries";
67 import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
68 import {
69 resolveThreadPrBadgeAction,
70 type ThreadPrPresentation,
71 } from "../../state/thread-pr-presentation";
72 import { useThreadPr } from "../../state/use-thread-pr";
73 import { useSwipeRowDormant } from "../home/swipe-row-activation";
74 import { ThreadSwipeable } from "../home/thread-swipe-actions";
75 import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
76 import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject";
77 import { threadCanArchive } from "../home/threadArchive";
78 import { useCanShareWithGuest } from "./useCanShareWithGuest";
79 import {
80 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
81 resolveThreadListV2SnoozeGateExpiryMs,
82 resolveThreadListV2SnoozeMenuSelection,
83 resolveThreadListV2SnoozePresets,
84 threadHasUnseenCompletion,
85 resolveThreadListV2RowStatus,
86 resolveThreadListV2Status,
87 resolveThreadListV2ProviderDrivers,
88 resolveThreadListV2SwipeActions,
89 layoutThreadListV2RowMenuActions,
90 threadListV2RowAccessibilityLabel,
91 type ThreadListV2Status,
92 } from "./threadListV2";
93 import { QueuedMessageIcon } from "./queued-message-icon";
94 import { shouldRecedeThreadRow } from "./thread-row-emphasis";
95 import { ThreadSearchMatchExcerpt } from "./thread-search-match";
96 import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
97 import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
98 import { pullRequestStatus } from "../pull-requests/pullRequestStatus";
99
100 interface StatusLabel {
101 // Null when the icon and timer carry the status on their own.
102 readonly label: string | null;
103 readonly icon: AppSymbolName;
104 readonly className: string;
105 readonly iconTintClassName: string;
106 }
107 const STATUS_LABEL_BY_STATUS: Partial<Record<ThreadListV2Status, StatusLabel>> = {
108 approval: {
109 label: msg("Approval", { $context: "thread status, waiting for approval" }),
110 icon: "exclamationmark.shield",
111 className: "text-warning-foreground",
112 iconTintClassName: "accent-warning-foreground",
113 },
114 input: {
115 label: msg("Input", { $context: "thread status, waiting for user input" }),
116 icon: "questionmark.bubble",
117 className: "text-adaptive-indigo-600-300",
118 iconTintClassName: "accent-adaptive-indigo-600-300",
119 },
120 request: {
121 label: msg("Request", { $context: "thread status, a guest request is waiting" }),
122 icon: "person.crop.circle",
123 className: "text-adaptive-fuchsia-600-300",
124 iconTintClassName: "accent-adaptive-fuchsia-600-300",
125 },
126 working: {
127 label: null,
128 icon: "circle.dashed",
129 className: "text-adaptive-sky-600-400",
130 iconTintClassName: "accent-adaptive-sky-600-400",
131 },
132 waiting: {
133 label: null,
134 icon: "circle.dashed.inset.filled",
135 className: "text-foreground-muted",
136 iconTintClassName: "accent-foreground-muted",
137 },
138 failed: {
139 label: msg("Failed", { $context: "thread status" }),
140 icon: "exclamationmark.circle",
141 className: "text-danger-foreground",
142 iconTintClassName: "accent-danger-foreground",
143 },
144 limited: {
145 label: msg("Limited", { $context: "thread status, usage limit reached" }),
146 icon: "exclamationmark.circle",
147 className: "text-warning-foreground",
148 iconTintClassName: "accent-warning-foreground",
149 },
150 };
151 const DONE_STATUS_LABEL: StatusLabel = {
152 label: msg("Done", { $context: "thread status, turn finished" }),
153 icon: "checkmark.circle",
154 className: "text-adaptive-emerald-700-300",
155 iconTintClassName: "accent-adaptive-emerald-700-300",
156 };
157
158 // DM Sans has no tabular figures, so a ticking timer in it reflows the row every second.
159 const TABULAR_DURATION_STYLE = {
160 fontFamily: Platform.OS === "ios" ? "System" : "sans-serif",
161 fontWeight: "700",
162 fontVariant: ["tabular-nums"],
163 } as const;
164
165 function ThreadListV2Duration(props: {
166 readonly environmentId: EnvironmentId;
167 readonly startedAt: string | null;
168 readonly leadingSpace: boolean;
169 }) {
170 const messages = useMessages();
171 const startedAtMs = Date.parse(props.startedAt ?? "");
172 const nowMs = useVisibleSecondClock(Number.isFinite(startedAtMs));
173 if (!Number.isFinite(startedAtMs)) return null;
174 return (
175 <>
176 {props.leadingSpace ? " " : null}
177 <RNText style={TABULAR_DURATION_STYLE}>
178 {formatWorkingDurationLabel(
179 toServerClock(props.environmentId, nowMs) - startedAtMs,
180 messages,
181 )}
182 </RNText>
183 </>
184 );
185 }
186
187 const CARD_MENU_ACTIONS: MenuAction[] = [
188 { id: "settle", title: msg("Settle", { $context: "verb, thread action" }), image: "checkmark" },
189 {
190 id: "delete",
191 title: msg("Delete", { $context: "verb, thread action" }),
192 image: "trash",
193 attributes: { destructive: true },
194 },
195 ];
196
197 const SLIM_MENU_ACTIONS: MenuAction[] = [
198 {
199 id: "unsettle",
200 title: msg("Un-settle", { $context: "verb, thread action" }),
201 image: "arrow.uturn.backward",
202 },
203 {
204 id: "delete",
205 title: msg("Delete", { $context: "verb, thread action" }),
206 image: "trash",
207 attributes: { destructive: true },
208 },
209 ];
210
211 const SNOOZED_MENU_ACTIONS: MenuAction[] = [
212 { id: "unsnooze", title: msg("Wake thread"), image: "clock" },
213 {
214 id: "delete",
215 title: msg("Delete", { $context: "verb, thread action" }),
216 image: "trash",
217 attributes: { destructive: true },
218 },
219 ];
220
221 const LEGACY_MENU_ACTIONS: MenuAction[] = [
222 {
223 id: "archive",
224 title: msg("Archive", { $context: "verb, thread action" }),
225 image: "archivebox",
226 },
227 {
228 id: "delete",
229 title: msg("Delete", { $context: "verb, thread action" }),
230 image: "trash",
231 attributes: { destructive: true },
232 },
233 ];
234
235 function ThreadListV2Section(props: {
236 readonly label: string;
237 readonly pane?: "screen" | "sidebar";
238 readonly tone?: "default" | "snoozed";
239 readonly disclosure?: {
240 readonly expanded: boolean;
241 readonly disabled?: boolean;
242 readonly onToggle: () => void;
243 readonly accessibilityLabel: string;
244 readonly accessibilityHint: string;
245 };
246 }) {
247 const snoozed = props.tone === "snoozed";
248 const sidebarPane = props.pane === "sidebar";
249 const className = cn(
250 "mb-1.5 mt-4 flex-row items-center gap-2.5",
251 props.pane === "sidebar" ? "px-3" : "px-5",
252 );
253 const content = (
254 <>
255 <Text
256 className={cn(
257 "text-xs font-t3-medium",
258 sidebarPane
259 ? "text-drawer-foreground-muted"
260 : snoozed
261 ? "text-foreground-secondary"
262 : "text-foreground-tertiary",
263 )}
264 >
265 {props.label}
266 </Text>
267 <View
268 className={cn(
269 "h-px flex-1",
270 snoozed ? "bg-primary/20" : sidebarPane ? "bg-drawer-border" : "bg-border",
271 )}
272 />
273 {props.disclosure ? (
274 <SymbolView
275 name="chevron.down"
276 size={10}
277 tintColorClassName={
278 sidebarPane
279 ? "accent-drawer-foreground-muted"
280 : snoozed
281 ? "accent-icon-muted"
282 : "accent-foreground-muted"
283 }
284 type="monochrome"
285 style={{ transform: [{ rotate: props.disclosure.expanded ? "180deg" : "0deg" }] }}
286 />
287 ) : null}
288 </>
289 );
290
291 return props.disclosure ? (
292 <Pressable
293 accessibilityHint={props.disclosure.accessibilityHint}
294 accessibilityLabel={props.disclosure.accessibilityLabel}
295 accessibilityRole="button"
296 accessibilityState={{
297 disabled: props.disclosure.disabled,
298 expanded: props.disclosure.expanded,
299 }}
300 className={className}
301 disabled={props.disclosure.disabled}
302 onPress={props.disclosure.onToggle}
303 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
304 >
305 {content}
306 </Pressable>
307 ) : (
308 <View className={className}>{content}</View>
309 );
310 }
311
312 const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivider(props: {
313 readonly label: string;
314 readonly pane?: "screen" | "sidebar";
315 }) {
316 return <ThreadListV2Section {...props} />;
317 });
318
319 type ThreadListV2ShelfHeaderProps = {
320 readonly count: number;
321 readonly disabled?: boolean;
322 readonly expanded: boolean;
323 readonly onToggle: () => void;
324 readonly pane?: "screen" | "sidebar";
325 };
326
327 const SHELF_COPY = {
328 working: {
329 label: msg("Working", { $context: "thread list section" }),
330 count: msg("{count, plural, one {{count} working thread} other {{count} working threads}}"),
331 collapse: msg("Collapses the working threads."),
332 expand: msg("Expands the working threads."),
333 },
334 snoozed: {
335 label: msg("Snoozed", { $context: "thread list section" }),
336 count: msg("{count, plural, one {{count} snoozed thread} other {{count} snoozed threads}}"),
337 collapse: msg("Collapses the snoozed threads."),
338 expand: msg("Expands the snoozed threads."),
339 },
340 settled: {
341 label: msg("Settled", { $context: "thread list section" }),
342 count: msg("{count, plural, one {{count} settled thread} other {{count} settled threads}}"),
343 collapse: msg("Collapses the settled threads."),
344 expand: msg("Expands the settled threads."),
345 },
346 } as const;
347
348 function ThreadListV2ShelfHeader(
349 props: ThreadListV2ShelfHeaderProps & { readonly kind: keyof typeof SHELF_COPY },
350 ) {
351 const gt = useGT();
352 const m = useMessages();
353 const copy = SHELF_COPY[props.kind];
354 const label = m(copy.label);
355 return (
356 <ThreadListV2Section
357 label={props.expanded ? label : gt("{label} ({count})", { label, count: props.count })}
358 pane={props.pane}
359 tone={props.kind === "snoozed" ? "snoozed" : "default"}
360 disclosure={{
361 expanded: props.expanded,
362 disabled: props.disabled,
363 onToggle: props.onToggle,
364 accessibilityLabel: m(copy.count, { count: props.count }),
365 accessibilityHint: m(props.expanded ? copy.collapse : copy.expand),
366 }}
367 />
368 );
369 }
370
371 export const ThreadListV2WorkingShelfHeader = memo(function ThreadListV2WorkingShelfHeader(
372 props: ThreadListV2ShelfHeaderProps,
373 ) {
374 return <ThreadListV2ShelfHeader {...props} kind="working" />;
375 });
376
377 export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(
378 props: ThreadListV2ShelfHeaderProps,
379 ) {
380 return <ThreadListV2ShelfHeader {...props} kind="snoozed" />;
381 });
382
383 export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledShelfHeader(
384 props: ThreadListV2ShelfHeaderProps,
385 ) {
386 return <ThreadListV2ShelfHeader {...props} kind="settled" />;
387 });
388
389 export const ThreadListV2ShowMoreRow = memo(function ThreadListV2ShowMoreRow(props: {
390 readonly pane?: "screen" | "sidebar";
391 readonly hiddenCount: number;
392 /** Older settled threads are loading, or their last read failed. */
393 readonly state?: "loading" | "failed";
394 readonly onPress: () => void;
395 }) {
396 const gt = useGT();
397 const label =
398 props.state === "loading"
399 ? gt("Loading", { $context: "older threads are loading" })
400 : props.state === "failed"
401 ? gt("Could not load older threads. Retry")
402 : gt(
403 "{count, plural, one {Show more ({count} settled hidden)} other {Show more ({count} settled hidden)}}",
404 { count: props.hiddenCount },
405 );
406 return (
407 <Pressable
408 accessibilityRole="button"
409 accessibilityLabel={
410 props.state === undefined
411 ? gt(
412 "{count, plural, one {Show {count} more settled threads} other {Show {count} more settled threads}}",
413 {
414 count: Math.min(props.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT),
415 },
416 )
417 : label
418 }
419 disabled={props.state === "loading"}
420 onPress={props.onPress}
421 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
422 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
423 >
424 <Text
425 className={
426 props.pane === "sidebar"
427 ? "text-xs font-t3-medium text-drawer-foreground-muted"
428 : "text-xs font-t3-medium text-foreground-muted"
429 }
430 >
431 {label}
432 </Text>
433 </Pressable>
434 );
435 });
436
437 const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [
438 {
439 id: "delete",
440 title: msg("Delete", { $context: "verb, thread action" }),
441 image: "trash",
442 attributes: { destructive: true },
443 },
444 ];
445
446 const DRAFT_TASK_MENU_ACTIONS: MenuAction[] = [
447 {
448 id: "delete",
449 title: msg("Discard", { $context: "verb, thread action" }),
450 image: "trash",
451 attributes: { destructive: true },
452 },
453 ];
454
455 export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props: {
456 readonly pendingTask: PendingNewTask;
457 readonly selected?: boolean;
458 readonly project: EnvironmentProject | null;
459 readonly environmentLabel: string | null;
460 readonly environmentMachine?: EnvironmentMachineKind;
461 readonly pane?: "screen" | "sidebar";
462 readonly showPendingDivider: boolean;
463 readonly showTrailingDivider?: boolean;
464 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
465 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
466 readonly fullSwipeWidth?: number;
467 readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
468 readonly onSwipeableClose: (methods: SwipeableMethods) => void;
469 readonly activationKey?: string;
470 readonly simultaneousSwipeGesture?: ComponentProps<typeof ThreadSwipeable>["simultaneousWith"];
471 }) {
472 const { pendingTask, onSelectPendingTask, onDeletePendingTask } = props;
473 const { width: windowWidth, fontScale } = useWindowDimensions();
474 const titleTypography = useScaledTextRole("body");
475 const metadataTypography = useScaledTextRole("label");
476 const projectIconSize = titleTypography.fontSize * 1.25 * fontScale;
477 const machineIconSize = metadataTypography.fontSize * fontScale;
478 // Android's nonlinear system text scaling can differ from the fontScale estimate.
479 const [androidTitleLineHeight, setTitleLineHeight] = useState(
480 titleTypography.lineHeight * fontScale,
481 );
482 const titleLineHeight =
483 Platform.OS === "android" ? androidTitleLineHeight : titleTypography.lineHeight * fontScale;
484 const dormant = useSwipeRowDormant(props.activationKey);
485 const theme = useUniwindTheme();
486 const sidebarPane = props.pane === "sidebar";
487 const selected = props.selected ?? false;
488 const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, selected);
489 const gt = useGT();
490 const m = useMessages();
491 const isDraft = pendingTask.kind === "draft";
492 const deleteLabel = isDraft
493 ? gt("Discard", { $context: "verb, thread action" })
494 : gt("Delete", { $context: "verb, thread action" });
495 const handleDelete = useCallback(
496 () => onDeletePendingTask(pendingTask),
497 [onDeletePendingTask, pendingTask],
498 );
499 const deleteAction = useMemo(
500 () => ({
501 accessibilityLabel: isDraft
502 ? gt("Discard {title}", { title: pendingTask.title })
503 : gt("Delete {title}", { title: pendingTask.title }),
504 destructive: true,
505 icon: "trash" as const,
506 label: deleteLabel,
507 onPress: handleDelete,
508 }),
509 [deleteLabel, gt, handleDelete, isDraft, pendingTask.title],
510 );
511 const projectCwd = props.project?.workspaceRoot || null;
512 // Drafts only; the reads are shared per-project atoms, and queued rows skip them.
513 const projectDefaults = useNewTaskProjectDefaults(isDraft ? props.project : null);
514 const draftDefaults = {
515 canChooseWorkspace: !projectDefaults.isScratch,
516 defaultMode: projectDefaults.defaultWorkspaceMode,
517 defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled,
518 };
519 const draftBranchRefs = useBranches({
520 environmentId: pendingTask.environmentId,
521 cwd:
522 isDraft && pendingDraftBranchNeedsRefs(pendingTask.draft, draftDefaults) ? projectCwd : null,
523 });
524 const branch = isDraft
525 ? resolvePendingDraftBranch({
526 draft: pendingTask.draft,
527 defaults: draftDefaults,
528 isGitRepo: draftBranchRefs.data?.isRepo ?? true,
529 branches: draftBranchRefs.data?.refs ?? [],
530 projectCwd,
531 })
532 : pendingTask.branch;
533
534 const handleMenuAction = useCallback(
535 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
536 if (nativeEvent.event === "delete") onDeletePendingTask(pendingTask);
537 },
538 [onDeletePendingTask, pendingTask],
539 );
540
541 const titleTextInset = props.project ? projectIconSize + 8 : 0;
542 const rowContent = (
543 <>
544 <View className="flex-row items-start gap-2">
545 {props.project ? (
546 <View className="justify-center" style={{ height: titleLineHeight }}>
547 <ProjectFavicon
548 environmentId={pendingTask.environmentId}
549 faviconPath={props.project.faviconPath}
550 projectIcon={props.project.projectIcon}
551 size={projectIconSize}
552 projectTitle={props.project.title}
553 workspaceRoot={props.project.workspaceRoot}
554 />
555 </View>
556 ) : null}
557 <Text
558 className={cn(
559 "flex-1 text-base font-t3-medium",
560 selected
561 ? selectedThreadRowColors.foregroundClassName
562 : rowAppearance.foregroundClassName,
563 )}
564 numberOfLines={2}
565 onTextLayout={
566 Platform.OS === "android"
567 ? ({ nativeEvent }) => {
568 const firstLine = nativeEvent.lines[0];
569 if (firstLine && Math.abs(firstLine.height - titleLineHeight) > 0.5) {
570 setTitleLineHeight(firstLine.height);
571 }
572 }
573 : undefined
574 }
575 >
576 {pendingTask.title}
577 </Text>
578 {isDraft ? (
579 <View className="flex-row items-center gap-1" style={{ minHeight: titleLineHeight }}>
580 <SymbolView
581 name="square.and.pencil"
582 size={13}
583 tintColorClassName={
584 selected
585 ? selectedThreadRowColors.iconTintClassName
586 : "accent-adaptive-amber-700-300"
587 }
588 type="monochrome"
589 weight="semibold"
590 />
591 <Text
592 className={cn(
593 "text-xs font-t3-bold",
594 selected
595 ? selectedThreadRowColors.foregroundClassName
596 : "text-adaptive-amber-700-300",
597 )}
598 >
599 <T>Draft</T>
600 </Text>
601 </View>
602 ) : null}
603 </View>
604 {!isDraft ? (
605 <View className="mt-1" style={{ paddingLeft: titleTextInset }}>
606 <Text
607 className={cn(
608 "text-xs",
609 selected
610 ? selectedThreadRowColors.foregroundClassName
611 : rowAppearance.tertiaryForegroundClassName,
612 )}
613 >
614 <T>Sends on reconnect</T>
615 </Text>
616 </View>
617 ) : null}
618 {branch || props.environmentLabel ? (
619 <View className="mt-1 flex-row items-center gap-1" style={{ paddingLeft: titleTextInset }}>
620 {props.environmentLabel && props.environmentMachine ? (
621 <EnvironmentMachineSymbol
622 kind={props.environmentMachine}
623 size={machineIconSize}
624 tintColorClassName={
625 selected
626 ? selectedThreadRowColors.mutedIconTintClassName
627 : rowAppearance.tertiaryIconTintClassName
628 }
629 />
630 ) : null}
631 <Text
632 className={cn(
633 "shrink text-xs text-foreground-muted",
634 selected
635 ? selectedThreadRowColors.mutedForegroundClassName
636 : rowAppearance.mutedForegroundClassName,
637 )}
638 numberOfLines={1}
639 >
640 {branch ? (
641 <Text
642 className={cn(
643 "text-xs",
644 selected
645 ? selectedThreadRowColors.mutedForegroundClassName
646 : rowAppearance.mutedForegroundClassName,
647 )}
648 style={{ fontFamily: MONO_FONT }}
649 >
650 {branch}
651 </Text>
652 ) : null}
653 {branch && props.environmentLabel ? " · " : null}
654 {props.environmentLabel ? (
655 <Text
656 className={cn(
657 "text-xs",
658 selected
659 ? selectedThreadRowColors.mutedForegroundClassName
660 : rowAppearance.tertiaryForegroundClassName,
661 )}
662 >
663 {props.environmentLabel}
664 </Text>
665 ) : null}
666 </Text>
667 </View>
668 ) : null}
669 </>
670 );
671
672 return (
673 <>
674 {props.showPendingDivider ? (
675 <ThreadListV2SectionDivider
676 label={gt("Unsent", { $context: "section of tasks not yet sent" })}
677 pane={props.pane}
678 />
679 ) : null}
680 <ThreadSwipeable
681 dormant={dormant}
682 threadKey={pendingTask.key}
683 backgroundColor={rowAppearance.swipeBackgroundColor}
684 containerStyle={rowAppearance.swipeContainerStyle}
685 enableTrackpadSwipe
686 fullSwipeAction="primary"
687 fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
688 listAnimatesLayout
689 onDelete={handleDelete}
690 onSwipeableClose={props.onSwipeableClose}
691 onSwipeableWillOpen={props.onSwipeableWillOpen}
692 primaryAction={deleteAction}
693 secondaryAction={null}
694 resetKey={pendingTask.key}
695 simultaneousWith={props.simultaneousSwipeGesture}
696 threadTitle={pendingTask.title}
697 >
698 {() => (
699 <Menu
700 actions={(isDraft ? DRAFT_TASK_MENU_ACTIONS : PENDING_TASK_MENU_ACTIONS).map(
701 (action) => ({
702 ...action,
703 title: m(action.title),
704 }),
705 )}
706 onPressAction={handleMenuAction}
707 shouldOpenOnLongPress
708 >
709 <RowPressable
710 accessibilityHint={
711 isDraft
712 ? gt("Opens the draft in the new task composer. Swipe left to discard.")
713 : gt(
714 "Sends when the environment reconnects. Opens the task for editing. Swipe left to delete.",
715 )
716 }
717 accessibilityLabel={pendingTask.title}
718 accessibilityRole="button"
719 accessibilityState={{ selected: props.selected ?? false }}
720 key={pendingTask.key}
721 className={rowAppearance.className}
722 interactionClassName={rowAppearance.interactionClassName}
723 interactionOpacity={rowAppearance.interactionOpacity}
724 onPress={() => onSelectPendingTask(pendingTask)}
725 style={rowAppearance.cardStyle}
726 >
727 {sidebarPane ? (
728 rowContent
729 ) : (
730 <View>
731 <View className={THREAD_LIST_V2_ROW_CONTENT_CLASS_NAME}>{rowContent}</View>
732 {THREAD_LIST_V2_ROW_DIVIDERS && props.showTrailingDivider !== false ? (
733 <View className="ml-5 h-px bg-border-subtle" />
734 ) : null}
735 </View>
736 )}
737 </RowPressable>
738 </Menu>
739 )}
740 </ThreadSwipeable>
741 </>
742 );
743 });
744
745 export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
746 readonly thread: EnvironmentThreadShell;
747 readonly variant: "card" | "slim";
748 readonly hasQueuedMessages?: boolean;
749 readonly snoozed?: boolean;
750 readonly pinned?: boolean;
751 readonly wokeAt: string | null;
752 readonly snoozeWakeLabelText?: string;
753 readonly timeLabel: string;
754 readonly snoozePresetMinute: string;
755 readonly project: EnvironmentProject | null;
756 readonly providers: ReadonlyArray<ThreadListProvider> | undefined;
757 readonly providerInstance: ThreadRowProviderInstance | null;
758 readonly environmentLabel: string | null;
759 readonly environmentMachine?: EnvironmentMachineKind;
760 readonly pane?: "screen" | "sidebar";
761 readonly showTrailingDivider?: boolean;
762 readonly selected?: boolean;
763 readonly fullSwipeWidth?: number;
764 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
765 readonly onOpenThreadPullRequests: (
766 thread: EnvironmentThreadShell,
767 pr: ThreadPrPresentation,
768 ) => void;
769 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
770 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
771 readonly onRenameThread: (thread: EnvironmentThreadShell) => void;
772 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
773 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
774 readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
775 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
776 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
777 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
778 readonly onPinThread: (thread: EnvironmentThreadShell) => void;
779 readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;
780 readonly onSetThreadAutoSettle: (thread: EnvironmentThreadShell, enabled: boolean) => void;
781 readonly settlementSupported: boolean;
782 readonly snoozeSupported: boolean;
783 readonly snoozePresets: ReadonlyArray<SnoozePresetSetting> | undefined;
784 readonly pinningSupported: boolean;
785 readonly autoSettleOptOutSupported: boolean;
786 readonly titleRegenerationSupported: boolean;
787 readonly reorderSupported?: boolean;
788 readonly onMoveThread?: (
789 thread: EnvironmentThreadShell,
790 direction: ThreadMoveDestination,
791 ) => void;
792 readonly canMoveUp?: boolean;
793 readonly canMoveDown?: boolean;
794 readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
795 readonly onSwipeableClose: (methods: SwipeableMethods) => void;
796 readonly activationKey?: string;
797 readonly searchMatch?: EnvironmentThreadSearchMatch;
798 readonly searchQuery?: string;
799 readonly simultaneousSwipeGesture?: ComponentProps<typeof ThreadSwipeable>["simultaneousWith"];
800 }) {
801 const { width: windowWidth, fontScale } = useWindowDimensions();
802 const titleTypography = useScaledTextRole("body");
803 const metadataTypography = useScaledTextRole("label");
804 const projectIconSize = titleTypography.fontSize * 1.25 * fontScale;
805 const machineIconSize = metadataTypography.fontSize * fontScale;
806 // Android's nonlinear system text scaling can differ from the fontScale estimate.
807 const [androidTitleLineHeight, setTitleLineHeight] = useState(
808 titleTypography.lineHeight * fontScale,
809 );
810 const titleLineHeight =
811 Platform.OS === "android" ? androidTitleLineHeight : titleTypography.lineHeight * fontScale;
812 const gt = useGT();
813 const m = useMessages();
814 const {
815 thread,
816 variant,
817 onSelectThread,
818 onOpenThreadPullRequests,
819 onDeleteThread,
820 onRenameThread,
821 onRegenerateThreadTitle,
822 onNewThreadOnBranch,
823 onSettleThread,
824 onSnoozeThread,
825 onUnsnoozeThread,
826 onUnsettleThread,
827 onArchiveThread,
828 onPinThread,
829 onUnpinThread,
830 onSetThreadAutoSettle,
831 onMoveThread,
832 } = props;
833 const snoozedRow = props.snoozed === true;
834 const pinnedRow = props.pinned === true;
835 const dormant = useSwipeRowDormant(props.activationKey);
836
837 const selectThread = () => onSelectThread(thread);
838 const { providerDrivers, providerIconUrl } = useMemo(() => {
839 const provider = props.providers?.find(
840 (candidate) =>
841 candidate.instanceId ===
842 (thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
843 );
844 return {
845 providerDrivers: resolveThreadListV2ProviderDrivers(thread, props.providers),
846 providerIconUrl: provider?.iconUrl,
847 };
848 }, [thread, props.providers]);
849
850 const providerInstance = props.providerInstance;
851 const providerNameLabel = providerInstance
852 ? providerInstanceNameLabel({
853 provider: providerInstance.driverKind,
854 iconUrl: providerIconUrl,
855 displayName: providerInstance.displayName,
856 showBadge: providerInstance.showBadge,
857 })
858 : null;
859 const pr = useThreadPr(thread);
860 const prBadgeLabel = pr ? resolveThreadPrBadgeAction(pr, m).accessibilityLabel : null;
861 const handleOpenPullRequests = useCallback(() => {
862 if (pr) onOpenThreadPullRequests(thread, pr);
863 }, [onOpenThreadPullRequests, pr, thread]);
864
865 const theme = useUniwindTheme();
866 const sidebarPane = props.pane === "sidebar";
867 const selected = props.selected === true;
868 const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, selected);
869
870 const rawStatus = resolveThreadListV2Status(thread);
871 const status = resolveThreadListV2RowStatus(thread);
872 const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
873 const workingLabel = STATUS_LABEL_BY_STATUS[status];
874 const showsWoke = status === "ready" && props.wokeAt !== null;
875 const statusEntry =
876 (status === "working" && workingLabel !== undefined && thread.goal?.status === "active"
877 ? {
878 ...workingLabel,
879 label: msg("Goal", { $context: "thread status, working toward a goal" }),
880 }
881 : workingLabel) ?? (isUnread ? DONE_STATUS_LABEL : undefined);
882 const statusLabel = statusEntry && {
883 ...statusEntry,
884 label: statusEntry.label === null ? null : m(statusEntry.label),
885 };
886 const recede = shouldRecedeThreadRow({ status, selected });
887 const isRegeneratingTitle = thread.titleRegeneration != null;
888 // List items keep marked text so they stay the same objects across a language switch.
889 const timeLabel = props.timeLabel && m(props.timeLabel);
890 const snoozeWakeLabelText =
891 props.snoozeWakeLabelText === undefined ? undefined : m(props.snoozeWakeLabelText);
892 const rowAccessibilityLabel = threadListV2RowAccessibilityLabel(
893 {
894 title: thread.title,
895 variant,
896 woke: showsWoke,
897 // Working and waiting rows show only an icon and a duration, so name them for speech.
898 statusLabel:
899 statusLabel &&
900 (statusLabel.label ??
901 (status === "waiting"
902 ? gt("Waiting", { $context: "thread status" })
903 : gt("Working", { $context: "thread status" }))),
904 timeLabel,
905 snoozeWakeLabel: snoozedRow ? snoozeWakeLabelText : undefined,
906 providerNameLabel,
907 hasQueuedMessages: props.hasQueuedMessages === true,
908 regeneratingTitle: isRegeneratingTitle,
909 },
910 m,
911 );
912
913 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
914 const markThreadUnread = useAtomCommand(threadEnvironment.markUnread, { reportFailure: false });
915 const handleAcknowledgeWoke = useCallback(() => {
916 if (props.wokeAt === null) return;
917 void visitThread({
918 environmentId: thread.environmentId,
919 input: { threadId: thread.id, visitedAt: props.wokeAt },
920 });
921 }, [props.wokeAt, thread.environmentId, thread.id, visitThread]);
922 // VoiceOver cannot focus buttons inside the accessible row.
923 const rowAccessibilityActions = useMemo(
924 () => [
925 ...(prBadgeLabel ? [{ name: "openPullRequests", label: prBadgeLabel }] : []),
926 ...(showsWoke ? [{ name: "dismissWoke", label: gt("Dismiss Woke notification") }] : []),
927 ],
928 [gt, prBadgeLabel, showsWoke],
929 );
930
931 const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
932 const handleRename = useCallback(() => onRenameThread(thread), [onRenameThread, thread]);
933 const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
934 const canShareWithGuest = useCanShareWithGuest(thread.environmentId);
935 const navigation = useNavigation();
936 const handleRegenerateTitle = useCallback(
937 () => onRegenerateThreadTitle(thread),
938 [onRegenerateThreadTitle, thread],
939 );
940 const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
941 const [customSnoozeOpen, setCustomSnoozeOpen] = useState(false);
942 // Recycling changes identity without remounting; clear local UI directly because equality may skip the render closure.
943 const rowIdentity = `${thread.environmentId}:${thread.id}`;
944 const [boundIdentity, setBoundIdentity] = useState(rowIdentity);
945 if (boundIdentity !== rowIdentity) {
946 setBoundIdentity(rowIdentity);
947 setCustomSnoozeOpen(false);
948 }
949 const handleSnooze = useCallback(
950 (snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
951 [onSnoozeThread, thread],
952 );
953 const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
954 const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
955 const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
956 const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
957 const handleSetAutoSettle = useCallback(
958 (enabled: boolean) => onSetThreadAutoSettle(thread, enabled),
959 [onSetThreadAutoSettle, thread],
960 );
961 const handleMoveUp = useCallback(() => onMoveThread?.(thread, "up"), [onMoveThread, thread]);
962 const handleMoveDown = useCallback(() => onMoveThread?.(thread, "down"), [onMoveThread, thread]);
963 const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
964
965 const canUnsettle = variant === "slim";
966 // The gate's only time-dependent edge is the queued-turn grace window, so its
967 // expiry is known without a clock: evaluate at the message's own timestamp.
968 // A gate held by runtime status has no expiry, and no clock tick opens it.
969 const snoozeGateExpiryMs = props.snoozeSupported
970 ? resolveThreadListV2SnoozeGateExpiryMs(thread, { now: thread.latestUserMessageAt ?? "" })
971 : null;
972 // The window is inclusive, so wake just past it.
973 const snoozeGateNowMs = useNowAfter(snoozeGateExpiryMs === null ? null : snoozeGateExpiryMs + 1);
974 const snoozeGateNow = new Date(snoozeGateNowMs).toISOString();
975 const swipeActions = resolveThreadListV2SwipeActions({
976 variant,
977 settlementSupported: props.settlementSupported,
978 snoozeSupported: props.snoozeSupported,
979 snoozable: canSnooze(thread, { now: snoozeGateNow }),
980 snoozed: snoozedRow,
981 });
982 const snoozePresets = resolveThreadListV2SnoozePresets(
983 {
984 secondary: swipeActions.secondary,
985 now: props.snoozePresetMinute || snoozeGateNow,
986 presets: props.snoozePresets,
987 },
988 m,
989 );
990 const snoozePresetActions = useMemo<MenuAction[]>(
991 () => [
992 ...snoozePresets.map((preset) => ({
993 id: `snooze:${preset.id}`,
994 title: preset.label,
995 subtitle: preset.whenLabel,
996 })),
997 { id: "snooze:custom", title: gt("Custom…", { $context: "custom snooze time" }) },
998 ],
999 [gt, snoozePresets],
1000 );
1001 const reorderMenuItems = useMemo<MenuAction[]>(
1002 () =>
1003 props.reorderSupported === true
1004 ? [
1005 { id: "arrange", title: gt("Arrange threads…"), image: "line.3.horizontal" },
1006 {
1007 id: "move-up",
1008 title: gt("Move up"),
1009 image: "arrow.up",
1010 attributes: { disabled: props.canMoveUp !== true },
1011 } satisfies MenuAction,
1012 {
1013 id: "move-down",
1014 title: gt("Move down"),
1015 image: "arrow.down",
1016 attributes: { disabled: props.canMoveDown !== true },
1017 } satisfies MenuAction,
1018 ]
1019 : [],
1020 [gt, props.canMoveDown, props.canMoveUp, props.reorderSupported],
1021 );
1022 const pinMenuItems = useMemo<MenuAction[]>(
1023 () =>
1024 props.pinningSupported
1025 ? [
1026 thread.pinnedAt != null
1027 ? {
1028 id: "unpin",
1029 title: gt("Unpin", { $context: "verb, thread action" }),
1030 image: "pin.slash",
1031 }
1032 : { id: "pin", title: gt("Pin", { $context: "verb, thread action" }), image: "pin" },
1033 ]
1034 : [],
1035 [gt, props.pinningSupported, thread.pinnedAt],
1036 );
1037 const autoSettleMenuItems = useMemo<MenuAction[]>(
1038 () =>
1039 props.autoSettleOptOutSupported
1040 ? [
1041 {
1042 id: "auto-settle",
1043 title: gt("Auto-settle behavior"),
1044 image: "timer",
1045 subactions: [
1046 {
1047 id: "auto-settle:enabled",
1048 title: gt("Follow settings"),
1049 state: thread.autoSettleDisabledAt == null ? "on" : "off",
1050 },
1051 {
1052 id: "auto-settle:disabled",
1053 title: gt("Never", { $context: "never auto-settle this thread" }),
1054 state: thread.autoSettleDisabledAt == null ? "off" : "on",
1055 },
1056 ],
1057 } satisfies MenuAction,
1058 ]
1059 : [],
1060 [gt, props.autoSettleOptOutSupported, thread.autoSettleDisabledAt],
1061 );
1062 const canTurnIntoProject = canTurnThreadIntoProject(thread);
1063 const titleMenuItems = useMemo<MenuAction[]>(
1064 () => [
1065 {
1066 id: "rename",
1067 title: gt("Rename", { $context: "verb, thread action" }),
1068 image: "square.and.pencil",
1069 },
1070 ...buildThreadTitleRegenerationMenuItems(
1071 {
1072 supported: props.titleRegenerationSupported,
1073 isRegenerating: isRegeneratingTitle,
1074 },
1075 m,
1076 ),
1077 { id: "mark-unread", title: gt("Mark unread"), image: "envelope.badge" },
1078 ...(canTurnIntoProject
1079 ? [
1080 {
1081 id: "turn-into-project",
1082 title: gt("Turn into project"),
1083 image: "folder.badge.plus",
1084 attributes: { disabled: !threadCanArchive(thread.runtime) },
1085 } satisfies MenuAction,
1086 ]
1087 : []),
1088 ],
1089 [
1090 canTurnIntoProject,
1091 gt,
1092 m,
1093 props.titleRegenerationSupported,
1094 thread.runtime,
1095 isRegeneratingTitle,
1096 ],
1097 );
1098 const menuActions = useMemo<MenuAction[]>(() => {
1099 const nested = Platform.OS === "ios";
1100 const localized = (action: MenuAction): MenuAction => ({ ...action, title: m(action.title) });
1101 const direct: MenuAction[] = [
1102 ...(thread.branch
1103 ? [
1104 {
1105 id: "new-thread-on-branch",
1106 title: getThreadListV2NewBranchMenuTitle(thread.branch, m),
1107 image: "square.and.pencil",
1108 },
1109 ]
1110 : []),
1111 { id: "copy-thread", title: gt("Copy thread"), image: "text.bubble" },
1112 { id: "copy-thread-id", title: gt("Copy thread ID"), image: "doc.on.doc" },
1113 ...(canShareWithGuest
1114 ? [{ id: "share-guest", title: gt("Share with guest"), image: "person.badge.plus" }]
1115 : []),
1116 ];
1117 if (snoozedRow) {
1118 return layoutThreadListV2RowMenuActions(
1119 {
1120 nested,
1121 direct: [...direct, localized(SNOOZED_MENU_ACTIONS[0]!)],
1122 reorder: [],
1123 pin: [],
1124 secondary: [
1125 ...titleMenuItems,
1126 ...autoSettleMenuItems,
1127 localized(LEGACY_MENU_ACTIONS[0]!),
1128 localized(SNOOZED_MENU_ACTIONS[1]!),
1129 ],
1130 },
1131 m,
1132 );
1133 }
1134 if (!props.settlementSupported) {
1135 return layoutThreadListV2RowMenuActions(
1136 {
1137 nested,
1138 direct: [...direct, localized(LEGACY_MENU_ACTIONS[0]!)],
1139 reorder: reorderMenuItems,
1140 pin: pinMenuItems,
1141 secondary: [...titleMenuItems, localized(LEGACY_MENU_ACTIONS[1]!)],
1142 },
1143 m,
1144 );
1145 }
1146 if (canUnsettle) {
1147 return layoutThreadListV2RowMenuActions(
1148 {
1149 nested,
1150 direct: [...direct, localized(SLIM_MENU_ACTIONS[0]!)],
1151 reorder: reorderMenuItems.filter(
1152 (action) => action.id !== "move-up" && action.id !== "move-down",
1153 ),
1154 pin: pinMenuItems,
1155 secondary: [
1156 ...titleMenuItems,
1157 ...autoSettleMenuItems,
1158 localized(LEGACY_MENU_ACTIONS[0]!),
1159 localized(SLIM_MENU_ACTIONS[1]!),
1160 ],
1161 },
1162 m,
1163 );
1164 }
1165 return layoutThreadListV2RowMenuActions(
1166 {
1167 nested,
1168 direct: [
1169 ...direct,
1170 localized(CARD_MENU_ACTIONS[0]!),
1171 ...(swipeActions.secondary === "snooze"
1172 ? [
1173 {
1174 id: "snooze",
1175 title: gt("Snooze", { $context: "verb, thread action" }),
1176 image: "clock",
1177 subactions: snoozePresetActions,
1178 },
1179 ]
1180 : []),
1181 ],
1182 reorder: reorderMenuItems,
1183 pin: pinMenuItems,
1184 secondary: [
1185 ...titleMenuItems,
1186 ...autoSettleMenuItems,
1187 localized(LEGACY_MENU_ACTIONS[0]!),
1188 localized(CARD_MENU_ACTIONS[1]!),
1189 ],
1190 },
1191 m,
1192 );
1193 }, [
1194 autoSettleMenuItems,
1195 canShareWithGuest,
1196 canUnsettle,
1197 pinMenuItems,
1198 props.settlementSupported,
1199 reorderMenuItems,
1200 snoozePresetActions,
1201 snoozedRow,
1202 gt,
1203 m,
1204 swipeActions.secondary,
1205 thread.branch,
1206 titleMenuItems,
1207 ]);
1208 const handleMenuAction = useCallback(
1209 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
1210 if (nativeEvent.event === "new-thread-on-branch") onNewThreadOnBranch(thread);
1211 if (nativeEvent.event === "settle") handleSettle();
1212 if (nativeEvent.event === "unsettle") handleUnsettle();
1213 if (nativeEvent.event === "unsnooze") handleUnsnooze();
1214 if (nativeEvent.event === "pin") handlePin();
1215 if (nativeEvent.event === "unpin") handleUnpin();
1216 if (nativeEvent.event === "auto-settle:enabled") handleSetAutoSettle(true);
1217 if (nativeEvent.event === "auto-settle:disabled") handleSetAutoSettle(false);
1218 if (nativeEvent.event === "arrange") appAtomRegistry.set(threadArrangementOpenAtom, true);
1219 if (nativeEvent.event === "move-up") handleMoveUp();
1220 if (nativeEvent.event === "move-down") handleMoveDown();
1221 if (nativeEvent.event === "archive") handleArchive();
1222 if (nativeEvent.event === "rename") handleRename();
1223 if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
1224 if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread);
1225 if (nativeEvent.event === "mark-unread") {
1226 void markThreadUnread({
1227 environmentId: thread.environmentId,
1228 input: { threadId: thread.id },
1229 });
1230 }
1231 if (nativeEvent.event === "copy-thread") {
1232 const target = threadChipCopyTarget(
1233 { environmentId: thread.environmentId, threadId: thread.id },
1234 thread.title,
1235 undefined,
1236 m,
1237 );
1238 void copyThreadReference(target).then((didCopy) => {
1239 if (!didCopy) Dialog.alert(target.failureTitle, gt("Try copying this thread again."));
1240 });
1241 }
1242 if (nativeEvent.event === "copy-thread-id") {
1243 copyTextWithHaptic(thread.id, { target: "thread-id" });
1244 }
1245 if (nativeEvent.event === "share-guest") {
1246 navigation.navigate("ThreadGuestShare", {
1247 environmentId: thread.environmentId,
1248 threadId: thread.id,
1249 });
1250 }
1251 if (nativeEvent.event === "delete") handleDelete();
1252 if (nativeEvent.event === "snooze:custom") {
1253 setCustomSnoozeOpen(true);
1254 return;
1255 }
1256 const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
1257 event: nativeEvent.event,
1258 displayedPresets: snoozePresets,
1259 now: new Date(),
1260 presets: props.snoozePresets,
1261 });
1262 if (snoozeSelection._tag === "selected") {
1263 handleSnooze(snoozeSelection.preset.snoozedUntil);
1264 } else if (snoozeSelection._tag === "expired") {
1265 Dialog.alert(
1266 gt("Could not snooze thread"),
1267 gt("That snooze time has passed. Choose another time."),
1268 );
1269 }
1270 },
1271 [
1272 gt,
1273 m,
1274 onNewThreadOnBranch,
1275 thread,
1276 navigation,
1277 handleArchive,
1278 handleDelete,
1279 handleRegenerateTitle,
1280 handleRename,
1281 handleMoveDown,
1282 handleMoveUp,
1283 handlePin,
1284 handleSettle,
1285 handleSnooze,
1286 handleSetAutoSettle,
1287 handleUnpin,
1288 handleUnsettle,
1289 handleUnsnooze,
1290 markThreadUnread,
1291 setCustomSnoozeOpen,
1292 snoozePresets,
1293 props.snoozePresets,
1294 ],
1295 );
1296 const primaryAction = useMemo(() => {
1297 if (swipeActions.primary === "archive") {
1298 return {
1299 accessibilityLabel: gt("Archive {title}", { title: thread.title }),
1300 icon: "archivebox" as const,
1301 label: gt("Archive", { $context: "verb, thread action" }),
1302 swipeHint: gt("Opens the thread. Swipe left to archive."),
1303 swipeSnoozeHint: gt("Opens the thread. Swipe left for archive and snooze actions."),
1304 onPress: handleArchive,
1305 };
1306 }
1307 if (swipeActions.primary === "unsnooze") {
1308 return {
1309 accessibilityLabel: gt("Wake {title} now", { title: thread.title }),
1310 icon: "clock" as const,
1311 label: gt("Wake", { $context: "verb, thread action" }),
1312 swipeHint: gt("Opens the thread. Swipe left to wake."),
1313 swipeSnoozeHint: gt("Opens the thread. Swipe left for wake and snooze actions."),
1314 onPress: handleUnsnooze,
1315 };
1316 }
1317 return swipeActions.primary === "unsettle"
1318 ? {
1319 accessibilityLabel: gt("Un-settle {title}", { title: thread.title }),
1320 icon: "arrow.uturn.backward" as const,
1321 label: gt("Un-settle", { $context: "verb, thread action" }),
1322 swipeHint: gt("Opens the thread. Swipe left to un-settle."),
1323 swipeSnoozeHint: gt("Opens the thread. Swipe left for un-settle and snooze actions."),
1324 onPress: handleUnsettle,
1325 }
1326 : {
1327 accessibilityLabel: gt("Settle {title}", { title: thread.title }),
1328 icon: "checkmark" as const,
1329 label: gt("Settle", { $context: "verb, thread action" }),
1330 swipeHint: gt("Opens the thread. Swipe left to settle."),
1331 swipeSnoozeHint: gt("Opens the thread. Swipe left for settle and snooze actions."),
1332 onPress: handleSettle,
1333 };
1334 }, [
1335 gt,
1336 handleArchive,
1337 handleSettle,
1338 handleUnsettle,
1339 handleUnsnooze,
1340 swipeActions.primary,
1341 thread.title,
1342 ]);
1343 const secondaryAction = useMemo(
1344 () =>
1345 swipeActions.secondary === "snooze"
1346 ? {
1347 accessibilityLabel: gt("Choose when to snooze {title}", { title: thread.title }),
1348 icon: "clock" as const,
1349 label: gt("Snooze", { $context: "verb, thread action" }),
1350 menu: {
1351 actions: snoozePresetActions,
1352 onPressAction: handleMenuAction,
1353 title: gt("Snooze until"),
1354 },
1355 onPress: () => undefined,
1356 }
1357 : null,
1358 [gt, handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
1359 );
1360 const swipeAccessibilityHint = !canOperateThread
1361 ? gt("Opens the thread")
1362 : secondaryAction === null
1363 ? primaryAction.swipeHint
1364 : primaryAction.swipeSnoozeHint;
1365
1366 const titleTextInset = props.project ? projectIconSize + 8 : 0;
1367 const cardContent = (
1368 <>
1369 <View className="flex-row items-start gap-2">
1370 {props.project ? (
1371 <View className="justify-center" style={{ height: titleLineHeight }}>
1372 <ProjectFavicon
1373 environmentId={thread.environmentId}
1374 faviconPath={props.project.faviconPath}
1375 projectIcon={props.project.projectIcon}
1376 size={projectIconSize}
1377 projectTitle={props.project.title}
1378 workspaceRoot={props.project.workspaceRoot}
1379 />
1380 </View>
1381 ) : null}
1382 <Text
1383 className={cn(
1384 "flex-1 text-base",
1385 !recede && "font-t3-medium",
1386 selected
1387 ? selectedThreadRowColors.foregroundClassName
1388 : rowAppearance.foregroundClassName,
1389 isRegeneratingTitle && "opacity-55",
1390 )}
1391 numberOfLines={2}
1392 onTextLayout={
1393 Platform.OS === "android"
1394 ? ({ nativeEvent }) => {
1395 const firstLine = nativeEvent.lines[0];
1396 if (firstLine && Math.abs(firstLine.height - titleLineHeight) > 0.5) {
1397 setTitleLineHeight(firstLine.height);
1398 }
1399 }
1400 : undefined
1401 }
1402 >
1403 {thread.title}
1404 </Text>
1405 <View className="flex-row items-center gap-1.5" style={{ minHeight: titleLineHeight }}>
1406 {props.hasQueuedMessages ? <QueuedMessageIcon selected={selected} /> : null}
1407 {pinnedRow ? (
1408 <SymbolView
1409 name="pin"
1410 size={11}
1411 tintColorClassName={rowAppearance.mutedIconTintClassName}
1412 type="monochrome"
1413 />
1414 ) : null}
1415 {showsWoke ? (
1416 <Pressable
1417 className="-m-2.5 flex-row items-center gap-1 p-2.5"
1418 accessibilityRole="button"
1419 accessibilityLabel={gt("Dismiss Woke notification")}
1420 onPress={handleAcknowledgeWoke}
1421 onLongPress={() => undefined}
1422 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
1423 >
1424 <SymbolView
1425 name="bell.badge"
1426 size={13}
1427 tintColorClassName={
1428 selected ? selectedThreadRowColors.iconTintClassName : "accent-warning-foreground"
1429 }
1430 type="monochrome"
1431 weight="semibold"
1432 />
1433 <Text
1434 className={cn(
1435 "text-xs font-t3-bold",
1436 selected
1437 ? selectedThreadRowColors.foregroundClassName
1438 : "text-warning-foreground",
1439 )}
1440 >
1441 {gt("Woke", { $context: "thread came back from snooze" })}
1442 </Text>
1443 </Pressable>
1444 ) : statusLabel ? (
1445 <View className="flex-row items-center gap-1">
1446 <SymbolView
1447 name={statusLabel.icon}
1448 size={13}
1449 tintColorClassName={
1450 selected
1451 ? selectedThreadRowColors.iconTintClassName
1452 : statusLabel.iconTintClassName
1453 }
1454 type="monochrome"
1455 weight="semibold"
1456 />
1457 <Text
1458 className={cn(
1459 "text-xs font-t3-bold",
1460 selected ? selectedThreadRowColors.foregroundClassName : statusLabel.className,
1461 )}
1462 >
1463 {statusLabel.label}
1464 {status === "working" ? (
1465 <ThreadListV2Duration
1466 environmentId={thread.environmentId}
1467 startedAt={resolveThreadWorkingStartedAt(thread)}
1468 leadingSpace={statusLabel.label !== null}
1469 />
1470 ) : status === "waiting" ? (
1471 <ThreadListV2Duration
1472 environmentId={thread.environmentId}
1473 startedAt={thread.latestRun?.completedAt ?? null}
1474 leadingSpace={statusLabel.label !== null}
1475 />
1476 ) : null}
1477 </Text>
1478 </View>
1479 ) : (
1480 <Text
1481 className={cn(
1482 "text-xs tabular-nums",
1483 selected
1484 ? selectedThreadRowColors.foregroundClassName
1485 : rowAppearance.tertiaryForegroundClassName,
1486 )}
1487 >
1488 {timeLabel}
1489 </Text>
1490 )}
1491 </View>
1492 </View>
1493 {props.searchMatch ? (
1494 <View className="mt-1" style={{ paddingLeft: titleTextInset }}>
1495 <ThreadSearchMatchExcerpt
1496 sidebar={sidebarPane}
1497 match={props.searchMatch}
1498 query={props.searchQuery ?? ""}
1499 selected={selected}
1500 />
1501 </View>
1502 ) : null}
1503 <View className="mt-1 flex-row items-center gap-2" style={{ paddingLeft: titleTextInset }}>
1504 {(rawStatus === "failed" || rawStatus === "limited") && thread.runtime?.lastError ? (
1505 <Text
1506 className={cn(
1507 "flex-1 text-xs",
1508 selected
1509 ? selectedThreadRowColors.mutedForegroundClassName
1510 : status === "limited"
1511 ? "text-warning-foreground"
1512 : "text-danger-foreground",
1513 )}
1514 numberOfLines={1}
1515 >
1516 {thread.runtime.lastError}
1517 </Text>
1518 ) : props.environmentLabel ? (
1519 <View className="min-w-0 flex-1 flex-row items-center gap-1">
1520 {props.environmentMachine ? (
1521 <EnvironmentMachineSymbol
1522 kind={props.environmentMachine}
1523 size={machineIconSize}
1524 tintColorClassName={
1525 selected
1526 ? selectedThreadRowColors.mutedIconTintClassName
1527 : rowAppearance.tertiaryIconTintClassName
1528 }
1529 />
1530 ) : null}
1531 <Text
1532 className={cn(
1533 "shrink text-xs",
1534 selected
1535 ? selectedThreadRowColors.mutedForegroundClassName
1536 : rowAppearance.tertiaryForegroundClassName,
1537 )}
1538 numberOfLines={1}
1539 >
1540 {props.environmentLabel}
1541 </Text>
1542 </View>
1543 ) : (
1544 <View className="flex-1" />
1545 )}
1546 {pr ? (
1547 <Pressable
1548 // Padding cancelled by negative margin grows the touch target into
1549 // the row padding without moving the badge.
1550 className="-m-2.5 flex-row items-center gap-1 p-2.5"
1551 accessibilityRole="button"
1552 accessibilityLabel={prBadgeLabel ?? undefined}
1553 onPress={handleOpenPullRequests}
1554 // Handle long-press so opening the iOS row menu cannot also open the PR on release.
1555 onLongPress={() => undefined}
1556 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
1557 >
1558 <SymbolView
1559 name={
1560 pr.kind === "stack"
1561 ? PullRequestGlyph.stack
1562 : pr.state === null
1563 ? PullRequestGlyph.pullRequest
1564 : pullRequestStatus({ state: pr.state, isDraft: pr.isDraft }).icon
1565 }
1566 size={12}
1567 tintColorClassName={
1568 pr.state === null || pr.isDraft
1569 ? rowAppearance.mutedIconTintClassName
1570 : pr.state === "open"
1571 ? "accent-adaptive-emerald-600-400"
1572 : pr.state === "closed"
1573 ? "accent-adaptive-rose-600-400"
1574 : "accent-adaptive-violet-600-400"
1575 }
1576 />
1577 <Text
1578 accessibilityLabel={pr.accessibilityLabel}
1579 className={cn("text-xs", pr.textClassName)}
1580 style={{ fontFamily: MONO_FONT }}
1581 >
1582 {pr.label}
1583 </Text>
1584 </Pressable>
1585 ) : null}
1586 {providerInstance ? (
1587 <View className="flex-row items-center">
1588 {providerDrivers.slice(0, -1).map(
1589 (driver, index) => (
1590 /* oxlint-disable react/no-array-index-key -- Provider history can repeat a driver; these decorative icons have no local state. */ <View
1591 key={`${driver}:${index}`}
1592 className="-mr-1 opacity-30"
1593 >
1594 <ProviderIcon provider={driver} size={12} />
1595 </View>
1596 ) /* oxlint-enable react/no-array-index-key */,
1597 )}
1598 <ProviderInstanceIcon
1599 iconUrl={providerIconUrl}
1600 provider={providerInstance.driverKind}
1601 size={14}
1602 displayName={providerInstance.displayName}
1603 accentColor={providerInstance.accentColor}
1604 showBadge={providerInstance.showBadge}
1605 surfaceColor={rowAppearance.providerIconSurfaceColor}
1606 />
1607 {providerNameLabel ? (
1608 <Text
1609 className={cn(
1610 "ml-1.5 text-xs",
1611 selected
1612 ? selectedThreadRowColors.mutedForegroundClassName
1613 : rowAppearance.tertiaryForegroundClassName,
1614 )}
1615 ellipsizeMode="middle"
1616 numberOfLines={1}
1617 style={{ maxWidth: 140 }}
1618 >
1619 {providerNameLabel}
1620 </Text>
1621 ) : null}
1622 </View>
1623 ) : null}
1624 </View>
1625 </>
1626 );
1627
1628 const fadedCardContent = recede ? (
1629 <View style={{ opacity: 0.55 }}>{cardContent}</View>
1630 ) : (
1631 cardContent
1632 );
1633
1634 const rowContent = (close: () => void) =>
1635 variant === "card" ? (
1636 <RowPressable
1637 key={`${thread.environmentId}:${thread.id}`}
1638 interactionClassName={rowAppearance.interactionClassName}
1639 interactionOpacity={rowAppearance.interactionOpacity}
1640 className={rowAppearance.className}
1641 accessibilityHint={swipeAccessibilityHint}
1642 accessibilityLabel={rowAccessibilityLabel}
1643 accessibilityRole="button"
1644 accessibilityState={{ selected }}
1645 accessibilityActions={rowAccessibilityActions}
1646 onAccessibilityAction={(event) => {
1647 if (event.nativeEvent.actionName === "openPullRequests") handleOpenPullRequests();
1648 if (event.nativeEvent.actionName === "dismissWoke") handleAcknowledgeWoke();
1649 }}
1650 onPress={() => {
1651 close();
1652 selectThread();
1653 }}
1654 style={rowAppearance.cardStyle}
1655 >
1656 {sidebarPane ? (
1657 fadedCardContent
1658 ) : (
1659 <View>
1660 <View className={THREAD_LIST_V2_ROW_CONTENT_CLASS_NAME}>{fadedCardContent}</View>
1661 {THREAD_LIST_V2_ROW_DIVIDERS && props.showTrailingDivider !== false ? (
1662 <View className="ml-5 h-px bg-border-subtle" />
1663 ) : null}
1664 </View>
1665 )}
1666 </RowPressable>
1667 ) : (
1668 <RowPressable
1669 key={`${thread.environmentId}:${thread.id}`}
1670 interactionClassName={rowAppearance.interactionClassName}
1671 interactionOpacity={rowAppearance.interactionOpacity}
1672 accessibilityHint={swipeAccessibilityHint}
1673 accessibilityLabel={rowAccessibilityLabel}
1674 accessibilityRole="button"
1675 accessibilityState={{ selected }}
1676 className={rowAppearance.className}
1677 onPress={() => {
1678 close();
1679 selectThread();
1680 }}
1681 style={rowAppearance.style}
1682 >
1683 <View
1684 className={cn(
1685 THREAD_LIST_V2_ROW_CONTENT_CLASS_NAME,
1686 "min-h-[44px] flex-row items-center gap-2 py-2",
1687 sidebarPane && "px-3",
1688 )}
1689 >
1690 {props.project ? (
1691 <View className="opacity-40">
1692 <ProjectFavicon
1693 environmentId={thread.environmentId}
1694 faviconPath={props.project.faviconPath}
1695 projectIcon={props.project.projectIcon}
1696 size={projectIconSize}
1697 projectTitle={props.project.title}
1698 workspaceRoot={props.project.workspaceRoot}
1699 />
1700 </View>
1701 ) : null}
1702 <View className="min-w-0 flex-1">
1703 <Text
1704 className={cn(
1705 "text-base",
1706 selected
1707 ? selectedThreadRowColors.foregroundClassName
1708 : rowAppearance.mutedForegroundClassName,
1709 isRegeneratingTitle && "opacity-55",
1710 )}
1711 numberOfLines={1}
1712 >
1713 {thread.title}
1714 </Text>
1715 {providerNameLabel ? (
1716 <Text
1717 className={cn(
1718 "text-xs",
1719 selected
1720 ? selectedThreadRowColors.mutedForegroundClassName
1721 : rowAppearance.tertiaryForegroundClassName,
1722 )}
1723 ellipsizeMode="middle"
1724 numberOfLines={1}
1725 >
1726 {providerNameLabel}
1727 </Text>
1728 ) : null}
1729 {props.searchMatch ? (
1730 <ThreadSearchMatchExcerpt
1731 sidebar={sidebarPane}
1732 match={props.searchMatch}
1733 query={props.searchQuery ?? ""}
1734 selected={selected}
1735 />
1736 ) : null}
1737 </View>
1738 {props.hasQueuedMessages ? <QueuedMessageIcon selected={selected} /> : null}
1739 <Text
1740 className={cn(
1741 "text-sm tabular-nums",
1742 selected
1743 ? selectedThreadRowColors.mutedForegroundClassName
1744 : snoozedRow
1745 ? rowAppearance.mutedForegroundClassName
1746 : rowAppearance.tertiaryForegroundClassName,
1747 )}
1748 style={{ fontFamily: MONO_FONT }}
1749 >
1750 {snoozedRow && snoozeWakeLabelText !== undefined ? snoozeWakeLabelText : timeLabel}
1751 </Text>
1752 </View>
1753 </RowPressable>
1754 );
1755
1756 if (!canOperateThread)
1757 return <View style={rowAppearance.swipeContainerStyle}>{rowContent(() => {})}</View>;
1758
1759 return (
1760 <View collapsable={false}>
1761 {customSnoozeOpen && (
1762 <CustomSnoozeSheet onClose={() => setCustomSnoozeOpen(false)} onSnooze={handleSnooze} />
1763 )}
1764 <ThreadSwipeable
1765 dormant={dormant}
1766 threadKey={`${thread.environmentId}:${thread.id}`}
1767 backgroundColor={rowAppearance.swipeBackgroundColor}
1768 compactActions={variant === "slim"}
1769 containerStyle={rowAppearance.swipeContainerStyle}
1770 enableTrackpadSwipe
1771 fullSwipeAction="primary"
1772 fullSwipeWidth={props.fullSwipeWidth ?? windowWidth - 32}
1773 listAnimatesLayout
1774 onDelete={handleDelete}
1775 onSwipeableClose={props.onSwipeableClose}
1776 onSwipeableWillOpen={props.onSwipeableWillOpen}
1777 primaryAction={primaryAction}
1778 secondaryAction={secondaryAction}
1779 resetKey={`${thread.environmentId}:${thread.id}:${variant}:${snoozedRow}:${thread.settledAt}:${thread.unsettledAt}:${thread.snoozedUntil}:${thread.pinnedAt}`}
1780 simultaneousWith={props.simultaneousSwipeGesture}
1781 threadTitle={thread.title}
1782 >
1783 {(close) => (
1784 <Menu
1785 accessibilityLabel={rowAccessibilityLabel}
1786 actions={menuActions}
1787 onPressAction={handleMenuAction}
1788 shouldOpenOnLongPress
1789 >
1790 {rowContent(close)}
1791 </Menu>
1792 )}
1793 </ThreadSwipeable>
1794 </View>
1795 );
1796 });