The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | CommandId, |
| 3 | type EnvironmentId, |
| 4 | type ModelSelection, |
| 5 | type ScopedThreadRef, |
| 6 | type ThreadId, |
| 7 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { |
| 10 | wasBootstrapThreadDeleted, |
| 11 | wasBootstrapThreadNotCreated, |
| 12 | } from "@t3tools/client-runtime/errors"; |
| 13 | import { Atom } from "effect/reactivity"; |
| 14 | import { msg } from "gt-react"; |
| 15 | import { |
| 16 | squashAtomCommandFailure, |
| 17 | type AtomCommandResult, |
| 18 | } from "@t3tools/client-runtime/state/runtime"; |
| 19 | import { m } from "../../i18n/messages"; |
| 20 | import { readLocalApi } from "../../localApi"; |
| 21 | import { |
| 22 | getUploadedAttachments, |
| 23 | refreshExpiredAttachmentUploads, |
| 24 | } from "../../lib/attachmentUploadQueue"; |
| 25 | import { findRevertCheckpoint } from "../../session-logic"; |
| 26 | import { type ChatMessage } from "../../types"; |
| 27 | import { randomUUID } from "~/lib/utils"; |
| 28 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 29 | import { newThreadId } from "~/lib/utils"; |
| 30 | import { |
| 31 | type ComposerFileAttachment, |
| 32 | type ComposerImageAttachment, |
| 33 | type ComposerThreadTarget, |
| 34 | useComposerDraftStore, |
| 35 | DraftId, |
| 36 | } from "../../composerDraftStore"; |
| 37 | import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; |
| 38 | import { createModelSelection } from "@t3tools/shared/model"; |
| 39 | import type { ProviderInstanceEntry } from "../../providerInstances"; |
| 40 | import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState"; |
| 41 | import { |
| 42 | formatOutgoingPrompt, |
| 43 | getAntigravitySendBlockReason, |
| 44 | cloneComposerImageForRetry, |
| 45 | type ComposerSendSnapshot, |
| 46 | readFileAsDataUrl, |
| 47 | prepareRevertedMessageAttachments, |
| 48 | waitForRevertedMessage, |
| 49 | } from "../ChatView.logic"; |
| 50 | import { readPreparedConnection } from "../../state/session"; |
| 51 | import { recallComposerMessage } from "./composerPromptHistory"; |
| 52 | |
| 53 | // Kept per route so a send in flight, and the multiple-model selections, survive |
| 54 | // ChatView remounting while the user navigates. |
| 55 | export const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) => |
| 56 | Atom.make<ReadonlyArray<ModelSelection> | null>(null).pipe(Atom.keepAlive), |
| 57 | ); |
| 58 | const draftSendStateByRouteKey = new Map< |
| 59 | string, |
| 60 | { |
| 61 | readonly sendInFlight: { current: boolean }; |
| 62 | readonly uncertainSubmissions: { current: Map<string, ThreadId> }; |
| 63 | } |
| 64 | >(); |
| 65 | export function draftSendState(routeKey: string) { |
| 66 | let state = draftSendStateByRouteKey.get(routeKey); |
| 67 | if (!state) { |
| 68 | state = { sendInFlight: { current: false }, uncertainSubmissions: { current: new Map() } }; |
| 69 | draftSendStateByRouteKey.set(routeKey, state); |
| 70 | } |
| 71 | return state; |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Starts one thread of a multiple-model send. A request that may have |
| 76 | * reached the server before failing is remembered by `retryKey`, so sending |
| 77 | * again cannot silently create a duplicate thread; its failure toast offers |
| 78 | * to open that thread or to allow the retry. |
| 79 | */ |
| 80 | export async function startFanoutThread(input: { |
| 81 | readonly retryKey: string; |
| 82 | readonly model: string; |
| 83 | readonly uncertainSubmissions: Map<string, ThreadId>; |
| 84 | readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>; |
| 85 | readonly openThread: (threadId: ThreadId) => void; |
| 86 | }): Promise<boolean> { |
| 87 | const { retryKey, uncertainSubmissions } = input; |
| 88 | const uncertainThreadId = uncertainSubmissions.get(retryKey); |
| 89 | const targetThreadId = uncertainThreadId ?? newThreadId(); |
| 90 | let requestMayHaveStarted = false; |
| 91 | try { |
| 92 | if (uncertainThreadId) { |
| 93 | throw new Error( |
| 94 | m( |
| 95 | msg( |
| 96 | "The previous request may have started. Open its thread to check before sending again.", |
| 97 | ), |
| 98 | ), |
| 99 | ); |
| 100 | } |
| 101 | requestMayHaveStarted = true; |
| 102 | const result = await input.start(targetThreadId); |
| 103 | if (result._tag === "Failure") { |
| 104 | const error = squashAtomCommandFailure(result); |
| 105 | if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) { |
| 106 | requestMayHaveStarted = false; |
| 107 | } |
| 108 | throw error; |
| 109 | } |
| 110 | return true; |
| 111 | } catch (error) { |
| 112 | if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) { |
| 113 | uncertainSubmissions.set(retryKey, targetThreadId); |
| 114 | } |
| 115 | const retainedThreadId = uncertainSubmissions.get(retryKey); |
| 116 | const failureToastId = toastManager.add( |
| 117 | stackedThreadToast({ |
| 118 | type: "error", |
| 119 | title: m(msg("Could not start {model}", { model: input.model })), |
| 120 | description: error instanceof Error ? error.message : m(msg("Failed to send message.")), |
| 121 | ...(retainedThreadId |
| 122 | ? { |
| 123 | timeout: 0, |
| 124 | data: { |
| 125 | secondaryActionProps: { |
| 126 | children: m(msg("Allow retry")), |
| 127 | onClick: () => { |
| 128 | void readLocalApi() |
| 129 | ?.dialogs.confirm( |
| 130 | m( |
| 131 | msg( |
| 132 | "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?", |
| 133 | ), |
| 134 | ), |
| 135 | ) |
| 136 | .then( |
| 137 | (confirmed) => { |
| 138 | if ( |
| 139 | confirmed && |
| 140 | uncertainSubmissions.get(retryKey) === retainedThreadId |
| 141 | ) { |
| 142 | uncertainSubmissions.delete(retryKey); |
| 143 | toastManager.close(failureToastId); |
| 144 | } |
| 145 | }, |
| 146 | () => undefined, |
| 147 | ); |
| 148 | }, |
| 149 | }, |
| 150 | }, |
| 151 | actionProps: { |
| 152 | children: m(msg("Open thread")), |
| 153 | onClick: () => input.openThread(retainedThreadId), |
| 154 | }, |
| 155 | } |
| 156 | : {}), |
| 157 | }), |
| 158 | ); |
| 159 | return false; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Reverts the thread to before `message` and puts that message's text, mentions |
| 165 | * and attachments back in the composer draft. Returns the restored prompt, or the |
| 166 | * error to show; on error the draft is untouched. |
| 167 | */ |
| 168 | export async function rewindToMessage(input: { |
| 169 | readonly message: ChatMessage; |
| 170 | readonly environmentId: EnvironmentId; |
| 171 | readonly routeThreadRef: ScopedThreadRef; |
| 172 | readonly threadId: ThreadId; |
| 173 | readonly turnCount: number; |
| 174 | readonly restoreFiles: boolean; |
| 175 | readonly checkpoint: ReturnType<typeof findRevertCheckpoint>; |
| 176 | readonly draftTarget: ScopedThreadRef | DraftId; |
| 177 | readonly composerHasPendingAttachments: boolean; |
| 178 | readonly createAssetUrl: Parameters< |
| 179 | typeof prepareRevertedMessageAttachments |
| 180 | >[0]["createAssetUrl"]; |
| 181 | readonly revertThreadCheckpoint: (value: { |
| 182 | environmentId: EnvironmentId; |
| 183 | input: { |
| 184 | commandId: CommandId; |
| 185 | threadId: ThreadId; |
| 186 | turnCount: number; |
| 187 | restoreFiles: boolean; |
| 188 | checkpointId?: string; |
| 189 | scopeId?: string; |
| 190 | }; |
| 191 | }) => Promise<AtomCommandResult<unknown, unknown>>; |
| 192 | }): Promise< |
| 193 | | { readonly error: string; readonly prompt?: never } |
| 194 | | { readonly error: null; readonly prompt: string } |
| 195 | > { |
| 196 | const { message, environmentId, draftTarget } = input; |
| 197 | try { |
| 198 | if (input.composerHasPendingAttachments) { |
| 199 | throw new Error(m(msg("Wait for attachments to finish preparing before rewinding."))); |
| 200 | } |
| 201 | const connection = readPreparedConnection(environmentId); |
| 202 | if (!connection) throw new Error(m(msg("The environment is not connected."))); |
| 203 | const files = await prepareRevertedMessageAttachments({ |
| 204 | message, |
| 205 | environmentId, |
| 206 | httpBaseUrl: connection.httpBaseUrl, |
| 207 | createAssetUrl: input.createAssetUrl, |
| 208 | }); |
| 209 | const store = useComposerDraftStore.getState(); |
| 210 | const draft = store.getComposerDraft(draftTarget); |
| 211 | if ( |
| 212 | (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length > |
| 213 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS |
| 214 | ) { |
| 215 | throw new Error( |
| 216 | m(msg("Make room for this message's attachments in the composer before rewinding.")), |
| 217 | ); |
| 218 | } |
| 219 | const commandId = CommandId.make(randomUUID()); |
| 220 | await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => { |
| 221 | const result = await input.revertThreadCheckpoint({ |
| 222 | environmentId, |
| 223 | input: { |
| 224 | commandId, |
| 225 | threadId: input.threadId, |
| 226 | turnCount: input.turnCount, |
| 227 | restoreFiles: input.restoreFiles, |
| 228 | ...(input.checkpoint === undefined |
| 229 | ? {} |
| 230 | : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }), |
| 231 | }, |
| 232 | }); |
| 233 | if (result._tag === "Failure") throw squashAtomCommandFailure(result); |
| 234 | }); |
| 235 | const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? ""; |
| 236 | const { prompt: restoredPrompt, mentions } = recallComposerMessage(message); |
| 237 | const nextPrompt = |
| 238 | restoredPrompt.length === 0 |
| 239 | ? currentPrompt |
| 240 | : currentPrompt.length > 0 |
| 241 | ? `${currentPrompt}\n\n${restoredPrompt}` |
| 242 | : restoredPrompt; |
| 243 | store.setPrompt(draftTarget, nextPrompt); |
| 244 | // The restored prompt already carries the chips; these add only their records. |
| 245 | store.addThreadContexts(draftTarget, mentions.threadContexts, { appendReference: false }); |
| 246 | store.addEnvironmentContexts(draftTarget, mentions.environmentContexts, { |
| 247 | appendReference: false, |
| 248 | }); |
| 249 | const images: ComposerImageAttachment[] = []; |
| 250 | const restoredFiles: ComposerFileAttachment[] = []; |
| 251 | files.forEach((file, index) => { |
| 252 | const attachment = { |
| 253 | id: randomUUID(), |
| 254 | name: file.name, |
| 255 | mimeType: file.type, |
| 256 | sizeBytes: file.size, |
| 257 | file, |
| 258 | }; |
| 259 | if (message.attachments?.[index]?.type === "image") { |
| 260 | images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) }); |
| 261 | } else { |
| 262 | restoredFiles.push({ ...attachment, type: "file" }); |
| 263 | } |
| 264 | }); |
| 265 | store.addImages(draftTarget, images, { allowDuplicates: true }); |
| 266 | store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true }); |
| 267 | return { error: null, prompt: nextPrompt }; |
| 268 | } catch (error) { |
| 269 | return { |
| 270 | error: error instanceof Error ? error.message : m(msg("Failed to revert thread state.")), |
| 271 | }; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | function withRestored<T>( |
| 276 | existing: ReadonlyArray<T> | undefined, |
| 277 | restored: ReadonlyArray<T>, |
| 278 | key: (item: T) => string, |
| 279 | ): T[] { |
| 280 | const kept = existing ?? []; |
| 281 | return [...kept, ...restored.filter((item) => !kept.some((other) => key(other) === key(item)))]; |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Writes a failed send's composer contents back into its draft, after anything |
| 286 | * typed since. Returns the restored images, which are fresh copies so their |
| 287 | * preview URLs outlive the optimistic row that held the originals. |
| 288 | */ |
| 289 | export function restoreComposerDraft( |
| 290 | draftTarget: ScopedThreadRef | DraftId, |
| 291 | snapshot: ComposerSendSnapshot, |
| 292 | ): ComposerImageAttachment[] { |
| 293 | const store = useComposerDraftStore.getState(); |
| 294 | const current = store.getComposerDraft(draftTarget); |
| 295 | const images = snapshot.images.map(cloneComposerImageForRetry); |
| 296 | store.setPrompt( |
| 297 | draftTarget, |
| 298 | current?.prompt.trim() ? `${current.prompt}\n\n${snapshot.draftText}` : snapshot.draftText, |
| 299 | ); |
| 300 | store.setReplyTo(draftTarget, current?.replyTo ?? snapshot.replyTo); |
| 301 | store.addImages(draftTarget, images); |
| 302 | store.addFiles(draftTarget, snapshot.files); |
| 303 | store.setTerminalContexts( |
| 304 | draftTarget, |
| 305 | withRestored(current?.terminalContexts, snapshot.terminalContexts, (context) => context.id), |
| 306 | ); |
| 307 | store.setPreviewAnnotations( |
| 308 | draftTarget, |
| 309 | withRestored(current?.previewAnnotations, snapshot.previewAnnotations, (entry) => entry.id), |
| 310 | ); |
| 311 | store.setReviewComments( |
| 312 | draftTarget, |
| 313 | withRestored(current?.reviewComments, snapshot.reviewComments, (comment) => comment.id), |
| 314 | ); |
| 315 | store.setThreadContexts( |
| 316 | draftTarget, |
| 317 | withRestored(current?.threadContexts, snapshot.threadContexts, (record) => record.contextId), |
| 318 | ); |
| 319 | store.setEnvironmentContexts( |
| 320 | draftTarget, |
| 321 | withRestored( |
| 322 | current?.environmentContexts, |
| 323 | snapshot.environmentContexts, |
| 324 | (record) => record.contextId, |
| 325 | ), |
| 326 | ); |
| 327 | return images; |
| 328 | } |
| 329 | |
| 330 | export interface MultipleModelTarget { |
| 331 | readonly selection: ModelSelection; |
| 332 | readonly text: string; |
| 333 | } |
| 334 | |
| 335 | /** |
| 336 | * The thread each selected model starts for a multiple-model send, in |
| 337 | * selection order, or why that model cannot take the message. |
| 338 | */ |
| 339 | export function resolveMultipleModelTargets(input: { |
| 340 | readonly selections: ReadonlyArray<ModelSelection>; |
| 341 | readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>; |
| 342 | readonly messageText: string; |
| 343 | }): Array<MultipleModelTarget | { readonly error: string }> { |
| 344 | const { messageText } = input; |
| 345 | return input.selections.map((selection) => { |
| 346 | const provider = input.providerInstanceEntries.find( |
| 347 | (entry) => entry.instanceId === selection.instanceId, |
| 348 | ); |
| 349 | if (!provider?.enabled || !provider.isAvailable || provider.status !== "ready") { |
| 350 | return { error: m(msg("Provider for {model} is unavailable.", { model: selection.model })) }; |
| 351 | } |
| 352 | const providerBlockReason = getAntigravitySendBlockReason(provider.snapshot, selection.model); |
| 353 | if (providerBlockReason) return { error: providerBlockReason }; |
| 354 | const providerState = getComposerProviderState({ |
| 355 | provider: provider.driverKind, |
| 356 | model: selection.model, |
| 357 | models: provider.models, |
| 358 | modelOptions: selection.options, |
| 359 | promptInjectionState: getComposerPromptInjectionState(messageText), |
| 360 | }); |
| 361 | return { |
| 362 | selection: createModelSelection( |
| 363 | selection.instanceId, |
| 364 | selection.model, |
| 365 | providerState.modelOptionsForDispatch, |
| 366 | ), |
| 367 | text: formatOutgoingPrompt({ |
| 368 | provider: provider.driverKind, |
| 369 | model: selection.model, |
| 370 | models: provider.models, |
| 371 | effort: providerState.promptEffort, |
| 372 | text: messageText || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, |
| 373 | }), |
| 374 | }; |
| 375 | }); |
| 376 | } |
| 377 | |
| 378 | /** |
| 379 | * The attachments a turn sends: the server's upload records when it takes uploads, otherwise |
| 380 | * images inlined as data URLs. Waits for in-flight uploads; rejects when one cannot go out. |
| 381 | */ |
| 382 | export function prepareTurnAttachments(input: { |
| 383 | readonly environmentId: EnvironmentId; |
| 384 | readonly attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>; |
| 385 | readonly usesAttachmentUploads: boolean; |
| 386 | readonly draftTarget: ComposerThreadTarget; |
| 387 | }) { |
| 388 | const { environmentId, usesAttachmentUploads, draftTarget } = input; |
| 389 | return Promise.all( |
| 390 | input.attachments.map(async (attachment) => { |
| 391 | if (usesAttachmentUploads) { |
| 392 | await refreshExpiredAttachmentUploads({ |
| 393 | environmentId, |
| 394 | images: [attachment], |
| 395 | draftTarget, |
| 396 | }); |
| 397 | const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0]; |
| 398 | if (!uploaded) { |
| 399 | throw new Error( |
| 400 | m(msg("Attachment ''{name}'' failed to upload.", { name: attachment.name })), |
| 401 | ); |
| 402 | } |
| 403 | return uploaded; |
| 404 | } |
| 405 | if (attachment.type !== "image") { |
| 406 | throw new Error(m(msg("This server does not support file attachments."))); |
| 407 | } |
| 408 | return { |
| 409 | type: "image" as const, |
| 410 | id: attachment.id, |
| 411 | name: attachment.name, |
| 412 | mimeType: attachment.mimeType, |
| 413 | sizeBytes: attachment.sizeBytes, |
| 414 | dataUrl: await readFileAsDataUrl(attachment.file), |
| 415 | ...(attachment.source ? { source: attachment.source } : {}), |
| 416 | }; |
| 417 | }), |
| 418 | ); |
| 419 | } |