Open History to see the last commit
1import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";
2import { useAtomValue } from "@effect/atom-react";
3import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4import { Alert } from "react-native";
5import * as Cause from "effect/Cause";
6
7import {
8 CommandId,
9 DEFAULT_PROVIDER_INTERACTION_MODE,
10 MessageId,
11 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
12 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
13 type EnvironmentId,
14 type ModelSelection,
15 type ProviderInteractionMode,
16 type RuntimeMode,
17 type ThreadId,
18} from "@t3tools/contracts";
19import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
20import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
21import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
22import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
23import {
24 isReconnectMcpCommand,
25 parseCodexFeedbackCommand,
26 submitCodexFeedback,
27 type CodexFeedbackSubmission,
28} from "@t3tools/client-runtime/state/threads";
29import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
30import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
31import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
32import { uuidv4 } from "../lib/uuid";
33
34import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
35import { isModelSelectionUnavailable } from "../lib/modelOptions";
36import { resolveProviderInteractionMode } from "../features/threads/legacy-plan-mode";
37import {
38 convertPastedImagesToAttachments,
39 createPastedTextComposerAttachment,
40 pasteComposerClipboard,
41 pickComposerFiles,
42 pickComposerMedia,
43 removePersistedComposerAttachmentFile,
44} from "../lib/composerImages";
45import type { DraftComposerImageAttachment } from "../lib/composerImages";
46import { scopedThreadKey } from "../lib/scopedEntities";
47import { buildThreadFeed } from "../lib/threadActivity";
48import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
49import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
50import { appAtomRegistry } from "../state/atom-registry";
51import { pendingThreadCreationMessage } from "./pending-thread-creation";
52import {
53 appendComposerDraftAttachments,
54 captureComposerDraftInsertion,
55 countComposerDraftAttachmentsAfterSelection,
56 insertComposerDraftText,
57 insertComposerDraftContext,
58 clearComposerDraftContent,
59 composerDraftsAtom,
60 composerContextImportsAtom,
61 ensureComposerDraftsLoaded,
62 getComposerDraftSnapshot,
63 mergeComposerDraftContent,
64 removeComposerDraftAttachment,
65 scheduleUnusedComposerAttachmentCleanup,
66 setComposerDraftText,
67 updateComposerDraftSettings,
68 useComposerDraft,
69} from "./use-composer-drafts";
70import { setPendingConnectionError } from "../state/use-remote-environment-registry";
71import { useSelectedThreadDetail } from "../state/use-thread-detail";
72import { useThreadSelection } from "../state/use-thread-selection";
73import { enqueueThreadOutboxMessage } from "./thread-outbox";
74import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
75import { threadEnvironment } from "./threads";
76import { useAtomCommand } from "./use-atom-command";
77import {
78 composerAttachmentUploadBlockReason,
79 composerAttachmentUploadsAtom,
80} from "./composer-attachment-uploads";
81
82export function appendReviewCommentToDraft(input: {
83 readonly environmentId: EnvironmentId;
84 readonly threadId: ThreadId;
85 readonly text: string;
86 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
87}): void {
88 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
89 const upgraded = upgradeLegacyContextMessage(input.text);
90 if (
91 !insertComposerDraftContext(
92 threadKey,
93 reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4),
94 )
95 ) {
96 Alert.alert("Too many context items", "Remove some context from the draft and try again.");
97 return;
98 }
99 if (input.attachments && input.attachments.length > 0) {
100 // Capped: a review comment is new content, not a send-failure restore, so
101 // it must not push the draft over the send limit. Overflow is released.
102 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
103 appendReference: true,
104 });
105 if (rejectedCount > 0) {
106 setPendingConnectionError(
107 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
108 );
109 }
110 }
111}
112
113export function useThreadDraftForThread(input: {
114 readonly environmentId?: EnvironmentId;
115 readonly threadId?: ThreadId;
116}) {
117 const threadKey =
118 input.environmentId && input.threadId
119 ? scopedThreadKey(input.environmentId, input.threadId)
120 : null;
121 const draft = useComposerDraft(threadKey);
122
123 return {
124 draftMessage: draft.text,
125 draftAttachments: draft.attachments,
126 };
127}
128
129export function useThreadComposerState() {
130 const {
131 selectedThread: selectedThreadShell,
132 selectedThreadCreation,
133 selectedEnvironmentRuntime,
134 } = useThreadSelection();
135 const selectedThreadDetail = useSelectedThreadDetail();
136 const composerDrafts = useAtomValue(composerDraftsAtom);
137 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
138 const queuedMessagesByThreadKey = useThreadOutboxMessages();
139 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
140 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
141 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
142 >({});
143 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
144 reportFailure: false,
145 });
146 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, {
147 reportFailure: false,
148 });
149 const pastedTextFileNamesRef = useRef<{ threadKey: string | null; names: Set<string> }>({
150 threadKey: null,
151 names: new Set(),
152 });
153 const reservePastedTextFileName = useCallback(
154 (threadKey: string, existingNames: ReadonlyArray<string>) => {
155 if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
156 pastedTextFileNamesRef.current = { threadKey, names: new Set() };
157 }
158 const names = pastedTextFileNamesRef.current.names;
159 for (const name of existingNames) names.add(name);
160 const nextName = nextPastedTextFileName([...names]);
161 names.add(nextName);
162 return nextName;
163 },
164 [],
165 );
166
167 useEffect(() => {
168 ensureComposerDraftsLoaded();
169 }, []);
170
171 const selectedThreadKey = selectedThreadShell
172 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
173 : null;
174 // The creation entry is the thread itself (rendered as the first message),
175 // not a follow-up waiting behind it.
176 const selectedThreadQueuedMessages = useMemo(
177 () =>
178 selectedThreadKey
179 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
180 (message) => message.creation === undefined,
181 )
182 : [],
183 [queuedMessagesByThreadKey, selectedThreadKey],
184 );
185 const feedbackSubmissions = useMemo(
186 () => (selectedThreadKey ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) : []),
187 [feedbackSubmissionsByThreadKey, selectedThreadKey],
188 );
189 const dismissFeedback = useCallback(
190 (id: MessageId) => {
191 if (!selectedThreadKey) return;
192 setFeedbackSubmissionsByThreadKey((current) => ({
193 ...current,
194 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
195 }));
196 },
197 [selectedThreadKey],
198 );
199 const selectedThreadMessages = selectedThreadDetail?.messages;
200 const selectedThreadActivities = selectedThreadDetail?.activities;
201 // A thread whose creation has not delivered its turn yet: the prompt only
202 // exists in the outbox, so it is appended to whatever the server has. The
203 // detail is usually present but empty during a worktree checkout, so this
204 // cannot be an either/or with the loaded messages.
205 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
206 const selectedThreadFeed = useMemo(() => {
207 const loadedMessages = selectedThreadMessages ?? [];
208 const feed =
209 (selectedThreadMessages && selectedThreadActivities) || pendingCreationMessage !== null
210 ? buildThreadFeed({
211 messages:
212 pendingCreationMessage !== null &&
213 !loadedMessages.some((message) => message.id === pendingCreationMessage.messageId)
214 ? [...loadedMessages, pendingThreadCreationMessage(pendingCreationMessage)]
215 : loadedMessages,
216 activities: selectedThreadActivities ?? [],
217 })
218 : [];
219 const pendingAcknowledgments = acknowledgedMessages.filter(
220 (message) =>
221 scopedThreadKey(message.environmentId, message.threadId) === selectedThreadKey &&
222 !selectedThreadQueuedMessages.some((queued) => queued.messageId === message.messageId),
223 );
224 if (pendingAcknowledgments.length === 0) return feed;
225 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
226 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
227 );
228 }, [
229 selectedThreadActivities,
230 selectedThreadMessages,
231 pendingCreationMessage,
232 selectedThreadKey,
233 selectedThreadQueuedMessages,
234 acknowledgedMessages,
235 ]);
236 useEffect(() => {
237 const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
238 if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
239 appAtomRegistry.set(
240 acknowledgedThreadMessagesAtom,
241 appAtomRegistry
242 .get(acknowledgedThreadMessagesAtom)
243 .filter((message) => !echoedIds.has(message.messageId)),
244 );
245 }
246 }, [acknowledgedMessages, selectedThreadMessages]);
247
248 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
249 const draftMessage = selectedDraft?.text ?? "";
250 const draftAttachments = selectedDraft?.attachments ?? [];
251 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
252 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
253 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
254 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
255 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
256 (provider) => provider.instanceId === modelSelection?.instanceId,
257 );
258 const interactionMode = selectedThread
259 ? resolveProviderInteractionMode(
260 selectedProvider,
261 selectedDraft?.interactionMode ?? selectedThread.interactionMode,
262 )
263 : null;
264
265 const selectedThreadSessionActivity = useMemo(() => {
266 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
267 if (!selectedThread?.session) {
268 return null;
269 }
270
271 return {
272 orchestrationStatus: selectedThread.session.status,
273 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
274 };
275 }, [selectedThreadDetail, selectedThreadShell]);
276
277 const isCompacting = useMemo(() => {
278 const queuedMessage = selectedThreadQueuedMessages.findLast(
279 (message) =>
280 message.messageId === dispatchingQueuedMessageId &&
281 message.text.trim().toLowerCase() === "/compact" &&
282 message.attachments.length === 0,
283 );
284 const latestCompactMessage = selectedThreadDetail?.messages.findLast(
285 (message) =>
286 message.role === "user" &&
287 message.text.trim().toLowerCase() === "/compact" &&
288 !message.attachments?.length,
289 );
290 const compactRequestIsActive =
291 latestCompactMessage !== undefined &&
292 (latestCompactMessage.createdAt >
293 (selectedThread?.latestTurn?.requestedAt ?? latestCompactMessage.createdAt) ||
294 (selectedThread?.latestTurn?.state === "running" &&
295 latestCompactMessage.createdAt === selectedThread.latestTurn.requestedAt));
296 const compactionSettled = selectedThreadDetail?.activities.some((activity) => {
297 if (!["context-compaction", "provider.turn.start.failed"].includes(activity.kind))
298 return false;
299 const payload =
300 typeof activity.payload === "object" && activity.payload !== null
301 ? (activity.payload as { readonly requestId?: unknown })
302 : null;
303 return payload?.requestId === latestCompactMessage?.id;
304 });
305 return (
306 queuedMessage !== undefined ||
307 ((selectedThread?.session?.status === "starting" ||
308 selectedThread?.session?.status === "running") &&
309 compactRequestIsActive &&
310 !compactionSettled)
311 );
312 }, [
313 dispatchingQueuedMessageId,
314 selectedThread,
315 selectedThreadDetail,
316 selectedThreadQueuedMessages,
317 ]);
318
319 const activeWorkStartedAt = useMemo(() => {
320 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
321 if (!selectedThread) {
322 return null;
323 }
324
325 return deriveActiveWorkStartedAt(
326 selectedThread.latestTurn,
327 selectedThreadSessionActivity,
328 null,
329 );
330 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
331
332 const onSendMessage = useCallback(async () => {
333 if (!selectedThreadShell) {
334 return null;
335 }
336 // The server has not created this thread yet. Queuing a follow-up against
337 // its id would strand the message: if the creation is rejected the thread
338 // never appears and the drain drops the orphan. The composer disables its
339 // send button too; this guard also covers the editor's submit key.
340 if (selectedThreadCreation !== null) {
341 return null;
342 }
343
344 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
345 const draft = getComposerDraftSnapshot(threadKey);
346 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
347 const thread = selectedThreadDetail ?? selectedThreadShell;
348 const text = draft.text.trim();
349 const attachments = draft.attachments;
350 if (
351 composerAttachmentUploadBlockReason({
352 environmentId: selectedThreadShell.environmentId,
353 attachments,
354 connected: selectedEnvironmentRuntime?.connectionState === "connected",
355 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
356 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
357 }) !== null
358 )
359 return null;
360 if (text.length === 0 && attachments.length === 0) {
361 return null;
362 }
363 // A send-failure restore appends with allowOverflow so it never drops the
364 // user's files, which can leave the draft over the cap. Sending it anyway
365 // would enqueue a message that outbox recovery rejects forever, so block
366 // here until the user removes attachments.
367 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
368 Alert.alert(
369 "Too many attachments",
370 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
371 );
372 return null;
373 }
374
375 const contextBlockReason = composerContextSendBlockReason(draft.context);
376 if (contextBlockReason) {
377 Alert.alert("Too much context", contextBlockReason);
378 return null;
379 }
380
381 const modelSelection = draft.modelSelection ?? thread.modelSelection;
382 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
383 if (
384 selectedEnvironmentRuntime?.connectionState === "connected" &&
385 isModelSelectionUnavailable(serverConfig, modelSelection)
386 ) {
387 Alert.alert(
388 "Antigravity model unavailable",
389 "Set up Antigravity on web or desktop, or choose another model.",
390 );
391 return null;
392 }
393 const provider = serverConfig?.providers.find(
394 (entry) => entry.instanceId === modelSelection.instanceId,
395 );
396 const reconnectMcpCommand =
397 attachments.length === 0 &&
398 (draft.context?.records.length ?? 0) === 0 &&
399 isReconnectMcpCommand(text);
400 if (reconnectMcpCommand) {
401 if (thread.session === null) {
402 Alert.alert("Start a thread first", "Send a message before reconnecting its MCP servers.");
403 return null;
404 }
405 if (thread.session.status === "starting" || thread.session.status === "running") {
406 Alert.alert(
407 "Agent is still working",
408 "Wait for the current turn to finish, then reconnect MCP servers.",
409 );
410 return null;
411 }
412 clearComposerDraftContent(threadKey);
413 const result = await stopThreadSession({
414 environmentId: selectedThreadShell.environmentId,
415 input: { threadId: selectedThreadShell.id, onlyIfIdle: true },
416 });
417 if (result._tag === "Failure") {
418 const currentDraft = getComposerDraftSnapshot(threadKey);
419 if (
420 currentDraft.text.length === 0 &&
421 currentDraft.attachments.length === 0 &&
422 (currentDraft.context?.records.length ?? 0) === 0
423 ) {
424 setComposerDraftText(threadKey, text);
425 }
426 if (!isAtomCommandInterrupted(result)) {
427 const error = Cause.squash(result.cause);
428 Alert.alert(
429 "Could not reconnect MCP servers",
430 error instanceof Error ? error.message : "An error occurred.",
431 );
432 }
433 return null;
434 }
435 Alert.alert(
436 "MCP reconnect requested",
437 "Wait for the session to stop, then send a message to reconnect with fresh tool schemas. Any stop failure appears in the thread.",
438 );
439 return null;
440 }
441 const feedbackCommand =
442 attachments.length === 0 &&
443 (provider?.driver === "codex" || thread.session?.providerName === "codex")
444 ? parseCodexFeedbackCommand(text)
445 : null;
446 if (feedbackCommand) {
447 if (thread.session === null) {
448 Alert.alert("Start a Codex thread first", "Send a message before you submit feedback.");
449 return null;
450 }
451 const metadata = makeQueuedMessageMetadata();
452 await submitCodexFeedback({
453 submission: {
454 id: MessageId.make(metadata.messageId),
455 command: text,
456 createdAt: metadata.createdAt,
457 },
458 clearDraft: () => clearComposerDraftContent(threadKey),
459 onUpdate: (submission) => {
460 setFeedbackSubmissionsByThreadKey((current) => {
461 const existing = current[threadKey] ?? [];
462 const found = existing.some((entry) => entry.id === submission.id);
463 return {
464 ...current,
465 [threadKey]: found
466 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
467 : [...existing, submission],
468 };
469 });
470 },
471 upload: () =>
472 uploadThreadFeedback({
473 environmentId: selectedThreadShell.environmentId,
474 input: {
475 threadId: selectedThreadShell.id,
476 ...feedbackCommand,
477 },
478 }),
479 });
480 return null;
481 }
482
483 const metadata = makeQueuedMessageMetadata();
484 const messageId = MessageId.make(metadata.messageId);
485 // Enqueue publishes the queued atom synchronously (the durable write
486 // happens behind it), so clearing the draft here gives send feedback on
487 // the tap frame instead of after file I/O. If the write fails the message
488 // is rolled out of the queue and the content is merged back into the
489 // draft, preserving anything typed since.
490 const enqueuePromise = enqueueThreadOutboxMessage({
491 environmentId: selectedThreadShell.environmentId,
492 threadId: selectedThreadShell.id,
493 messageId,
494 commandId: CommandId.make(metadata.commandId),
495 text,
496 attachments,
497 context: draft.context,
498 modelSelection,
499 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
500 interactionMode: resolveProviderInteractionMode(
501 provider,
502 draft.interactionMode ?? thread.interactionMode,
503 ),
504 createdAt: metadata.createdAt,
505 });
506 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
507 enqueuePromise.then(
508 () => {
509 // The queued message owns the files now; the sweep sees that and
510 // spares them. Deferred to here so a failed write cannot roll the
511 // message out of the queue mid-sweep and lose the bytes.
512 scheduleUnusedComposerAttachmentCleanup(attachments);
513 },
514 (error: unknown) => {
515 // Restore text via merge (idempotent) but attachments via the uncapped
516 // append: the merge path slots existing attachments first and truncates
517 // at the send limit, which would silently drop this message's images if
518 // the user attached new ones while the write was in flight.
519 void mergeComposerDraftContent(threadKey, {
520 text,
521 context: draft.context,
522 attachments: [],
523 });
524 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
525 setPendingConnectionError(
526 error instanceof Error ? error.message : "Failed to save the queued message.",
527 );
528 },
529 );
530 return messageId;
531 }, [
532 selectedEnvironmentRuntime?.connectionState,
533 selectedEnvironmentRuntime?.serverConfig,
534 selectedThreadCreation,
535 selectedThreadDetail,
536 selectedThreadShell,
537 stopThreadSession,
538 uploadThreadFeedback,
539 ]);
540
541 const onChangeDraftMessage = useCallback(
542 (value: string) => {
543 if (!selectedThreadShell) {
544 return;
545 }
546
547 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
548 setComposerDraftText(threadKey, value);
549 },
550 [selectedThreadShell],
551 );
552
553 const onPickDraftMedia = useCallback(async () => {
554 if (!selectedThreadShell) {
555 return;
556 }
557
558 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
559 const insertion = captureComposerDraftInsertion(threadKey);
560 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
561 const result = await pickComposerMedia({
562 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
563 maxVideoBytes:
564 capabilities?.attachmentUploads === true
565 ? capabilities.fileAttachments?.maxUploadBytes
566 : undefined,
567 });
568 const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
569 appendReference: true,
570 insertion,
571 });
572 const problems = [
573 ...(result.error ? [result.error] : []),
574 ...(rejectedCount > 0
575 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
576 : []),
577 ];
578 if (problems.length > 0) {
579 Alert.alert("Could not attach photo or video", problems.join("\n\n"));
580 }
581 }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
582
583 const onPickDraftFiles = useCallback(async () => {
584 if (!selectedThreadShell) {
585 return;
586 }
587 const maxBytes =
588 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
589 ?.maxUploadBytes;
590 if (maxBytes === undefined) {
591 Alert.alert("Could not attach file", "This server does not support file attachments.");
592 return;
593 }
594
595 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
596 const insertion = captureComposerDraftInsertion(threadKey);
597 // pickComposerFiles clamps the advertised limit to the contract maximum.
598 const result = await pickComposerFiles({
599 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
600 maxBytes,
601 });
602 const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
603 appendReference: true,
604 insertion,
605 });
606 // The picker error and the live-cap rejection can both happen in one
607 // pick; report both in a single alert.
608 const problems = [
609 ...(result.error ? [result.error] : []),
610 ...(rejectedCount > 0
611 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
612 : []),
613 ];
614 if (problems.length > 0) {
615 Alert.alert("Could not attach file", problems.join("\n\n"));
616 }
617 }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
618
619 const onPasteIntoDraft = useCallback(async () => {
620 if (!selectedThreadShell) {
621 return;
622 }
623
624 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
625 const insertion = captureComposerDraftInsertion(threadKey);
626 const result = await pasteComposerClipboard({
627 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
628 });
629 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
630 appendReference: true,
631 insertion,
632 });
633 if (result.text) {
634 const currentDraft = getComposerDraftSnapshot(threadKey);
635 const currentAttachments = currentDraft.attachments;
636 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
637 const advertisedMax =
638 capabilities?.attachmentUploads === true
639 ? capabilities.fileAttachments?.maxUploadBytes
640 : undefined;
641 const maxBytes =
642 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
643 const wouldExceedInputLimit =
644 currentDraft.text.length -
645 (currentDraft.text === insertion.text
646 ? Math.max(0, insertion.end - insertion.start)
647 : 0) +
648 result.text.length >
649 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
650 const shouldFold =
651 pastedTextDisposition({
652 text: result.text,
653 wouldExceedInputLimit,
654 canAttach: true,
655 }) === "attachment";
656 const canAttach =
657 maxBytes !== null &&
658 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
659 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
660 new TextEncoder().encode(result.text).byteLength <= maxBytes;
661 if (shouldFold && canAttach && maxBytes !== null) {
662 try {
663 const attachment = await createPastedTextComposerAttachment({
664 text: result.text,
665 name: reservePastedTextFileName(
666 threadKey,
667 currentAttachments.map((item) => item.name),
668 ),
669 maxBytes,
670 });
671 // Same reference the pasted images above get: a folded paste is only visible
672 // as its chip until the message is sent.
673 if (
674 appendComposerDraftAttachments(threadKey, [attachment], {
675 appendReference: true,
676 insertion,
677 }) > 0
678 ) {
679 await removePersistedComposerAttachmentFile(attachment.fileUri);
680 setPendingConnectionError(
681 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
682 );
683 }
684 } catch (error) {
685 setPendingConnectionError(
686 error instanceof Error ? error.message : "Could not attach pasted text.",
687 );
688 }
689 } else if (shouldFold && !wouldExceedInputLimit) {
690 insertComposerDraftText(threadKey, result.text, insertion);
691 } else if (shouldFold) {
692 setPendingConnectionError(
693 wouldExceedInputLimit
694 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
695 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
696 );
697 } else {
698 insertComposerDraftText(threadKey, result.text, insertion);
699 }
700 }
701 if (result.error) {
702 setPendingConnectionError(result.error);
703 } else if (rejectedPasteCount > 0) {
704 setPendingConnectionError(
705 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
706 );
707 }
708 }, [
709 composerDrafts,
710 reservePastedTextFileName,
711 selectedEnvironmentRuntime?.serverConfig,
712 selectedThreadShell,
713 ]);
714
715 const onNativePasteImages = useCallback(
716 async (uris: ReadonlyArray<string>) => {
717 if (!selectedThreadShell || uris.length === 0) {
718 return;
719 }
720
721 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
722 const insertion = captureComposerDraftInsertion(threadKey);
723 try {
724 const images = await convertPastedImagesToAttachments({
725 uris,
726 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
727 });
728 if (images.length > 0) {
729 appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
730 }
731 } catch (error) {
732 console.error("[native paste] error converting images", {
733 environmentId: selectedThreadShell.environmentId,
734 threadId: selectedThreadShell.id,
735 uriCount: uris.length,
736 ...safeErrorLogAttributes(error),
737 });
738 }
739 },
740 [composerDrafts, selectedThreadShell],
741 );
742
743 const onNativePasteText = useCallback(
744 async (paste: ComposerTextPaste) => {
745 if (!selectedThreadShell) return;
746 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
747 const advertisedMax =
748 capabilities?.attachmentUploads === true
749 ? capabilities.fileAttachments?.maxUploadBytes
750 : undefined;
751 if (advertisedMax === undefined) return;
752
753 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
754 const insertion = { text: paste.value, ...paste.selection };
755 const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
756 try {
757 const attachment = await createPastedTextComposerAttachment({
758 text: paste.text,
759 name: reservePastedTextFileName(
760 threadKey,
761 currentAttachments.map((item) => item.name),
762 ),
763 maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
764 });
765 // The chip is how a folded paste stays visible: without it the attachment is in the
766 // draft but nothing in the composer says so until the message is sent. Web folds
767 // through its ordinary attach path, which always writes a reference; match that.
768 const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
769 appendReference: true,
770 insertion,
771 });
772 if (rejectedCount > 0) {
773 await removePersistedComposerAttachmentFile(attachment.fileUri);
774 setPendingConnectionError(
775 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
776 );
777 }
778 } catch (error) {
779 setPendingConnectionError(
780 error instanceof Error ? error.message : "Could not attach pasted text.",
781 );
782 }
783 },
784 [
785 composerDrafts,
786 reservePastedTextFileName,
787 selectedEnvironmentRuntime?.serverConfig,
788 selectedThreadShell,
789 ],
790 );
791
792 const onRemoveDraftImage = useCallback(
793 (imageId: string) => {
794 if (!selectedThreadShell) {
795 return;
796 }
797
798 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
799 removeComposerDraftAttachment(threadKey, imageId);
800 },
801 [selectedThreadShell],
802 );
803
804 const onUpdateModelSelection = useCallback(
805 (value: ModelSelection) => {
806 if (!selectedThreadKey) {
807 return;
808 }
809 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
810 (candidate) => candidate.instanceId === value.instanceId,
811 );
812 updateComposerDraftSettings(selectedThreadKey, {
813 modelSelection: value,
814 ...(provider?.showInteractionModeToggle === false
815 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
816 : {}),
817 });
818 },
819 [selectedEnvironmentRuntime?.serverConfig, selectedThreadKey],
820 );
821
822 const onUpdateRuntimeMode = useCallback(
823 (value: RuntimeMode) => {
824 if (!selectedThreadKey) {
825 return;
826 }
827 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
828 },
829 [selectedThreadKey],
830 );
831
832 const onUpdateInteractionMode = useCallback(
833 (value: ProviderInteractionMode) => {
834 if (!selectedThreadKey) {
835 return;
836 }
837 const modelSelection =
838 getComposerDraftSnapshot(selectedThreadKey).modelSelection ??
839 selectedThread?.modelSelection;
840 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
841 (candidate) => candidate.instanceId === modelSelection?.instanceId,
842 );
843 updateComposerDraftSettings(selectedThreadKey, {
844 interactionMode: resolveProviderInteractionMode(provider, value),
845 });
846 },
847 [selectedEnvironmentRuntime?.serverConfig, selectedThread?.modelSelection, selectedThreadKey],
848 );
849
850 return {
851 feedbackSubmissions,
852 dismissFeedback,
853 selectedThreadFeed,
854 selectedThreadQueueCount,
855 selectedThreadQueuedMessages,
856 dispatchingQueuedMessageId,
857 activeWorkStartedAt,
858 isCompacting,
859 draftMessage,
860 draftAttachments,
861 modelSelection,
862 runtimeMode,
863 interactionMode,
864 onChangeDraftMessage,
865 onPickDraftMedia,
866 onPickDraftFiles,
867 onPasteIntoDraft,
868 onNativePasteImages,
869 onNativePasteText,
870 onRemoveDraftImage,
871 onSendMessage,
872 onUpdateModelSelection,
873 onUpdateRuntimeMode,
874 onUpdateInteractionMode,
875 };
876}