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

use-thread-composer-state.ts

415 lines14.3 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 type EnvironmentId,
10 type ModelSelection,
11 type ProviderInteractionMode,
12 type RuntimeMode,
13 type ThreadId,
14} from "@t3tools/contracts";
15import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
16import {
17 codexFeedbackMessage,
18 parseCodexFeedbackCommand,
19 submitCodexFeedback,
20 type CodexFeedbackSubmission,
21} from "@t3tools/client-runtime/state/threads";
22import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
23import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
24​
25import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
26import {
27 convertPastedImagesToAttachments,
28 pasteComposerClipboard,
29 pickComposerImages,
30} from "../lib/composerImages";
31import type { DraftComposerImageAttachment } from "../lib/composerImages";
32import { scopedThreadKey } from "../lib/scopedEntities";
33import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
34import { buildThreadFeed } from "../lib/threadActivity";
35import { appAtomRegistry } from "../state/atom-registry";
36import {
37 appendComposerDraftAttachments,
38 appendComposerDraftText,
39 clearComposerDraftContent,
40 composerDraftsAtom,
41 ensureComposerDraftsLoaded,
42 getComposerDraftSnapshot,
43 mergeComposerDraftContent,
44 removeComposerDraftAttachment,
45 setComposerDraftText,
46 updateComposerDraftSettings,
47 useComposerDraft,
48} from "./use-composer-drafts";
49import { setPendingConnectionError } from "../state/use-remote-environment-registry";
50import { useSelectedThreadDetail } from "../state/use-thread-detail";
51import { useThreadSelection } from "../state/use-thread-selection";
52import { enqueueThreadOutboxMessage } from "./thread-outbox";
53import { useThreadOutboxMessages } from "./use-thread-outbox";
54import { threadEnvironment } from "./threads";
55import { useAtomCommand } from "./use-atom-command";
56​
57export function appendReviewCommentToDraft(input: {
58 readonly environmentId: EnvironmentId;
59 readonly threadId: ThreadId;
60 readonly text: string;
61 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
62}): void {
63 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
64 const existing = appAtomRegistry.get(composerDraftsAtom)[threadKey]?.text ?? "";
65 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
66 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
67 if (input.attachments && input.attachments.length > 0) {
68 appendComposerDraftAttachments(threadKey, input.attachments);
69 }
71​
72export function useThreadDraftForThread(input: {
73 readonly environmentId?: EnvironmentId;
74 readonly threadId?: ThreadId;
75}) {
76 const threadKey =
77 input.environmentId && input.threadId
78 ? scopedThreadKey(input.environmentId, input.threadId)
79 : null;
80 const draft = useComposerDraft(threadKey);
81​
82 return {
83 draftMessage: draft.text,
84 draftAttachments: draft.attachments,
85 };
87​
88export function useThreadComposerState() {
89 const { selectedThread: selectedThreadShell, selectedEnvironmentRuntime } = useThreadSelection();
90 const selectedThreadDetail = useSelectedThreadDetail();
91 const composerDrafts = useAtomValue(composerDraftsAtom);
92 const queuedMessagesByThreadKey = useThreadOutboxMessages();
93 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
94 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
95 >({});
96 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
97 reportFailure: false,
98 });
99​
100 useEffect(() => {
101 ensureComposerDraftsLoaded();
102 }, []);
103​
104 const selectedThreadKey = selectedThreadShell
105 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
106 : null;
107 const selectedThreadQueuedMessages = useMemo(
108 () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
109 [queuedMessagesByThreadKey, selectedThreadKey],
110 );
111 const selectedThreadFeed = useMemo(() => {
112 if (!selectedThreadDetail) {
113 return [];
114 }
115 const submissions = selectedThreadKey
116 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
117 : [];
118 return buildThreadFeed(selectedThreadDetail, {
119 localMessages: submissions.flatMap((submission) =>
120 submission.status === "interrupted"
121 ? []
122 : [codexFeedbackMessage(submission), codexFeedbackMessage(submission, "assistant")],
123 ),
124 });
125 }, [feedbackSubmissionsByThreadKey, selectedThreadDetail, selectedThreadKey]);
126​
127 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
128 const draftMessage = selectedDraft?.text ?? "";
129 const draftAttachments = selectedDraft?.attachments ?? [];
130 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
131 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
132 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
133 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
134 const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
135​
136 const selectedThreadSessionActivity = useMemo(() => {
137 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
138 if (!selectedThread?.session) {
139 return null;
140 }
141​
142 return {
143 orchestrationStatus: selectedThread.session.status,
144 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
145 };
146 }, [selectedThreadDetail, selectedThreadShell]);
147​
148 const activeWorkStartedAt = useMemo(() => {
149 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
150 if (!selectedThread) {
151 return null;
152 }
153​
154 return deriveActiveWorkStartedAt(
155 selectedThread.latestTurn,
156 selectedThreadSessionActivity,
157 null,
158 );
159 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
160​
161 const onSendMessage = useCallback(async () => {
162 if (!selectedThreadShell) {
163 return null;
164 }
165​
166 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
167 const draft = getComposerDraftSnapshot(threadKey);
168 const thread = selectedThreadDetail ?? selectedThreadShell;
169 const text = draft.text.trim();
170 const attachments = draft.attachments;
171 if (text.length === 0 && attachments.length === 0) {
172 return null;
173 }
174​
175 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
176 (entry) => entry.instanceId === thread.modelSelection.instanceId,
177 );
178 const feedbackCommand =
179 attachments.length === 0 &&
180 (provider?.driver === "codex" || thread.session?.providerName === "codex")
181 ? parseCodexFeedbackCommand(text)
182 : null;
183 if (feedbackCommand) {
184 if (thread.session === null) {
185 Alert.alert("Start a Codex thread first", "Send a message before you submit feedback.");
186 return null;
187 }
188 const metadata = makeQueuedMessageMetadata();
189 const result = await submitCodexFeedback({
190 submission: {
191 id: MessageId.make(metadata.messageId),
192 command: text,
193 createdAt: metadata.createdAt,
194 },
195 clearDraft: () => clearComposerDraftContent(threadKey),
196 onUpdate: (submission) => {
197 setFeedbackSubmissionsByThreadKey((current) => {
198 const existing = current[threadKey] ?? [];
199 const found = existing.some((entry) => entry.id === submission.id);
200 return {
201 ...current,
202 [threadKey]: found
203 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
204 : [...existing, submission],
205 };
206 });
207 },
208 upload: () =>
209 uploadThreadFeedback({
210 environmentId: selectedThreadShell.environmentId,
211 input: {
212 threadId: selectedThreadShell.id,
213 ...feedbackCommand,
214 },
215 }),
216 });
217 if (result._tag === "Failure") {
218 if (isAtomCommandInterrupted(result)) {
219 return null;
220 }
221 const error = Cause.squash(result.cause);
222 Alert.alert(
223 "Could not send feedback to OpenAI",
224 error instanceof Error ? error.message : "An error occurred.",
225 );
226 return null;
227 }
228 const feedbackId = result.value.feedbackId;
229 Alert.alert("Feedback sent to OpenAI", `Thread ID: ${feedbackId}`, [
230 { text: "OK", style: "cancel" },
231 {
232 text: "Copy ID",
233 onPress: () => copyTextWithHaptic(feedbackId, { target: "Codex feedback thread ID" }),
234 },
235 ]);
236 return null;
237 }
238​
239 const metadata = makeQueuedMessageMetadata();
240 const messageId = MessageId.make(metadata.messageId);
241 // Enqueue publishes the queued atom synchronously (the durable write
242 // happens behind it), so clearing the draft here gives send feedback on
243 // the tap frame instead of after file I/O. If the write fails the message
244 // is rolled out of the queue and the content is merged back into the
245 // draft, preserving anything typed since.
246 const enqueuePromise = enqueueThreadOutboxMessage({
247 environmentId: selectedThreadShell.environmentId,
248 threadId: selectedThreadShell.id,
249 messageId,
250 commandId: CommandId.make(metadata.commandId),
251 text,
252 attachments,
253 modelSelection: draft.modelSelection ?? thread.modelSelection,
254 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
255 interactionMode: draft.interactionMode ?? thread.interactionMode,
256 createdAt: metadata.createdAt,
257 });
258 clearComposerDraftContent(threadKey);
259 enqueuePromise.catch((error: unknown) => {
260 // Restore text via merge (idempotent) but attachments via the uncapped
261 // append: the merge path slots existing attachments first and truncates
262 // at the send limit, which would silently drop this message's images if
263 // the user attached new ones while the write was in flight.
264 void mergeComposerDraftContent(threadKey, { text, attachments: [] });
265 appendComposerDraftAttachments(threadKey, attachments);
266 setPendingConnectionError(
267 error instanceof Error ? error.message : "Failed to save the queued message.",
268 );
269 });
270 return messageId;
271 }, [
272 selectedEnvironmentRuntime?.serverConfig?.providers,
273 selectedThreadDetail,
274 selectedThreadShell,
275 uploadThreadFeedback,
276 ]);
277​
278 const onChangeDraftMessage = useCallback(
279 (value: string) => {
280 if (!selectedThreadShell) {
281 return;
282 }
283​
284 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
285 setComposerDraftText(threadKey, value);
286 },
287 [selectedThreadShell],
288 );
289​
290 const onPickDraftImages = useCallback(async () => {
291 if (!selectedThreadShell) {
292 return;
293 }
294​
295 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
296 const result = await pickComposerImages({
297 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
298 });
299 if (result.images.length > 0) {
300 appendComposerDraftAttachments(threadKey, result.images);
301 }
302 if (result.error) {
303 setPendingConnectionError(result.error);
304 }
305 }, [composerDrafts, selectedThreadShell]);
306​
307 const onPasteIntoDraft = useCallback(async () => {
308 if (!selectedThreadShell) {
309 return;
310 }
311​
312 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
313 const result = await pasteComposerClipboard({
314 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
315 });
316 if (result.images.length > 0) {
317 appendComposerDraftAttachments(threadKey, result.images);
318 }
319 if (result.text) {
320 appendComposerDraftText(threadKey, result.text);
321 }
322 if (result.error) {
323 setPendingConnectionError(result.error);
324 }
325 }, [composerDrafts, selectedThreadShell]);
326​
327 const onNativePasteImages = useCallback(
328 async (uris: ReadonlyArray<string>) => {
329 if (!selectedThreadShell || uris.length === 0) {
330 return;
331 }
332​
333 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
334 try {
335 const images = await convertPastedImagesToAttachments({
336 uris,
337 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
338 });
339 if (images.length > 0) {
340 appendComposerDraftAttachments(threadKey, images);
341 }
342 } catch (error) {
343 console.error("[native paste] error converting images", {
344 environmentId: selectedThreadShell.environmentId,
345 threadId: selectedThreadShell.id,
346 uriCount: uris.length,
347 ...safeErrorLogAttributes(error),
348 });
349 }
350 },
351 [composerDrafts, selectedThreadShell],
352 );
353​
354 const onRemoveDraftImage = useCallback(
355 (imageId: string) => {
356 if (!selectedThreadShell) {
357 return;
358 }
359​
360 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
361 removeComposerDraftAttachment(threadKey, imageId);
362 },
363 [selectedThreadShell],
364 );
365​
366 const onUpdateModelSelection = useCallback(
367 (value: ModelSelection) => {
368 if (!selectedThreadKey) {
369 return;
370 }
371 updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
372 },
373 [selectedThreadKey],
374 );
375​
376 const onUpdateRuntimeMode = useCallback(
377 (value: RuntimeMode) => {
378 if (!selectedThreadKey) {
379 return;
380 }
381 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
382 },
383 [selectedThreadKey],
384 );
385​
386 const onUpdateInteractionMode = useCallback(
387 (value: ProviderInteractionMode) => {
388 if (!selectedThreadKey) {
389 return;
390 }
391 updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
392 },
393 [selectedThreadKey],
394 );
395​
396 return {
397 selectedThreadFeed,
398 selectedThreadQueueCount,
399 activeWorkStartedAt,
400 draftMessage,
401 draftAttachments,
402 modelSelection,
403 runtimeMode,
404 interactionMode,
405 onChangeDraftMessage,
406 onPickDraftImages,
407 onPasteIntoDraft,
408 onNativePasteImages,
409 onRemoveDraftImage,
410 onSendMessage,
411 onUpdateModelSelection,
412 onUpdateRuntimeMode,
413 onUpdateInteractionMode,
414 };