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

use-thread-composer-state.ts

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