Open History to see the last commit
1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import {
3 runAtomCommand,
4 squashAtomCommandFailure,
5 type AtomCommand,
6} from "@t3tools/client-runtime/state/runtime";
7import type { ScopedThreadRef } from "@t3tools/contracts";
8import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";
9import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
10
11import { buildMessageContext, terminalContextReference } from "../../lib/composerContextRecords";
12import { removeInlineContextReference } from "../../lib/composerContextReferences";
13import {
14 awaitAttachmentUploads,
15 getUploadedAttachments,
16 releaseDraftAttachments,
17 startAttachmentUpload,
18} from "../../lib/attachmentUploadQueue";
19import { newMessageId } from "../../lib/utils";
20import { latestCompletedToolActivityId, useQueuedMessageStore } from "../../queuedMessageStore";
21import { appAtomRegistry } from "../../rpc/atomRegistry";
22import { readThread, readThreadShell } from "../../state/entities";
23import { environmentServerConfigsAtom } from "../../state/server";
24import { threadEnvironment } from "../../state/threads";
25import {
26 createLocalDispatchSnapshot,
27 deriveComposerSendState,
28 readFileAsDataUrl,
29 resolveThreadMetadataUpdateForNextTurn,
30 revokeBlobPreviewUrl,
31} from "../ChatView.logic";
32import { toastManager } from "../ui/toast";
33import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
34import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "./composerPromptHistory";
35
36async function run<W, A, E>(command: AtomCommand<W, A, E>, input: W): Promise<A> {
37 const result = await runAtomCommand(appAtomRegistry, command, input, { reportFailure: false });
38 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
39 return result.value;
40}
41
42/**
43 * Sends one queued message as a turn on its thread. `QueuedMessageSender`
44 * calls it when the head message is due, and Send now calls it directly. It
45 * reads nothing from the composer, so it works for threads that are not on
46 * screen. A failed send stays at the head of the queue, held for Send now.
47 */
48export async function sendQueuedMessage(
49 threadRef: ScopedThreadRef,
50 messageId: string,
51): Promise<void> {
52 const { environmentId, threadId } = threadRef;
53 const threadKey = scopedThreadKey(threadRef);
54 const queue = useQueuedMessageStore.getState();
55 const message = queue.beginSend(
56 threadKey,
57 messageId,
58 latestCompletedToolActivityId(readThread(threadRef)?.activities ?? []),
59 );
60 if (!message) return;
61 const { sendSettings } = message;
62 const attachments = [...message.images, ...message.files];
63 const readConfig = () => appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId);
64 const assertFilesAllowed = () => {
65 const config = readConfig();
66 const reason = fileAttachmentCapabilityBlockReason({
67 files: message.files,
68 attachmentUploadsCapabilityKnown: config !== undefined,
69 supportsAttachmentUploads: config?.environment.capabilities.attachmentUploads === true,
70 maxFileAttachmentBytes:
71 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
72 });
73 if (reason !== null) throw new Error(reason);
74 };
75 try {
76 const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
77 prompt: message.prompt,
78 imageCount: attachments.length,
79 terminalContexts: message.terminalContexts,
80 elementContextCount: message.previewAnnotations.length + message.reviewComments.length,
81 });
82 // Only expired terminal context was left. Retrying would block the queue
83 // on every boundary, so drop it and let the queue move on.
84 if (!hasSendableContent) {
85 queue.finishSend(threadKey, message.id);
86 return;
87 }
88 // Expired terminal excerpts are not sent; their chips leave the text with them.
89 const prompt = message.terminalContexts
90 .filter((context) => !sendableTerminalContexts.includes(context))
91 .reduce(
92 (text, context) =>
93 removeInlineContextReference(text, terminalContextReference(context).contextId).prompt,
94 message.prompt,
95 )
96 .trim();
97 const text = applyClaudePromptEffortPrefix(
98 prompt || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
99 sendSettings.promptEffort,
100 );
101
102 assertFilesAllowed();
103 const useUploads = readConfig()?.environment.capabilities.attachmentUploads === true;
104 if (useUploads && attachments.length > 0) {
105 for (const attachment of attachments) {
106 startAttachmentUpload({ environmentId, image: attachment, draftTarget: threadRef });
107 }
108 await awaitAttachmentUploads(attachments.map((attachment) => attachment.id));
109 }
110 const wireAttachments = await Promise.all(
111 attachments.map(async (attachment) => {
112 if (useUploads) {
113 const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
114 if (!uploaded) throw new Error(`Attachment '${attachment.name}' did not upload.`);
115 return uploaded;
116 }
117 if (attachment.type !== "image") {
118 throw new Error("This server does not support file attachments.");
119 }
120 return {
121 type: "image" as const,
122 id: attachment.id,
123 name: attachment.name,
124 mimeType: attachment.mimeType,
125 sizeBytes: attachment.sizeBytes,
126 dataUrl: await readFileAsDataUrl(attachment.file),
127 ...(attachment.source ? { source: attachment.source } : {}),
128 };
129 }),
130 );
131 assertFilesAllowed();
132
133 // The server starts the turn with the thread's stored modes, so a change
134 // made in the composer before queueing is saved first.
135 const createdAt = new Date().toISOString();
136 const shell = readThreadShell(threadRef);
137 const metadataUpdate = shell
138 ? resolveThreadMetadataUpdateForNextTurn({
139 currentModelSelection: shell.modelSelection,
140 nextModelSelection: sendSettings.modelSelection,
141 currentBranch: shell.branch,
142 })
143 : null;
144 if (metadataUpdate) {
145 await run(threadEnvironment.updateMetadata, {
146 environmentId,
147 input: { threadId, ...metadataUpdate },
148 });
149 }
150 if (shell && shell.runtimeMode !== sendSettings.runtimeMode) {
151 await run(threadEnvironment.setRuntimeMode, {
152 environmentId,
153 input: { threadId, runtimeMode: sendSettings.runtimeMode, createdAt },
154 });
155 }
156 if (shell && shell.interactionMode !== sendSettings.interactionMode) {
157 await run(threadEnvironment.setInteractionMode, {
158 environmentId,
159 input: { threadId, interactionMode: sendSettings.interactionMode, createdAt },
160 });
161 }
162
163 // Stop hands a preparing message back to the composer. Past this point
164 // the send can no longer be taken back.
165 const thread = readThread(threadRef) ?? undefined;
166 if (!queue.markDispatching(threadKey, message.id, createLocalDispatchSnapshot(thread))) return;
167 const context = buildMessageContext({
168 terminalContexts: sendableTerminalContexts,
169 reviewComments: message.reviewComments,
170 previewAnnotations: message.previewAnnotations,
171 attachments: attachments.map((attachment, index) => ({
172 attachment,
173 attachmentId: wireAttachments[index]?.id ?? attachment.id,
174 })),
175 });
176 // Servers from before inline context drop the records, so their turns
177 // carry the payload in the text instead.
178 const inlineContext = readConfig()?.environment.capabilities.inlineMessageContext === true;
179 await run(threadEnvironment.startTurn, {
180 environmentId,
181 input: {
182 threadId,
183 message: {
184 messageId: newMessageId(),
185 role: "user",
186 text:
187 context !== undefined && !inlineContext
188 ? serializeLegacyContextMessage({ text, records: context.records })
189 : text,
190 attachments: wireAttachments,
191 ...(context !== undefined && inlineContext ? { context } : {}),
192 },
193 modelSelection: sendSettings.modelSelection,
194 runtimeMode: sendSettings.runtimeMode,
195 interactionMode: sendSettings.interactionMode,
196 createdAt,
197 },
198 });
199 queue.finishSend(threadKey, message.id);
200 if (useUploads) releaseDraftAttachments(attachments);
201 for (const image of message.images) revokeBlobPreviewUrl(image.previewUrl);
202 } catch (error) {
203 if (!queue.failSend(threadKey, message.id)) return;
204 const title = readThreadShell(threadRef)?.title;
205 toastManager.add({
206 type: "error",
207 title: title ? `Queued message not sent in "${title}"` : "Queued message not sent",
208 description: error instanceof Error ? error.message : "Use Send now to try again.",
209 });
210 }
211}