Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadQueueControl.tsx

540 lines20.8 KB

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