The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-react"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import { useAtomValue } from "@effect/atom-react"; |
| 5 | import { |
| 6 | makeQueuedRunEditStore, |
| 7 | makeQueuedRunsAtom, |
| 8 | } from "@t3tools/client-runtime/queued-run-edit"; |
| 9 | import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; |
| 10 | import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; |
| 11 | import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; |
| 12 | import { |
| 13 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 14 | type ChatAttachment, |
| 15 | type ComposerContextRecord, |
| 16 | type EnvironmentContextRecord, |
| 17 | type ResponseContextRecord, |
| 18 | type EnvironmentId, |
| 19 | type MessageId, |
| 20 | type OrchestrationMessageContext, |
| 21 | type PreviewAnnotationPayload, |
| 22 | type RunId, |
| 23 | type ScopedThreadRef, |
| 24 | type ThreadContextRecord, |
| 25 | type ThreadId, |
| 26 | } from "@t3tools/contracts"; |
| 27 | import { scopedThreadKey } from "@t3tools/client-runtime/environment"; |
| 28 | import { |
| 29 | restoreAttachmentOnlyBootstrapPrompt, |
| 30 | stripAttachmentOnlyBootstrapPrompt, |
| 31 | } from "@t3tools/shared/composerContextReferences"; |
| 32 | import { Atom } from "effect/reactivity"; |
| 33 | import type { RefObject } from "react"; |
| 34 | import { useAssetUrls } from "../../assets/assetUrls"; |
| 35 | import { |
| 36 | queuedRunEditDraftId, |
| 37 | useComposerDraftStore, |
| 38 | type ComposerFileAttachment, |
| 39 | type ComposerImageAttachment, |
| 40 | type ComposerThreadTarget, |
| 41 | } from "../../composerDraftStore"; |
| 42 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 43 | import { |
| 44 | awaitAttachmentUploads, |
| 45 | getUploadedAttachments, |
| 46 | refreshExpiredAttachmentUploads, |
| 47 | releaseDraftAttachments, |
| 48 | startAttachmentUpload, |
| 49 | } from "../../lib/attachmentUploadQueue"; |
| 50 | import { buildMessageContext, isResponseContextRecord } from "../../lib/composerContextRecords"; |
| 51 | import { |
| 52 | collectInlineContextIds, |
| 53 | removeInlineContextReference, |
| 54 | } from "../../lib/composerContextReferences"; |
| 55 | import { readFileAsDataUrl } from "../../lib/imageCompression"; |
| 56 | import type { TerminalContextDraft } from "../../lib/terminalContext"; |
| 57 | import type { ComposerSubmissionIntent } from "../../composer-logic"; |
| 58 | import type { ReviewCommentContext } from "../../reviewCommentContext"; |
| 59 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 60 | import { environmentServerConfigsAtom } from "../../state/server"; |
| 61 | import { |
| 62 | environmentThreadDetails, |
| 63 | environmentThreadShells, |
| 64 | threadEnvironment, |
| 65 | } from "../../state/threads"; |
| 66 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 67 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 68 | import type { ChatComposerHandle } from "./ChatComposer"; |
| 69 | import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; |
| 70 | import { composerDraftContentChanged } from "./composerSend.logic"; |
| 71 | import { |
| 72 | discardQueuedEditDraft, |
| 73 | prepareQueuedEditAttachments, |
| 74 | recoverQueuedMessageEdit, |
| 75 | } from "./queuedMessageEdit"; |
| 76 | import type { EditQueuedRunRequest } from "./QueuedRunsControl"; |
| 77 | |
| 78 | interface EditingQueuedRun { |
| 79 | readonly threadId: ThreadId; |
| 80 | readonly runId: RunId; |
| 81 | readonly messageId: MessageId; |
| 82 | readonly originalText: string; |
| 83 | readonly existingAttachments: ReadonlyArray<ChatAttachment>; |
| 84 | readonly context?: OrchestrationMessageContext | undefined; |
| 85 | /** Removing a server attachment changes the message even when the draft looks untouched. */ |
| 86 | readonly removedExistingAttachment?: true; |
| 87 | } |
| 88 | |
| 89 | // Keyed by the route thread, so an edit survives navigating away and back. |
| 90 | const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({ |
| 91 | registry: appAtomRegistry, |
| 92 | label: "web-queued-run-edits", |
| 93 | }); |
| 94 | |
| 95 | interface QueuedRunEditContent { |
| 96 | readonly prompt: string; |
| 97 | readonly images: ReadonlyArray<ComposerImageAttachment>; |
| 98 | readonly files: ReadonlyArray<ComposerFileAttachment>; |
| 99 | readonly terminalContexts: ReadonlyArray<TerminalContextDraft>; |
| 100 | readonly reviewComments: ReadonlyArray<ReviewCommentContext>; |
| 101 | readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>; |
| 102 | readonly threadContexts: ReadonlyArray<ThreadContextRecord>; |
| 103 | readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>; |
| 104 | readonly replyTo?: ResponseContextRecord | null; |
| 105 | } |
| 106 | |
| 107 | const isDraftOwnedRecord = (record: ComposerContextRecord) => |
| 108 | record.kind === "thread" || record.kind === "environment"; |
| 109 | |
| 110 | async function submitQueuedRunEdit(input: { |
| 111 | readonly environmentId: EnvironmentId; |
| 112 | readonly draftTarget: ComposerThreadTarget; |
| 113 | readonly editing: EditingQueuedRun; |
| 114 | readonly content: QueuedRunEditContent; |
| 115 | readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>; |
| 116 | readonly draftChanged: () => boolean; |
| 117 | }): Promise<string | null> { |
| 118 | const { environmentId, draftTarget, editing, content } = input; |
| 119 | const editText = content.prompt.trim(); |
| 120 | const newAttachments = [...content.images, ...content.files]; |
| 121 | const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => { |
| 122 | const validateFiles = () => { |
| 123 | const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; |
| 124 | const reason = fileAttachmentCapabilityBlockReason({ |
| 125 | files, |
| 126 | attachmentUploadsCapabilityKnown: config !== null, |
| 127 | supportsAttachmentUploads: config !== null, |
| 128 | maxFileAttachmentBytes: |
| 129 | config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null, |
| 130 | }); |
| 131 | if (reason !== null) throw new Error(reason); |
| 132 | }; |
| 133 | validateFiles(); |
| 134 | for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget }); |
| 135 | await awaitAttachmentUploads(files.map((file) => file.id)); |
| 136 | await refreshExpiredAttachmentUploads({ environmentId, images: files, draftTarget }); |
| 137 | validateFiles(); |
| 138 | const uploaded = getUploadedAttachments({ environmentId, images: files }); |
| 139 | if (uploaded === null) throw new Error(m(msg("Retry or remove failed uploads before saving."))); |
| 140 | return uploaded; |
| 141 | }; |
| 142 | try { |
| 143 | const uploads = await prepareQueuedEditAttachments({ |
| 144 | existingAttachments: editing.existingAttachments, |
| 145 | images: content.images, |
| 146 | files: content.files, |
| 147 | readImage: readFileAsDataUrl, |
| 148 | uploadFiles, |
| 149 | }); |
| 150 | if (input.draftChanged()) |
| 151 | return m(msg("Draft changed while preparing this message. Review it and save again.")); |
| 152 | // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped. |
| 153 | const keptRecords = (editing.context?.records ?? []).filter( |
| 154 | (record) => |
| 155 | !isDraftOwnedRecord(record) && |
| 156 | (!("attachmentId" in record) || |
| 157 | editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId)), |
| 158 | ); |
| 159 | const newRecords = |
| 160 | buildMessageContext({ |
| 161 | terminalContexts: content.terminalContexts.filter( |
| 162 | (context) => context.text.trim().length > 0, |
| 163 | ), |
| 164 | reviewComments: content.reviewComments, |
| 165 | previewAnnotations: content.previewAnnotations, |
| 166 | threadContexts: content.threadContexts, |
| 167 | environmentContexts: content.environmentContexts, |
| 168 | replyTo: content.replyTo ?? null, |
| 169 | attachments: newAttachments.map((attachment, index) => ({ |
| 170 | attachment, |
| 171 | attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id, |
| 172 | })), |
| 173 | })?.records ?? []; |
| 174 | const result = await input.editQueuedRun({ |
| 175 | environmentId, |
| 176 | input: { |
| 177 | threadId: editing.threadId, |
| 178 | runId: editing.runId, |
| 179 | text: restoreAttachmentOnlyBootstrapPrompt(editText, uploads.length > 0), |
| 180 | edit: { |
| 181 | messageId: editing.messageId, |
| 182 | attachments: uploads, |
| 183 | context: { |
| 184 | version: 1, |
| 185 | records: [ |
| 186 | ...new Map( |
| 187 | [...keptRecords, ...newRecords].map( |
| 188 | (record) => [record.contextId, record] as const, |
| 189 | ), |
| 190 | ).values(), |
| 191 | ], |
| 192 | }, |
| 193 | }, |
| 194 | }, |
| 195 | }); |
| 196 | return result._tag === "Failure" ? m(msg("Could not save the edited queued message.")) : null; |
| 197 | } catch (error) { |
| 198 | return thrownErrorMessage(error, m) ?? m(msg("Could not save the edited queued message.")); |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | function useEditQueuedRunCommand() { |
| 203 | return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false }); |
| 204 | } |
| 205 | |
| 206 | /** Edits preserve the thread draft; attachment removals stay local until save. */ |
| 207 | export function useQueuedRunEdit(input: { |
| 208 | readonly environmentId: EnvironmentId; |
| 209 | readonly routeThreadRef: ScopedThreadRef; |
| 210 | readonly threadDraftTarget: ComposerThreadTarget; |
| 211 | readonly activeThreadId: ThreadId | null; |
| 212 | readonly serverProjection: ThreadStructure | null; |
| 213 | readonly promptRef: { current: string }; |
| 214 | readonly composerRef: RefObject<ChatComposerHandle | null>; |
| 215 | }) { |
| 216 | const { |
| 217 | environmentId, |
| 218 | routeThreadRef, |
| 219 | threadDraftTarget, |
| 220 | activeThreadId, |
| 221 | serverProjection, |
| 222 | promptRef, |
| 223 | composerRef, |
| 224 | } = input; |
| 225 | const editQueuedRunCommand = useEditQueuedRunCommand(); |
| 226 | const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun); |
| 227 | const editKey = scopedThreadKey(routeThreadRef); |
| 228 | const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null; |
| 229 | const editing = activeThreadId === null ? null : storedEdit; |
| 230 | const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true; |
| 231 | const draftTarget = |
| 232 | editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId); |
| 233 | |
| 234 | const imageResources = (editing?.existingAttachments ?? []) |
| 235 | .filter((attachment) => attachment.type === "image") |
| 236 | .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id })); |
| 237 | const imageUrls = useAssetUrls(environmentId, imageResources); |
| 238 | const urlByAttachmentId = new Map( |
| 239 | imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), |
| 240 | ); |
| 241 | const editingAttachments = |
| 242 | editing === null |
| 243 | ? null |
| 244 | : editing.existingAttachments.map((attachment) => ({ |
| 245 | attachment, |
| 246 | url: urlByAttachmentId.get(attachment.id) ?? null, |
| 247 | })); |
| 248 | |
| 249 | const focusComposerSoon = () => { |
| 250 | window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); |
| 251 | }; |
| 252 | const clearEditDraft = (runId: RunId) => { |
| 253 | const target = queuedRunEditDraftId(routeThreadRef, runId); |
| 254 | // A save in flight still sends these uploads. |
| 255 | if (isSaving) useComposerDraftStore.getState().clearComposerContent(target); |
| 256 | else discardQueuedEditDraft(target); |
| 257 | }; |
| 258 | |
| 259 | const beginEdit = useStableCallback((request: EditQueuedRunRequest) => { |
| 260 | if (activeThreadId === null) return; |
| 261 | if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId); |
| 262 | const target = queuedRunEditDraftId(routeThreadRef, request.runId); |
| 263 | const sentText = stripAttachmentOnlyBootstrapPrompt(request.text); |
| 264 | const context = serverProjection?.messages.find( |
| 265 | (message) => message.id === request.messageId, |
| 266 | )?.context; |
| 267 | const referenced = new Set(collectInlineContextIds(sentText)); |
| 268 | const records = (context?.records ?? []).filter((record) => referenced.has(record.contextId)); |
| 269 | // A reply shows above the composer while its message is edited, not as a chip in the text. |
| 270 | // Only the reply the text still points at: a removed or replaced one stays behind as a record. |
| 271 | const reply = records.find(isResponseContextRecord); |
| 272 | const text = reply ? removeInlineContextReference(sentText, reply.contextId).prompt : sentText; |
| 273 | const store = useComposerDraftStore.getState(); |
| 274 | store.clearComposerContent(target); |
| 275 | store.setPrompt(target, text); |
| 276 | store.setThreadContexts( |
| 277 | target, |
| 278 | records.filter((record): record is ThreadContextRecord => record.kind === "thread"), |
| 279 | ); |
| 280 | store.setEnvironmentContexts( |
| 281 | target, |
| 282 | records.filter((record): record is EnvironmentContextRecord => record.kind === "environment"), |
| 283 | ); |
| 284 | if (reply) store.setReplyTo(target, reply); |
| 285 | const threadRef = { environmentId, threadId: activeThreadId }; |
| 286 | queuedRunEdits.begin( |
| 287 | editKey, |
| 288 | { |
| 289 | threadId: activeThreadId, |
| 290 | runId: request.runId, |
| 291 | messageId: request.messageId, |
| 292 | originalText: text, |
| 293 | existingAttachments: request.attachments, |
| 294 | context, |
| 295 | }, |
| 296 | { |
| 297 | runs: makeQueuedRunsAtom({ |
| 298 | threadId: activeThreadId, |
| 299 | snapshot: threadEnvironment.snapshotAtom(environmentId), |
| 300 | detailStatus: environmentThreadDetails.statusAtom(threadRef), |
| 301 | runs: Atom.make( |
| 302 | (get) => |
| 303 | get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null, |
| 304 | ), |
| 305 | }), |
| 306 | // The run started or was cancelled from another client. A changed |
| 307 | // edit moves into the thread's own draft when that draft is empty; |
| 308 | // otherwise it is dropped. Edits outlive navigation, so the toast is |
| 309 | // unscoped and names the thread: the user may be anywhere by now. |
| 310 | onRunLeftQueue: (_, edit) => { |
| 311 | const recovery = recoverQueuedMessageEdit({ |
| 312 | editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId), |
| 313 | threadTarget: threadDraftTarget, |
| 314 | originalText: edit.originalText, |
| 315 | removedExistingAttachment: edit.removedExistingAttachment === true, |
| 316 | }); |
| 317 | if (recovery === "clean") return; |
| 318 | const title = appAtomRegistry.get( |
| 319 | environmentThreadShells.threadShellAtom(threadRef), |
| 320 | )?.title; |
| 321 | toastManager.add( |
| 322 | stackedThreadToast({ |
| 323 | type: recovery === "kept" ? "info" : "warning", |
| 324 | title: m(msg("Queued message is no longer queued")), |
| 325 | description: |
| 326 | title === undefined |
| 327 | ? recovery === "kept" |
| 328 | ? m(msg("Your unsaved edit was kept in the composer.")) |
| 329 | : m(msg("Your unsaved edit was discarded.")) |
| 330 | : recovery === "kept" |
| 331 | ? m(msg("Your unsaved edit in “{title}” was kept in the composer.", { title })) |
| 332 | : m(msg("Your unsaved edit in “{title}” was discarded.", { title })), |
| 333 | }), |
| 334 | ); |
| 335 | }, |
| 336 | }, |
| 337 | ); |
| 338 | focusComposerSoon(); |
| 339 | }); |
| 340 | const cancelEdit = useStableCallback(() => { |
| 341 | if (editing === null) return; |
| 342 | clearEditDraft(editing.runId); |
| 343 | queuedRunEdits.end(editKey); |
| 344 | focusComposerSoon(); |
| 345 | }); |
| 346 | const removeEditingAttachment = useStableCallback((attachmentId: string) => { |
| 347 | queuedRunEdits.update(editKey, (current) => ({ |
| 348 | ...current, |
| 349 | removedExistingAttachment: true, |
| 350 | existingAttachments: current.existingAttachments.filter( |
| 351 | (attachment) => attachment.id !== attachmentId, |
| 352 | ), |
| 353 | })); |
| 354 | }); |
| 355 | |
| 356 | // The same move as the queued row's "Send now" while a turn runs. |
| 357 | const steerSavedRun = async (edited: EditingQueuedRun) => { |
| 358 | const projection = appAtomRegistry.get( |
| 359 | environmentThreadDetails.quietThreadAtom({ environmentId, threadId: edited.threadId }), |
| 360 | )?.projection; |
| 361 | if (!projection) return; |
| 362 | const workflow = deriveThreadQueueWorkflowState(projection); |
| 363 | const queued = workflow.queuedRuns.find(({ run }) => run.id === edited.runId); |
| 364 | if ( |
| 365 | queued === undefined || |
| 366 | workflow.activeRun === null || |
| 367 | !workflow.canPromoteToSteer || |
| 368 | (queued.run.freshContext === true && !workflow.promoteSkipsCompaction) |
| 369 | ) { |
| 370 | return; |
| 371 | } |
| 372 | await promoteQueuedRun({ |
| 373 | environmentId, |
| 374 | input: { |
| 375 | threadId: edited.threadId, |
| 376 | queuedRunId: edited.runId, |
| 377 | targetRunId: workflow.activeRun.id, |
| 378 | }, |
| 379 | }); |
| 380 | }; |
| 381 | |
| 382 | const saveEdit = async ( |
| 383 | content: QueuedRunEditContent, |
| 384 | setThreadError: (threadId: ThreadId, error: string | null) => void, |
| 385 | submission?: { |
| 386 | readonly dispatchMode: ComposerDispatchMode; |
| 387 | readonly submissionIntent: ComposerSubmissionIntent; |
| 388 | }, |
| 389 | ) => { |
| 390 | if (editing === null || isSaving) return; |
| 391 | const newAttachments = [...content.images, ...content.files]; |
| 392 | if ( |
| 393 | editing.existingAttachments.length + newAttachments.length > |
| 394 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS |
| 395 | ) { |
| 396 | setThreadError( |
| 397 | editing.threadId, |
| 398 | m( |
| 399 | msg("A message can have at most {max} attachments.", { |
| 400 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 401 | }), |
| 402 | ), |
| 403 | ); |
| 404 | return; |
| 405 | } |
| 406 | if ( |
| 407 | content.prompt.trim().length === 0 && |
| 408 | editing.existingAttachments.length === 0 && |
| 409 | newAttachments.length === 0 |
| 410 | ) { |
| 411 | return; |
| 412 | } |
| 413 | // The save's result decides the edit's fate, even if the run starts meanwhile. |
| 414 | const finishSave = queuedRunEdits.startSave(editKey); |
| 415 | if (finishSave === null) return; |
| 416 | const draftBeforeSave = useComposerDraftStore.getState().getComposerDraft(draftTarget); |
| 417 | const draftChanged = () => |
| 418 | appAtomRegistry.get(queuedRunEdits.atom)[editKey] !== editing || |
| 419 | composerDraftContentChanged( |
| 420 | draftBeforeSave, |
| 421 | useComposerDraftStore.getState().getComposerDraft(draftTarget), |
| 422 | ); |
| 423 | const error = await submitQueuedRunEdit({ |
| 424 | environmentId, |
| 425 | draftTarget, |
| 426 | editing, |
| 427 | content, |
| 428 | editQueuedRun: editQueuedRunCommand, |
| 429 | draftChanged, |
| 430 | }); |
| 431 | const changedAfterSave = error === null && draftChanged(); |
| 432 | setThreadError( |
| 433 | editing.threadId, |
| 434 | changedAfterSave |
| 435 | ? m(msg("The earlier edit was saved. Review your newer changes and save again.")) |
| 436 | : error, |
| 437 | ); |
| 438 | const current = finishSave(error === null && !changedAfterSave); |
| 439 | if (!current) { |
| 440 | // A failed save can recover into the thread draft; a newer edit can also retain resources. |
| 441 | const drafts = Object.values(useComposerDraftStore.getState().draftsByThreadKey); |
| 442 | const retainedIds = new Set( |
| 443 | drafts.flatMap((draft) => |
| 444 | [...draft.images, ...draft.files].map((attachment) => attachment.id), |
| 445 | ), |
| 446 | ); |
| 447 | releaseDraftAttachments( |
| 448 | newAttachments.filter((attachment) => !retainedIds.has(attachment.id)), |
| 449 | ); |
| 450 | const retainedPreviews = new Set( |
| 451 | drafts.flatMap((draft) => draft.images.map((image) => image.previewUrl)), |
| 452 | ); |
| 453 | for (const image of content.images) { |
| 454 | if (image.previewUrl.startsWith("blob:") && !retainedPreviews.has(image.previewUrl)) { |
| 455 | URL.revokeObjectURL(image.previewUrl); |
| 456 | } |
| 457 | } |
| 458 | return; |
| 459 | } |
| 460 | if (error !== null) return; |
| 461 | if (changedAfterSave) return; |
| 462 | releaseDraftAttachments(newAttachments); |
| 463 | promptRef.current = ""; |
| 464 | clearEditDraft(editing.runId); |
| 465 | composerRef.current?.resetCursorState(); |
| 466 | focusComposerSoon(); |
| 467 | // A plain submit means "Update queued message"; only the opposite-action shortcut or |
| 468 | // modifier-click asks to steer, as it does for a new follow-up. |
| 469 | if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") { |
| 470 | await steerSavedRun(editing); |
| 471 | } |
| 472 | }; |
| 473 | |
| 474 | return { |
| 475 | editingRunId: editing?.runId ?? null, |
| 476 | isEditing: editing !== null, |
| 477 | isSaving, |
| 478 | draftTarget, |
| 479 | editingAttachments, |
| 480 | beginEdit, |
| 481 | cancelEdit, |
| 482 | removeEditingAttachment, |
| 483 | saveEdit, |
| 484 | }; |
| 485 | } |