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