Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-thread-composer-state.ts

824 lines31.1 KB

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