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