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 { |
| 2 | OrchestrationV2AppThread, |
| 3 | ThreadLinkedPullRequest, |
| 4 | ThreadPullRequestKey, |
| 5 | ThreadPullRequestLink, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { canonicalRepositoryPath } from "@t3tools/shared/git"; |
| 8 | import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; |
| 9 | |
| 10 | import type { SourceControlDefinitionRegistry } from "./definition.ts"; |
| 11 | |
| 12 | type ThreadPullRequestKeySource = ThreadPullRequestKey & { |
| 13 | readonly authority?: string; |
| 14 | readonly url?: string; |
| 15 | }; |
| 16 | |
| 17 | function isOpen(link: ThreadPullRequestLink): boolean { |
| 18 | return link.snapshot === null || link.snapshot.state === "open"; |
| 19 | } |
| 20 | |
| 21 | function latestUpdatedAt(link: ThreadPullRequestLink): number { |
| 22 | const value = link.snapshot?.updatedAt ?? link.linkedAt; |
| 23 | const ms = Date.parse(value); |
| 24 | return Number.isNaN(ms) ? 0 : ms; |
| 25 | } |
| 26 | |
| 27 | export type ThreadCurrentPullRequest = |
| 28 | | { readonly kind: "single"; readonly link: ThreadPullRequestLink } |
| 29 | | { |
| 30 | readonly kind: "stack"; |
| 31 | readonly open: ReadonlyArray<ThreadPullRequestLink>; |
| 32 | readonly top: ThreadPullRequestLink; |
| 33 | }; |
| 34 | |
| 35 | function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> { |
| 36 | // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023 |
| 37 | // array methods, and a TypeError here is fatal on every mobile launch that renders a stack. |
| 38 | return chain.layers |
| 39 | .map((link, index) => ({ link, index, depth: chain.depths[index]! })) |
| 40 | .sort((left, right) => right.depth - left.depth || right.index - left.index) |
| 41 | .map((entry) => entry.link); |
| 42 | } |
| 43 | |
| 44 | export interface ThreadPullRequestChain { |
| 45 | readonly kind: "native" | "derived"; |
| 46 | readonly layers: ReadonlyArray<ThreadPullRequestLink>; |
| 47 | /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */ |
| 48 | readonly depths: ReadonlyArray<number>; |
| 49 | } |
| 50 | |
| 51 | export type ThreadPullRequestBadge = { |
| 52 | readonly state: "open" | "closed" | "merged" | "draft"; |
| 53 | } & ( |
| 54 | | { |
| 55 | readonly kind: "stack"; |
| 56 | readonly layers: number; |
| 57 | } |
| 58 | | { readonly kind: "pull-request"; readonly others: number } |
| 59 | ); |
| 60 | |
| 61 | /** |
| 62 | * Thread pull request identity reads a link's URL through the hosts in `registry`, so each side |
| 63 | * binds these once to its own registry. |
| 64 | */ |
| 65 | export function makeThreadPullRequests( |
| 66 | registry: Pick< |
| 67 | SourceControlDefinitionRegistry, |
| 68 | "parseChangeRequestUrl" | "canonicalRepositoryKey" | "findByRepositoryKey" |
| 69 | >, |
| 70 | ) { |
| 71 | const parse = (url: string) => registry.parseChangeRequestUrl(url)?.link ?? null; |
| 72 | |
| 73 | function normalizeThreadPullRequestKey(key: ThreadPullRequestKeySource): ThreadPullRequestKey { |
| 74 | const parsed = key.url === undefined ? null : parse(key.url); |
| 75 | const authority = |
| 76 | key.authority ?? |
| 77 | (parsed?.repository === canonicalRepositoryPath(key.repository.trim()) && |
| 78 | parsed.number === key.number |
| 79 | ? parsed.authority |
| 80 | : undefined); |
| 81 | const canonical = registry.canonicalRepositoryKey( |
| 82 | `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`, |
| 83 | ); |
| 84 | const separator = canonical.indexOf("/"); |
| 85 | return { |
| 86 | host: canonical.slice(0, separator), |
| 87 | repository: canonical.slice(separator + 1), |
| 88 | number: key.number, |
| 89 | }; |
| 90 | } |
| 91 | |
| 92 | function legacyThreadPullRequestKey( |
| 93 | linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">, |
| 94 | fallbackHost?: string, |
| 95 | ): ThreadPullRequestKey { |
| 96 | const parsed = parse(linked.url); |
| 97 | if (parsed !== null && parsed.number === linked.number) { |
| 98 | if ( |
| 99 | parsed.authority !== undefined || |
| 100 | registry.findByRepositoryKey(`${parsed.host}/${parsed.repository}`) !== undefined |
| 101 | ) { |
| 102 | return normalizeThreadPullRequestKey(parsed); |
| 103 | } |
| 104 | } |
| 105 | let host = fallbackHost; |
| 106 | if (host === undefined) { |
| 107 | try { |
| 108 | host = new URL(linked.url).hostname; |
| 109 | } catch { |
| 110 | host = "unknown"; |
| 111 | } |
| 112 | } |
| 113 | return { |
| 114 | host: host.trim().toLowerCase() || "unknown", |
| 115 | repository: linked.repository.trim().toLowerCase(), |
| 116 | number: linked.number, |
| 117 | }; |
| 118 | } |
| 119 | |
| 120 | function threadPullRequestKeysEqual( |
| 121 | left: ThreadPullRequestKeySource, |
| 122 | right: ThreadPullRequestKeySource, |
| 123 | ): boolean { |
| 124 | return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right); |
| 125 | } |
| 126 | |
| 127 | // Clients re-derive chains for every link on each render, and normalizing parses the |
| 128 | // link's URL. Links are immutable and keep their identity until they change. |
| 129 | const normalizedKeys = new WeakMap<ThreadPullRequestKeySource, ThreadPullRequestKey>(); |
| 130 | |
| 131 | function normalizedKeyOf(key: ThreadPullRequestKeySource): ThreadPullRequestKey { |
| 132 | let normalized = normalizedKeys.get(key); |
| 133 | if (normalized === undefined) { |
| 134 | normalized = normalizeThreadPullRequestKey(key); |
| 135 | normalizedKeys.set(key, normalized); |
| 136 | } |
| 137 | return normalized; |
| 138 | } |
| 139 | |
| 140 | function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string { |
| 141 | const normalized = normalizedKeyOf(key); |
| 142 | return `${normalized.host}/${normalized.repository}#${normalized.number}`; |
| 143 | } |
| 144 | |
| 145 | function resolveThreadCurrentPullRequest( |
| 146 | links: ReadonlyArray<ThreadPullRequestLink>, |
| 147 | ): ThreadCurrentPullRequest | null { |
| 148 | const visible = visibleThreadPullRequests(links); |
| 149 | if (visible.length === 0) return null; |
| 150 | const open = visible.filter(isOpen); |
| 151 | if (open.length === 1) return { kind: "single", link: open[0]! }; |
| 152 | const chains = resolveThreadPullRequestChains(visible); |
| 153 | if (open.length > 1) { |
| 154 | const openChains = chains |
| 155 | .map((chain) => layersFromTop(chain).filter(isOpen)) |
| 156 | .filter((layers) => layers.length > 0); |
| 157 | const ordered = |
| 158 | openChains.length === 1 |
| 159 | ? openChains[0]! |
| 160 | : openChains |
| 161 | .map((layers) => ({ |
| 162 | layers, |
| 163 | newestLinkedAt: Math.max(...layers.map((link) => Date.parse(link.linkedAt))), |
| 164 | })) |
| 165 | .sort((left, right) => right.newestLinkedAt - left.newestLinkedAt) |
| 166 | .flatMap((chain) => chain.layers); |
| 167 | return { kind: "stack", open: ordered, top: ordered[0]! }; |
| 168 | } |
| 169 | if (chains.length === 1) { |
| 170 | return { kind: "single", link: layersFromTop(chains[0]!)[0]! }; |
| 171 | } |
| 172 | let latest = visible[0]!; |
| 173 | let latestTimestamp = latestUpdatedAt(latest); |
| 174 | for (let index = 1; index < visible.length; index++) { |
| 175 | const link = visible[index]!; |
| 176 | const timestamp = latestUpdatedAt(link); |
| 177 | if (timestamp > latestTimestamp) { |
| 178 | latest = link; |
| 179 | latestTimestamp = timestamp; |
| 180 | } |
| 181 | } |
| 182 | return { kind: "single", link: latest }; |
| 183 | } |
| 184 | |
| 185 | function resolveThreadCurrentPullRequestLink( |
| 186 | links: ReadonlyArray<ThreadPullRequestLink>, |
| 187 | ): ThreadPullRequestLink | null { |
| 188 | const current = resolveThreadCurrentPullRequest(links); |
| 189 | if (current === null) return null; |
| 190 | return current.kind === "single" ? current.link : current.top; |
| 191 | } |
| 192 | |
| 193 | function resolveThreadPullRequestChains( |
| 194 | links: ReadonlyArray<ThreadPullRequestLink>, |
| 195 | ): ReadonlyArray<ThreadPullRequestChain> { |
| 196 | const visible = visibleThreadPullRequests(links); |
| 197 | const chains: Array<ThreadPullRequestChain> = []; |
| 198 | const placed = new Set<string>(); |
| 199 | |
| 200 | const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>(); |
| 201 | for (const link of visible) { |
| 202 | if (link.stack === null) continue; |
| 203 | const key = normalizedKeyOf(link); |
| 204 | const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`; |
| 205 | const members = nativeStacks.get(stackKey) ?? []; |
| 206 | members.push(link); |
| 207 | nativeStacks.set(stackKey, members); |
| 208 | } |
| 209 | for (const members of nativeStacks.values()) { |
| 210 | // Saved snapshots can lag behind newer members of the same stack. |
| 211 | const memberNumbers = new Set(members.map((member) => member.number)); |
| 212 | let layers = members[0]!.stack!.layers; |
| 213 | let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length; |
| 214 | for (const member of members.slice(1)) { |
| 215 | const candidate = member.stack!.layers; |
| 216 | const candidateCoverage = candidate.filter((layer) => |
| 217 | memberNumbers.has(layer.number), |
| 218 | ).length; |
| 219 | if ( |
| 220 | candidateCoverage > coverage || |
| 221 | (candidateCoverage === coverage && candidate.length > layers.length) |
| 222 | ) { |
| 223 | layers = candidate; |
| 224 | coverage = candidateCoverage; |
| 225 | } |
| 226 | } |
| 227 | const order = new Map(layers.map((layer, index) => [layer.number, index])); |
| 228 | members.sort( |
| 229 | (left, right) => |
| 230 | (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length), |
| 231 | ); |
| 232 | for (const member of members) placed.add(threadPullRequestKeyOf(member)); |
| 233 | chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) }); |
| 234 | } |
| 235 | |
| 236 | const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link))); |
| 237 | const branchKey = (link: ThreadPullRequestLink, branch: string) => { |
| 238 | const key = normalizedKeyOf(link); |
| 239 | return `${key.host}/${key.repository}:${branch}`; |
| 240 | }; |
| 241 | const byHead = new Map<string, ThreadPullRequestLink | null>(); |
| 242 | for (const link of remaining) { |
| 243 | if (link.snapshot === null) continue; |
| 244 | const key = branchKey(link, link.snapshot.headBranch); |
| 245 | byHead.set(key, byHead.has(key) ? null : link); |
| 246 | } |
| 247 | const parentOf = (link: ThreadPullRequestLink) => { |
| 248 | if (link.snapshot === null) return undefined; |
| 249 | const parent = byHead.get(branchKey(link, link.snapshot.baseBranch)); |
| 250 | return parent == null || parent === link ? undefined : parent; |
| 251 | }; |
| 252 | const children = new Map<string, Array<ThreadPullRequestLink>>(); |
| 253 | for (const link of remaining) { |
| 254 | const parent = parentOf(link); |
| 255 | if (parent === undefined) continue; |
| 256 | const key = threadPullRequestKeyOf(parent); |
| 257 | const siblings = children.get(key) ?? []; |
| 258 | siblings.push(link); |
| 259 | children.set(key, siblings); |
| 260 | } |
| 261 | for (const base of remaining) { |
| 262 | if (parentOf(base) !== undefined) continue; |
| 263 | const layers: Array<ThreadPullRequestLink> = []; |
| 264 | const depths: Array<number> = []; |
| 265 | const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [ |
| 266 | { link: base, depth: 0 }, |
| 267 | ]; |
| 268 | for (let next = pending.pop(); next !== undefined; next = pending.pop()) { |
| 269 | const key = threadPullRequestKeyOf(next.link); |
| 270 | // Two links with one identity would otherwise share a child list and expand forever. |
| 271 | if (placed.has(key)) continue; |
| 272 | placed.add(key); |
| 273 | layers.push(next.link); |
| 274 | depths.push(next.depth); |
| 275 | const below = children.get(key) ?? []; |
| 276 | for (let index = below.length - 1; index >= 0; index -= 1) { |
| 277 | pending.push({ link: below[index]!, depth: next.depth + 1 }); |
| 278 | } |
| 279 | } |
| 280 | if (layers.length > 0) chains.push({ kind: "derived", layers, depths }); |
| 281 | } |
| 282 | for (const link of remaining) { |
| 283 | if (!placed.has(threadPullRequestKeyOf(link))) { |
| 284 | chains.push({ kind: "derived", layers: [link], depths: [0] }); |
| 285 | } |
| 286 | } |
| 287 | return chains; |
| 288 | } |
| 289 | |
| 290 | function resolveThreadPullRequestBadge( |
| 291 | pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined, |
| 292 | ): ThreadPullRequestBadge | null { |
| 293 | const visible = visibleThreadPullRequests(pullRequests ?? []); |
| 294 | if (visible.length === 0) return null; |
| 295 | const states = visible.map((link) => link.snapshot?.state ?? "open"); |
| 296 | const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft) |
| 297 | ? "draft" |
| 298 | : states.includes("open") |
| 299 | ? "open" |
| 300 | : states.every((entry) => entry === "merged") |
| 301 | ? "merged" |
| 302 | : "closed"; |
| 303 | const chains = resolveThreadPullRequestChains(visible); |
| 304 | if (visible.length > 1 && chains.length === 1) { |
| 305 | return { kind: "stack", layers: visible.length, state }; |
| 306 | } |
| 307 | return { kind: "pull-request", others: visible.length - 1, state }; |
| 308 | } |
| 309 | |
| 310 | /** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */ |
| 311 | function threadPullRequestsOf(thread: { |
| 312 | readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined; |
| 313 | readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined; |
| 314 | }): ReadonlyArray<ThreadPullRequestLink> { |
| 315 | if (thread.pullRequests !== undefined) return thread.pullRequests; |
| 316 | const linked = thread.linkedPullRequest; |
| 317 | return linked == null |
| 318 | ? [] |
| 319 | : [ |
| 320 | { |
| 321 | ...legacyThreadPullRequestKey(linked), |
| 322 | url: linked.url, |
| 323 | source: "manual", |
| 324 | linkedAt: "1970-01-01T00:00:00.000Z", |
| 325 | snapshot: null, |
| 326 | stack: null, |
| 327 | }, |
| 328 | ]; |
| 329 | } |
| 330 | |
| 331 | function applyThreadPullRequestLinkUpdate( |
| 332 | thread: OrchestrationV2AppThread, |
| 333 | updated: ThreadPullRequestLink, |
| 334 | ): OrchestrationV2AppThread { |
| 335 | return { |
| 336 | ...thread, |
| 337 | pullRequests: threadPullRequestsOf(thread).map((link) => |
| 338 | threadPullRequestKeysEqual(link, updated) ? updated : link, |
| 339 | ), |
| 340 | }; |
| 341 | } |
| 342 | |
| 343 | return { |
| 344 | normalizeThreadPullRequestKey, |
| 345 | legacyThreadPullRequestKey, |
| 346 | threadPullRequestKeysEqual, |
| 347 | threadPullRequestKeyOf, |
| 348 | resolveThreadCurrentPullRequest, |
| 349 | resolveThreadCurrentPullRequestLink, |
| 350 | resolveThreadPullRequestChains, |
| 351 | resolveThreadPullRequestBadge, |
| 352 | threadPullRequestsOf, |
| 353 | applyThreadPullRequestLinkUpdate, |
| 354 | }; |
| 355 | } |
| 356 | |
| 357 | export interface PullRequestListLine { |
| 358 | readonly link: ThreadPullRequestLink; |
| 359 | readonly depth: number; |
| 360 | readonly chainKey: string; |
| 361 | readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null; |
| 362 | } |
| 363 | |
| 364 | function chainKeyOf(chain: ThreadPullRequestChain): string { |
| 365 | const bottom = chain.layers[0]!; |
| 366 | return `${bottom.host}/${bottom.repository}#${bottom.number}`; |
| 367 | } |
| 368 | |
| 369 | export function pullRequestListLines( |
| 370 | chains: ReadonlyArray<ThreadPullRequestChain>, |
| 371 | ): ReadonlyArray<PullRequestListLine> { |
| 372 | const ordered = [...chains].sort( |
| 373 | (left, right) => |
| 374 | Math.max(...right.layers.map(latestUpdatedAt)) - |
| 375 | Math.max(...left.layers.map(latestUpdatedAt)), |
| 376 | ); |
| 377 | return ordered.flatMap((chain) => { |
| 378 | const chainKey = chainKeyOf(chain); |
| 379 | return chain.layers.map((link, index) => ({ |
| 380 | link, |
| 381 | depth: chain.depths[index]!, |
| 382 | chainKey, |
| 383 | stack: |
| 384 | index === 0 && chain.layers.length > 1 |
| 385 | ? { kind: chain.kind, size: chain.layers.length } |
| 386 | : null, |
| 387 | })); |
| 388 | }); |
| 389 | } |