@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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