Open History to see the last commit
1import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2import { useAtomValue } from "@effect/atom-react";
3import {
4 makeQueuedRunsAtom,
5 queuedRunEditBlockedReason,
6} from "@t3tools/client-runtime/queued-run-edit";
7import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
8import { Atom } from "effect/reactivity";
9import { Image } from "expo-image";
10import * as Haptics from "expo-haptics";
11import { useEffect, useRef, useState } from "react";
12import { Platform, Pressable, ScrollView, View } from "react-native";
13import { GestureHandlerRootView } from "react-native-gesture-handler";
14import ReanimatedSwipeable, {
15 type SwipeableMethods,
16} from "react-native-gesture-handler/ReanimatedSwipeable";
17import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
18import { useSafeAreaInsets } from "react-native-safe-area-context";
19
20import { Button } from "../../components/ui/Button";
21import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader";
22import { AppText as Text } from "../../components/ui/AppText";
23import { SymbolView } from "../../components/ui/AppSymbol";
24import { Menu } from "../../components/ui/Menu";
25import { ScreenContent } from "../../components/ui/ScreenContent";
26import { scopedThreadKey } from "../../lib/scopedEntities";
27import { useUniwindTheme } from "../../lib/useUniwindTheme";
28import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
29import { useAssetUrl } from "../../state/assets";
30import { assetImageSource } from "../../lib/assetImageSource";
31import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit";
32import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
33import { useAtomCommand } from "../../state/use-atom-command";
34import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
35import {
36 REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
37 buildCancelQueuedRunCommand,
38 resolveThreadQueueRowControls,
39} from "./threadQueueControlPresentation";
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" | "remove";
50
51export function useThreadQueueWorkflow(target: QueueTarget) {
52 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
53}
54
55export function useThreadQueuedCount(target: QueueTarget | null) {
56 return useAtomValue(
57 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
58 );
59}
60
61export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
62 const { layout } = useAdaptiveWorkspaceLayout();
63 const target = route.params;
64 const navigation = useNavigation();
65 const insets = useSafeAreaInsets();
66 const theme = useUniwindTheme();
67 const workflow = useThreadQueueWorkflow(target);
68 const threadKey = scopedThreadKey(target.environmentId, target.threadId);
69 const editing = useQueuedRunEdit(threadKey);
70 const pendingRequests = useAtomValue(environmentThreadDetails.pendingRequestsAtom(target));
71 const editBlockedReason = queuedRunEditBlockedReason({
72 openQuestionCount: pendingRequests?.userInputs.length ?? 0,
73 });
74 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
75 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
76 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
77 const [resuming, setResuming] = useState(false);
78 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
79 const busyRef = useRef(false);
80 const queuedRuns = workflow?.queuedRuns ?? [];
81
82 const hadQueuedRuns = useRef(queuedRuns.length > 0);
83 useEffect(() => {
84 if (queuedRuns.length > 0) {
85 hadQueuedRuns.current = true;
86 return;
87 }
88 if (hadQueuedRuns.current) navigation.goBack();
89 }, [navigation, queuedRuns.length]);
90
91 const act = async (runId: RunId, action: QueueAction) => {
92 if (busyRef.current) return;
93 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
94 if (index < 0) return;
95 if (action === "edit") {
96 if (editBlockedReason !== null) return;
97 const entry = queuedRuns[index]!;
98 void Haptics.selectionAsync();
99 beginQueuedRunEdit(
100 threadKey,
101 {
102 runId,
103 messageId: entry.messageId,
104 originalText: entry.text,
105 existingAttachments: entry.attachments,
106 ...(entry.context ? { context: entry.context } : {}),
107 },
108 makeQueuedRunsAtom({
109 threadId: target.threadId,
110 snapshot: threadEnvironment.snapshotAtom(target.environmentId),
111 detailStatus: environmentThreadDetails.statusAtom(target),
112 runs: Atom.make(
113 (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null,
114 ),
115 }),
116 );
117 navigation.goBack();
118 return;
119 }
120 if (action !== "steer" && action !== "remove") return;
121 busyRef.current = true;
122 setBusyRunId(runId);
123 void Haptics.selectionAsync();
124 if (action === "remove") {
125 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
126 } else if (workflow?.canSendNow) {
127 await resume({ ...target, input: { threadId: target.threadId, runId } });
128 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
129 await promote({
130 ...target,
131 input: {
132 threadId: target.threadId,
133 queuedRunId: runId,
134 targetRunId: workflow.activeRun.id,
135 },
136 });
137 }
138 busyRef.current = false;
139 setBusyRunId(null);
140 };
141
142 const content = (
143 <ScrollView
144 nestedScrollEnabled
145 className="flex-1"
146 // UIKit must inset content beneath the floating translucent iOS header.
147 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
148 contentContainerClassName="px-5 pb-6"
149 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
150 >
151 {workflow?.isHeld && queuedRuns.length > 0 ? (
152 <View className="gap-2 py-3">
153 <Text className="text-sm text-foreground-muted">Queue paused</Text>
154 <Button
155 label="Resume queue"
156 disabled={resuming || busyRunId !== null}
157 onPress={async () => {
158 if (busyRef.current) return;
159 busyRef.current = true;
160 setResuming(true);
161 await resume({ ...target, input: { threadId: target.threadId } });
162 busyRef.current = false;
163 setResuming(false);
164 }}
165 />
166 </View>
167 ) : null}
168 {editBlockedReason !== null && queuedRuns.length > 0 ? (
169 <Text className="py-3 text-sm text-foreground-muted">{editBlockedReason}</Text>
170 ) : null}
171 {queuedRuns.length === 0 ? (
172 <Text className="pt-6 text-center text-sm text-foreground-muted">
173 No messages waiting in this queue.
174 </Text>
175 ) : null}
176 {queuedRuns.map(({ run, text, attachments, context }, index) => {
177 const controls = resolveThreadQueueRowControls({
178 busy: busyRunId !== null,
179 canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
180 canSendNow: workflow?.canSendNow ?? false,
181 editBlocked: editBlockedReason !== null,
182 isEditing: editing?.runId === run.id,
183 isGuestMessage: context?.guest !== undefined,
184 text,
185 });
186 const title =
187 controls.displayText || (attachments.length > 0 ? "Attachments" : "Queued message");
188 return (
189 <View key={run.id} className="flex-row items-center border-b border-border bg-sheet">
190 <QueueRowSwipeable
191 enabled={busyRunId === null && controls.canDismiss}
192 background={theme["--color-sheet"]}
193 onRemove={() => void act(run.id, "remove")}
194 >
195 <View className="flex-row items-center">
196 <Menu
197 accessibilityLabel={`Actions for queued message ${index + 1}`}
198 shouldOpenOnLongPress
199 style={{ flex: 1 }}
200 actions={[
201 ...(workflow?.canPromoteToSteer || workflow?.canSendNow
202 ? [
203 {
204 id: "steer",
205 title: "Send now",
206 attributes: { disabled: !controls.canSend },
207 image: Platform.OS === "ios" ? "arrow.up" : "arrow_upward",
208 },
209 ]
210 : []),
211 {
212 id: "edit",
213 title: "Edit",
214 attributes: { disabled: !controls.canEdit },
215 image: Platform.OS === "ios" ? "pencil" : "edit",
216 },
217 {
218 id: "remove",
219 title: "Remove",
220 attributes: { disabled: !controls.canDismiss, destructive: true },
221 },
222 ]}
223 onPressAction={({ nativeEvent }) =>
224 void act(run.id, nativeEvent.event as QueueAction)
225 }
226 >
227 <Pressable
228 accessibilityRole="button"
229 accessibilityLabel={title}
230 accessibilityHint={
231 controls.canEdit
232 ? "Opens this message in the composer for editing"
233 : (editBlockedReason ?? undefined)
234 }
235 disabled={!controls.canEdit}
236 onPress={() => void act(run.id, "edit")}
237 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
238 >
239 <QueueAttachmentThumbnails
240 environmentId={target.environmentId}
241 attachments={attachments}
242 />
243 <Text
244 className={
245 controls.isEditing
246 ? "min-w-0 flex-1 text-sm text-foreground-muted"
247 : "min-w-0 flex-1 text-sm text-foreground"
248 }
249 numberOfLines={1}
250 >
251 {context?.guest === undefined ? null : (
252 <Text className="font-t3-medium text-adaptive-fuchsia-600-300">
253 {`${context.guest.name} `}
254 </Text>
255 )}
256 {title}
257 </Text>
258 {controls.isEditing ? (
259 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
260 Editing
261 </Text>
262 ) : null}
263 </Pressable>
264 </Menu>
265 {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
266 // Outside the edit row and full row height, so a near miss never opens the editor.
267 <Pressable
268 accessibilityRole="button"
269 accessibilityLabel={`Send now, queued message ${index + 1}`}
270 disabled={!controls.canSend}
271 onPress={() => void act(run.id, "steer")}
272 className="shrink-0 justify-center self-stretch pl-4 active:opacity-70 disabled:opacity-40"
273 >
274 <View className="min-h-9 flex-row items-center gap-1.5 rounded-full bg-primary px-4">
275 <SymbolView
276 name="arrow.up"
277 size={13}
278 tintColorClassName="accent-primary-foreground"
279 />
280 <Text className="font-t3-medium text-sm text-primary-foreground">
281 Send now
282 </Text>
283 </View>
284 </Pressable>
285 ) : null}
286 </View>
287 </QueueRowSwipeable>
288 </View>
289 );
290 })}
291 </ScrollView>
292 );
293
294 if (Platform.OS === "ios") {
295 // Plain formSheets lack stack headers; host one in a nested native stack.
296 return (
297 <GestureHandlerRootView style={{ flex: 1 }}>
298 <View collapsable={false} className="flex-1 bg-sheet">
299 <ScreenStack style={{ flex: 1 }}>
300 <Screen
301 activityState={2}
302 enabled
303 isNativeStack
304 screenId="thread-queue-sheet-native"
305 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
306 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
307 >
308 {content}
309 <ScreenStackHeaderConfig
310 backgroundColor="rgba(0,0,0,0)"
311 color={theme["--color-foreground"]}
312 hideBackButton
313 hideShadow={false}
314 title="Queued"
315 titleColor={theme["--color-foreground"]}
316 titleFontSize={18}
317 titleFontWeight="800"
318 translucent
319 />
320 </Screen>
321 </ScreenStack>
322 </View>
323 </GestureHandlerRootView>
324 );
325 }
326
327 return (
328 <GestureHandlerRootView style={{ flex: 1 }}>
329 <View collapsable={false} className="flex-1 bg-sheet">
330 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
331 <AndroidSheetHeader title="Queued" onBack={() => navigation.goBack()} />
332 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
333 </View>
334 </GestureHandlerRootView>
335 );
336}
337
338function QueueRowSwipeable(props: {
339 readonly enabled: boolean;
340 readonly background: string;
341 readonly onRemove: () => void;
342 readonly children: React.ReactNode;
343}) {
344 const swipeableRef = useRef<SwipeableMethods | null>(null);
345 return (
346 <ReanimatedSwipeable
347 ref={swipeableRef}
348 enabled={props.enabled}
349 friction={2}
350 rightThreshold={40}
351 overshootRight={false}
352 // Require a clearly sideways swipe to avoid competing with sheet scroll.
353 failOffsetY={[-12, 12]}
354 containerStyle={{ backgroundColor: props.background, flex: 1 }}
355 childrenContainerStyle={{ backgroundColor: props.background }}
356 onSwipeableOpen={(direction) => {
357 if (direction !== "right") return;
358 swipeableRef.current?.close();
359 props.onRemove();
360 }}
361 renderRightActions={() => (
362 <Pressable
363 accessibilityRole="button"
364 accessibilityLabel={REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL}
365 disabled={!props.enabled}
366 onPress={() => {
367 swipeableRef.current?.close();
368 props.onRemove();
369 }}
370 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
371 style={{ width: REMOVE_ACTION_WIDTH }}
372 >
373 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
374 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
375 </Pressable>
376 )}
377 >
378 {props.children}
379 </ReanimatedSwipeable>
380 );
381}
382
383function QueueAttachmentThumbnails(props: {
384 readonly environmentId: EnvironmentId;
385 readonly attachments: ReadonlyArray<ChatAttachment>;
386}) {
387 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
388 const shown = images.slice(0, THUMBNAIL_LIMIT);
389 const overflow = props.attachments.length - shown.length;
390 if (props.attachments.length === 0) return null;
391 return (
392 <View className="shrink-0 flex-row items-center gap-1">
393 {shown.map((attachment) => (
394 <QueueAttachmentThumbnail
395 key={attachment.id}
396 environmentId={props.environmentId}
397 attachment={attachment}
398 />
399 ))}
400 {overflow > 0 ? (
401 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
402 <Text className="text-2xs tabular-nums text-foreground-muted">
403 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
404 </Text>
405 </View>
406 ) : null}
407 </View>
408 );
409}
410
411function QueueAttachmentThumbnail(props: {
412 readonly environmentId: EnvironmentId;
413 readonly attachment: ChatAttachment;
414}) {
415 const resource = {
416 _tag: "attachment",
417 attachmentId: props.attachment.id,
418 fileName: props.attachment.name,
419 mimeType: props.attachment.mimeType,
420 disposition: "inline",
421 } as const;
422 const url = useAssetUrl(props.environmentId, resource);
423 if (url === null) {
424 return <View className="h-6 w-6 rounded bg-subtle" />;
425 }
426 return (
427 <Image
428 source={assetImageSource(props.environmentId, resource, url)}
429 cachePolicy="memory-disk"
430 contentFit="cover"
431 style={{ width: 24, height: 24, borderRadius: 4 }}
432 accessibilityIgnoresInvertColors
433 />
434 );
435}