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, 03:37 UTC
| 1 | import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 2 | import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; |
| 3 | import { |
| 4 | onThreadRequestsResolved, |
| 5 | pruneResolvedUserInputDrafts, |
| 6 | resolvedQuestionDraftKeys, |
| 7 | userInputDraftKey, |
| 8 | } from "@t3tools/client-runtime/state/thread-requests"; |
| 9 | import type { |
| 10 | EnvironmentId, |
| 11 | RuntimeRequestId, |
| 12 | ScopedThreadRef, |
| 13 | ThreadContextRecord, |
| 14 | ThreadId, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { create } from "zustand"; |
| 17 | import { DraftId, useComposerDraftStore } from "./composerDraftStore"; |
| 18 | import { |
| 19 | cancelPreparingComposerImages, |
| 20 | countPreparingComposerImages, |
| 21 | movePreparingComposerImagesToThread, |
| 22 | } from "./components/chat/preparingComposerImages"; |
| 23 | import { releaseDraftAttachments } from "./lib/attachmentUploadQueue"; |
| 24 | import { |
| 25 | carryDisplacedCustomAnswerIntoPrompt, |
| 26 | threadContextsReferencedByAnswer, |
| 27 | } from "./pendingUserInput"; |
| 28 | |
| 29 | /** Edited question answers, keyed by `userInputDraftKey`; suggested answers are not stored. */ |
| 30 | export const usePendingUserInputAnswers = create< |
| 31 | Record<string, Record<string, PendingUserInputDraftAnswer>> |
| 32 | >(() => ({})); |
| 33 | export const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({})); |
| 34 | |
| 35 | export function questionAttachmentDraftPrefix( |
| 36 | environmentId: EnvironmentId, |
| 37 | threadId: ThreadId, |
| 38 | ): string { |
| 39 | return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`; |
| 40 | } |
| 41 | |
| 42 | export function questionAttachmentDraftId( |
| 43 | environmentId: EnvironmentId, |
| 44 | threadId: ThreadId, |
| 45 | requestId: string, |
| 46 | questionId: string, |
| 47 | ): DraftId { |
| 48 | return DraftId.make( |
| 49 | `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`, |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | type OpenQuestionAttachmentDraft = { |
| 54 | readonly draftId: DraftId; |
| 55 | readonly requestKeys: ReadonlyArray<DraftId>; |
| 56 | }; |
| 57 | |
| 58 | const openQuestionDrafts = new Map<string, OpenQuestionAttachmentDraft>(); |
| 59 | |
| 60 | export function openQuestionAttachmentDraft( |
| 61 | threadRef: ScopedThreadRef, |
| 62 | ): OpenQuestionAttachmentDraft | null { |
| 63 | return openQuestionDrafts.get(scopedThreadKey(threadRef)) ?? null; |
| 64 | } |
| 65 | |
| 66 | export function countQuestionRequestAttachments(draftId: DraftId): number | null { |
| 67 | for (const draft of openQuestionDrafts.values()) { |
| 68 | if (draft.draftId === draftId) return countQuestionAttachments(draft.requestKeys); |
| 69 | } |
| 70 | return null; |
| 71 | } |
| 72 | |
| 73 | export function trackOpenQuestionAttachmentDraft( |
| 74 | threadRef: ScopedThreadRef, |
| 75 | draft: OpenQuestionAttachmentDraft, |
| 76 | ): () => void { |
| 77 | const key = scopedThreadKey(threadRef); |
| 78 | openQuestionDrafts.set(key, draft); |
| 79 | return () => { |
| 80 | if (openQuestionDrafts.get(key) === draft) openQuestionDrafts.delete(key); |
| 81 | }; |
| 82 | } |
| 83 | |
| 84 | export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({ |
| 85 | counts: {}, |
| 86 | })); |
| 87 | |
| 88 | export function countQuestionAttachments(keys: ReadonlyArray<DraftId>): number { |
| 89 | const store = useComposerDraftStore.getState(); |
| 90 | const { counts } = useQuestionAttachmentPreparation.getState(); |
| 91 | return keys.reduce((total, key) => { |
| 92 | const draft = store.getComposerDraft(key); |
| 93 | return total + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + (counts[key] ?? 0); |
| 94 | }, 0); |
| 95 | } |
| 96 | |
| 97 | export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void { |
| 98 | useQuestionAttachmentPreparation.setState((state) => |
| 99 | delta < 0 && !(key in state.counts) |
| 100 | ? state |
| 101 | : { |
| 102 | counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) }, |
| 103 | }, |
| 104 | ); |
| 105 | } |
| 106 | |
| 107 | /** Releases the draft's attachments except `keepIds`, which have moved to another draft. */ |
| 108 | export function clearQuestionAttachmentDraft( |
| 109 | key: DraftId, |
| 110 | keepIds: ReadonlySet<string> = new Set(), |
| 111 | ): void { |
| 112 | const store = useComposerDraftStore.getState(); |
| 113 | const draft = store.getComposerDraft(key); |
| 114 | if (draft) { |
| 115 | releaseDraftAttachments([...draft.images, ...draft.files].filter(({ id }) => !keepIds.has(id))); |
| 116 | for (const image of draft.images) { |
| 117 | if (!keepIds.has(image.id) && image.previewUrl.startsWith("blob:")) { |
| 118 | URL.revokeObjectURL(image.previewUrl); |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | store.clearComposerContent(key); |
| 123 | if (countPreparingComposerImages(key) > 0) cancelPreparingComposerImages(key); |
| 124 | useQuestionAttachmentPreparation.setState(({ counts }) => { |
| 125 | const next = { ...counts }; |
| 126 | delete next[key]; |
| 127 | return { counts: next }; |
| 128 | }); |
| 129 | } |
| 130 | |
| 131 | /** Clears the thread's question attachment drafts for every request outside `pendingRequestIds`. */ |
| 132 | function pruneResolvedQuestionAttachmentDrafts( |
| 133 | environmentId: EnvironmentId, |
| 134 | threadId: ThreadId, |
| 135 | pendingRequestIds: ReadonlyArray<string>, |
| 136 | ): void { |
| 137 | const keys = new Set([ |
| 138 | ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey), |
| 139 | ...Object.keys(useQuestionAttachmentPreparation.getState().counts), |
| 140 | ]); |
| 141 | const prefix = questionAttachmentDraftPrefix(environmentId, threadId); |
| 142 | for (const key of resolvedQuestionDraftKeys(keys, prefix, pendingRequestIds)) { |
| 143 | clearQuestionAttachmentDraft(DraftId.make(key)); |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Stop cancels an open question and a provider timeout expires it; neither sent |
| 149 | * the typed answers, so they move to the thread's own draft (not a queued-message |
| 150 | * edit the composer may be showing) with the thread chips they reference and |
| 151 | * every file or image attached to them. |
| 152 | */ |
| 153 | function returnUnsentAnswersToThreadDraft( |
| 154 | environmentId: EnvironmentId, |
| 155 | threadId: ThreadId, |
| 156 | unansweredRequestIds: ReadonlyArray<RuntimeRequestId>, |
| 157 | ): void { |
| 158 | const answers = usePendingUserInputAnswers.getState(); |
| 159 | const store = useComposerDraftStore.getState(); |
| 160 | const target = scopeThreadRef(environmentId, threadId); |
| 161 | const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; |
| 162 | let prompt = currentPrompt; |
| 163 | const threadContexts: ThreadContextRecord[] = []; |
| 164 | for (const requestId of unansweredRequestIds) { |
| 165 | const drafts = answers[userInputDraftKey(environmentId, threadId, requestId)] ?? {}; |
| 166 | for (const [questionId, { customAnswer }] of Object.entries(drafts)) { |
| 167 | const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(prompt, customAnswer); |
| 168 | if (nextPrompt === prompt) continue; |
| 169 | prompt = nextPrompt; |
| 170 | const questionDraft = store.getComposerDraft( |
| 171 | questionAttachmentDraftId(environmentId, threadId, requestId, questionId), |
| 172 | ); |
| 173 | threadContexts.push( |
| 174 | ...threadContextsReferencedByAnswer( |
| 175 | customAnswer ?? "", |
| 176 | questionDraft?.threadContexts ?? [], |
| 177 | ), |
| 178 | ); |
| 179 | } |
| 180 | } |
| 181 | if (prompt !== currentPrompt) { |
| 182 | store.setPrompt(target, prompt); |
| 183 | store.addThreadContexts(target, threadContexts, { appendReference: false }); |
| 184 | } |
| 185 | |
| 186 | const threadPrefix = questionAttachmentDraftPrefix(environmentId, threadId); |
| 187 | const preparingKeys = Object.keys(useQuestionAttachmentPreparation.getState().counts); |
| 188 | const otherRequestKeys = new Set( |
| 189 | resolvedQuestionDraftKeys( |
| 190 | [...preparingKeys, ...Object.keys(store.draftsByThreadKey)], |
| 191 | threadPrefix, |
| 192 | unansweredRequestIds, |
| 193 | ), |
| 194 | ); |
| 195 | const wasUnanswered = (key: string) => key.startsWith(threadPrefix) && !otherRequestKeys.has(key); |
| 196 | for (const key of preparingKeys.filter(wasUnanswered)) { |
| 197 | movePreparingComposerImagesToThread(key, target); |
| 198 | } |
| 199 | const questionDrafts = Object.entries(store.draftsByThreadKey).filter(([key]) => |
| 200 | wasUnanswered(key), |
| 201 | ); |
| 202 | const images = questionDrafts.flatMap(([, draft]) => draft.images); |
| 203 | const files = questionDrafts.flatMap(([, draft]) => draft.files); |
| 204 | if (images.length === 0 && files.length === 0) return; |
| 205 | store.addImages(target, images); |
| 206 | store.addFiles(target, files); |
| 207 | const moved = useComposerDraftStore.getState().getComposerDraft(target); |
| 208 | const movedIds = new Set([...(moved?.images ?? []), ...(moved?.files ?? [])].map(({ id }) => id)); |
| 209 | // Only a mounted composer re-serializes images, so carry their saved copies for a reload. |
| 210 | void store.appendPersistedAttachments( |
| 211 | target, |
| 212 | images, |
| 213 | questionDrafts.flatMap(([, draft]) => draft.persistedAttachments), |
| 214 | ); |
| 215 | for (const [key] of questionDrafts) clearQuestionAttachmentDraft(DraftId.make(key), movedIds); |
| 216 | } |
| 217 | |
| 218 | // Resolution can come from anywhere: another device, an interrupt, the turn |
| 219 | // ending, or a reload over drafts for requests resolved meanwhile. One listener, |
| 220 | // so unsent answers and their chips are read before their drafts are pruned. |
| 221 | onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => { |
| 222 | returnUnsentAnswersToThreadDraft(environmentId, threadId, unansweredRequestIds); |
| 223 | usePendingUserInputAnswers.setState( |
| 224 | (existing) => |
| 225 | pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds), |
| 226 | true, |
| 227 | ); |
| 228 | usePendingUserInputQuestionIndex.setState( |
| 229 | (existing) => |
| 230 | pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds), |
| 231 | true, |
| 232 | ); |
| 233 | pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds); |
| 234 | }); |