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

ThreadQueueControl.tsx

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