Open History to see the last commit
1import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { useAtomValue } from "@effect/atom-react";
4import {
5 makeQueuedRunsAtom,
6 queuedRunEditBlockedReason,
7} from "@t3tools/client-runtime/queued-run-edit";
8import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
14import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
15import { Atom } from "effect/reactivity";
16import { Image } from "expo-image";
17import * as Haptics from "expo-haptics";
18import { msg, T, useGT, useMessages } from "gt-react-native";
19import { useEffect, useRef, useState } from "react";
20import { Pressable, ScrollView, View } from "react-native";
21import { GestureHandlerRootView } from "react-native-gesture-handler";
22import ReanimatedSwipeable, {
23 type SwipeableMethods,
24} from "react-native-gesture-handler/ReanimatedSwipeable";
25import { useUniwindTheme } from "../../lib/useUniwindTheme";
26import { useSafeAreaInsets } from "react-native-safe-area-context";
27
28import { Button } from "../../components/ui/Button";
29import * as Dialog from "../../components/ui/Dialog";
30import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
31import { SheetHeader } from "../../components/ui/SheetHeader";
32import { AppText as Text } from "../../components/ui/AppText";
33import { SymbolView } from "../../components/ui/AppSymbol";
34import { Menu } from "../../components/ui/Menu";
35import { ScreenContent } from "../../components/ui/ScreenContent";
36import { scopedThreadKey } from "../../lib/scopedEntities";
37import { useAssetUrl } from "../../state/assets";
38import { useQuietThreadShell } from "../../state/entities";
39import { useEnvironmentQuery } from "../../state/query";
40import { serverEnvironment } from "../../state/server";
41import { assetImageSource } from "../../lib/assetImageSource";
42import { appAtomRegistry } from "../../state/atom-registry";
43import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit";
44import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
45import { useAtomCommand } from "../../state/use-atom-command";
46import {
47 REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
48 buildCancelQueuedRunCommand,
49 resolveThreadQueueRowControls,
50} from "./threadQueueControlPresentation";
51
52const REMOVE_ACTION_WIDTH = 76;
53const THUMBNAIL_LIMIT = 3;
54const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe(
55 Atom.withLabel("mobile-thread-queue-count:empty"),
56);
57
58type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
59type QueueAction = "steer" | "edit" | "remove";
60
61function useThreadQueueWorkflow(target: QueueTarget) {
62 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
63}
64
65export function useThreadQueuedCount(target: QueueTarget | null) {
66 return useAtomValue(
67 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
68 );
69}
70
71type QueuedRunMessage = NonNullable<
72 NonNullable<ReturnType<typeof useThreadQueueWorkflow>>["queuedRuns"][number]["message"]
73>;
74
75/** Who sent a queued message, as its sent form shows it in the thread. */
76function QueuedRunSender(props: {
77 readonly environmentId: EnvironmentId;
78 readonly message: QueuedRunMessage;
79}) {
80 const gt = useGT();
81 const { attribution, scheduledTaskId } = resolveUserMessagePresentation(props.message);
82 const senderThreadId = attribution === "agent" ? props.message.senderThreadId : undefined;
83 // A linked environment's agent sent it from a thread there.
84 const linkedSender = attribution === "agent" ? props.message.linkedSender : undefined;
85 const senderShell = useQuietThreadShell(
86 linkedSender ?? (senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null),
87 );
88 const tasks = useEnvironmentQuery(
89 scheduledTaskId
90 ? serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} })
91 : null,
92 );
93 const sender =
94 attribution === "automation"
95 ? {
96 icon: "calendar.badge.clock" as const,
97 label:
98 tasks.data?.tasks.find((task) => task.id === scheduledTaskId)?.title ??
99 gt("Automation"),
100 }
101 : attribution === "agent"
102 ? {
103 icon: "bubble.left.and.bubble.right" as const,
104 label: senderShell?.title.trim() || linkedSender?.title.trim() || gt("Agent"),
105 }
106 : attribution === "t3code"
107 ? { icon: null, label: gt("Sent by T3 Code") }
108 : null;
109 if (sender === null) return null;
110 return (
111 <View className="flex-row items-center gap-1">
112 {sender.icon ? (
113 <SymbolView
114 name={sender.icon}
115 size={11}
116 weight="medium"
117 tintColorClassName="accent-foreground-muted"
118 type="monochrome"
119 />
120 ) : null}
121 <Text
122 numberOfLines={1}
123 className="min-w-0 shrink font-t3-medium text-2xs text-foreground-muted"
124 >
125 {sender.label}
126 </Text>
127 </View>
128 );
129}
130
131export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
132 const theme = useUniwindTheme();
133 const target = route.params;
134 const navigation = useNavigation();
135 const insets = useSafeAreaInsets();
136 const gt = useGT();
137 const m = useMessages();
138 const workflow = useThreadQueueWorkflow(target);
139 const threadKey = scopedThreadKey(target.environmentId, target.threadId);
140 const editing = useQueuedRunEdit(threadKey);
141 const pendingRequests = useAtomValue(environmentThreadDetails.pendingRequestsAtom(target));
142 const editBlockedReason = queuedRunEditBlockedReason(
143 {
144 openQuestionCount: pendingRequests?.userInputs.length ?? 0,
145 },
146 m,
147 );
148 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
149 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
150 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
151 const resumeHeldQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
152 label: "resume queue",
153 reportFailure: false,
154 });
155 const [resuming, setResuming] = useState(false);
156 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
157 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
158 const busyRef = useRef(false);
159 const queuedRuns = workflow?.queuedRuns ?? [];
160
161 const hadQueuedRuns = useRef(queuedRuns.length > 0);
162 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops the navigator once the server-side queue empties after it had runs
163 useEffect(() => {
164 if (queuedRuns.length > 0) {
165 hadQueuedRuns.current = true;
166 return;
167 }
168 if (hadQueuedRuns.current) navigation.goBack();
169 }, [navigation, queuedRuns.length]);
170
171 const act = async (runId: RunId, action: QueueAction) => {
172 if (busyRef.current) return;
173 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
174 if (index < 0) return;
175 if (action === "edit") {
176 if (editBlockedReason !== null) return;
177 const entry = queuedRuns[index]!;
178 void Haptics.selectionAsync();
179 beginQueuedRunEdit(
180 threadKey,
181 {
182 runId,
183 messageId: entry.messageId,
184 originalText: entry.text,
185 modelSelection: entry.message?.followsThreadSelection
186 ? (appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(target))?.projection
187 .thread.modelSelection ?? entry.run.modelSelection)
188 : entry.run.modelSelection,
189 followsThreadSelection: entry.message?.followsThreadSelection === true,
190 existingAttachments: entry.attachments,
191 ...(entry.context ? { context: entry.context } : {}),
192 },
193 makeQueuedRunsAtom({
194 threadId: target.threadId,
195 snapshot: threadEnvironment.snapshotAtom(target.environmentId),
196 detailStatus: environmentThreadDetails.statusAtom(target),
197 runs: Atom.make(
198 (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null,
199 ),
200 }),
201 );
202 navigation.goBack();
203 return;
204 }
205 if (action !== "steer" && action !== "remove") return;
206 busyRef.current = true;
207 setBusyRunId(runId);
208 void Haptics.selectionAsync();
209 const result =
210 action === "remove"
211 ? await cancel(buildCancelQueuedRunCommand({ ...target, runId }))
212 : workflow?.canSendNow
213 ? await resume({ ...target, input: { threadId: target.threadId, runId } })
214 : workflow?.activeRun && workflow.canPromoteToSteer
215 ? await promote({
216 ...target,
217 input: {
218 threadId: target.threadId,
219 queuedRunId: runId,
220 targetRunId: workflow.activeRun.id,
221 },
222 })
223 : null;
224 busyRef.current = false;
225 setBusyRunId(null);
226 if (action === "steer" && result?._tag === "Failure" && !isAtomCommandInterrupted(result)) {
227 const error = squashAtomCommandFailure(result);
228 Dialog.alert(
229 m(msg("Could not send queued message")),
230 errorDisplayMessage(error, m) ?? m(msg("Try again.")),
231 );
232 }
233 };
234
235 const content = (
236 <ScrollView
237 nestedScrollEnabled
238 className="flex-1"
239 // UIKit must inset content beneath the floating translucent iOS header.
240 contentInsetAdjustmentBehavior="automatic"
241 contentContainerClassName="px-5 pb-6"
242 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
243 >
244 {workflow?.isHeld && queuedRuns.length > 0 ? (
245 <View className="gap-2 py-3">
246 <Text className="text-sm text-foreground-muted">
247 <T>Queue paused</T>
248 </Text>
249 <Button
250 label={gt("Resume queue")}
251 disabled={resuming || busyRunId !== null}
252 onPress={async () => {
253 if (busyRef.current) return;
254 busyRef.current = true;
255 setResuming(true);
256 const result = await resumeHeldQueue({
257 ...target,
258 input: { threadId: target.threadId },
259 });
260 busyRef.current = false;
261 setResuming(false);
262 // A usage limit holds the queue until the composer's Resume thread continues the run.
263 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
264 const error = squashAtomCommandFailure(result);
265 Dialog.alert(
266 gt("Could not resume queue"),
267 errorDisplayMessage(error, m) ?? gt("Try again."),
268 );
269 }
270 }}
271 />
272 </View>
273 ) : null}
274 {editBlockedReason !== null && queuedRuns.length > 0 ? (
275 <Text className="py-3 text-sm text-foreground-muted">{editBlockedReason}</Text>
276 ) : null}
277 {queuedRuns.length === 0 ? (
278 <Text className="pt-6 text-center text-sm text-foreground-muted">
279 <T>No messages waiting in this queue.</T>
280 </Text>
281 ) : null}
282 {queuedRuns.map(({ run, text, attachments, context, message }, index) => {
283 const controls = resolveThreadQueueRowControls({
284 busy: busyRunId !== null,
285 // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
286 canPromoteToSteer:
287 (workflow?.canPromoteToSteer ?? false) &&
288 !queuedRuns[index]!.stopBlocksPromotion &&
289 (run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
290 canSendNow: workflow?.canSendNow ?? false,
291 editBlocked: editBlockedReason !== null,
292 isEditing: editing?.runId === run.id,
293 isGuestMessage: context?.guest !== undefined,
294 text,
295 });
296 const title =
297 controls.displayText ||
298 (attachments.length > 0 ? gt("Attachments") : gt("Queued message"));
299 return (
300 <View key={run.id} className="flex-row items-center border-b border-border bg-sheet">
301 <QueueRowSwipeable
302 enabled={busyRunId === null && controls.canDismiss}
303 background={theme["--color-sheet"]}
304 onRemove={() => void act(run.id, "remove")}
305 >
306 <View className="flex-row items-center">
307 <Menu
308 accessibilityLabel={gt("Actions for queued message {number}", {
309 number: index + 1,
310 })}
311 shouldOpenOnLongPress
312 style={{ flex: 1 }}
313 actions={[
314 ...(workflow?.canPromoteToSteer || workflow?.canSendNow
315 ? [
316 {
317 id: "steer",
318 title: gt("Send now"),
319 attributes: { disabled: !controls.canSend },
320 image: "arrow.up",
321 },
322 ]
323 : []),
324 {
325 id: "edit",
326 title: gt("Edit", { $context: "verb, menu action" }),
327 attributes: { disabled: !controls.canEdit },
328 image: "pencil",
329 },
330 {
331 id: "remove",
332 title: gt("Remove", { $context: "verb, menu action" }),
333 attributes: { disabled: !controls.canDismiss, destructive: true },
334 },
335 ]}
336 onPressAction={({ nativeEvent }) =>
337 void act(run.id, nativeEvent.event as QueueAction)
338 }
339 >
340 <Pressable
341 accessibilityRole="button"
342 accessibilityLabel={title}
343 accessibilityHint={
344 controls.canEdit
345 ? gt("Opens this message in the composer for editing")
346 : (editBlockedReason ?? undefined)
347 }
348 disabled={!controls.canEdit}
349 onPress={() => void act(run.id, "edit")}
350 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
351 >
352 <QueueAttachmentThumbnails
353 environmentId={target.environmentId}
354 attachments={attachments}
355 onPressPreview={setPreviewFile}
356 />
357 <View className="min-w-0 flex-1 gap-0.5">
358 {message ? (
359 <QueuedRunSender environmentId={target.environmentId} message={message} />
360 ) : null}
361 <Text
362 className={
363 controls.isEditing
364 ? "text-sm text-foreground-muted"
365 : "text-sm text-foreground"
366 }
367 numberOfLines={1}
368 >
369 {context?.guest === undefined ? null : (
370 <Text className="font-t3-medium text-adaptive-fuchsia-600-300">
371 {`${context.guest.name} `}
372 </Text>
373 )}
374 {title}
375 </Text>
376 </View>
377 {controls.isEditing ? (
378 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
379 {gt("Editing", {
380 $context: "status badge on the queued message being edited",
381 })}
382 </Text>
383 ) : null}
384 </Pressable>
385 </Menu>
386 {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
387 // Outside the edit row and full row height, so a near miss never opens the editor.
388 <Pressable
389 accessibilityRole="button"
390 accessibilityLabel={gt("Send now, queued message {number}", {
391 number: index + 1,
392 })}
393 disabled={!controls.canSend}
394 onPress={() => void act(run.id, "steer")}
395 className="shrink-0 justify-center self-stretch pl-4 active:opacity-70 disabled:opacity-40"
396 >
397 <View className="min-h-9 flex-row items-center gap-1.5 rounded-full bg-primary px-4">
398 <SymbolView
399 name="arrow.up"
400 size={13}
401 tintColorClassName="accent-primary-foreground"
402 />
403 <Text className="font-t3-medium text-sm text-primary-foreground">
404 <T>Send now</T>
405 </Text>
406 </View>
407 </Pressable>
408 ) : null}
409 </View>
410 </QueueRowSwipeable>
411 </View>
412 );
413 })}
414 </ScrollView>
415 );
416
417 return (
418 <GestureHandlerRootView style={{ flex: 1 }}>
419 <View collapsable={false} className="flex-1 bg-sheet">
420 <SheetHeader
421 title={gt("Queued", { $context: "title of the queued messages sheet" })}
422 onClose={() => navigation.goBack()}
423 />
424 <ScreenContent>{content}</ScreenContent>
425 </View>
426 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
427 </GestureHandlerRootView>
428 );
429}
430
431function QueueRowSwipeable(props: {
432 readonly enabled: boolean;
433 readonly background: string;
434 readonly onRemove: () => void;
435 readonly children: React.ReactNode;
436}) {
437 const swipeableRef = useRef<SwipeableMethods | null>(null);
438 const gt = useGT();
439 const m = useMessages();
440 return (
441 <ReanimatedSwipeable
442 ref={swipeableRef}
443 enabled={props.enabled}
444 friction={2}
445 rightThreshold={40}
446 overshootRight={false}
447 // Require a clearly sideways swipe to avoid competing with sheet scroll.
448 failOffsetY={[-12, 12]}
449 containerStyle={{ backgroundColor: props.background, flex: 1 }}
450 childrenContainerStyle={{ backgroundColor: props.background }}
451 onSwipeableOpen={(direction) => {
452 if (direction !== "right") return;
453 swipeableRef.current?.close();
454 props.onRemove();
455 }}
456 renderRightActions={() => (
457 <Pressable
458 accessibilityRole="button"
459 accessibilityLabel={m(REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL)}
460 disabled={!props.enabled}
461 onPress={() => {
462 swipeableRef.current?.close();
463 props.onRemove();
464 }}
465 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
466 style={{ width: REMOVE_ACTION_WIDTH }}
467 >
468 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
469 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">
470 {gt("Remove", { $context: "verb, menu action" })}
471 </Text>
472 </Pressable>
473 )}
474 >
475 {props.children}
476 </ReanimatedSwipeable>
477 );
478}
479
480function QueueAttachmentThumbnails(props: {
481 readonly environmentId: EnvironmentId;
482 readonly attachments: ReadonlyArray<ChatAttachment>;
483 readonly onPressPreview: (source: FilePreviewSource) => void;
484}) {
485 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
486 const gallery = images.map((attachment) => queueImagePreview(props.environmentId, attachment));
487 const shown = images.slice(0, THUMBNAIL_LIMIT);
488 const overflow = props.attachments.length - shown.length;
489 if (props.attachments.length === 0) return null;
490 return (
491 <View className="shrink-0 flex-row items-center gap-1">
492 {shown.map((attachment) => (
493 <QueueAttachmentThumbnail
494 key={attachment.id}
495 environmentId={props.environmentId}
496 attachment={attachment}
497 onPress={() =>
498 props.onPressPreview({
499 ...queueImagePreview(props.environmentId, attachment),
500 gallery,
501 })
502 }
503 />
504 ))}
505 {overflow > 0 ? (
506 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
507 <Text className="text-2xs tabular-nums text-foreground-muted">
508 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
509 </Text>
510 </View>
511 ) : null}
512 </View>
513 );
514}
515
516function queueAttachmentResource(attachment: ChatAttachment) {
517 return {
518 _tag: "attachment",
519 attachmentId: attachment.id,
520 fileName: attachment.name,
521 mimeType: attachment.mimeType,
522 disposition: "inline",
523 } as const;
524}
525
526function queueImagePreview(environmentId: EnvironmentId, attachment: ChatAttachment) {
527 const resource = queueAttachmentResource(attachment);
528 return {
529 kind: "image",
530 environmentId,
531 resource,
532 name: attachment.name,
533 mimeType: attachment.mimeType,
534 actionsSource: {
535 name: attachment.name,
536 mimeType: attachment.mimeType,
537 environmentId,
538 resource,
539 },
540 } as const;
541}
542
543function QueueAttachmentThumbnail(props: {
544 readonly environmentId: EnvironmentId;
545 readonly attachment: ChatAttachment;
546 readonly onPress: () => void;
547}) {
548 const resource = queueAttachmentResource(props.attachment);
549 const url = useAssetUrl(props.environmentId, resource);
550 const gt = useGT();
551 return (
552 // Its own press target, so tapping an image previews it instead of editing the message.
553 <Pressable
554 accessibilityRole="imagebutton"
555 accessibilityLabel={gt("Open {name}", { name: props.attachment.name })}
556 hitSlop={6}
557 onPress={props.onPress}
558 className="active:opacity-70"
559 >
560 {url === null ? (
561 <View className="h-6 w-6 rounded bg-subtle" />
562 ) : (
563 <Image
564 source={assetImageSource(props.environmentId, resource, url)}
565 cachePolicy="memory-disk"
566 contentFit="cover"
567 style={{ width: 24, height: 24, borderRadius: 4 }}
568 accessibilityIgnoresInvertColors
569 />
570 )}
571 </Pressable>
572 );
573}