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 type { MessageId, ThreadId } from "@t3tools/contracts"; |
| 2 | import { parseUrl } from "@t3tools/shared/url"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Schema from "effect/Schema"; |
| 5 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 6 | import type { SetStateAction } from "react"; |
| 7 | import type { ChatMessage } from "../../types"; |
| 8 | import { collectUserMessageBlobPreviewUrls } from "../ChatView.logic"; |
| 9 | |
| 10 | /** |
| 11 | * Messages shown before the server echoes them. An acknowledged message leaves `messages` in the |
| 12 | * render its ack arrives, so it never reappears even if the server later drops its row. Its blob |
| 13 | * previews stay in `handoff` until the server's copies load (see useAttachmentPreviewHandoff). |
| 14 | */ |
| 15 | export interface OptimisticUserMessages { |
| 16 | readonly threadId: ThreadId; |
| 17 | readonly messages: ChatMessage[]; |
| 18 | readonly handoff: Readonly<Record<string, ReadonlyArray<string>>>; |
| 19 | } |
| 20 | |
| 21 | export function emptyOptimisticUserMessages(threadId: ThreadId): OptimisticUserMessages { |
| 22 | return { threadId, messages: [], handoff: {} }; |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * The view's state for `threadId`: the previous thread's messages are released when the thread |
| 27 | * changes, and acknowledged messages are moved out of `messages`. Returns `state` when nothing changes. |
| 28 | */ |
| 29 | export function reconcileOptimisticUserMessages( |
| 30 | state: OptimisticUserMessages, |
| 31 | threadId: ThreadId, |
| 32 | acknowledgedIds: ReadonlySet<MessageId>, |
| 33 | ): OptimisticUserMessages { |
| 34 | if (state.threadId !== threadId) return emptyOptimisticUserMessages(threadId); |
| 35 | if (!state.messages.some((message) => acknowledgedIds.has(message.id))) return state; |
| 36 | const messages: ChatMessage[] = []; |
| 37 | const handoff: Record<string, ReadonlyArray<string>> = { ...state.handoff }; |
| 38 | for (const message of state.messages) { |
| 39 | if (!acknowledgedIds.has(message.id)) { |
| 40 | messages.push(message); |
| 41 | continue; |
| 42 | } |
| 43 | const previewUrls = collectUserMessageBlobPreviewUrls(message); |
| 44 | if (previewUrls.length > 0) handoff[message.id] = previewUrls; |
| 45 | } |
| 46 | return { ...state, messages, handoff }; |
| 47 | } |
| 48 | |
| 49 | /** Applies a send-path update. An update for a thread the view has since left is dropped. */ |
| 50 | export function applyOptimisticUserMessagesAction( |
| 51 | state: OptimisticUserMessages, |
| 52 | threadId: ThreadId, |
| 53 | action: SetStateAction<ChatMessage[]>, |
| 54 | ): OptimisticUserMessages { |
| 55 | if (state.threadId !== threadId) return state; |
| 56 | const next = typeof action === "function" ? action(state.messages) : action; |
| 57 | const unchanged = |
| 58 | next.length === state.messages.length && |
| 59 | next.every((message, index) => message === state.messages[index]); |
| 60 | return unchanged ? state : { ...state, messages: next }; |
| 61 | } |
| 62 | |
| 63 | export function dropOptimisticHandoff( |
| 64 | state: OptimisticUserMessages, |
| 65 | threadId: ThreadId, |
| 66 | messageId: MessageId, |
| 67 | ): OptimisticUserMessages { |
| 68 | if (state.threadId !== threadId || !(messageId in state.handoff)) return state; |
| 69 | const { [messageId]: _released, ...handoff } = state.handoff; |
| 70 | return { ...state, handoff }; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Blob previews a chat view owns per thread. Revocation cannot run in a state updater, so handlers |
| 75 | * revoke here and leaving the thread revokes the rest. A handed-off preview still stands in for the |
| 76 | * server's row, so releasing its message (a send failing after the ack) leaves it to the handoff. |
| 77 | */ |
| 78 | export interface OptimisticBlobPreviews { |
| 79 | readonly track: (threadId: ThreadId, message: ChatMessage) => void; |
| 80 | readonly handOff: (state: OptimisticUserMessages) => void; |
| 81 | readonly revoke: (threadId: ThreadId, previewUrls: ReadonlyArray<string>) => void; |
| 82 | readonly release: (threadId: ThreadId, message: ChatMessage) => void; |
| 83 | readonly revokeThread: (threadId: ThreadId) => void; |
| 84 | } |
| 85 | |
| 86 | export function createOptimisticBlobPreviews(): OptimisticBlobPreviews { |
| 87 | const ownedByThread = new Map<ThreadId, Set<string>>(); |
| 88 | const handedOff = new Set<string>(); |
| 89 | const revoke = (threadId: ThreadId, previewUrls: ReadonlyArray<string>) => { |
| 90 | const owned = ownedByThread.get(threadId); |
| 91 | for (const previewUrl of previewUrls) { |
| 92 | owned?.delete(previewUrl); |
| 93 | handedOff.delete(previewUrl); |
| 94 | if (typeof URL !== "undefined") URL.revokeObjectURL(previewUrl); |
| 95 | } |
| 96 | }; |
| 97 | return { |
| 98 | track: (threadId, message) => { |
| 99 | const previewUrls = collectUserMessageBlobPreviewUrls(message); |
| 100 | if (previewUrls.length === 0) return; |
| 101 | const owned = ownedByThread.get(threadId) ?? new Set<string>(); |
| 102 | for (const previewUrl of previewUrls) owned.add(previewUrl); |
| 103 | ownedByThread.set(threadId, owned); |
| 104 | }, |
| 105 | handOff: (state) => { |
| 106 | for (const previewUrls of Object.values(state.handoff)) { |
| 107 | for (const previewUrl of previewUrls) handedOff.add(previewUrl); |
| 108 | } |
| 109 | }, |
| 110 | revoke, |
| 111 | release: (threadId, message) => |
| 112 | revoke( |
| 113 | threadId, |
| 114 | collectUserMessageBlobPreviewUrls(message).filter((url) => !handedOff.has(url)), |
| 115 | ), |
| 116 | revokeThread: (threadId) => { |
| 117 | revoke(threadId, [...(ownedByThread.get(threadId) ?? [])]); |
| 118 | ownedByThread.delete(threadId); |
| 119 | }, |
| 120 | }; |
| 121 | } |
| 122 | |
| 123 | // Server asset URLs carry a signed token, so the error keeps only where the image was loaded from. |
| 124 | class ImagePreloadError extends Schema.TaggedError<ImagePreloadError>()("ImagePreloadError", { |
| 125 | protocol: Schema.String, |
| 126 | host: Schema.String, |
| 127 | }) { |
| 128 | static fromUrl(url: string) { |
| 129 | const parsed = parseUrl(url, globalThis.location?.href); |
| 130 | return new ImagePreloadError({ protocol: parsed?.protocol ?? "", host: parsed?.host ?? "" }); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | const preloadImage = Effect.fn("optimisticUserMessages.preloadImage")(function* (url: string) { |
| 135 | yield* Effect.callback<void, ImagePreloadError>((resume) => { |
| 136 | const image = new Image(); |
| 137 | image.addEventListener("load", () => resume(Effect.void), { once: true }); |
| 138 | image.addEventListener("error", () => resume(Effect.fail(ImagePreloadError.fromUrl(url))), { |
| 139 | once: true, |
| 140 | }); |
| 141 | image.src = url; |
| 142 | return Effect.sync(() => { |
| 143 | image.src = ""; |
| 144 | }); |
| 145 | }); |
| 146 | }); |
| 147 | |
| 148 | /** |
| 149 | * Loads one handoff's server previews, keyed by `[serverUrls, blobUrls]`. Once they have all |
| 150 | * loaded the blobs are no longer shown, so they are revoked here, once per load. A failed load |
| 151 | * keeps the handoff, and its blobs, until the thread is left. |
| 152 | */ |
| 153 | const handoffPreloadAtom = Atom.family((key: string) => { |
| 154 | const [serverUrls, blobUrls] = JSON.parse(key) as [string[], string[]]; |
| 155 | return Atom.make( |
| 156 | typeof Image === "undefined" |
| 157 | ? Effect.never |
| 158 | : Effect.forEach(serverUrls, preloadImage, { concurrency: "unbounded", discard: true }).pipe( |
| 159 | Effect.tap(() => |
| 160 | Effect.sync(() => { |
| 161 | for (const blobUrl of blobUrls) URL.revokeObjectURL(blobUrl); |
| 162 | }), |
| 163 | ), |
| 164 | ), |
| 165 | ); |
| 166 | }); |
| 167 | |
| 168 | /** |
| 169 | * The message ids, among `[messageId, serverUrls, blobUrls]` entries, whose server previews have |
| 170 | * loaded. Each handoff preloads in its own atom, so a change to the set does not restart the rest. |
| 171 | */ |
| 172 | export const loadedHandoffMessageIdsAtom = Atom.family((key: string) => { |
| 173 | const preloads = JSON.parse(key) as Array<[MessageId, string[], string[]]>; |
| 174 | return Atom.make((get) => |
| 175 | preloads.flatMap(([messageId, serverUrls, blobUrls]) => |
| 176 | AsyncResult.isSuccess(get(handoffPreloadAtom(JSON.stringify([serverUrls, blobUrls])))) |
| 177 | ? [messageId] |
| 178 | : [], |
| 179 | ), |
| 180 | ); |
| 181 | }); |