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

use-thread-composer-state.ts

579 lines21.2 KB

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