Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useCallback, useEffect, useMemo } from "react";
3
4import {
5 CommandId,
6 MessageId,
7 type EnvironmentId,
8 type ModelSelection,
9 type ProviderInteractionMode,
10 type RuntimeMode,
11 type ThreadId,
12} from "@t3tools/contracts";
13import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
14import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
15
16import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
17import {
18 convertPastedImagesToAttachments,
19 pasteComposerClipboard,
20 pickComposerImages,
21} from "../lib/composerImages";
22import type { DraftComposerImageAttachment } from "../lib/composerImages";
23import { scopedThreadKey } from "../lib/scopedEntities";
24import { buildThreadFeed } from "../lib/threadActivity";
25import { appAtomRegistry } from "../state/atom-registry";
26import {
27 appendComposerDraftAttachments,
28 appendComposerDraftText,
29 clearComposerDraftContent,
30 composerDraftsAtom,
31 ensureComposerDraftsLoaded,
32 getComposerDraftSnapshot,
33 mergeComposerDraftContent,
34 removeComposerDraftAttachment,
35 setComposerDraftText,
36 updateComposerDraftSettings,
37 useComposerDraft,
38} from "./use-composer-drafts";
39import { setPendingConnectionError } from "../state/use-remote-environment-registry";
40import { useSelectedThreadDetail } from "../state/use-thread-detail";
41import { useThreadSelection } from "../state/use-thread-selection";
42import { enqueueThreadOutboxMessage } from "./thread-outbox";
43import { useThreadOutboxMessages } from "./use-thread-outbox";
44
45export function appendReviewCommentToDraft(input: {
46 readonly environmentId: EnvironmentId;
47 readonly threadId: ThreadId;
48 readonly text: string;
49 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
50}): void {
51 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
52 const existing = appAtomRegistry.get(composerDraftsAtom)[threadKey]?.text ?? "";
53 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
54 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
55 if (input.attachments && input.attachments.length > 0) {
56 appendComposerDraftAttachments(threadKey, input.attachments);
57 }
58}
59
60export function useThreadDraftForThread(input: {
61 readonly environmentId?: EnvironmentId;
62 readonly threadId?: ThreadId;
63}) {
64 const threadKey =
65 input.environmentId && input.threadId
66 ? scopedThreadKey(input.environmentId, input.threadId)
67 : null;
68 const draft = useComposerDraft(threadKey);
69
70 return {
71 draftMessage: draft.text,
72 draftAttachments: draft.attachments,
73 };
74}
75
76export function useThreadComposerState() {
77 const { selectedThread: selectedThreadShell } = useThreadSelection();
78 const selectedThreadDetail = useSelectedThreadDetail();
79 const composerDrafts = useAtomValue(composerDraftsAtom);
80 const queuedMessagesByThreadKey = useThreadOutboxMessages();
81
82 useEffect(() => {
83 ensureComposerDraftsLoaded();
84 }, []);
85
86 const selectedThreadKey = selectedThreadShell
87 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
88 : null;
89 const selectedThreadQueuedMessages = useMemo(
90 () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
91 [queuedMessagesByThreadKey, selectedThreadKey],
92 );
93 const selectedThreadFeed = useMemo(
94 () => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
95 [selectedThreadDetail],
96 );
97
98 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
99 const draftMessage = selectedDraft?.text ?? "";
100 const draftAttachments = selectedDraft?.attachments ?? [];
101 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
102 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
103 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
104 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
105 const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
106
107 const selectedThreadSessionActivity = useMemo(() => {
108 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
109 if (!selectedThread?.session) {
110 return null;
111 }
112
113 return {
114 orchestrationStatus: selectedThread.session.status,
115 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
116 };
117 }, [selectedThreadDetail, selectedThreadShell]);
118
119 const activeWorkStartedAt = useMemo(() => {
120 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
121 if (!selectedThread) {
122 return null;
123 }
124
125 return deriveActiveWorkStartedAt(
126 selectedThread.latestTurn,
127 selectedThreadSessionActivity,
128 null,
129 );
130 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
131
132 const activeThreadBusy =
133 !!selectedThread &&
134 (selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
135
136 const onSendMessage = useCallback(async () => {
137 if (!selectedThreadShell) {
138 return null;
139 }
140
141 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
142 const draft = getComposerDraftSnapshot(threadKey);
143 const thread = selectedThreadDetail ?? selectedThreadShell;
144 const text = draft.text.trim();
145 const attachments = draft.attachments;
146 if (text.length === 0 && attachments.length === 0) {
147 return null;
148 }
149
150 const metadata = makeQueuedMessageMetadata();
151 const messageId = MessageId.make(metadata.messageId);
152 // Enqueue publishes the queued atom synchronously (the durable write
153 // happens behind it), so clearing the draft here gives send feedback on
154 // the tap frame instead of after file I/O. If the write fails the message
155 // is rolled out of the queue and the content is merged back into the
156 // draft, preserving anything typed since.
157 const enqueuePromise = enqueueThreadOutboxMessage({
158 environmentId: selectedThreadShell.environmentId,
159 threadId: selectedThreadShell.id,
160 messageId,
161 commandId: CommandId.make(metadata.commandId),
162 text,
163 attachments,
164 modelSelection: draft.modelSelection ?? thread.modelSelection,
165 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
166 interactionMode: draft.interactionMode ?? thread.interactionMode,
167 createdAt: metadata.createdAt,
168 });
169 clearComposerDraftContent(threadKey);
170 enqueuePromise.catch((error: unknown) => {
171 // Restore text via merge (idempotent) but attachments via the uncapped
172 // append: the merge path slots existing attachments first and truncates
173 // at the send limit, which would silently drop this message's images if
174 // the user attached new ones while the write was in flight.
175 void mergeComposerDraftContent(threadKey, { text, attachments: [] });
176 appendComposerDraftAttachments(threadKey, attachments);
177 setPendingConnectionError(
178 error instanceof Error ? error.message : "Failed to save the queued message.",
179 );
180 });
181 return messageId;
182 }, [selectedThreadDetail, selectedThreadShell]);
183
184 const onChangeDraftMessage = useCallback(
185 (value: string) => {
186 if (!selectedThreadShell) {
187 return;
188 }
189
190 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
191 setComposerDraftText(threadKey, value);
192 },
193 [selectedThreadShell],
194 );
195
196 const onPickDraftImages = useCallback(async () => {
197 if (!selectedThreadShell) {
198 return;
199 }
200
201 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
202 const result = await pickComposerImages({
203 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
204 });
205 if (result.images.length > 0) {
206 appendComposerDraftAttachments(threadKey, result.images);
207 }
208 if (result.error) {
209 setPendingConnectionError(result.error);
210 }
211 }, [composerDrafts, selectedThreadShell]);
212
213 const onPasteIntoDraft = useCallback(async () => {
214 if (!selectedThreadShell) {
215 return;
216 }
217
218 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
219 const result = await pasteComposerClipboard({
220 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
221 });
222 if (result.images.length > 0) {
223 appendComposerDraftAttachments(threadKey, result.images);
224 }
225 if (result.text) {
226 appendComposerDraftText(threadKey, result.text);
227 }
228 if (result.error) {
229 setPendingConnectionError(result.error);
230 }
231 }, [composerDrafts, selectedThreadShell]);
232
233 const onNativePasteImages = useCallback(
234 async (uris: ReadonlyArray<string>) => {
235 if (!selectedThreadShell || uris.length === 0) {
236 return;
237 }
238
239 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
240 try {
241 const images = await convertPastedImagesToAttachments({
242 uris,
243 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
244 });
245 if (images.length > 0) {
246 appendComposerDraftAttachments(threadKey, images);
247 }
248 } catch (error) {
249 console.error("[native paste] error converting images", {
250 environmentId: selectedThreadShell.environmentId,
251 threadId: selectedThreadShell.id,
252 uriCount: uris.length,
253 ...safeErrorLogAttributes(error),
254 });
255 }
256 },
257 [composerDrafts, selectedThreadShell],
258 );
259
260 const onRemoveDraftImage = useCallback(
261 (imageId: string) => {
262 if (!selectedThreadShell) {
263 return;
264 }
265
266 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
267 removeComposerDraftAttachment(threadKey, imageId);
268 },
269 [selectedThreadShell],
270 );
271
272 const onUpdateModelSelection = useCallback(
273 (value: ModelSelection) => {
274 if (!selectedThreadKey) {
275 return;
276 }
277 updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
278 },
279 [selectedThreadKey],
280 );
281
282 const onUpdateRuntimeMode = useCallback(
283 (value: RuntimeMode) => {
284 if (!selectedThreadKey) {
285 return;
286 }
287 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
288 },
289 [selectedThreadKey],
290 );
291
292 const onUpdateInteractionMode = useCallback(
293 (value: ProviderInteractionMode) => {
294 if (!selectedThreadKey) {
295 return;
296 }
297 updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
298 },
299 [selectedThreadKey],
300 );
301
302 return {
303 selectedThreadFeed,
304 selectedThreadQueueCount,
305 activeWorkStartedAt,
306 draftMessage,
307 draftAttachments,
308 modelSelection,
309 runtimeMode,
310 interactionMode,
311 activeThreadBusy,
312 onChangeDraftMessage,
313 onPickDraftImages,
314 onPasteIntoDraft,
315 onNativePasteImages,
316 onRemoveDraftImage,
317 onSendMessage,
318 onUpdateModelSelection,
319 onUpdateRuntimeMode,
320 onUpdateInteractionMode,
321 };
322}