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