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

ThreadQueueControl.tsx

572 lines22.1 KB

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));
64​
65export function useThreadQueuedCount(target: QueueTarget | null) {
66 return useAtomValue(
67 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
68 );
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 );
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 (run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
289 canSendNow: workflow?.canSendNow ?? false,
290 editBlocked: editBlockedReason !== null,
291 isEditing: editing?.runId === run.id,
292 isGuestMessage: context?.guest !== undefined,
293 text,
294 });
295 const title =
296 controls.displayText ||
297 (attachments.length > 0 ? gt("Attachments") : gt("Queued message"));
298 return (
299 <View key={run.id} className="flex-row items-center border-b border-border bg-sheet">
300 <QueueRowSwipeable
301 enabled={busyRunId === null && controls.canDismiss}
302 background={theme["--color-sheet"]}
303 onRemove={() => void act(run.id, "remove")}
304 >
305 <View className="flex-row items-center">
306 <Menu
307 accessibilityLabel={gt("Actions for queued message {number}", {
308 number: index + 1,
309 })}
310 shouldOpenOnLongPress
311 style={{ flex: 1 }}
312 actions={[
313 ...(workflow?.canPromoteToSteer || workflow?.canSendNow
314 ? [
315 {
316 id: "steer",
317 title: gt("Send now"),
318 attributes: { disabled: !controls.canSend },
319 image: "arrow.up",
320 },
321 ]
322 : []),
323 {
324 id: "edit",
325 title: gt("Edit", { $context: "verb, menu action" }),
326 attributes: { disabled: !controls.canEdit },
327 image: "pencil",
328 },
329 {
330 id: "remove",
331 title: gt("Remove", { $context: "verb, menu action" }),
332 attributes: { disabled: !controls.canDismiss, destructive: true },
333 },
334 ]}
335 onPressAction={({ nativeEvent }) =>
336 void act(run.id, nativeEvent.event as QueueAction)
337 }
338 >
339 <Pressable
340 accessibilityRole="button"
341 accessibilityLabel={title}
342 accessibilityHint={
343 controls.canEdit
344 ? gt("Opens this message in the composer for editing")
345 : (editBlockedReason ?? undefined)
346 }
347 disabled={!controls.canEdit}
348 onPress={() => void act(run.id, "edit")}
349 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
350 >
351 <QueueAttachmentThumbnails
352 environmentId={target.environmentId}
353 attachments={attachments}
354 onPressPreview={setPreviewFile}
355 />
356 <View className="min-w-0 flex-1 gap-0.5">
357 {message ? (
358 <QueuedRunSender environmentId={target.environmentId} message={message} />
359 ) : null}
360 <Text
361 className={
362 controls.isEditing
363 ? "text-sm text-foreground-muted"
364 : "text-sm text-foreground"
365 }
366 numberOfLines={1}
367 >
368 {context?.guest === undefined ? null : (
369 <Text className="font-t3-medium text-adaptive-fuchsia-600-300">
370 {`${context.guest.name} `}
371 </Text>
372 )}
373 {title}
374 </Text>
375 </View>
376 {controls.isEditing ? (
377 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
378 {gt("Editing", {
379 $context: "status badge on the queued message being edited",
380 })}
381 </Text>
382 ) : null}
383 </Pressable>
384 </Menu>
385 {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
386 // Outside the edit row and full row height, so a near miss never opens the editor.
387 <Pressable
388 accessibilityRole="button"
389 accessibilityLabel={gt("Send now, queued message {number}", {
390 number: index + 1,
391 })}
392 disabled={!controls.canSend}
393 onPress={() => void act(run.id, "steer")}
394 className="shrink-0 justify-center self-stretch pl-4 active:opacity-70 disabled:opacity-40"
395 >
396 <View className="min-h-9 flex-row items-center gap-1.5 rounded-full bg-primary px-4">
397 <SymbolView
398 name="arrow.up"
399 size={13}
400 tintColorClassName="accent-primary-foreground"
401 />
402 <Text className="font-t3-medium text-sm text-primary-foreground">
403 <T>Send now</T>
404 </Text>
405 </View>
406 </Pressable>
407 ) : null}
408 </View>
409 </QueueRowSwipeable>
410 </View>
411 );
412 })}
413 </ScrollView>
414 );
415​
416 return (
417 <GestureHandlerRootView style={{ flex: 1 }}>
418 <View collapsable={false} className="flex-1 bg-sheet">
419 <SheetHeader
420 title={gt("Queued", { $context: "title of the queued messages sheet" })}
421 onClose={() => navigation.goBack()}
422 />
423 <ScreenContent>{content}</ScreenContent>
424 </View>
425 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
426 </GestureHandlerRootView>
427 );
429​
430function QueueRowSwipeable(props: {
431 readonly enabled: boolean;
432 readonly background: string;
433 readonly onRemove: () => void;
434 readonly children: React.ReactNode;
435}) {
436 const swipeableRef = useRef<SwipeableMethods | null>(null);
437 const gt = useGT();
438 const m = useMessages();
439 return (
440 <ReanimatedSwipeable
441 ref={swipeableRef}
442 enabled={props.enabled}
443 friction={2}
444 rightThreshold={40}
445 overshootRight={false}
446 // Require a clearly sideways swipe to avoid competing with sheet scroll.
447 failOffsetY={[-12, 12]}
448 containerStyle={{ backgroundColor: props.background, flex: 1 }}
449 childrenContainerStyle={{ backgroundColor: props.background }}
450 onSwipeableOpen={(direction) => {
451 if (direction !== "right") return;
452 swipeableRef.current?.close();
453 props.onRemove();
454 }}
455 renderRightActions={() => (
456 <Pressable
457 accessibilityRole="button"
458 accessibilityLabel={m(REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL)}
459 disabled={!props.enabled}
460 onPress={() => {
461 swipeableRef.current?.close();
462 props.onRemove();
463 }}
464 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
465 style={{ width: REMOVE_ACTION_WIDTH }}
466 >
467 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
468 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">
469 {gt("Remove", { $context: "verb, menu action" })}
470 </Text>
471 </Pressable>
472 )}
473 >
474 {props.children}
475 </ReanimatedSwipeable>
476 );
478​
479function QueueAttachmentThumbnails(props: {
480 readonly environmentId: EnvironmentId;
481 readonly attachments: ReadonlyArray<ChatAttachment>;
482 readonly onPressPreview: (source: FilePreviewSource) => void;
483}) {
484 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
485 const gallery = images.map((attachment) => queueImagePreview(props.environmentId, attachment));
486 const shown = images.slice(0, THUMBNAIL_LIMIT);
487 const overflow = props.attachments.length - shown.length;
488 if (props.attachments.length === 0) return null;
489 return (
490 <View className="shrink-0 flex-row items-center gap-1">
491 {shown.map((attachment) => (
492 <QueueAttachmentThumbnail
493 key={attachment.id}
494 environmentId={props.environmentId}
495 attachment={attachment}
496 onPress={() =>
497 props.onPressPreview({
498 ...queueImagePreview(props.environmentId, attachment),
499 gallery,
500 })
501 }
502 />
503 ))}
504 {overflow > 0 ? (
505 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
506 <Text className="text-2xs tabular-nums text-foreground-muted">
507 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
508 </Text>
509 </View>
510 ) : null}
511 </View>
512 );
514​
515function queueAttachmentResource(attachment: ChatAttachment) {
516 return {
517 _tag: "attachment",
518 attachmentId: attachment.id,
519 fileName: attachment.name,
520 mimeType: attachment.mimeType,
521 disposition: "inline",
522 } as const;
524​
525function queueImagePreview(environmentId: EnvironmentId, attachment: ChatAttachment) {
526 const resource = queueAttachmentResource(attachment);
527 return {
528 kind: "image",
529 environmentId,
530 resource,
531 name: attachment.name,
532 mimeType: attachment.mimeType,
533 actionsSource: {
534 name: attachment.name,
535 mimeType: attachment.mimeType,
536 environmentId,
537 resource,
538 },
539 } as const;
541​
542function QueueAttachmentThumbnail(props: {
543 readonly environmentId: EnvironmentId;
544 readonly attachment: ChatAttachment;
545 readonly onPress: () => void;
546}) {
547 const resource = queueAttachmentResource(props.attachment);
548 const url = useAssetUrl(props.environmentId, resource);
549 const gt = useGT();
550 return (
551 // Its own press target, so tapping an image previews it instead of editing the message.
552 <Pressable
553 accessibilityRole="imagebutton"
554 accessibilityLabel={gt("Open {name}", { name: props.attachment.name })}
555 hitSlop={6}
556 onPress={props.onPress}
557 className="active:opacity-70"
558 >
559 {url === null ? (
560 <View className="h-6 w-6 rounded bg-subtle" />
561 ) : (
562 <Image
563 source={assetImageSource(props.environmentId, resource, url)}
564 cachePolicy="memory-disk"
565 contentFit="cover"
566 style={{ width: 24, height: 24, borderRadius: 4 }}
567 accessibilityIgnoresInvertColors
568 />
569 )}
570 </Pressable>
571 );