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

use-thread-composer-state.ts

589 lines21.7 KB

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