Open History to see the last commit
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, useEffectEvent, 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));
54}
55
56export function useThreadQueuedCount(target: QueueTarget | null) {
57 return useAtomValue(
58 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
59 );
60}
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 await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
117 busyRef.current = false;
118 setBusyRunId(null);
119 };
120
121 const act = async (runId: RunId, action: QueueAction) => {
122 if (busyRef.current) return;
123 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
124 if (index < 0) return;
125 if (action === "up" && index > 0) {
126 await move(runId, queuedRuns[index - 1]!.run.id);
127 return;
128 }
129 if (action === "down" && index < queuedRuns.length - 1) {
130 await move(runId, queuedRuns[index + 2]?.run.id ?? null);
131 return;
132 }
133 if (action === "edit") {
134 const entry = queuedRuns[index]!;
135 void Haptics.selectionAsync();
136 beginQueuedRunEdit(threadKey, {
137 runId,
138 messageId: entry.messageId,
139 originalText: entry.text,
140 existingAttachments: entry.attachments,
141 ...(entry.context ? { context: entry.context } : {}),
142 });
143 navigation.goBack();
144 return;
145 }
146 if (action !== "steer" && action !== "remove") return;
147 busyRef.current = true;
148 setBusyRunId(runId);
149 void Haptics.selectionAsync();
150 if (action === "remove") {
151 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
152 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
153 await promote({
154 ...target,
155 input: {
156 threadId: target.threadId,
157 queuedRunId: runId,
158 targetRunId: workflow.activeRun.id,
159 },
160 });
161 }
162 busyRef.current = false;
163 setBusyRunId(null);
164 };
165
166 const canReorder = workflow?.canReorder === true && queuedRuns.length > 1;
167 const sourceLayout = dragRows?.find((row) => row.id === draggedRunId);
168 const lastLayout = dragRows?.at(-1);
169 const insertionOffset =
170 previewBeforeRunId === undefined
171 ? undefined
172 : previewBeforeRunId === null
173 ? lastLayout?.y === undefined || lastLayout.height === undefined
174 ? undefined
175 : lastLayout.y + lastLayout.height
176 : dragRows?.find((row) => row.id === previewBeforeRunId)?.y;
177 const queueRows = () =>
178 queuedRuns.map(({ run }) => ({ id: run.id, ...rowLayouts.current.get(run.id) }));
179 const content = (
180 <ScrollView
181 nestedScrollEnabled
182 className="flex-1"
183 scrollEnabled={draggedRunId === null}
184 // The iOS header is translucent and floats over this view; UIKit has to
185 // inset the content or the first row sits underneath the title.
186 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
187 contentContainerClassName="px-5 pb-6"
188 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
189 >
190 {workflow?.isHeld && queuedRuns.length > 0 ? (
191 <View className="gap-2 py-3">
192 <Text className="text-sm text-foreground-muted">Queue held after restart</Text>
193 <Button
194 label="Resume queue"
195 disabled={resuming || busyRunId !== null}
196 onPress={async () => {
197 if (busyRef.current) return;
198 busyRef.current = true;
199 setResuming(true);
200 await resume({ ...target, input: { threadId: target.threadId } });
201 busyRef.current = false;
202 setResuming(false);
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 if (!success || started?.order !== order || started.runId !== run.id) {
288 stop();
289 return;
290 }
291 const before = resolveQueueDropBeforeRunId(started.rows, run.id, y);
292 if (before === undefined) {
293 stop();
294 return;
295 }
296 const source = started.rows.find((row) => row.id === run.id);
297 const tail = started.rows.at(-1);
298 const insertion =
299 before === null
300 ? tail?.y !== undefined && tail.height !== undefined
301 ? tail.y + tail.height
302 : undefined
303 : started.rows.find((row) => row.id === before)?.y;
304 if (
305 source?.y !== undefined &&
306 source.height !== undefined &&
307 insertion !== undefined
308 ) {
309 Animated.timing(translation, {
310 toValue: insertion - source.y - (insertion > source.y ? source.height : 0),
311 duration: 160,
312 useNativeDriver: true,
313 }).start();
314 }
315 setPreviewBeforeRunId(before);
316 void move(run.id, before).finally(stop);
317 }}
318 />
319 ) : null}
320 <QueueRowSwipeable
321 enabled={draggedRunId === null && busyRunId === null && controls.canDismiss}
322 background={theme["--color-sheet"]}
323 onRemove={() => void act(run.id, "remove")}
324 >
325 <Menu
326 accessibilityLabel={`Actions for queued message ${index + 1}`}
327 shouldOpenOnLongPress
328 actions={[
329 ...(workflow?.canPromoteToSteer
330 ? [
331 {
332 id: "steer",
333 title: "Steer now",
334 attributes: { disabled: !controls.canSteer },
335 image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
336 },
337 ]
338 : []),
339 {
340 id: "edit",
341 title: "Edit",
342 attributes: { disabled: !controls.canEdit },
343 image: Platform.OS === "ios" ? "pencil" : "edit",
344 },
345 { id: "up", title: "Move up", attributes: { disabled: !controls.canMoveUp } },
346 {
347 id: "down",
348 title: "Move down",
349 attributes: { disabled: !controls.canMoveDown },
350 },
351 {
352 id: "remove",
353 title: "Remove",
354 attributes: { disabled: !controls.canDismiss, destructive: true },
355 },
356 ]}
357 onPressAction={({ nativeEvent }) =>
358 void act(run.id, nativeEvent.event as QueueAction)
359 }
360 >
361 <Pressable
362 accessibilityRole="button"
363 accessibilityLabel={title}
364 accessibilityHint="Opens this message in the composer for editing"
365 disabled={!controls.canEdit}
366 onPress={() => void act(run.id, "edit")}
367 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
368 >
369 <QueueAttachmentThumbnails
370 environmentId={target.environmentId}
371 attachments={attachments}
372 />
373 <Text
374 className={
375 controls.isEditing
376 ? "min-w-0 flex-1 text-sm text-foreground-muted"
377 : "min-w-0 flex-1 text-sm text-foreground"
378 }
379 numberOfLines={1}
380 >
381 {title}
382 </Text>
383 {controls.isEditing ? (
384 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
385 Editing
386 </Text>
387 ) : null}
388 {workflow?.canPromoteToSteer ? (
389 <Pressable
390 accessibilityRole="button"
391 accessibilityLabel={`Steer with message ${index + 1} now`}
392 disabled={!controls.canSteer}
393 onPress={() => void act(run.id, "steer")}
394 className="h-8 shrink-0 justify-center rounded-full bg-primary px-3 active:opacity-70 disabled:opacity-40"
395 >
396 <Text className="font-t3-medium text-xs text-primary-foreground">
397 Steer
398 </Text>
399 </Pressable>
400 ) : null}
401 </Pressable>
402 </Menu>
403 </QueueRowSwipeable>
404 </Animated.View>
405 </QueueShiftedRow>
406 );
407 })}
408 </ScrollView>
409 );
410
411 if (Platform.OS === "ios") {
412 // A plain formSheet screen never renders a stack header, so it comes from
413 // a nested native stack inside the sheet (same shape as the git sheet).
414 return (
415 <GestureHandlerRootView style={{ flex: 1 }}>
416 <View collapsable={false} className="flex-1 bg-sheet">
417 <ScreenStack style={{ flex: 1 }}>
418 <Screen
419 activityState={2}
420 enabled
421 isNativeStack
422 screenId="thread-queue-sheet-native"
423 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
424 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
425 >
426 {content}
427 <ScreenStackHeaderConfig
428 backgroundColor="rgba(0,0,0,0)"
429 color={theme["--color-foreground"]}
430 hideBackButton
431 hideShadow={false}
432 title="Queued"
433 titleColor={theme["--color-foreground"]}
434 titleFontSize={18}
435 titleFontWeight="800"
436 translucent
437 />
438 </Screen>
439 </ScreenStack>
440 </View>
441 </GestureHandlerRootView>
442 );
443 }
444
445 return (
446 <GestureHandlerRootView style={{ flex: 1 }}>
447 <View collapsable={false} className="flex-1 bg-sheet">
448 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
449 <AndroidSheetHeader title="Queued" onBack={() => navigation.goBack()} />
450 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
451 </View>
452 </GestureHandlerRootView>
453 );
454}
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 );
478}
479
480function QueueRowSwipeable(props: {
481 readonly enabled: boolean;
482 readonly background: string;
483 readonly onRemove: () => void;
484 readonly children: React.ReactNode;
485}) {
486 const swipeableRef = useRef<SwipeableMethods | null>(null);
487 return (
488 <ReanimatedSwipeable
489 ref={swipeableRef}
490 enabled={props.enabled}
491 friction={2}
492 rightThreshold={40}
493 overshootRight={false}
494 // The sheet's own vertical scroll and the drag handle both move up and
495 // down; a swipe has to be clearly sideways before it takes the gesture.
496 failOffsetY={[-12, 12]}
497 containerStyle={{ backgroundColor: props.background, flex: 1 }}
498 childrenContainerStyle={{ backgroundColor: props.background }}
499 onSwipeableOpen={(direction) => {
500 if (direction !== "right") return;
501 swipeableRef.current?.close();
502 props.onRemove();
503 }}
504 renderRightActions={() => (
505 <Pressable
506 accessibilityRole="button"
507 accessibilityLabel={REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL}
508 disabled={!props.enabled}
509 onPress={() => {
510 swipeableRef.current?.close();
511 props.onRemove();
512 }}
513 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
514 style={{ width: REMOVE_ACTION_WIDTH }}
515 >
516 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
517 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
518 </Pressable>
519 )}
520 >
521 {props.children}
522 </ReanimatedSwipeable>
523 );
524}
525
526function QueueAttachmentThumbnails(props: {
527 readonly environmentId: EnvironmentId;
528 readonly attachments: ReadonlyArray<ChatAttachment>;
529}) {
530 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
531 const shown = images.slice(0, THUMBNAIL_LIMIT);
532 const overflow = props.attachments.length - shown.length;
533 if (props.attachments.length === 0) return null;
534 return (
535 <View className="shrink-0 flex-row items-center gap-1">
536 {shown.map((attachment) => (
537 <QueueAttachmentThumbnail
538 key={attachment.id}
539 environmentId={props.environmentId}
540 attachment={attachment}
541 />
542 ))}
543 {overflow > 0 ? (
544 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
545 <Text className="text-2xs tabular-nums text-foreground-muted">
546 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
547 </Text>
548 </View>
549 ) : null}
550 </View>
551 );
552}
553
554function QueueAttachmentThumbnail(props: {
555 readonly environmentId: EnvironmentId;
556 readonly attachment: ChatAttachment;
557}) {
558 const resource = {
559 _tag: "attachment",
560 attachmentId: props.attachment.id,
561 fileName: props.attachment.name,
562 mimeType: props.attachment.mimeType,
563 disposition: "inline",
564 } as const;
565 const url = useAssetUrl(props.environmentId, resource);
566 if (url === null) {
567 return <View className="h-6 w-6 rounded bg-subtle" />;
568 }
569 return (
570 <Image
571 source={assetImageSource(props.environmentId, resource, url)}
572 cachePolicy="memory-disk"
573 contentFit="cover"
574 style={{ width: 24, height: 24, borderRadius: 4 }}
575 accessibilityIgnoresInvertColors
576 />
577 );
578}
579
580function QueueDragHandle(props: {
581 disabled: boolean;
582 title: string;
583 canMoveUp: boolean;
584 canMoveDown: boolean;
585 onStep: (action: "up" | "down") => void;
586 onStart: () => void;
587 onMove: (y: number) => void;
588 onEnd: (y: number, success: boolean) => void;
589}) {
590 // Gesture callbacks fire outside render, so effect events read the latest
591 // props without rebuilding the gesture.
592 const onStart = useEffectEvent(() => props.onStart());
593 const onMove = useEffectEvent((y: number) => props.onMove(y));
594 const onEnd = useEffectEvent((y: number, success: boolean) => props.onEnd(y, success));
595 const gesture = Gesture.Pan()
596 .enabled(!props.disabled)
597 .minDistance(0)
598 .shouldCancelWhenOutside(false)
599 .runOnJS(true)
600 .onStart(() => onStart())
601 .onUpdate((event) => onMove(event.translationY))
602 .onFinalize((event, success) => onEnd(event.translationY, success));
603 return (
604 <GestureDetector gesture={gesture}>
605 <View
606 collapsable={false}
607 accessible
608 accessibilityRole="adjustable"
609 accessibilityLabel={`Reorder ${props.title}`}
610 accessibilityState={{ disabled: props.disabled }}
611 accessibilityActions={[
612 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
613 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
614 ]}
615 onAccessibilityAction={({ nativeEvent }) => {
616 if (props.disabled) return;
617 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
618 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
619 }}
620 className="h-12 w-8 items-center justify-center"
621 >
622 <SymbolView
623 name="line.3.horizontal"
624 size={16}
625 tintColorClassName="accent-foreground-muted"
626 />
627 </View>
628 </GestureDetector>
629 );
630}