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

ThreadQueueControl.tsx

642 lines25.0 KB

1import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2import { useAtomValue } from "@effect/atom-react";
3import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5import { Image } from "expo-image";
6import * as Haptics from "expo-haptics";
7import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
8import { Animated, Platform, Pressable, ScrollView, View } from "react-native";
9import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
10import ReanimatedSwipeable, {
11 type SwipeableMethods,
12} from "react-native-gesture-handler/ReanimatedSwipeable";
13import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
14import { useSafeAreaInsets } from "react-native-safe-area-context";
15import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
16​
17import { Button } from "../../components/ui/Button";
18import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader";
19import { AppText as Text } from "../../components/ui/AppText";
20import { SymbolView } from "../../components/ui/AppSymbol";
21import { Menu } from "../../components/ui/Menu";
22import { ScreenContent } from "../../components/ui/ScreenContent";
23import { scopedThreadKey } from "../../lib/scopedEntities";
24import { useUniwindTheme } from "../../lib/useUniwindTheme";
25import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
26import { useAssetUrl } from "../../state/assets";
27import { assetImageSource } from "../../lib/assetImageSource";
28import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit";
29import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
32import {
33 REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
34 buildCancelQueuedRunCommand,
35 resolveQueueDragBeforeRunId,
36 resolveQueueDropBeforeRunId,
37 resolveThreadQueueRowControls,
38} from "./threadQueueControlPresentation";
39import { threadDragGapOffset } from "./threadDragGap";
40​
41const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
42const REMOVE_ACTION_WIDTH = 76;
43const THUMBNAIL_LIMIT = 3;
44const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe(
45 Atom.withLabel("mobile-thread-queue-count:empty"),
46);
47​
48type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
49type QueueAction = "steer" | "edit" | "up" | "down" | "remove";
50type QueueRowLayout = { readonly id: RunId; readonly y?: number; readonly height?: number };
51​
52export function useThreadQueueWorkflow(target: QueueTarget) {
53 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
55​
56export function useThreadQueuedCount(target: QueueTarget | null) {
57 return useAtomValue(
58 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
59 );
61​
62export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
63 const { layout } = useAdaptiveWorkspaceLayout();
64 const target = route.params;
65 const navigation = useNavigation();
66 const insets = useSafeAreaInsets();
67 const theme = useUniwindTheme();
68 const workflow = useThreadQueueWorkflow(target);
69 const threadKey = scopedThreadKey(target.environmentId, target.threadId);
70 const editing = useQueuedRunEdit(threadKey);
71 const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
72 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
73 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
74 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
75 const [resuming, setResuming] = useState(false);
76 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
77 const busyRef = useRef(false);
78 const [draggedRunId, setDraggedRunId] = useState<RunId | null>(null);
79 const [previewBeforeRunId, setPreviewBeforeRunId] = useState<RunId | null | undefined>();
80 const [dragRows, setDragRows] = useState<ReadonlyArray<QueueRowLayout> | null>(null);
81 const rowLayouts = useRef(new Map<RunId, { y: number; height: number }>());
82 const drag = useRef<{
83 runId: RunId;
84 order: string;
85 beforeRunId: RunId | null | undefined;
86 rows: ReadonlyArray<QueueRowLayout>;
87 } | null>(null);
88 const [translation] = useState(() => new Animated.Value(0));
89 const queuedRuns = workflow?.queuedRuns ?? [];
90 const order = queuedRuns.map(({ run }) => run.id).join(",");
91​
92 useEffect(() => {
93 if (drag.current && drag.current.order !== order) {
94 drag.current = null;
95 setDraggedRunId(null);
96 setPreviewBeforeRunId(undefined);
97 setDragRows(null);
98 translation.setValue(0);
99 }
100 }, [order, translation]);
101​
102 const hadQueuedRuns = useRef(queuedRuns.length > 0);
103 useEffect(() => {
104 if (queuedRuns.length > 0) {
105 hadQueuedRuns.current = true;
106 return;
107 }
108 if (hadQueuedRuns.current) navigation.goBack();
109 }, [navigation, queuedRuns.length]);
110​
111 const move = async (runId: RunId, beforeRunId: RunId | null) => {
112 if (busyRef.current || !workflow?.canReorder) return;
113 busyRef.current = true;
114 setBusyRunId(runId);
115 void Haptics.selectionAsync();
116 try {
117 await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
118 } finally {
119 busyRef.current = false;
120 setBusyRunId(null);
121 }
122 };
123​
124 const act = async (runId: RunId, action: QueueAction) => {
125 if (busyRef.current) return;
126 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
127 if (index < 0) return;
128 if (action === "up" && index > 0) {
129 await move(runId, queuedRuns[index - 1]!.run.id);
130 return;
131 }
132 if (action === "down" && index < queuedRuns.length - 1) {
133 await move(runId, queuedRuns[index + 2]?.run.id ?? null);
134 return;
135 }
136 if (action === "edit") {
137 const entry = queuedRuns[index]!;
138 void Haptics.selectionAsync();
139 beginQueuedRunEdit(threadKey, {
140 runId,
141 messageId: entry.messageId,
142 originalText: entry.text,
143 existingAttachments: entry.attachments,
144 ...(entry.context ? { context: entry.context } : {}),
145 });
146 navigation.goBack();
147 return;
148 }
149 if (action !== "steer" && action !== "remove") return;
150 busyRef.current = true;
151 setBusyRunId(runId);
152 void Haptics.selectionAsync();
153 try {
154 if (action === "remove") {
155 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
156 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
157 await promote({
158 ...target,
159 input: {
160 threadId: target.threadId,
161 queuedRunId: runId,
162 targetRunId: workflow.activeRun.id,
163 },
164 });
165 }
166 } finally {
167 busyRef.current = false;
168 setBusyRunId(null);
169 }
170 };
171​
172 const canReorder = workflow?.canReorder === true && queuedRuns.length > 1;
173 const sourceLayout = dragRows?.find((row) => row.id === draggedRunId);
174 const lastLayout = dragRows?.at(-1);
175 const insertionOffset =
176 previewBeforeRunId === undefined
177 ? undefined
178 : previewBeforeRunId === null
179 ? lastLayout?.y === undefined || lastLayout.height === undefined
180 ? undefined
181 : lastLayout.y + lastLayout.height
182 : dragRows?.find((row) => row.id === previewBeforeRunId)?.y;
183 const queueRows = () =>
184 queuedRuns.map(({ run }) => ({ id: run.id, ...rowLayouts.current.get(run.id) }));
185 const content = (
186 <ScrollView
187 nestedScrollEnabled
188 className="flex-1"
189 scrollEnabled={draggedRunId === null}
190 // The iOS header is translucent and floats over this view; UIKit has to
191 // inset the content or the first row sits underneath the title.
192 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
193 contentContainerClassName="px-5 pb-6"
194 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
195 >
196 {workflow?.isHeld && queuedRuns.length > 0 ? (
197 <View className="gap-2 py-3">
198 <Text className="text-sm text-foreground-muted">Queue held after restart</Text>
199 <Button
200 label="Resume queue"
201 disabled={resuming || busyRunId !== null}
202 onPress={async () => {
203 if (busyRef.current) return;
204 busyRef.current = true;
205 setResuming(true);
206 try {
207 await resume({ ...target, input: { threadId: target.threadId } });
208 } finally {
209 busyRef.current = false;
210 setResuming(false);
211 }
212 }}
213 />
214 </View>
215 ) : null}
216 {queuedRuns.length === 0 ? (
217 <Text className="pt-6 text-center text-sm text-foreground-muted">
218 No messages waiting in this queue.
219 </Text>
220 ) : null}
221 {queuedRuns.map(({ run, text, attachments }, index) => {
222 const layout = dragRows?.find((row) => row.id === run.id);
223 const offset =
224 sourceLayout?.y !== undefined &&
225 sourceLayout.height !== undefined &&
226 layout?.y !== undefined &&
227 insertionOffset !== undefined
228 ? threadDragGapOffset(layout.y, sourceLayout.y, sourceLayout.height, insertionOffset)
229 : 0;
230 const controls = resolveThreadQueueRowControls({
231 busy: busyRunId !== null || draggedRunId !== null,
232 canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
233 canReorder: workflow?.canReorder ?? false,
234 index,
235 isEditing: editing?.runId === run.id,
236 queuedCount: queuedRuns.length,
237 text,
238 });
239 const title =
240 controls.displayText || (attachments.length > 0 ? "Attachments" : "Queued message");
241 return (
242 <QueueShiftedRow
243 key={run.id}
244 offset={offset}
245 dragging={draggedRunId !== null}
246 lifted={draggedRunId === run.id}
247 onLayout={({ nativeEvent }) => rowLayouts.current.set(run.id, nativeEvent.layout)}
248 >
249 <Animated.View
250 className="flex-row items-center border-b border-border bg-sheet"
251 style={
252 draggedRunId === run.id
253 ? { transform: [{ translateY: translation }], zIndex: 1, opacity: 0.85 }
254 : undefined
255 }
256 >
257 {canReorder ? (
258 // Outside the swipeable: two pans on one row would race, and
259 // the handle owns vertical movement while the row owns sideways.
260 <QueueDragHandle
261 disabled={busyRunId !== null}
262 title={title}
263 canMoveUp={controls.canMoveUp}
264 canMoveDown={controls.canMoveDown}
265 onStep={(action) => void act(run.id, action)}
266 onStart={() => {
267 const rows = queueRows();
268 const beforeRunId = resolveQueueDragBeforeRunId(rows, run.id, 0);
269 drag.current = { runId: run.id, order, beforeRunId, rows };
270 translation.setValue(0);
271 setDragRows(rows);
272 setPreviewBeforeRunId(beforeRunId);
273 setDraggedRunId(run.id);
274 void Haptics.selectionAsync();
275 }}
276 onMove={(y) => {
277 const current = drag.current;
278 if (current?.runId !== run.id || current.order !== order) return;
279 translation.setValue(y);
280 const before = resolveQueueDragBeforeRunId(current.rows, run.id, y);
281 if (current.beforeRunId !== before) {
282 current.beforeRunId = before;
283 setPreviewBeforeRunId(before);
284 }
285 }}
286 onEnd={(y, success) => {
287 const started = drag.current;
288 const stop = () => {
289 if (drag.current !== started) return;
290 drag.current = null;
291 setDraggedRunId(null);
292 setPreviewBeforeRunId(undefined);
293 setDragRows(null);
294 translation.setValue(0);
295 };
296 if (!success || started?.order !== order || started.runId !== run.id) {
297 stop();
298 return;
299 }
300 const before = resolveQueueDropBeforeRunId(started.rows, run.id, y);
301 if (before === undefined) {
302 stop();
303 return;
304 }
305 const source = started.rows.find((row) => row.id === run.id);
306 const tail = started.rows.at(-1);
307 const insertion =
308 before === null
309 ? tail?.y !== undefined && tail.height !== undefined
310 ? tail.y + tail.height
311 : undefined
312 : started.rows.find((row) => row.id === before)?.y;
313 if (
314 source?.y !== undefined &&
315 source.height !== undefined &&
316 insertion !== undefined
317 ) {
318 Animated.timing(translation, {
319 toValue: insertion - source.y - (insertion > source.y ? source.height : 0),
320 duration: 160,
321 useNativeDriver: true,
322 }).start();
323 }
324 setPreviewBeforeRunId(before);
325 void move(run.id, before).finally(stop);
326 }}
327 />
328 ) : null}
329 <QueueRowSwipeable
330 enabled={draggedRunId === null && busyRunId === null && controls.canDismiss}
331 background={theme["--color-sheet"]}
332 onRemove={() => void act(run.id, "remove")}
333 >
334 <Menu
335 accessibilityLabel={`Actions for queued message ${index + 1}`}
336 shouldOpenOnLongPress
337 actions={[
338 ...(workflow?.canPromoteToSteer
339 ? [
340 {
341 id: "steer",
342 title: "Steer now",
343 attributes: { disabled: !controls.canSteer },
344 image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
345 },
346 ]
347 : []),
348 {
349 id: "edit",
350 title: "Edit",
351 attributes: { disabled: !controls.canEdit },
352 image: Platform.OS === "ios" ? "pencil" : "edit",
353 },
354 { id: "up", title: "Move up", attributes: { disabled: !controls.canMoveUp } },
355 {
356 id: "down",
357 title: "Move down",
358 attributes: { disabled: !controls.canMoveDown },
359 },
360 {
361 id: "remove",
362 title: "Remove",
363 attributes: { disabled: !controls.canDismiss, destructive: true },
364 },
365 ]}
366 onPressAction={({ nativeEvent }) =>
367 void act(run.id, nativeEvent.event as QueueAction)
368 }
369 >
370 <Pressable
371 accessibilityRole="button"
372 accessibilityLabel={title}
373 accessibilityHint="Opens this message in the composer for editing"
374 disabled={!controls.canEdit}
375 onPress={() => void act(run.id, "edit")}
376 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
377 >
378 <QueueAttachmentThumbnails
379 environmentId={target.environmentId}
380 attachments={attachments}
381 />
382 <Text
383 className={
384 controls.isEditing
385 ? "min-w-0 flex-1 text-sm text-foreground-muted"
386 : "min-w-0 flex-1 text-sm text-foreground"
387 }
388 numberOfLines={1}
389 >
390 {title}
391 </Text>
392 {controls.isEditing ? (
393 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
394 Editing
395 </Text>
396 ) : null}
397 {workflow?.canPromoteToSteer ? (
398 <Pressable
399 accessibilityRole="button"
400 accessibilityLabel={`Steer with message ${index + 1} now`}
401 disabled={!controls.canSteer}
402 onPress={() => void act(run.id, "steer")}
403 className="h-8 shrink-0 justify-center rounded-full bg-primary px-3 active:opacity-70 disabled:opacity-40"
404 >
405 <Text className="font-t3-medium text-xs text-primary-foreground">
406 Steer
407 </Text>
408 </Pressable>
409 ) : null}
410 </Pressable>
411 </Menu>
412 </QueueRowSwipeable>
413 </Animated.View>
414 </QueueShiftedRow>
415 );
416 })}
417 </ScrollView>
418 );
419​
420 if (Platform.OS === "ios") {
421 // A plain formSheet screen never renders a stack header, so it comes from
422 // a nested native stack inside the sheet (same shape as the git sheet).
423 return (
424 <GestureHandlerRootView style={{ flex: 1 }}>
425 <View collapsable={false} className="flex-1 bg-sheet">
426 <ScreenStack style={{ flex: 1 }}>
427 <Screen
428 activityState={2}
429 enabled
430 isNativeStack
431 screenId="thread-queue-sheet-native"
432 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
433 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
434 >
435 {content}
436 <ScreenStackHeaderConfig
437 backgroundColor="rgba(0,0,0,0)"
438 color={theme["--color-foreground"]}
439 hideBackButton
440 hideShadow={false}
441 title="Queued"
442 titleColor={theme["--color-foreground"]}
443 titleFontSize={18}
444 titleFontWeight="800"
445 translucent
446 />
447 </Screen>
448 </ScreenStack>
449 </View>
450 </GestureHandlerRootView>
451 );
452 }
453​
454 return (
455 <GestureHandlerRootView style={{ flex: 1 }}>
456 <View collapsable={false} className="flex-1 bg-sheet">
457 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
458 <AndroidSheetHeader title="Queued" onBack={() => navigation.goBack()} />
459 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
460 </View>
461 </GestureHandlerRootView>
462 );
464​
465function QueueShiftedRow(props: {
466 readonly offset: number;
467 readonly dragging: boolean;
468 readonly lifted: boolean;
469 readonly onLayout: React.ComponentProps<typeof View>["onLayout"];
470 readonly children: React.ReactNode;
471}) {
472 const { dragging, offset } = props;
473 const style = useAnimatedStyle(() => ({
474 transform: [
475 {
476 translateY: dragging
477 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
478 : offset,
479 },
480 ],
481 }));
482 return (
483 <Reanimated.View onLayout={props.onLayout} style={[style, { zIndex: props.lifted ? 1 : 0 }]}>
484 {props.children}
485 </Reanimated.View>
486 );
488​
489function QueueRowSwipeable(props: {
490 readonly enabled: boolean;
491 readonly background: string;
492 readonly onRemove: () => void;
493 readonly children: React.ReactNode;
494}) {
495 const swipeableRef = useRef<SwipeableMethods | null>(null);
496 return (
497 <ReanimatedSwipeable
498 ref={swipeableRef}
499 enabled={props.enabled}
500 friction={2}
501 rightThreshold={40}
502 overshootRight={false}
503 // The sheet's own vertical scroll and the drag handle both move up and
504 // down; a swipe has to be clearly sideways before it takes the gesture.
505 failOffsetY={[-12, 12]}
506 containerStyle={{ backgroundColor: props.background, flex: 1 }}
507 childrenContainerStyle={{ backgroundColor: props.background }}
508 onSwipeableOpen={(direction) => {
509 if (direction !== "right") return;
510 swipeableRef.current?.close();
511 props.onRemove();
512 }}
513 renderRightActions={() => (
514 <Pressable
515 accessibilityRole="button"
516 accessibilityLabel={REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL}
517 disabled={!props.enabled}
518 onPress={() => {
519 swipeableRef.current?.close();
520 props.onRemove();
521 }}
522 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
523 style={{ width: REMOVE_ACTION_WIDTH }}
524 >
525 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
526 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
527 </Pressable>
528 )}
529 >
530 {props.children}
531 </ReanimatedSwipeable>
532 );
534​
535function QueueAttachmentThumbnails(props: {
536 readonly environmentId: EnvironmentId;
537 readonly attachments: ReadonlyArray<ChatAttachment>;
538}) {
539 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
540 const shown = images.slice(0, THUMBNAIL_LIMIT);
541 const overflow = props.attachments.length - shown.length;
542 if (props.attachments.length === 0) return null;
543 return (
544 <View className="shrink-0 flex-row items-center gap-1">
545 {shown.map((attachment) => (
546 <QueueAttachmentThumbnail
547 key={attachment.id}
548 environmentId={props.environmentId}
549 attachment={attachment}
550 />
551 ))}
552 {overflow > 0 ? (
553 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
554 <Text className="text-2xs tabular-nums text-foreground-muted">
555 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
556 </Text>
557 </View>
558 ) : null}
559 </View>
560 );
562​
563function QueueAttachmentThumbnail(props: {
564 readonly environmentId: EnvironmentId;
565 readonly attachment: ChatAttachment;
566}) {
567 const resource = {
568 _tag: "attachment",
569 attachmentId: props.attachment.id,
570 fileName: props.attachment.name,
571 mimeType: props.attachment.mimeType,
572 disposition: "inline",
573 } as const;
574 const url = useAssetUrl(props.environmentId, resource);
575 if (url === null) {
576 return <View className="h-6 w-6 rounded bg-subtle" />;
577 }
578 return (
579 <Image
580 source={assetImageSource(props.environmentId, resource, url)}
581 cachePolicy="memory-disk"
582 contentFit="cover"
583 style={{ width: 24, height: 24, borderRadius: 4 }}
584 accessibilityIgnoresInvertColors
585 />
586 );
588​
589function QueueDragHandle(props: {
590 disabled: boolean;
591 title: string;
592 canMoveUp: boolean;
593 canMoveDown: boolean;
594 onStep: (action: "up" | "down") => void;
595 onStart: () => void;
596 onMove: (y: number) => void;
597 onEnd: (y: number, success: boolean) => void;
598}) {
599 const latest = useRef(props);
600 useLayoutEffect(() => {
601 latest.current = props;
602 });
603 const gesture = useMemo(
604 () =>
605 Gesture.Pan()
606 .enabled(!props.disabled)
607 .minDistance(0)
608 .shouldCancelWhenOutside(false)
609 .runOnJS(true)
610 .onStart(() => latest.current.onStart())
611 .onUpdate((event) => latest.current.onMove(event.translationY))
612 .onFinalize((event, success) => latest.current.onEnd(event.translationY, success)),
613 [props.disabled],
614 );
615 return (
616 <GestureDetector gesture={gesture}>
617 <View
618 collapsable={false}
619 accessible
620 accessibilityRole="adjustable"
621 accessibilityLabel={`Reorder ${props.title}`}
622 accessibilityState={{ disabled: props.disabled }}
623 accessibilityActions={[
624 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
625 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
626 ]}
627 onAccessibilityAction={({ nativeEvent }) => {
628 if (props.disabled) return;
629 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
630 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
631 }}
632 className="h-12 w-8 items-center justify-center"
633 >
634 <SymbolView
635 name="line.3.horizontal"
636 size={16}
637 tintColorClassName="accent-foreground-muted"
638 />
639 </View>
640 </GestureDetector>
641 );