Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useCallback, useEffect, useMemo, useState } from "react";
3import { Alert } from "react-native";
4import * as Cause from "effect/Cause";
5
6import {
7 CommandId,
8 MessageId,
9 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
10 type EnvironmentId,
11 type ModelSelection,
12 type ProviderInteractionMode,
13 type RuntimeMode,
14 type ThreadId,
15} from "@t3tools/contracts";
16import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
17import {
18 codexFeedbackMessage,
19 parseCodexFeedbackCommand,
20 submitCodexFeedback,
21 type CodexFeedbackSubmission,
22} from "@t3tools/client-runtime/state/threads";
23import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
24import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
25
26import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
27import {
28 convertPastedImagesToAttachments,
29 pasteComposerClipboard,
30 pickComposerFiles,
31 pickComposerImages,
32} from "../lib/composerImages";
33import type { DraftComposerImageAttachment } from "../lib/composerImages";
34import { scopedThreadKey } from "../lib/scopedEntities";
35import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
36import { buildThreadFeed } from "../lib/threadActivity";
37import { appAtomRegistry } from "../state/atom-registry";
38import {
39 appendComposerDraftAttachments,
40 appendComposerDraftText,
41 clearComposerDraftContent,
42 composerDraftsAtom,
43 ensureComposerDraftsLoaded,
44 getComposerDraftSnapshot,
45 mergeComposerDraftContent,
46 removeComposerDraftAttachment,
47 scheduleUnusedComposerAttachmentCleanup,
48 setComposerDraftText,
49 updateComposerDraftSettings,
50 useComposerDraft,
51} from "./use-composer-drafts";
52import { setPendingConnectionError } from "../state/use-remote-environment-registry";
53import { useSelectedThreadDetail } from "../state/use-thread-detail";
54import { useThreadSelection } from "../state/use-thread-selection";
55import { enqueueThreadOutboxMessage } from "./thread-outbox";
56import { useThreadOutboxMessages } from "./use-thread-outbox";
57import { threadEnvironment } from "./threads";
58import { useAtomCommand } from "./use-atom-command";
59
60export function appendReviewCommentToDraft(input: {
61 readonly environmentId: EnvironmentId;
62 readonly threadId: ThreadId;
63 readonly text: string;
64 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
65}): void {
66 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
67 const existing = appAtomRegistry.get(composerDraftsAtom)[threadKey]?.text ?? "";
68 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
69 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
70 if (input.attachments && input.attachments.length > 0) {
71 // Capped: a review comment is new content, not a send-failure restore, so
72 // it must not push the draft over the send limit. Overflow is released.
73 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments);
74 if (rejectedCount > 0) {
75 setPendingConnectionError(
76 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
77 );
78 }
79 }
80}
81
82export function useThreadDraftForThread(input: {
83 readonly environmentId?: EnvironmentId;
84 readonly threadId?: ThreadId;
85}) {
86 const threadKey =
87 input.environmentId && input.threadId
88 ? scopedThreadKey(input.environmentId, input.threadId)
89 : null;
90 const draft = useComposerDraft(threadKey);
91
92 return {
93 draftMessage: draft.text,
94 draftAttachments: draft.attachments,
95 };
96}
97
98export function useThreadComposerState() {
99 const { selectedThread: selectedThreadShell, selectedEnvironmentRuntime } = useThreadSelection();
100 const selectedThreadDetail = useSelectedThreadDetail();
101 const composerDrafts = useAtomValue(composerDraftsAtom);
102 const queuedMessagesByThreadKey = useThreadOutboxMessages();
103 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
104 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
105 >({});
106 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
107 reportFailure: false,
108 });
109
110 useEffect(() => {
111 ensureComposerDraftsLoaded();
112 }, []);
113
114 const selectedThreadKey = selectedThreadShell
115 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
116 : null;
117 const selectedThreadQueuedMessages = useMemo(
118 () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
119 [queuedMessagesByThreadKey, selectedThreadKey],
120 );
121 const selectedThreadFeed = useMemo(() => {
122 if (!selectedThreadDetail) {
123 return [];
124 }
125 const submissions = selectedThreadKey
126 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
127 : [];
128 return buildThreadFeed(selectedThreadDetail, {
129 localMessages: submissions.flatMap((submission) =>
130 submission.status === "interrupted"
131 ? []
132 : [codexFeedbackMessage(submission), codexFeedbackMessage(submission, "assistant")],
133 ),
134 });
135 }, [feedbackSubmissionsByThreadKey, selectedThreadDetail, selectedThreadKey]);
136
137 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
138 const draftMessage = selectedDraft?.text ?? "";
139 const draftAttachments = selectedDraft?.attachments ?? [];
140 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
141 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
142 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
143 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
144 const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
145
146 const selectedThreadSessionActivity = useMemo(() => {
147 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
148 if (!selectedThread?.session) {
149 return null;
150 }
151
152 return {
153 orchestrationStatus: selectedThread.session.status,
154 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
155 };
156 }, [selectedThreadDetail, selectedThreadShell]);
157
158 const activeWorkStartedAt = useMemo(() => {
159 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
160 if (!selectedThread) {
161 return null;
162 }
163
164 return deriveActiveWorkStartedAt(
165 selectedThread.latestTurn,
166 selectedThreadSessionActivity,
167 null,
168 );
169 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
170
171 const onSendMessage = useCallback(async () => {
172 if (!selectedThreadShell) {
173 return null;
174 }
175
176 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
177 const draft = getComposerDraftSnapshot(threadKey);
178 const thread = selectedThreadDetail ?? selectedThreadShell;
179 const text = draft.text.trim();
180 const attachments = draft.attachments;
181 if (text.length === 0 && attachments.length === 0) {
182 return null;
183 }
184 // A send-failure restore appends with allowOverflow so it never drops the
185 // user's files, which can leave the draft over the cap. Sending it anyway
186 // would enqueue a message that outbox recovery rejects forever, so block
187 // here until the user removes attachments.
188 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
189 Alert.alert(
190 "Too many attachments",
191 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
192 );
193 return null;
194 }
195
196 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
197 (entry) => entry.instanceId === thread.modelSelection.instanceId,
198 );
199 const feedbackCommand =
200 attachments.length === 0 &&
201 (provider?.driver === "codex" || thread.session?.providerName === "codex")
202 ? parseCodexFeedbackCommand(text)
203 : null;
204 if (feedbackCommand) {
205 if (thread.session === null) {
206 Alert.alert("Start a Codex thread first", "Send a message before you submit feedback.");
207 return null;
208 }
209 const metadata = makeQueuedMessageMetadata();
210 const result = await submitCodexFeedback({
211 submission: {
212 id: MessageId.make(metadata.messageId),
213 command: text,
214 createdAt: metadata.createdAt,
215 },
216 clearDraft: () => clearComposerDraftContent(threadKey),
217 onUpdate: (submission) => {
218 setFeedbackSubmissionsByThreadKey((current) => {
219 const existing = current[threadKey] ?? [];
220 const found = existing.some((entry) => entry.id === submission.id);
221 return {
222 ...current,
223 [threadKey]: found
224 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
225 : [...existing, submission],
226 };
227 });
228 },
229 upload: () =>
230 uploadThreadFeedback({
231 environmentId: selectedThreadShell.environmentId,
232 input: {
233 threadId: selectedThreadShell.id,
234 ...feedbackCommand,
235 },
236 }),
237 });
238 if (result._tag === "Failure") {
239 if (isAtomCommandInterrupted(result)) {
240 return null;
241 }
242 const error = Cause.squash(result.cause);
243 Alert.alert(
244 "Could not send feedback to OpenAI",
245 error instanceof Error ? error.message : "An error occurred.",
246 );
247 return null;
248 }
249 const feedbackId = result.value.feedbackId;
250 Alert.alert("Feedback sent to OpenAI", `Thread ID: ${feedbackId}`, [
251 { text: "OK", style: "cancel" },
252 {
253 text: "Copy ID",
254 onPress: () => copyTextWithHaptic(feedbackId, { target: "Codex feedback thread ID" }),
255 },
256 ]);
257 return null;
258 }
259
260 const metadata = makeQueuedMessageMetadata();
261 const messageId = MessageId.make(metadata.messageId);
262 // Enqueue publishes the queued atom synchronously (the durable write
263 // happens behind it), so clearing the draft here gives send feedback on
264 // the tap frame instead of after file I/O. If the write fails the message
265 // is rolled out of the queue and the content is merged back into the
266 // draft, preserving anything typed since.
267 const enqueuePromise = enqueueThreadOutboxMessage({
268 environmentId: selectedThreadShell.environmentId,
269 threadId: selectedThreadShell.id,
270 messageId,
271 commandId: CommandId.make(metadata.commandId),
272 text,
273 attachments,
274 modelSelection: draft.modelSelection ?? thread.modelSelection,
275 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
276 interactionMode: draft.interactionMode ?? thread.interactionMode,
277 createdAt: metadata.createdAt,
278 });
279 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
280 enqueuePromise.then(
281 () => {
282 // The queued message owns the files now; the sweep sees that and
283 // spares them. Deferred to here so a failed write cannot roll the
284 // message out of the queue mid-sweep and lose the bytes.
285 scheduleUnusedComposerAttachmentCleanup(attachments);
286 },
287 (error: unknown) => {
288 // Restore text via merge (idempotent) but attachments via the uncapped
289 // append: the merge path slots existing attachments first and truncates
290 // at the send limit, which would silently drop this message's images if
291 // the user attached new ones while the write was in flight.
292 void mergeComposerDraftContent(threadKey, { text, attachments: [] });
293 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
294 setPendingConnectionError(
295 error instanceof Error ? error.message : "Failed to save the queued message.",
296 );
297 },
298 );
299 return messageId;
300 }, [
301 selectedEnvironmentRuntime?.serverConfig?.providers,
302 selectedThreadDetail,
303 selectedThreadShell,
304 uploadThreadFeedback,
305 ]);
306
307 const onChangeDraftMessage = useCallback(
308 (value: string) => {
309 if (!selectedThreadShell) {
310 return;
311 }
312
313 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
314 setComposerDraftText(threadKey, value);
315 },
316 [selectedThreadShell],
317 );
318
319 const onPickDraftImages = useCallback(async () => {
320 if (!selectedThreadShell) {
321 return;
322 }
323
324 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
325 const result = await pickComposerImages({
326 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
327 });
328 const rejectedImageCount = appendComposerDraftAttachments(threadKey, result.images);
329 const problems = [
330 ...(result.error ? [result.error] : []),
331 ...(rejectedImageCount > 0
332 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
333 : []),
334 ];
335 if (problems.length > 0) {
336 Alert.alert("Could not attach image", problems.join("\n\n"));
337 }
338 }, [composerDrafts, selectedThreadShell]);
339
340 const onPickDraftFiles = useCallback(async () => {
341 if (!selectedThreadShell) {
342 return;
343 }
344 const maxBytes =
345 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
346 ?.maxUploadBytes;
347 if (maxBytes === undefined) {
348 Alert.alert("Could not attach file", "This server does not support file attachments.");
349 return;
350 }
351
352 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
353 // pickComposerFiles clamps the advertised limit to the contract maximum.
354 const result = await pickComposerFiles({
355 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
356 maxBytes,
357 });
358 const rejectedCount = appendComposerDraftAttachments(threadKey, result.files);
359 // The picker error and the live-cap rejection can both happen in one
360 // pick; report both in a single alert.
361 const problems = [
362 ...(result.error ? [result.error] : []),
363 ...(rejectedCount > 0
364 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
365 : []),
366 ];
367 if (problems.length > 0) {
368 Alert.alert("Could not attach file", problems.join("\n\n"));
369 }
370 }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
371
372 const onPasteIntoDraft = useCallback(async () => {
373 if (!selectedThreadShell) {
374 return;
375 }
376
377 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
378 const result = await pasteComposerClipboard({
379 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
380 });
381 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images);
382 if (result.text) {
383 appendComposerDraftText(threadKey, result.text);
384 }
385 if (result.error) {
386 setPendingConnectionError(result.error);
387 } else if (rejectedPasteCount > 0) {
388 setPendingConnectionError(
389 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
390 );
391 }
392 }, [composerDrafts, selectedThreadShell]);
393
394 const onNativePasteImages = useCallback(
395 async (uris: ReadonlyArray<string>) => {
396 if (!selectedThreadShell || uris.length === 0) {
397 return;
398 }
399
400 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
401 try {
402 const images = await convertPastedImagesToAttachments({
403 uris,
404 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
405 });
406 if (images.length > 0) {
407 appendComposerDraftAttachments(threadKey, images);
408 }
409 } catch (error) {
410 console.error("[native paste] error converting images", {
411 environmentId: selectedThreadShell.environmentId,
412 threadId: selectedThreadShell.id,
413 uriCount: uris.length,
414 ...safeErrorLogAttributes(error),
415 });
416 }
417 },
418 [composerDrafts, selectedThreadShell],
419 );
420
421 const onRemoveDraftImage = useCallback(
422 (imageId: string) => {
423 if (!selectedThreadShell) {
424 return;
425 }
426
427 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
428 removeComposerDraftAttachment(threadKey, imageId);
429 },
430 [selectedThreadShell],
431 );
432
433 const onUpdateModelSelection = useCallback(
434 (value: ModelSelection) => {
435 if (!selectedThreadKey) {
436 return;
437 }
438 updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
439 },
440 [selectedThreadKey],
441 );
442
443 const onUpdateRuntimeMode = useCallback(
444 (value: RuntimeMode) => {
445 if (!selectedThreadKey) {
446 return;
447 }
448 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
449 },
450 [selectedThreadKey],
451 );
452
453 const onUpdateInteractionMode = useCallback(
454 (value: ProviderInteractionMode) => {
455 if (!selectedThreadKey) {
456 return;
457 }
458 updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
459 },
460 [selectedThreadKey],
461 );
462
463 return {
464 selectedThreadFeed,
465 selectedThreadQueueCount,
466 activeWorkStartedAt,
467 draftMessage,
468 draftAttachments,
469 modelSelection,
470 runtimeMode,
471 interactionMode,
472 onChangeDraftMessage,
473 onPickDraftImages,
474 onPickDraftFiles,
475 onPasteIntoDraft,
476 onNativePasteImages,
477 onRemoveDraftImage,
478 onSendMessage,
479 onUpdateModelSelection,
480 onUpdateRuntimeMode,
481 onUpdateInteractionMode,
482 };
483}