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