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