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

main
tsx 220 lines 9.14 KB
Raw
1 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { AsyncResult } from "effect/reactivity";
4 import * as Dialog from "../../components/ui/Dialog";
5 import { TextInputWrapper } from "expo-paste-input";
6 import { AppTextInput as TextInput } from "../../components/ui/AppText";
7 import { useNativePaste } from "../../lib/useNativePaste";
8 import { convertPastedImagesToAttachments } from "../../lib/composerImages";
9 import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type UserInputQuestion } from "@t3tools/contracts";
10 import { useAtomValue } from "@effect/atom-react";
11 import { View, type TextInputInstance } from "react-native";
12 import { useEffect, useEffectEvent, useRef, useState } from "react";
13 import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
14 import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
15 import { useThreadSelection } from "../../state/use-thread-selection";
16 import { useNavigation } from "@react-navigation/native";
17 import { useGT } from "gt-react-native";
18 import { m } from "../../i18n/messages";
19 import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
20 import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
21 import { useServerConfigs } from "../../state/entities";
22 import { appAtomRegistry } from "../../state/atom-registry";
23 import {
24 appendComposerDraftAttachments,
25 composerDraftsAtom,
26 removeComposerDraftAttachment,
27 } from "../../state/use-composer-drafts";
28 import { questionAttachmentDraftKey } from "../../state/question-attachments";
29 import {
30 pickQuestionAttachments,
31 startQuestionImagePreparation,
32 } from "../../state/question-attachment-preparation";
33
34 export function QuestionAttachments(props: {
35 requestId: string;
36 question: UserInputQuestion;
37 questions: ReadonlyArray<UserInputQuestion>;
38 disabled: boolean;
39 value: string;
40 onChangeText: (value: string) => void;
41 onInputFocusChange?: ((focused: boolean) => void) | undefined;
42 }) {
43 const gt = useGT();
44 const { selectedThread } = useThreadSelection();
45 const navigation = useNavigation();
46 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
47 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
48 const configs = useServerConfigs();
49 const drafts = useAtomValue(composerDraftsAtom);
50 const focusedRef = useRef(false);
51 const onInputFocusChange = props.onInputFocusChange;
52 // The caller keys this component by request and question, so unmounting ends any open
53 // picker's scope.
54 const pickerScope = useRef<{ active: boolean }>({ active: false });
55 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens a scope that native picker and paste callbacks check, and closes it on unmount
56 useEffect(() => {
57 const scope = { active: true };
58 pickerScope.current = scope;
59 return () => {
60 scope.active = false;
61 };
62 }, []);
63 // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.
64 const releaseFocus = useEffectEvent(() => {
65 if (focusedRef.current) onInputFocusChange?.(false);
66 });
67 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases keyboard ownership on unmount, since an unmounted native input never emits blur
68 useEffect(() => () => releaseFocus(), []);
69 // A controlled value makes Fabric rebuild the native text on every keystroke, which discards
70 // iOS's pending autocorrection. The input owns its text; the only outside write is an option
71 // selection clearing the draft.
72 const inputRef = useRef<TextInputInstance>(null);
73 const [initialText] = useState(props.value);
74 const nativeText = useRef(props.value);
75 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes an option selection's cleared draft into the uncontrolled native input
76 useEffect(() => {
77 if (props.value !== "" || nativeText.current === "") return;
78 nativeText.current = "";
79 inputRef.current?.clear();
80 }, [props.value]);
81 const append = (
82 key: string,
83 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
84 ) => {
85 if (!selectedThread) return 0;
86 const current = appAtomRegistry.get(composerDraftsAtom);
87 const otherCount = props.questions.reduce((count, question) => {
88 const target = questionAttachmentDraftKey(
89 selectedThread.environmentId,
90 selectedThread.id,
91 props.requestId,
92 question.id,
93 );
94 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
95 }, 0);
96 return appendComposerDraftAttachments(key, attachments, {
97 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
98 });
99 };
100 const paste = useNativePaste((uris) => {
101 const scope = pickerScope.current;
102 if (!selectedThread || props.disabled || !configs.get(selectedThread.environmentId)) return;
103 const key = questionAttachmentDraftKey(
104 selectedThread.environmentId,
105 selectedThread.id,
106 props.requestId,
107 props.question.id,
108 );
109 const preparation = startQuestionImagePreparation(key);
110 void convertPastedImagesToAttachments({ uris })
111 .then((result) =>
112 preparation.complete(result, {
113 isActive: () => scope.active,
114 append: (attachments) => append(key, attachments),
115 }),
116 )
117 .then(({ error, rejected }) => {
118 const problems = [
119 ...(error ? [error] : []),
120 ...(rejected > 0 ? [gt("Too many attachments.")] : []),
121 ];
122 if (problems.length) Dialog.alert(gt("Could not paste image"), problems.join("\n\n"));
123 })
124 .catch((error) =>
125 Dialog.alert(
126 gt("Could not paste image"),
127 errorDisplayMessage(error, m) ?? gt("Try again."),
128 ),
129 )
130 .finally(preparation.finish);
131 });
132 if (!selectedThread || props.question.allowCustomAnswer === false) return null;
133 const { environmentId, id: threadId } = selectedThread;
134 const capabilities = configs.get(environmentId)?.environment.capabilities;
135 const canAttach = capabilities !== undefined;
136 const key = questionAttachmentDraftKey(
137 environmentId,
138 threadId,
139 props.requestId,
140 props.question.id,
141 );
142 const attachments = drafts[key]?.attachments ?? [];
143 const pick = async (kind: "media" | "files") => {
144 const scope = pickerScope.current;
145 const picked = await settlePromise(async () => {
146 const result = await pickQuestionAttachments({
147 key,
148 kind,
149 maxUploadBytes: capabilities?.fileAttachments?.maxUploadBytes,
150 isActive: () => scope.active,
151 append: (attachments) => append(key, attachments),
152 });
153 if (result.error || result.rejected > 0)
154 Dialog.alert(gt("Could not attach file"), result.error ?? gt("Too many attachments."));
155 });
156 if (AsyncResult.isFailure(picked)) {
157 const error = squashAtomCommandFailure(picked);
158 Dialog.alert(gt("Could not attach file"), errorDisplayMessage(error, m) ?? gt("Try again."));
159 }
160 };
161 return (
162 <View className="gap-2">
163 {canAttach ? (
164 <ComposerAttachmentButton
165 disabled={props.disabled}
166 supportsFiles
167 onPickMedia={() => pick("media")}
168 onPickFiles={() => pick("files")}
169 />
170 ) : null}
171 <ComposerAttachmentStrip
172 environmentId={environmentId}
173 attachments={attachments}
174 onRemove={(id) => {
175 if (!props.disabled) removeComposerDraftAttachment(key, id);
176 }}
177 onPressPreview={setPreviewFile}
178 onPressVideo={(attachment, sourceIdentifier) =>
179 setPreviewVideo({ type: "local", attachment, sourceIdentifier })
180 }
181 onPressDocument={(attachment) =>
182 navigation.navigate("ThreadAttachment", {
183 environmentId: String(environmentId),
184 threadId: String(threadId),
185 attachmentId: attachment.id,
186 name: attachment.name,
187 mimeType: attachment.mimeType,
188 sizeBytes: String(attachment.sizeBytes),
189 draftKey: key,
190 })
191 }
192 />
193 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
194 <VideoPreviewModal source={previewVideo} onRequestClose={() => setPreviewVideo(null)} />
195 <TextInputWrapper onPaste={paste}>
196 <TextInput
197 ref={inputRef}
198 defaultValue={initialText}
199 multiline={props.question.initialAnswer !== undefined}
200 submitBehavior={props.question.initialAnswer !== undefined ? "newline" : undefined}
201 editable={!props.disabled}
202 onChangeText={(text) => {
203 nativeText.current = text;
204 props.onChangeText(text);
205 }}
206 onFocus={() => {
207 focusedRef.current = true;
208 onInputFocusChange?.(true);
209 }}
210 onBlur={() => {
211 focusedRef.current = false;
212 onInputFocusChange?.(false);
213 }}
214 placeholder={gt("Or type a custom answer")}
215 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
216 />
217 </TextInputWrapper>
218 </View>
219 );
220 }