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

use-thread-composer-state.ts

317 lines10.8 KB

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 }
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 };
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 onSendMessage = useCallback(async () => {
133 if (!selectedThreadShell) {
134 return null;
135 }
136​
137 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
138 const draft = getComposerDraftSnapshot(threadKey);
139 const thread = selectedThreadDetail ?? selectedThreadShell;
140 const text = draft.text.trim();
141 const attachments = draft.attachments;
142 if (text.length === 0 && attachments.length === 0) {
143 return null;
144 }
145​
146 const metadata = makeQueuedMessageMetadata();
147 const messageId = MessageId.make(metadata.messageId);
148 // Enqueue publishes the queued atom synchronously (the durable write
149 // happens behind it), so clearing the draft here gives send feedback on
150 // the tap frame instead of after file I/O. If the write fails the message
151 // is rolled out of the queue and the content is merged back into the
152 // draft, preserving anything typed since.
153 const enqueuePromise = enqueueThreadOutboxMessage({
154 environmentId: selectedThreadShell.environmentId,
155 threadId: selectedThreadShell.id,
156 messageId,
157 commandId: CommandId.make(metadata.commandId),
158 text,
159 attachments,
160 modelSelection: draft.modelSelection ?? thread.modelSelection,
161 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
162 interactionMode: draft.interactionMode ?? thread.interactionMode,
163 createdAt: metadata.createdAt,
164 });
165 clearComposerDraftContent(threadKey);
166 enqueuePromise.catch((error: unknown) => {
167 // Restore text via merge (idempotent) but attachments via the uncapped
168 // append: the merge path slots existing attachments first and truncates
169 // at the send limit, which would silently drop this message's images if
170 // the user attached new ones while the write was in flight.
171 void mergeComposerDraftContent(threadKey, { text, attachments: [] });
172 appendComposerDraftAttachments(threadKey, attachments);
173 setPendingConnectionError(
174 error instanceof Error ? error.message : "Failed to save the queued message.",
175 );
176 });
177 return messageId;
178 }, [selectedThreadDetail, selectedThreadShell]);
179​
180 const onChangeDraftMessage = useCallback(
181 (value: string) => {
182 if (!selectedThreadShell) {
183 return;
184 }
185​
186 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
187 setComposerDraftText(threadKey, value);
188 },
189 [selectedThreadShell],
190 );
191​
192 const onPickDraftImages = useCallback(async () => {
193 if (!selectedThreadShell) {
194 return;
195 }
196​
197 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
198 const result = await pickComposerImages({
199 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
200 });
201 if (result.images.length > 0) {
202 appendComposerDraftAttachments(threadKey, result.images);
203 }
204 if (result.error) {
205 setPendingConnectionError(result.error);
206 }
207 }, [composerDrafts, selectedThreadShell]);
208​
209 const onPasteIntoDraft = useCallback(async () => {
210 if (!selectedThreadShell) {
211 return;
212 }
213​
214 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
215 const result = await pasteComposerClipboard({
216 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
217 });
218 if (result.images.length > 0) {
219 appendComposerDraftAttachments(threadKey, result.images);
220 }
221 if (result.text) {
222 appendComposerDraftText(threadKey, result.text);
223 }
224 if (result.error) {
225 setPendingConnectionError(result.error);
226 }
227 }, [composerDrafts, selectedThreadShell]);
228​
229 const onNativePasteImages = useCallback(
230 async (uris: ReadonlyArray<string>) => {
231 if (!selectedThreadShell || uris.length === 0) {
232 return;
233 }
234​
235 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
236 try {
237 const images = await convertPastedImagesToAttachments({
238 uris,
239 existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
240 });
241 if (images.length > 0) {
242 appendComposerDraftAttachments(threadKey, images);
243 }
244 } catch (error) {
245 console.error("[native paste] error converting images", {
246 environmentId: selectedThreadShell.environmentId,
247 threadId: selectedThreadShell.id,
248 uriCount: uris.length,
249 ...safeErrorLogAttributes(error),
250 });
251 }
252 },
253 [composerDrafts, selectedThreadShell],
254 );
255​
256 const onRemoveDraftImage = useCallback(
257 (imageId: string) => {
258 if (!selectedThreadShell) {
259 return;
260 }
261​
262 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
263 removeComposerDraftAttachment(threadKey, imageId);
264 },
265 [selectedThreadShell],
266 );
267​
268 const onUpdateModelSelection = useCallback(
269 (value: ModelSelection) => {
270 if (!selectedThreadKey) {
271 return;
272 }
273 updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
274 },
275 [selectedThreadKey],
276 );
277​
278 const onUpdateRuntimeMode = useCallback(
279 (value: RuntimeMode) => {
280 if (!selectedThreadKey) {
281 return;
282 }
283 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
284 },
285 [selectedThreadKey],
286 );
287​
288 const onUpdateInteractionMode = useCallback(
289 (value: ProviderInteractionMode) => {
290 if (!selectedThreadKey) {
291 return;
292 }
293 updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
294 },
295 [selectedThreadKey],
296 );
297​
298 return {
299 selectedThreadFeed,
300 selectedThreadQueueCount,
301 activeWorkStartedAt,
302 draftMessage,
303 draftAttachments,
304 modelSelection,
305 runtimeMode,
306 interactionMode,
307 onChangeDraftMessage,
308 onPickDraftImages,
309 onPasteIntoDraft,
310 onNativePasteImages,
311 onRemoveDraftImage,
312 onSendMessage,
313 onUpdateModelSelection,
314 onUpdateRuntimeMode,
315 onUpdateInteractionMode,
316 };