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

use-thread-composer-state.ts

821 lines30.9 KB

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