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

ThreadQueueControl.tsx

532 lines20.4 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 if (action === "remove") {
195 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
196 } else if (workflow?.canSendNow) {
197 await resume({ ...target, input: { threadId: target.threadId, runId } });
198 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
199 await promote({
200 ...target,
201 input: {
202 threadId: target.threadId,
203 queuedRunId: runId,
204 targetRunId: workflow.activeRun.id,
205 },
206 });
207 }
208 busyRef.current = false;
209 setBusyRunId(null);
210 };
211​
212 const content = (
213 <ScrollView
214 nestedScrollEnabled
215 className="flex-1"
216 // UIKit must inset content beneath the floating translucent iOS header.
217 contentInsetAdjustmentBehavior="automatic"
218 contentContainerClassName="px-5 pb-6"
219 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
220 >
221 {workflow?.isHeld && queuedRuns.length > 0 ? (
222 <View className="gap-2 py-3">
223 <Text className="text-sm text-foreground-muted">Queue paused</Text>
224 <Button
225 label="Resume queue"
226 disabled={resuming || busyRunId !== null}
227 onPress={async () => {
228 if (busyRef.current) return;
229 busyRef.current = true;
230 setResuming(true);
231 const result = await resumeHeldQueue({
232 ...target,
233 input: { threadId: target.threadId },
234 });
235 busyRef.current = false;
236 setResuming(false);
237 // A usage limit holds the queue until the composer's Resume thread continues the run.
238 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
239 const error = squashAtomCommandFailure(result);
240 Dialog.alert(
241 "Could not resume queue",
242 error instanceof Error ? error.message : "Try again.",
243 );
244 }
245 }}
246 />
247 </View>
248 ) : null}
249 {editBlockedReason !== null && queuedRuns.length > 0 ? (
250 <Text className="py-3 text-sm text-foreground-muted">{editBlockedReason}</Text>
251 ) : null}
252 {queuedRuns.length === 0 ? (
253 <Text className="pt-6 text-center text-sm text-foreground-muted">
254 No messages waiting in this queue.
255 </Text>
256 ) : null}
257 {queuedRuns.map(({ run, text, attachments, context, message }, index) => {
258 const controls = resolveThreadQueueRowControls({
259 busy: busyRunId !== null,
260 // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
261 canPromoteToSteer:
262 (workflow?.canPromoteToSteer ?? false) &&
263 (run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
264 canSendNow: workflow?.canSendNow ?? false,
265 editBlocked: editBlockedReason !== null,
266 isEditing: editing?.runId === run.id,
267 isGuestMessage: context?.guest !== undefined,
268 text,
269 });
270 const title =
271 controls.displayText || (attachments.length > 0 ? "Attachments" : "Queued message");
272 return (
273 <View key={run.id} className="flex-row items-center border-b border-border bg-sheet">
274 <QueueRowSwipeable
275 enabled={busyRunId === null && controls.canDismiss}
276 background={theme["--color-sheet"]}
277 onRemove={() => void act(run.id, "remove")}
278 >
279 <View className="flex-row items-center">
280 <Menu
281 accessibilityLabel={`Actions for queued message ${index + 1}`}
282 shouldOpenOnLongPress
283 style={{ flex: 1 }}
284 actions={[
285 ...(workflow?.canPromoteToSteer || workflow?.canSendNow
286 ? [
287 {
288 id: "steer",
289 title: "Send now",
290 attributes: { disabled: !controls.canSend },
291 image: "arrow.up",
292 },
293 ]
294 : []),
295 {
296 id: "edit",
297 title: "Edit",
298 attributes: { disabled: !controls.canEdit },
299 image: "pencil",
300 },
301 {
302 id: "remove",
303 title: "Remove",
304 attributes: { disabled: !controls.canDismiss, destructive: true },
305 },
306 ]}
307 onPressAction={({ nativeEvent }) =>
308 void act(run.id, nativeEvent.event as QueueAction)
309 }
310 >
311 <Pressable
312 accessibilityRole="button"
313 accessibilityLabel={title}
314 accessibilityHint={
315 controls.canEdit
316 ? "Opens this message in the composer for editing"
317 : (editBlockedReason ?? undefined)
318 }
319 disabled={!controls.canEdit}
320 onPress={() => void act(run.id, "edit")}
321 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
322 >
323 <QueueAttachmentThumbnails
324 environmentId={target.environmentId}
325 attachments={attachments}
326 onPressPreview={setPreviewFile}
327 />
328 <View className="min-w-0 flex-1 gap-0.5">
329 {message ? (
330 <QueuedRunSender environmentId={target.environmentId} message={message} />
331 ) : null}
332 <Text
333 className={
334 controls.isEditing
335 ? "text-sm text-foreground-muted"
336 : "text-sm text-foreground"
337 }
338 numberOfLines={1}
339 >
340 {context?.guest === undefined ? null : (
341 <Text className="font-t3-medium text-adaptive-fuchsia-600-300">
342 {`${context.guest.name} `}
343 </Text>
344 )}
345 {title}
346 </Text>
347 </View>
348 {controls.isEditing ? (
349 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
350 Editing
351 </Text>
352 ) : null}
353 </Pressable>
354 </Menu>
355 {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
356 // Outside the edit row and full row height, so a near miss never opens the editor.
357 <Pressable
358 accessibilityRole="button"
359 accessibilityLabel={`Send now, queued message ${index + 1}`}
360 disabled={!controls.canSend}
361 onPress={() => void act(run.id, "steer")}
362 className="shrink-0 justify-center self-stretch pl-4 active:opacity-70 disabled:opacity-40"
363 >
364 <View className="min-h-9 flex-row items-center gap-1.5 rounded-full bg-primary px-4">
365 <SymbolView
366 name="arrow.up"
367 size={13}
368 tintColorClassName="accent-primary-foreground"
369 />
370 <Text className="font-t3-medium text-sm text-primary-foreground">
371 Send now
372 </Text>
373 </View>
374 </Pressable>
375 ) : null}
376 </View>
377 </QueueRowSwipeable>
378 </View>
379 );
380 })}
381 </ScrollView>
382 );
383​
384 return (
385 <GestureHandlerRootView style={{ flex: 1 }}>
386 <View collapsable={false} className="flex-1 bg-sheet">
387 <SheetHeader title="Queued" onClose={() => navigation.goBack()} />
388 <ScreenContent>{content}</ScreenContent>
389 </View>
390 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
391 </GestureHandlerRootView>
392 );
394​
395function QueueRowSwipeable(props: {
396 readonly enabled: boolean;
397 readonly background: string;
398 readonly onRemove: () => void;
399 readonly children: React.ReactNode;
400}) {
401 const swipeableRef = useRef<SwipeableMethods | null>(null);
402 return (
403 <ReanimatedSwipeable
404 ref={swipeableRef}
405 enabled={props.enabled}
406 friction={2}
407 rightThreshold={40}
408 overshootRight={false}
409 // Require a clearly sideways swipe to avoid competing with sheet scroll.
410 failOffsetY={[-12, 12]}
411 containerStyle={{ backgroundColor: props.background, flex: 1 }}
412 childrenContainerStyle={{ backgroundColor: props.background }}
413 onSwipeableOpen={(direction) => {
414 if (direction !== "right") return;
415 swipeableRef.current?.close();
416 props.onRemove();
417 }}
418 renderRightActions={() => (
419 <Pressable
420 accessibilityRole="button"
421 accessibilityLabel={REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL}
422 disabled={!props.enabled}
423 onPress={() => {
424 swipeableRef.current?.close();
425 props.onRemove();
426 }}
427 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
428 style={{ width: REMOVE_ACTION_WIDTH }}
429 >
430 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
431 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
432 </Pressable>
433 )}
434 >
435 {props.children}
436 </ReanimatedSwipeable>
437 );
439​
440function QueueAttachmentThumbnails(props: {
441 readonly environmentId: EnvironmentId;
442 readonly attachments: ReadonlyArray<ChatAttachment>;
443 readonly onPressPreview: (source: FilePreviewSource) => void;
444}) {
445 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
446 const gallery = images.map((attachment) => queueImagePreview(props.environmentId, attachment));
447 const shown = images.slice(0, THUMBNAIL_LIMIT);
448 const overflow = props.attachments.length - shown.length;
449 if (props.attachments.length === 0) return null;
450 return (
451 <View className="shrink-0 flex-row items-center gap-1">
452 {shown.map((attachment) => (
453 <QueueAttachmentThumbnail
454 key={attachment.id}
455 environmentId={props.environmentId}
456 attachment={attachment}
457 onPress={() =>
458 props.onPressPreview({
459 ...queueImagePreview(props.environmentId, attachment),
460 gallery,
461 })
462 }
463 />
464 ))}
465 {overflow > 0 ? (
466 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
467 <Text className="text-2xs tabular-nums text-foreground-muted">
468 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
469 </Text>
470 </View>
471 ) : null}
472 </View>
473 );
475​
476function queueAttachmentResource(attachment: ChatAttachment) {
477 return {
478 _tag: "attachment",
479 attachmentId: attachment.id,
480 fileName: attachment.name,
481 mimeType: attachment.mimeType,
482 disposition: "inline",
483 } as const;
485​
486function queueImagePreview(environmentId: EnvironmentId, attachment: ChatAttachment) {
487 const resource = queueAttachmentResource(attachment);
488 return {
489 kind: "image",
490 environmentId,
491 resource,
492 name: attachment.name,
493 mimeType: attachment.mimeType,
494 actionsSource: {
495 name: attachment.name,
496 mimeType: attachment.mimeType,
497 environmentId,
498 resource,
499 },
500 } as const;
502​
503function QueueAttachmentThumbnail(props: {
504 readonly environmentId: EnvironmentId;
505 readonly attachment: ChatAttachment;
506 readonly onPress: () => void;
507}) {
508 const resource = queueAttachmentResource(props.attachment);
509 const url = useAssetUrl(props.environmentId, resource);
510 return (
511 // Its own press target, so tapping an image previews it instead of editing the message.
512 <Pressable
513 accessibilityRole="imagebutton"
514 accessibilityLabel={`Open ${props.attachment.name}`}
515 hitSlop={6}
516 onPress={props.onPress}
517 className="active:opacity-70"
518 >
519 {url === null ? (
520 <View className="h-6 w-6 rounded bg-subtle" />
521 ) : (
522 <Image
523 source={assetImageSource(props.environmentId, resource, url)}
524 cachePolicy="memory-disk"
525 contentFit="cover"
526 style={{ width: 24, height: 24, borderRadius: 4 }}
527 accessibilityIgnoresInvertColors
528 />
529 )}
530 </Pressable>
531 );