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

ThreadQueueControl.tsx

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