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

ThreadQueueControl.tsx

502 lines19.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 { 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 { Platform, 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 { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21​
22import { Button } from "../../components/ui/Button";
23import { AppBar } from "../../components/ui/AppBar";
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 { useUniwindTheme } from "../../lib/useUniwindTheme";
30import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
31import { useAssetUrl } from "../../state/assets";
32import { useQuietThreadShell } from "../../state/entities";
33import { useEnvironmentQuery } from "../../state/query";
34import { serverEnvironment } from "../../state/server";
35import { assetImageSource } from "../../lib/assetImageSource";
36import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit";
37import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
38import { useAtomCommand } from "../../state/use-atom-command";
39import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
40import {
41 REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
42 buildCancelQueuedRunCommand,
43 resolveThreadQueueRowControls,
44} from "./threadQueueControlPresentation";
45​
46const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
47const REMOVE_ACTION_WIDTH = 76;
48const THUMBNAIL_LIMIT = 3;
49const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe(
50 Atom.withLabel("mobile-thread-queue-count:empty"),
51);
52​
53type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
54type QueueAction = "steer" | "edit" | "remove";
55​
56function useThreadQueueWorkflow(target: QueueTarget) {
57 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
59​
60export function useThreadQueuedCount(target: QueueTarget | null) {
61 return useAtomValue(
62 target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target),
63 );
65​
66type QueuedRunMessage = NonNullable<
67 NonNullable<ReturnType<typeof useThreadQueueWorkflow>>["queuedRuns"][number]["message"]
68>;
69​
70/** Who sent a queued message, as its sent form shows it in the thread. */
71function QueuedRunSender(props: {
72 readonly environmentId: EnvironmentId;
73 readonly message: QueuedRunMessage;
74}) {
75 const { attribution, scheduledTaskId } = resolveUserMessagePresentation(props.message);
76 const senderThreadId = attribution === "agent" ? props.message.senderThreadId : undefined;
77 const senderShell = useQuietThreadShell(
78 senderThreadId ? scopeThreadRef(props.environmentId, senderThreadId) : null,
79 );
80 const tasks = useEnvironmentQuery(
81 scheduledTaskId
82 ? serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} })
83 : null,
84 );
85 const sender =
86 attribution === "automation"
87 ? {
88 icon: "calendar.badge.clock" as const,
89 label:
90 tasks.data?.tasks.find((task) => task.id === scheduledTaskId)?.title ?? "Automation",
91 }
92 : attribution === "agent"
93 ? {
94 icon: "bubble.left.and.bubble.right" as const,
95 label: senderShell?.title.trim() || "Agent",
96 }
97 : attribution === "t3code"
98 ? { icon: null, label: "Sent by T3 Code" }
99 : null;
100 if (sender === null) return null;
101 return (
102 <View className="flex-row items-center gap-1">
103 {sender.icon ? (
104 <SymbolView
105 name={sender.icon}
106 size={11}
107 weight="medium"
108 tintColorClassName="accent-foreground-muted"
109 type="monochrome"
110 />
111 ) : null}
112 <Text
113 numberOfLines={1}
114 className="min-w-0 shrink font-t3-medium text-2xs text-foreground-muted"
115 >
116 {sender.label}
117 </Text>
118 </View>
119 );
121​
122export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
123 const { layout } = useAdaptiveWorkspaceLayout();
124 const target = route.params;
125 const navigation = useNavigation();
126 const insets = useSafeAreaInsets();
127 const theme = useUniwindTheme();
128 const workflow = useThreadQueueWorkflow(target);
129 const threadKey = scopedThreadKey(target.environmentId, target.threadId);
130 const editing = useQueuedRunEdit(threadKey);
131 const pendingRequests = useAtomValue(environmentThreadDetails.pendingRequestsAtom(target));
132 const editBlockedReason = queuedRunEditBlockedReason({
133 openQuestionCount: pendingRequests?.userInputs.length ?? 0,
134 });
135 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
136 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
137 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
138 const [resuming, setResuming] = useState(false);
139 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
140 const busyRef = useRef(false);
141 const queuedRuns = workflow?.queuedRuns ?? [];
142​
143 const hadQueuedRuns = useRef(queuedRuns.length > 0);
144 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops the navigator once the server-side queue empties after it had runs
145 useEffect(() => {
146 if (queuedRuns.length > 0) {
147 hadQueuedRuns.current = true;
148 return;
149 }
150 if (hadQueuedRuns.current) navigation.goBack();
151 }, [navigation, queuedRuns.length]);
152​
153 const act = async (runId: RunId, action: QueueAction) => {
154 if (busyRef.current) return;
155 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
156 if (index < 0) return;
157 if (action === "edit") {
158 if (editBlockedReason !== null) return;
159 const entry = queuedRuns[index]!;
160 void Haptics.selectionAsync();
161 beginQueuedRunEdit(
162 threadKey,
163 {
164 runId,
165 messageId: entry.messageId,
166 originalText: entry.text,
167 existingAttachments: entry.attachments,
168 ...(entry.context ? { context: entry.context } : {}),
169 },
170 makeQueuedRunsAtom({
171 threadId: target.threadId,
172 snapshot: threadEnvironment.snapshotAtom(target.environmentId),
173 detailStatus: environmentThreadDetails.statusAtom(target),
174 runs: Atom.make(
175 (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null,
176 ),
177 }),
178 );
179 navigation.goBack();
180 return;
181 }
182 if (action !== "steer" && action !== "remove") return;
183 busyRef.current = true;
184 setBusyRunId(runId);
185 void Haptics.selectionAsync();
186 if (action === "remove") {
187 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
188 } else if (workflow?.canSendNow) {
189 await resume({ ...target, input: { threadId: target.threadId, runId } });
190 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
191 await promote({
192 ...target,
193 input: {
194 threadId: target.threadId,
195 queuedRunId: runId,
196 targetRunId: workflow.activeRun.id,
197 },
198 });
199 }
200 busyRef.current = false;
201 setBusyRunId(null);
202 };
203​
204 const content = (
205 <ScrollView
206 nestedScrollEnabled
207 className="flex-1"
208 // UIKit must inset content beneath the floating translucent iOS header.
209 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
210 contentContainerClassName="px-5 pb-6"
211 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
212 >
213 {workflow?.isHeld && queuedRuns.length > 0 ? (
214 <View className="gap-2 py-3">
215 <Text className="text-sm text-foreground-muted">Queue paused</Text>
216 <Button
217 label="Resume queue"
218 disabled={resuming || busyRunId !== null}
219 onPress={async () => {
220 if (busyRef.current) return;
221 busyRef.current = true;
222 setResuming(true);
223 await resume({ ...target, input: { threadId: target.threadId } });
224 busyRef.current = false;
225 setResuming(false);
226 }}
227 />
228 </View>
229 ) : null}
230 {editBlockedReason !== null && queuedRuns.length > 0 ? (
231 <Text className="py-3 text-sm text-foreground-muted">{editBlockedReason}</Text>
232 ) : null}
233 {queuedRuns.length === 0 ? (
234 <Text className="pt-6 text-center text-sm text-foreground-muted">
235 No messages waiting in this queue.
236 </Text>
237 ) : null}
238 {queuedRuns.map(({ run, text, attachments, context, message }, index) => {
239 const controls = resolveThreadQueueRowControls({
240 busy: busyRunId !== null,
241 canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
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: Platform.OS === "ios" ? "arrow.up" : "arrow_upward",
270 },
271 ]
272 : []),
273 {
274 id: "edit",
275 title: "Edit",
276 attributes: { disabled: !controls.canEdit },
277 image: Platform.OS === "ios" ? "pencil" : "edit",
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 if (Platform.OS === "ios") {
362 // Plain formSheets lack stack headers; host one in a nested native stack.
363 return (
364 <GestureHandlerRootView style={{ flex: 1 }}>
365 <View collapsable={false} className="flex-1 bg-sheet">
366 <ScreenStack style={{ flex: 1 }}>
367 <Screen
368 activityState={2}
369 enabled
370 isNativeStack
371 screenId="thread-queue-sheet-native"
372 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
373 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
374 >
375 {content}
376 <ScreenStackHeaderConfig
377 backgroundColor="rgba(0,0,0,0)"
378 color={theme["--color-foreground"]}
379 hideBackButton
380 hideShadow={false}
381 title="Queued"
382 titleColor={theme["--color-foreground"]}
383 titleFontSize={18}
384 titleFontWeight="800"
385 translucent
386 />
387 </Screen>
388 </ScreenStack>
389 </View>
390 </GestureHandlerRootView>
391 );
392 }
393​
394 return (
395 <GestureHandlerRootView style={{ flex: 1 }}>
396 <View collapsable={false} className="flex-1 bg-sheet">
397 <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />
398 <AppBar sheet title="Queued" onBack={() => navigation.goBack()} />
399 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
400 </View>
401 </GestureHandlerRootView>
402 );
404​
405function QueueRowSwipeable(props: {
406 readonly enabled: boolean;
407 readonly background: string;
408 readonly onRemove: () => void;
409 readonly children: React.ReactNode;
410}) {
411 const swipeableRef = useRef<SwipeableMethods | null>(null);
412 return (
413 <ReanimatedSwipeable
414 ref={swipeableRef}
415 enabled={props.enabled}
416 friction={2}
417 rightThreshold={40}
418 overshootRight={false}
419 // Require a clearly sideways swipe to avoid competing with sheet scroll.
420 failOffsetY={[-12, 12]}
421 containerStyle={{ backgroundColor: props.background, flex: 1 }}
422 childrenContainerStyle={{ backgroundColor: props.background }}
423 onSwipeableOpen={(direction) => {
424 if (direction !== "right") return;
425 swipeableRef.current?.close();
426 props.onRemove();
427 }}
428 renderRightActions={() => (
429 <Pressable
430 accessibilityRole="button"
431 accessibilityLabel={REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL}
432 disabled={!props.enabled}
433 onPress={() => {
434 swipeableRef.current?.close();
435 props.onRemove();
436 }}
437 className="items-center justify-center bg-danger active:opacity-70 disabled:opacity-40"
438 style={{ width: REMOVE_ACTION_WIDTH }}
439 >
440 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
441 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
442 </Pressable>
443 )}
444 >
445 {props.children}
446 </ReanimatedSwipeable>
447 );
449​
450function QueueAttachmentThumbnails(props: {
451 readonly environmentId: EnvironmentId;
452 readonly attachments: ReadonlyArray<ChatAttachment>;
453}) {
454 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
455 const shown = images.slice(0, THUMBNAIL_LIMIT);
456 const overflow = props.attachments.length - shown.length;
457 if (props.attachments.length === 0) return null;
458 return (
459 <View className="shrink-0 flex-row items-center gap-1">
460 {shown.map((attachment) => (
461 <QueueAttachmentThumbnail
462 key={attachment.id}
463 environmentId={props.environmentId}
464 attachment={attachment}
465 />
466 ))}
467 {overflow > 0 ? (
468 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
469 <Text className="text-2xs tabular-nums text-foreground-muted">
470 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
471 </Text>
472 </View>
473 ) : null}
474 </View>
475 );
477​
478function QueueAttachmentThumbnail(props: {
479 readonly environmentId: EnvironmentId;
480 readonly attachment: ChatAttachment;
481}) {
482 const resource = {
483 _tag: "attachment",
484 attachmentId: props.attachment.id,
485 fileName: props.attachment.name,
486 mimeType: props.attachment.mimeType,
487 disposition: "inline",
488 } as const;
489 const url = useAssetUrl(props.environmentId, resource);
490 if (url === null) {
491 return <View className="h-6 w-6 rounded bg-subtle" />;
492 }
493 return (
494 <Image
495 source={assetImageSource(props.environmentId, resource, url)}
496 cachePolicy="memory-disk"
497 contentFit="cover"
498 style={{ width: 24, height: 24, borderRadius: 4 }}
499 accessibilityIgnoresInvertColors
500 />
501 );