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