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 removeComposerDraftAttachment,
34 setComposerDraftText,
35 updateComposerDraftSettings,
36 useComposerDraft,
37} from "./use-composer-drafts";
38import { setPendingConnectionError } from "../state/use-remote-environment-registry";
39import { useSelectedThreadDetail } from "../state/use-thread-detail";
40import { useThreadSelection } from "../state/use-thread-selection";
41import { enqueueThreadOutboxMessage } from "./thread-outbox";
42import { useThreadOutboxMessages } from "./use-thread-outbox";
43
44export function appendReviewCommentToDraft(input: {
45 readonly environmentId: EnvironmentId;
46 readonly threadId: ThreadId;
47 readonly text: string;
48 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
49}): void {
50 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
51 const existing = appAtomRegistry.get(composerDraftsAtom)[threadKey]?.text ?? "";
52 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
53 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
54 if (input.attachments && input.attachments.length > 0) {
55 appendComposerDraftAttachments(threadKey, input.attachments);
56 }
57}
58
59export function useThreadDraftForThread(input: {
60 readonly environmentId?: EnvironmentId;
61 readonly threadId?: ThreadId;
62}) {
63 const threadKey =
64 input.environmentId && input.threadId
65 ? scopedThreadKey(input.environmentId, input.threadId)
66 : null;
67 const draft = useComposerDraft(threadKey);
68
69 return {
70 draftMessage: draft.text,
71 draftAttachments: draft.attachments,
72 };
73}
74
75export function useThreadComposerState() {
76 const { selectedThread: selectedThreadShell } = useThreadSelection();
77 const selectedThreadDetail = useSelectedThreadDetail();
78 const composerDrafts = useAtomValue(composerDraftsAtom);
79 const queuedMessagesByThreadKey = useThreadOutboxMessages();
80
81 useEffect(() => {
82 ensureComposerDraftsLoaded();
83 }, []);
84
85 const selectedThreadKey = selectedThreadShell
86 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
87 : null;
88 const selectedThreadQueuedMessages = useMemo(
89 () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
90 [queuedMessagesByThreadKey, selectedThreadKey],
91 );
92 const selectedThreadFeed = useMemo(
93 () => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
94 [selectedThreadDetail],
95 );
96
97 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
98 const draftMessage = selectedDraft?.text ?? "";
99 const draftAttachments = selectedDraft?.attachments ?? [];
100 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
101 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
102 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
103 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
104 const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
105
106 const selectedThreadSessionActivity = useMemo(() => {
107 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
108 if (!selectedThread?.session) {
109 return null;
110 }
111
112 return {
113 orchestrationStatus: selectedThread.session.status,
114 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
115 };
116 }, [selectedThreadDetail, selectedThreadShell]);
117
118 const activeWorkStartedAt = useMemo(() => {
119 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
120 if (!selectedThread) {
121 return null;
122 }
123
124 return deriveActiveWorkStartedAt(
125 selectedThread.latestTurn,
126 selectedThreadSessionActivity,
127 null,
128 );
129 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
130
131 const activeThreadBusy =
132 !!selectedThread &&
133 (selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
134
135 const onSendMessage = useCallback(async () => {
136 if (!selectedThreadShell) {
137 return null;
138 }
139
140 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
141 const draft = getComposerDraftSnapshot(threadKey);
142 const thread = selectedThreadDetail ?? selectedThreadShell;
143 const text = draft.text.trim();
144 const attachments = draft.attachments;
145 if (text.length === 0 && attachments.length === 0) {
146 return null;
147 }
148
149 const metadata = makeQueuedMessageMetadata();
150 const messageId = MessageId.make(metadata.messageId);
151 try {
152 await enqueueThreadOutboxMessage({
153 environmentId: selectedThreadShell.environmentId,
154 threadId: selectedThreadShell.id,
155 messageId,
156 commandId: CommandId.make(metadata.commandId),
157 text,
158 attachments,
159 modelSelection: draft.modelSelection ?? thread.modelSelection,
160 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
161 interactionMode: draft.interactionMode ?? thread.interactionMode,
162 createdAt: metadata.createdAt,
163 });
164 clearComposerDraftContent(threadKey);
165 return messageId;
166 } catch (error) {
167 setPendingConnectionError(
168 error instanceof Error ? error.message : "Failed to save the queued message.",
169 );
170 return null;
171 }
172 }, [selectedThreadDetail, selectedThreadShell]);
173
174 const onChangeDraftMessage = useCallback(
175 (value: string) => {
176 if (!selectedThreadShell) {
177 return;
178 }
179
180 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
181 setComposerDraftText(threadKey, value);
182 },
183 [selectedThreadShell],
184 );
185
186 const onPickDraftImages = useCallback(async () => {
187 if (!selectedThreadShell) {
188 return;
189 }
190
191 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
192 const result = await pickComposerImages({
193 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
194 });
195 if (result.images.length > 0) {
196 appendComposerDraftAttachments(threadKey, result.images);
197 }
198 if (result.error) {
199 setPendingConnectionError(result.error);
200 }
201 }, [composerDrafts, selectedThreadShell]);
202
203 const onPasteIntoDraft = useCallback(async () => {
204 if (!selectedThreadShell) {
205 return;
206 }
207
208 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
209 const result = await pasteComposerClipboard({
210 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
211 });
212 if (result.images.length > 0) {
213 appendComposerDraftAttachments(threadKey, result.images);
214 }
215 if (result.text) {
216 appendComposerDraftText(threadKey, result.text);
217 }
218 if (result.error) {
219 setPendingConnectionError(result.error);
220 }
221 }, [composerDrafts, selectedThreadShell]);
222
223 const onNativePasteImages = useCallback(
224 async (uris: ReadonlyArray<string>) => {
225 if (!selectedThreadShell || uris.length === 0) {
226 return;
227 }
228
229 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
230 try {
231 const images = await convertPastedImagesToAttachments({
232 uris,
233 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
234 });
235 if (images.length > 0) {
236 appendComposerDraftAttachments(threadKey, images);
237 }
238 } catch (error) {
239 console.error("[native paste] error converting images", {
240 environmentId: selectedThreadShell.environmentId,
241 threadId: selectedThreadShell.id,
242 uriCount: uris.length,
243 ...safeErrorLogAttributes(error),
244 });
245 }
246 },
247 [composerDrafts, selectedThreadShell],
248 );
249
250 const onRemoveDraftImage = useCallback(
251 (imageId: string) => {
252 if (!selectedThreadShell) {
253 return;
254 }
255
256 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
257 removeComposerDraftAttachment(threadKey, imageId);
258 },
259 [selectedThreadShell],
260 );
261
262 const onUpdateModelSelection = useCallback(
263 (value: ModelSelection) => {
264 if (!selectedThreadKey) {
265 return;
266 }
267 updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
268 },
269 [selectedThreadKey],
270 );
271
272 const onUpdateRuntimeMode = useCallback(
273 (value: RuntimeMode) => {
274 if (!selectedThreadKey) {
275 return;
276 }
277 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
278 },
279 [selectedThreadKey],
280 );
281
282 const onUpdateInteractionMode = useCallback(
283 (value: ProviderInteractionMode) => {
284 if (!selectedThreadKey) {
285 return;
286 }
287 updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
288 },
289 [selectedThreadKey],
290 );
291
292 return {
293 selectedThreadFeed,
294 selectedThreadQueueCount,
295 activeWorkStartedAt,
296 draftMessage,
297 draftAttachments,
298 modelSelection,
299 runtimeMode,
300 interactionMode,
301 activeThreadBusy,
302 onChangeDraftMessage,
303 onPickDraftImages,
304 onPasteIntoDraft,
305 onNativePasteImages,
306 onRemoveDraftImage,
307 onSendMessage,
308 onUpdateModelSelection,
309 onUpdateRuntimeMode,
310 onUpdateInteractionMode,
311 };
312}