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

use-thread-composer-state.ts

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