Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { AsyncResult } from "effect/unstable/reactivity";
3import { useCallback, useEffect, useMemo } from "react";
4
5import {
6 CommandId,
7 MessageId,
8 type EnvironmentId,
9 type ModelSelection,
10 type ProviderInteractionMode,
11 type RuntimeMode,
12 type ThreadId,
13} from "@t3tools/contracts";
14import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
15import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
16
17import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
18import {
19 convertPastedImagesToAttachments,
20 pasteComposerClipboard,
21 pickComposerImages,
22} from "../lib/composerImages";
23import type { DraftComposerImageAttachment } from "../lib/composerImages";
24import { scopedThreadKey } from "../lib/scopedEntities";
25import { buildThreadFeed } from "../lib/threadActivity";
26import { appAtomRegistry } from "../state/atom-registry";
27import {
28 appendComposerDraftAttachments,
29 appendComposerDraftText,
30 clearComposerDraftContent,
31 composerDraftsAtom,
32 ensureComposerDraftsLoaded,
33 getComposerDraftSnapshot,
34 mergeComposerDraftContent,
35 removeComposerDraftAttachment,
36 setComposerDraftText,
37 updateComposerDraftSettings,
38 useComposerDraft,
39} from "./use-composer-drafts";
40import { setPendingConnectionError } from "../state/use-remote-environment-registry";
41import { useSelectedThreadDetail } from "../state/use-thread-detail";
42import { useThreadSelection } from "../state/use-thread-selection";
43import { enqueueThreadOutboxMessage } from "./thread-outbox";
44import { useThreadOutboxMessages } from "./use-thread-outbox";
45import { mobilePreferencesAtom } from "./preferences";
46
47export function appendReviewCommentToDraft(input: {
48 readonly environmentId: EnvironmentId;
49 readonly threadId: ThreadId;
50 readonly text: string;
51 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
52}): void {
53 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
54 const existing = appAtomRegistry.get(composerDraftsAtom)[threadKey]?.text ?? "";
55 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
56 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
57 if (input.attachments && input.attachments.length > 0) {
58 appendComposerDraftAttachments(threadKey, input.attachments);
59 }
60}
61
62export function useThreadDraftForThread(input: {
63 readonly environmentId?: EnvironmentId;
64 readonly threadId?: ThreadId;
65}) {
66 const threadKey =
67 input.environmentId && input.threadId
68 ? scopedThreadKey(input.environmentId, input.threadId)
69 : null;
70 const draft = useComposerDraft(threadKey);
71
72 return {
73 draftMessage: draft.text,
74 draftAttachments: draft.attachments,
75 };
76}
77
78export function useThreadComposerState() {
79 const { selectedThread: selectedThreadShell } = useThreadSelection();
80 const selectedThreadDetail = useSelectedThreadDetail();
81 const composerDrafts = useAtomValue(composerDraftsAtom);
82 const queuedMessagesByThreadKey = useThreadOutboxMessages();
83 const preferences = useAtomValue(mobilePreferencesAtom);
84
85 useEffect(() => {
86 ensureComposerDraftsLoaded();
87 }, []);
88
89 const selectedThreadKey = selectedThreadShell
90 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
91 : null;
92 const selectedThreadQueuedMessages = useMemo(
93 () => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
94 [queuedMessagesByThreadKey, selectedThreadKey],
95 );
96 const selectedThreadFeed = useMemo(
97 () => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
98 [selectedThreadDetail],
99 );
100
101 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
102 const draftMessage = selectedDraft?.text ?? "";
103 const draftAttachments = selectedDraft?.attachments ?? [];
104 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
105 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
106 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
107 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
108 const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
109
110 const selectedThreadSessionActivity = useMemo(() => {
111 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
112 if (!selectedThread?.session) {
113 return null;
114 }
115
116 return {
117 orchestrationStatus: selectedThread.session.status,
118 activeTurnId: selectedThread.session.activeTurnId ?? undefined,
119 };
120 }, [selectedThreadDetail, selectedThreadShell]);
121
122 const activeWorkStartedAt = useMemo(() => {
123 const selectedThread = selectedThreadDetail ?? selectedThreadShell;
124 if (!selectedThread) {
125 return null;
126 }
127
128 return deriveActiveWorkStartedAt(
129 selectedThread.latestTurn,
130 selectedThreadSessionActivity,
131 null,
132 );
133 }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
134
135 const onSendMessage = useCallback(async () => {
136 if (!selectedThreadShell || !AsyncResult.isSuccess(preferences)) {
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 // Enqueue publishes the queued atom synchronously (the durable write
152 // happens behind it), so clearing the draft here gives send feedback on
153 // the tap frame instead of after file I/O. If the write fails the message
154 // is rolled out of the queue and the content is merged back into the
155 // draft, preserving anything typed since.
156 const enqueuePromise = enqueueThreadOutboxMessage({
157 environmentId: selectedThreadShell.environmentId,
158 threadId: selectedThreadShell.id,
159 messageId,
160 commandId: CommandId.make(metadata.commandId),
161 text,
162 attachments,
163 modelSelection: draft.modelSelection ?? thread.modelSelection,
164 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
165 interactionMode: draft.interactionMode ?? thread.interactionMode,
166 deliveryMode: preferences.value.steerActiveTurns === false ? "after-current" : "immediate",
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 }, [preferences, 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 onChangeDraftMessage,
312 onPickDraftImages,
313 onPasteIntoDraft,
314 onNativePasteImages,
315 onRemoveDraftImage,
316 onSendMessage,
317 onUpdateModelSelection,
318 onUpdateRuntimeMode,
319 onUpdateInteractionMode,
320 };
321}