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