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

ThreadQueueControl.tsx

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