Open History to see the last commit
1import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2import { useAtomValue } from "@effect/atom-react";
3import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
4import * as Haptics from "expo-haptics";
5import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
6import { Animated, Platform, Pressable, ScrollView, View } from "react-native";
7import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9
10import { AppText as Text } from "../../components/AppText";
11import { SymbolView } from "../../components/AppSymbol";
12import { ControlPillMenu } from "../../components/ControlPill";
13import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
14import { useAtomCommand } from "../../state/use-atom-command";
15import { WorkingTimer } from "./floating-working-control";
16import {
17 buildCancelQueuedRunCommand,
18 resolveThreadQueueRowControls,
19 resolveQueueDropBeforeRunId,
20} from "./threadQueueControlPresentation";
21
22type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
23
24export function useThreadQueueWorkflow(target: QueueTarget) {
25 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
26}
27
28export function useThreadQueuedCount(target: QueueTarget) {
29 return useAtomValue(environmentThreadDetails.queuedCountAtom(target));
30}
31
32export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
33 const target = route.params;
34 const navigation = useNavigation();
35 const insets = useSafeAreaInsets();
36 const workflow = useThreadQueueWorkflow(target);
37 const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
38 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
39 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
40 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
41 const busyRef = useRef(false);
42 const [draggedRunId, setDraggedRunId] = useState<RunId | null>(null);
43 const rowLayouts = useRef(new Map<RunId, { y: number; height: number }>());
44 const drag = useRef<{ runId: RunId; order: string } | null>(null);
45 const [translation] = useState(() => new Animated.Value(0));
46 const [selectedRunId, setSelectedRunId] = useState<RunId | null>(
47 () => workflow?.queuedRuns[0]?.run.id ?? null,
48 );
49 const queuedRuns = workflow?.queuedRuns ?? [];
50 const order = queuedRuns.map(({ run }) => run.id).join(",");
51
52 useEffect(() => {
53 if (drag.current && drag.current.order !== order) {
54 drag.current = null;
55 setDraggedRunId(null);
56 translation.setValue(0);
57 }
58 }, [order, translation]);
59
60 const move = async (runId: RunId, beforeRunId: RunId | null) => {
61 if (busyRef.current || !workflow?.canReorder) return;
62 busyRef.current = true;
63 setBusyRunId(runId);
64 void Haptics.selectionAsync();
65 try {
66 await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
67 } finally {
68 busyRef.current = false;
69 setBusyRunId(null);
70 }
71 };
72
73 const act = async (runId: RunId, action: string) => {
74 if (busyRef.current) return;
75 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
76 if (index < 0) return;
77 if (action === "up" && index > 0) {
78 await move(runId, queuedRuns[index - 1]!.run.id);
79 return;
80 }
81 if (action === "down" && index < queuedRuns.length - 1) {
82 await move(runId, queuedRuns[index + 2]?.run.id ?? null);
83 return;
84 }
85 if (action !== "steer" && action !== "remove") return;
86 busyRef.current = true;
87 setBusyRunId(runId);
88 void Haptics.selectionAsync();
89 try {
90 if (action === "remove") {
91 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
92 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
93 await promote({
94 ...target,
95 input: {
96 threadId: target.threadId,
97 queuedRunId: runId,
98 targetRunId: workflow.activeRun.id,
99 },
100 });
101 }
102 } finally {
103 busyRef.current = false;
104 setBusyRunId(null);
105 }
106 };
107
108 return (
109 <GestureHandlerRootView style={{ flex: 1 }}>
110 <View
111 collapsable={false}
112 className="flex-1 bg-sheet"
113 style={{ paddingBottom: insets.bottom }}
114 >
115 <View className="flex-row items-center justify-between px-5 pt-5 pb-2">
116 <Text accessibilityRole="header" className="min-w-0 flex-1 font-t3-semibold text-lg">
117 Queued messages <Text className="text-foreground-muted">{queuedRuns.length}</Text>
118 </Text>
119 <Pressable
120 accessibilityRole="button"
121 onPress={() => navigation.goBack()}
122 className="min-h-12 justify-center px-3 active:opacity-70"
123 >
124 <Text className="font-t3-medium text-base text-primary">Done</Text>
125 </Pressable>
126 </View>
127 <View className="gap-2 px-5 pb-4">
128 {workflow?.activeRun?.startedAt ? (
129 <WorkingTimer
130 startedAt={new Date(workflow.activeRun.startedAt.epochMilliseconds).toISOString()}
131 />
132 ) : null}
133 <Text className="text-sm text-foreground-muted">
134 {queuedRuns.length === 0
135 ? "No messages waiting in this queue."
136 : "Queued messages run in order after this turn."}
137 </Text>
138 </View>
139 <ScrollView
140 className="flex-1"
141 scrollEnabled={draggedRunId === null}
142 contentContainerClassName="px-5 pb-6"
143 >
144 {queuedRuns.map(({ run, text, attachments }, index) => {
145 const controls = resolveThreadQueueRowControls({
146 busy: busyRunId !== null || draggedRunId !== null,
147 canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
148 canReorder: workflow?.canReorder ?? false,
149 index,
150 queuedCount: queuedRuns.length,
151 text,
152 });
153 const title =
154 controls.displayText || (attachments.length > 0 ? "Attachments" : "Queued message");
155 return (
156 <View
157 key={run.id}
158 style={{ zIndex: draggedRunId === run.id ? 1 : 0 }}
159 onLayout={({ nativeEvent }) => rowLayouts.current.set(run.id, nativeEvent.layout)}
160 >
161 <Animated.View
162 className="flex-row items-center gap-3 border-b border-border bg-sheet py-4"
163 style={
164 draggedRunId === run.id
165 ? { transform: [{ translateY: translation }], zIndex: 1, opacity: 0.85 }
166 : undefined
167 }
168 >
169 <Text className="w-5 text-sm tabular-nums text-foreground-muted">
170 {index + 1}
171 </Text>
172 <View className="min-w-0 flex-1 gap-2">
173 <Pressable
174 accessibilityRole="button"
175 accessibilityLabel={title}
176 accessibilityState={{ expanded: selectedRunId === run.id }}
177 disabled={busyRunId !== null || draggedRunId !== null}
178 onPress={() => setSelectedRunId(selectedRunId === run.id ? null : run.id)}
179 className="min-h-12 justify-center"
180 >
181 <Text className="text-base">{title}</Text>
182 </Pressable>
183 {selectedRunId === run.id ? (
184 <View className="flex-row flex-wrap gap-2">
185 {workflow?.canPromoteToSteer ? (
186 <Pressable
187 accessibilityRole="button"
188 disabled={!controls.canSteer}
189 onPress={() => void act(run.id, "steer")}
190 className="min-h-12 justify-center rounded-xl bg-primary px-3 disabled:opacity-40"
191 >
192 <Text className="font-t3-medium text-sm text-primary-foreground">
193 Steer now
194 </Text>
195 </Pressable>
196 ) : null}
197 <Pressable
198 accessibilityRole="button"
199 accessibilityLabel="Remove queued message"
200 disabled={!controls.canDismiss}
201 onPress={() => void act(run.id, "remove")}
202 className="min-h-12 justify-center rounded-xl bg-card px-3 disabled:opacity-40"
203 >
204 <Text className="text-sm">Remove</Text>
205 </Pressable>
206 </View>
207 ) : null}
208 {attachments.length > 0 ? (
209 <Text className="text-xs text-foreground-muted">
210 {attachments.length} attachment{attachments.length === 1 ? "" : "s"}
211 </Text>
212 ) : null}
213 </View>
214 <ControlPillMenu
215 accessibilityLabel={`Actions for queued message ${index + 1}`}
216 actions={[
217 {
218 id: "steer",
219 title: "Steer now",
220 attributes: { disabled: !controls.canSteer },
221 image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
222 },
223 { id: "up", title: "Move up", attributes: { disabled: !controls.canMoveUp } },
224 {
225 id: "down",
226 title: "Move down",
227 attributes: { disabled: !controls.canMoveDown },
228 },
229 {
230 id: "remove",
231 title: "Remove",
232 attributes: { disabled: !controls.canDismiss, destructive: true },
233 },
234 ]}
235 onPressAction={({ nativeEvent }) => void act(run.id, nativeEvent.event)}
236 >
237 <View className="h-12 w-10 items-center justify-center">
238 <SymbolView
239 name="ellipsis"
240 size={18}
241 tintColorClassName="accent-foreground-muted"
242 />
243 </View>
244 </ControlPillMenu>
245 {workflow?.canReorder && queuedRuns.length > 1 ? (
246 <QueueDragHandle
247 disabled={busyRunId !== null}
248 title={title}
249 canMoveUp={controls.canMoveUp}
250 canMoveDown={controls.canMoveDown}
251 onStep={(action) => void act(run.id, action)}
252 onStart={() => {
253 drag.current = { runId: run.id, order };
254 translation.setValue(0);
255 setDraggedRunId(run.id);
256 void Haptics.selectionAsync();
257 }}
258 onMove={(y) => translation.setValue(y)}
259 onEnd={(y, success) => {
260 const started = drag.current;
261 drag.current = null;
262 setDraggedRunId(null);
263 translation.setValue(0);
264 // A remote reorder or a newly started run invalidates this drag.
265 if (!success || started?.order !== order || started.runId !== run.id)
266 return;
267 const before = resolveQueueDropBeforeRunId(
268 queuedRuns.map(({ run: item }) => ({
269 id: item.id,
270 ...rowLayouts.current.get(item.id),
271 })),
272 run.id,
273 y,
274 );
275 if (before !== undefined) void move(run.id, before);
276 }}
277 />
278 ) : null}
279 </Animated.View>
280 </View>
281 );
282 })}
283 {workflow?.canReorder && queuedRuns.length > 1 ? (
284 <Text className="pt-5 text-center text-xs text-foreground-muted">
285 Drag the handles to reorder
286 </Text>
287 ) : null}
288 </ScrollView>
289 </View>
290 </GestureHandlerRootView>
291 );
292}
293
294function QueueDragHandle(props: {
295 disabled: boolean;
296 title: string;
297 canMoveUp: boolean;
298 canMoveDown: boolean;
299 onStep: (action: "up" | "down") => void;
300 onStart: () => void;
301 onMove: (y: number) => void;
302 onEnd: (y: number, success: boolean) => void;
303}) {
304 const latest = useRef(props);
305 useLayoutEffect(() => {
306 latest.current = props;
307 });
308 const gesture = useMemo(
309 () =>
310 Gesture.Pan()
311 .enabled(!props.disabled)
312 .minDistance(0)
313 .shouldCancelWhenOutside(false)
314 .runOnJS(true)
315 .onStart(() => latest.current.onStart())
316 .onUpdate((event) => latest.current.onMove(event.translationY))
317 .onFinalize((event, success) => latest.current.onEnd(event.translationY, success)),
318 [props.disabled],
319 );
320 return (
321 <GestureDetector gesture={gesture}>
322 <View
323 collapsable={false}
324 accessible
325 accessibilityRole="adjustable"
326 accessibilityLabel={`Reorder ${props.title}`}
327 accessibilityState={{ disabled: props.disabled }}
328 accessibilityActions={[
329 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
330 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
331 ]}
332 onAccessibilityAction={({ nativeEvent }) => {
333 if (props.disabled) return;
334 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
335 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
336 }}
337 className="h-12 w-10 items-center justify-center"
338 >
339 <SymbolView
340 name="line.3.horizontal"
341 size={18}
342 tintColorClassName="accent-foreground-muted"
343 />
344 </View>
345 </GestureDetector>
346 );
347}