The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { NativeReviewDiffSource } from "./nativeReviewDiffTypes"; |
| 2 | import { diffHighlightTraceId, traceDiffHighlight } from "./nativeReviewDiffTrace"; |
| 3 | |
| 4 | const MAX_SOURCE_FILES = 4; |
| 5 | // Bound retained UTF-16 text across files without discarding an already-fetched |
| 6 | // authoritative source just because it is large. Provider response limits still apply. |
| 7 | const MAX_CACHED_SOURCE_CHARACTERS = 8_000_000; |
| 8 | |
| 9 | function isWeakKey(value: unknown): value is object { |
| 10 | return (typeof value === "object" && value !== null) || typeof value === "function"; |
| 11 | } |
| 12 | |
| 13 | function permanentSourceFailureReason(error: unknown): string | undefined { |
| 14 | for (let depth = 0; depth < 8 && typeof error === "object" && error !== null; depth++) { |
| 15 | const reason = "reason" in error ? error.reason : undefined; |
| 16 | const name = "name" in error ? error.name : undefined; |
| 17 | // Defect serialization preserves error names and causes, but drops custom fields. |
| 18 | if (name === "GitCafeDiffSourceUnavailableError") return "gitcafe-source-unavailable"; |
| 19 | if (name === "GitHubDiffFileContentsUnavailableError") return "github-source-unavailable"; |
| 20 | for (const permanent of [ |
| 21 | "provider-unsupported", |
| 22 | "repository-without-project", |
| 23 | "unsupported", |
| 24 | "oversized", |
| 25 | "binary", |
| 26 | "not-found", |
| 27 | ]) { |
| 28 | if (permanent === reason) return permanent; |
| 29 | } |
| 30 | if ("status" in error && error.status === 413) return "http-413"; |
| 31 | if ("status" in error && error.status === 501) return "http-501"; |
| 32 | // Older servers have no structured reason for an unsupported contents RPC. |
| 33 | if ( |
| 34 | "detail" in error && |
| 35 | error.detail === "This host cannot expand unchanged pull request lines." |
| 36 | ) |
| 37 | return "legacy-host-unsupported"; |
| 38 | error = "cause" in error ? error.cause : undefined; |
| 39 | } |
| 40 | return undefined; |
| 41 | } |
| 42 | |
| 43 | function waitForSource( |
| 44 | promise: Promise<NativeReviewDiffSource | null>, |
| 45 | signal?: AbortSignal, |
| 46 | ): Promise<NativeReviewDiffSource | null> { |
| 47 | if (!signal) return promise; |
| 48 | if (signal.aborted) return Promise.resolve(null); |
| 49 | return new Promise((resolve, reject) => { |
| 50 | const abort = () => { |
| 51 | signal.removeEventListener("abort", abort); |
| 52 | resolve(null); |
| 53 | }; |
| 54 | signal.addEventListener("abort", abort, { once: true }); |
| 55 | void promise.then( |
| 56 | (source) => { |
| 57 | signal.removeEventListener("abort", abort); |
| 58 | resolve(source); |
| 59 | }, |
| 60 | (error: unknown) => { |
| 61 | signal.removeEventListener("abort", abort); |
| 62 | reject(error); |
| 63 | }, |
| 64 | ); |
| 65 | }); |
| 66 | } |
| 67 | |
| 68 | export function createNativeReviewDiffSourceLoader<FileId>( |
| 69 | fetchSource: (fileId: FileId) => Promise<NativeReviewDiffSource>, |
| 70 | ) { |
| 71 | const cached = new Map<FileId, NativeReviewDiffSource>(); |
| 72 | let cachedCharacters = 0; |
| 73 | type Failure = { attempts: number; unavailable: boolean }; |
| 74 | // Request closures can own parsed rows; failed versions must not retain them. |
| 75 | const objectFailures = new WeakMap<object, Failure>(); |
| 76 | const primitiveFailures = new Map<FileId, Failure>(); |
| 77 | const pending = new Map< |
| 78 | FileId, |
| 79 | { |
| 80 | readonly promise: Promise<NativeReviewDiffSource | null>; |
| 81 | readonly subscribers: Set<AbortSignal | undefined>; |
| 82 | } |
| 83 | >(); |
| 84 | // RPC commands cannot abort a request already sent. Serialize source fetches |
| 85 | // and drop queued requests whose viewports have all been cancelled. |
| 86 | let tail = Promise.resolve(); |
| 87 | const loader = diffHighlightTraceId(cached); |
| 88 | |
| 89 | return async (fileId: FileId, signal?: AbortSignal) => { |
| 90 | const file = diffHighlightTraceId(fileId); |
| 91 | const failure = (isWeakKey(fileId) |
| 92 | ? objectFailures.get(fileId) |
| 93 | : primitiveFailures.get(fileId)) ?? { attempts: 0, unavailable: false }; |
| 94 | if (signal?.aborted || failure.unavailable) { |
| 95 | traceDiffHighlight("source-skip", { |
| 96 | loader, |
| 97 | file, |
| 98 | aborted: signal?.aborted ?? false, |
| 99 | unavailable: failure.unavailable, |
| 100 | }); |
| 101 | return null; |
| 102 | } |
| 103 | if (cached.has(fileId)) { |
| 104 | traceDiffHighlight("source-cache", { loader, file }); |
| 105 | const source = cached.get(fileId)!; |
| 106 | cached.delete(fileId); |
| 107 | cached.set(fileId, source); |
| 108 | return source; |
| 109 | } |
| 110 | let request = pending.get(fileId); |
| 111 | if (!request) { |
| 112 | traceDiffHighlight("source-queued", { loader, file, pending: pending.size }); |
| 113 | const subscribers = new Set<AbortSignal | undefined>(); |
| 114 | const promise = tail |
| 115 | .then(async () => { |
| 116 | if ([...subscribers].every((subscriber) => subscriber?.aborted)) { |
| 117 | // A cancelled request must stop being shareable before its promise settles. |
| 118 | pending.delete(fileId); |
| 119 | traceDiffHighlight("source-dropped", { loader, file }); |
| 120 | return null; |
| 121 | } |
| 122 | const attempt = ++failure.attempts; |
| 123 | if (isWeakKey(fileId)) objectFailures.set(fileId, failure); |
| 124 | else primitiveFailures.set(fileId, failure); |
| 125 | traceDiffHighlight("source-start", { loader, file, attempt }); |
| 126 | try { |
| 127 | const contents = await fetchSource(fileId); |
| 128 | traceDiffHighlight("source-result", { |
| 129 | loader, |
| 130 | file, |
| 131 | oldCharacters: contents.oldContents.length, |
| 132 | newCharacters: contents.newContents.length, |
| 133 | }); |
| 134 | const characters = contents.oldContents.length + contents.newContents.length; |
| 135 | if (isWeakKey(fileId)) objectFailures.delete(fileId); |
| 136 | else primitiveFailures.delete(fileId); |
| 137 | if (characters <= MAX_CACHED_SOURCE_CHARACTERS) { |
| 138 | cached.set(fileId, contents); |
| 139 | cachedCharacters += characters; |
| 140 | while ( |
| 141 | cached.size > MAX_SOURCE_FILES || |
| 142 | cachedCharacters > MAX_CACHED_SOURCE_CHARACTERS |
| 143 | ) { |
| 144 | const oldest = cached.keys().next().value!; |
| 145 | const source = cached.get(oldest)!; |
| 146 | cachedCharacters -= source.oldContents.length + source.newContents.length; |
| 147 | cached.delete(oldest); |
| 148 | } |
| 149 | } |
| 150 | return contents; |
| 151 | } catch (error) { |
| 152 | const reason = permanentSourceFailureReason(error); |
| 153 | const permanent = reason !== undefined; |
| 154 | traceDiffHighlight("source-error", { |
| 155 | loader, |
| 156 | file, |
| 157 | attempt, |
| 158 | permanent, |
| 159 | reason: reason ?? "transient", |
| 160 | }); |
| 161 | if (permanent) { |
| 162 | failure.unavailable = true; |
| 163 | traceDiffHighlight("source-unavailable", { |
| 164 | loader, |
| 165 | file, |
| 166 | reason: "permanent-error", |
| 167 | }); |
| 168 | return null; |
| 169 | } |
| 170 | // Only a later viewport request retries; never loop inside this request. |
| 171 | throw error; |
| 172 | } |
| 173 | }) |
| 174 | .finally(() => { |
| 175 | if (pending.get(fileId) === request) pending.delete(fileId); |
| 176 | }); |
| 177 | tail = promise.then( |
| 178 | () => {}, |
| 179 | () => {}, |
| 180 | ); |
| 181 | request = { promise, subscribers }; |
| 182 | pending.set(fileId, request); |
| 183 | } else traceDiffHighlight("source-shared", { loader, file }); |
| 184 | request.subscribers.add(signal); |
| 185 | try { |
| 186 | return await waitForSource(request.promise, signal); |
| 187 | } finally { |
| 188 | if (signal?.aborted) traceDiffHighlight("source-wait-aborted", { loader, file }); |
| 189 | request.subscribers.delete(signal); |
| 190 | } |
| 191 | }; |
| 192 | } |