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

ThreadQueueControl.tsx

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