TypeScript
fix(mobile): images stop re-downloading when their URL is re-signed (#21527)
oliver90f064685e51
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsxindex b840ce47d9e..e09963c2bf3 100644--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx@@ -77,6 +77,7 @@ function MarkdownImage(props: {<ThreadMarkdownImageViewuri={media.uri}sourceKey={props.href}+ cacheKey={media.cacheKey}unavailable={media.unavailable || !/^https?:\/\//i.test(props.href)}alt={props.alt}onPressPreview={(source) =>diff --git a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsxindex 0665f045b84..54d3a822277 100644--- a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx@@ -12,6 +12,7 @@ import { Pressable, View } from "react-native";import { Image } from "expo-image";import { AppText } from "../../components/ui/AppText";import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";+import { assetImageCacheKey } from "../../lib/assetImageSource";import { MediaVideoPlayer } from "../../components/MediaVideoPlayer";import { VideoAttachmentTile } from "../../components/VideoAttachmentTile";import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";@@ -40,6 +41,7 @@ export function usePullRequestMediaUrl(url: string) {const refresh = useRefreshAssetUrl(context?.environmentId ?? null, resource);return {uri: asset._tag === "Success" ? asset.url : resource ? null : url,+ cacheKey: context && resource ? assetImageCacheKey(context.environmentId, resource) : undefined,unavailable: resource !== null && asset._tag === "Failure",source: pullRequestMediaSource(url, context),resolvePlaybackUri: resource ? async () => (await refresh()) ?? null : undefined,@@ -65,6 +67,7 @@ export function PullRequestMedia(props: {<ThreadMarkdownImageViewuri={media.uri}sourceKey={props.url}+ cacheKey={media.cacheKey}unavailable={media.unavailable}alt={name}onPressPreview={(source) =>@@ -134,7 +137,7 @@ export function PullRequestImageAttachment(props: {><View className="overflow-hidden rounded-2xl border border-border-subtle bg-grouped-card"><Image- source={media.uri ? { uri: media.uri } : null}+ source={media.uri ? { uri: media.uri, cacheKey: media.cacheKey } : null}style={{ width: 174, height: 112 }}contentFit="contain"cachePolicy="memory-disk"diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsxindex bad77ec4edd..88c64e4deda 100644--- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx@@ -19,6 +19,7 @@ import { PresentationSource } from "../../components/ui/NativePresentation";import { useMediaActions } from "../../state/mediaActions";import type { MediaActionsSource } from "../../lib/mediaActionsSource";import { useAssetUrlState } from "../../state/assets";+import { assetImageCacheKey } from "../../lib/assetImageSource";import {MARKDOWN_IMAGE_MAX_WIDTH,type MarkdownImageDisplaySize,@@ -84,6 +85,7 @@ const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadErroexport function ThreadMarkdownImageView(props: {readonly uri: string | null;readonly sourceKey: string;+ readonly cacheKey?: string | undefined;readonly unavailable: boolean;readonly unavailableDetail?: string | undefined;readonly alt: string | null;@@ -189,6 +191,7 @@ export function ThreadMarkdownImageView(props: {<ThreadMarkdownImageRequestkey={props.sourceKey}uri={props.uri}+ cacheKey={props.cacheKey}onLoad={(size) => setDecoded({ sourceKey: props.sourceKey, size })}onError={() => setFailure({ uri: props.uri, failed: true })}/>@@ -209,6 +212,7 @@ export function ThreadMarkdownImageView(props: {function ThreadMarkdownImageRequest(props: {readonly uri: string;+ readonly cacheKey: string | undefined;readonly onLoad: (sourceSize: ImageSize) => void;readonly onError: () => void;}) {@@ -217,7 +221,7 @@ function ThreadMarkdownImageRequest(props: {return (<><Image- source={{ uri: props.uri }}+ source={{ uri: props.uri, cacheKey: props.cacheKey }}contentFit="contain"cachePolicy="memory-disk"accessible={false}@@ -269,6 +273,11 @@ export function ThreadMarkdownImage(props: {return (<ThreadMarkdownImageViewuri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}+ cacheKey={+ assetUrl._tag === "Success"+ ? assetImageCacheKey(props.environmentId, props.resource, assetUrl.fileRevision)+ : undefined+ }sourceKey={props.resource._tag === "attachment"? `attachment:${props.resource.attachmentId}`diff --git a/apps/mobile/src/lib/assetImageSource.test.ts b/apps/mobile/src/lib/assetImageSource.test.tsindex ab4b302bcc0..b65ab84016f 100644--- a/apps/mobile/src/lib/assetImageSource.test.ts+++ b/apps/mobile/src/lib/assetImageSource.test.ts@@ -1,7 +1,7 @@-import { EnvironmentId } from "@t3tools/contracts";+import { EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET, ThreadId } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";-import { assetImageSource } from "./assetImageSource";+import { assetImageCacheKey, assetImageSource } from "./assetImageSource";const environmentId = EnvironmentId.make("environment-1");@@ -46,13 +46,61 @@ describe("assetImageSource", () => {expect(left.cacheKey).not.toBe(right.cacheKey);});- it("keeps workspace files keyed by URL because they can change on disk", () => {- const source = assetImageSource(+ it("keys host files by the revision the server read, and by URL without one", () => {+ const resource = {+ _tag: "media-file",+ threadId: ThreadId.make("thread-1"),+ path: "docs/shot.png",+ } as const;+ const first = assetImageSource(environmentId,- { _tag: "draft-workspace-file", cwd: "/repo", path: "logo.png" },- "https://host/api/assets/token-a/logo.png",+ resource,+ "https://host/api/assets/token-a/shot.png",+ "1:2:5:1000:1000",);- expect(source).toStrictEqual({ uri: "https://host/api/assets/token-a/logo.png" });+ expect(first.cacheKey).toBeDefined();+ expect(+ assetImageSource(+ environmentId,+ resource,+ "https://host/api/assets/token-b/shot.png",+ "1:2:5:1000:1000",+ ),+ ).toStrictEqual({ uri: "https://host/api/assets/token-b/shot.png", cacheKey: first.cacheKey });+ expect(assetImageCacheKey(environmentId, resource, "1:2:5:2000:2000")).not.toBe(first.cacheKey);+ expect(+ assetImageCacheKey(environmentId, { ...resource, path: "docs/other.png" }, "1:2:5:1000:1000"),+ ).not.toBe(first.cacheKey);+ expect(+ assetImageCacheKey(EnvironmentId.make("environment-2"), resource, "1:2:5:1000:1000"),+ ).not.toBe(first.cacheKey);+ expect(+ assetImageSource(+ environmentId,+ { _tag: "draft-workspace-file", cwd: "/repo", path: "logo.png" },+ "https://host/api/assets/token-a/logo.png",+ ),+ ).toStrictEqual({ uri: "https://host/api/assets/token-a/logo.png" });+ });++ it("keys source control media by URL only when its bytes cannot change", () => {+ const sha = "0123456789abcdef0123456789abcdef01234567";+ const key = (url: string, environment = environmentId) =>+ assetImageCacheKey(environment, { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url });+ const pinned = key(`https://raw.githubusercontent.com/owner/repo/${sha}/docs/shot.png`);++ expect(pinned).toBeDefined();+ expect(key(`https://github.com/owner/repo/blob/${sha}/docs/shot.png`)).toBe(pinned);+ expect(key(`https://raw.githubusercontent.com/owner/repo/${sha}/docs/other.png`)).not.toBe(+ pinned,+ );+ expect(+ key(+ `https://raw.githubusercontent.com/owner/repo/${sha}/docs/shot.png`,+ EnvironmentId.make("environment-2"),+ ),+ ).not.toBe(pinned);+ expect(key("https://raw.githubusercontent.com/owner/repo/main/docs/shot.png")).toBeUndefined();});});diff --git a/apps/mobile/src/lib/assetImageSource.ts b/apps/mobile/src/lib/assetImageSource.tsindex a8fb5236231..6ddd484a66a 100644--- a/apps/mobile/src/lib/assetImageSource.ts+++ b/apps/mobile/src/lib/assetImageSource.ts@@ -1,16 +1,53 @@-import type { AssetResource, EnvironmentId } from "@t3tools/contracts";+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";+import {+ SOURCE_CONTROL_MEDIA_ASSET,+ type AssetResource,+ type EnvironmentId,+} from "@t3tools/contracts";import type { ImageSource } from "expo-image";-/** Cache immutable attachments by id; signed URLs change on each mint and reconnect. */+/**+ * Signed URLs change on each mint and reconnect, so a URL-keyed cache misses every time.+ * Content that cannot change caches under its identity, and host files under the revision the+ * server read. Anything else stays keyed by URL.+ */+export function assetImageCacheKey(+ environmentId: EnvironmentId,+ resource: AssetResource,+ fileRevision?: string,+): string | undefined {+ switch (resource._tag) {+ case "attachment":+ return `t3-attachment:${JSON.stringify([environmentId, resource.attachmentId])}`;+ case SOURCE_CONTROL_MEDIA_ASSET: {+ const media = sourceControlClients.mediaUrl(resource.url);+ return media?.immutable+ ? `t3-media:${JSON.stringify([environmentId, media.fetchUrl])}`+ : undefined;+ }+ case "media-file":+ case "workspace-file":+ case "draft-workspace-file":+ return fileRevision === undefined+ ? undefined+ : `t3-file:${JSON.stringify([+ environmentId,+ resource._tag === "draft-workspace-file" ? resource.cwd : resource.threadId,+ resource.path,+ fileRevision,+ ])}`;+ // A tool can replace the image at its index, and nothing cheap identifies its bytes.+ default:+ return undefined;+ }+}+export function assetImageSource(environmentId: EnvironmentId,resource: AssetResource,uri: string,+ fileRevision?: string,): ImageSource {- return resource._tag === "attachment"- ? {- uri,- cacheKey: `t3-attachment:${JSON.stringify([environmentId, resource.attachmentId])}`,- }- : { uri };+ const cacheKey = assetImageCacheKey(environmentId, resource, fileRevision);+ return cacheKey === undefined ? { uri } : { uri, cacheKey };}diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.tsindex c766a92a5a5..30e88377590 100644--- a/packages/source-control-core/src/shared/definition.ts+++ b/packages/source-control-core/src/shared/definition.ts@@ -101,6 +101,8 @@ export interface SourceControlMediaUrl {readonly fileName: string;/** Set when the URL alone says what the media is, as an extensionless upload can. */readonly kind?: "image" | "video";+ /** Set when the bytes behind `fetchUrl` can never change, so a client may cache them by it. */+ readonly immutable?: true;}export interface ReferenceAutolink {diff --git a/packages/source-control-github/src/shared/definition.test.ts b/packages/source-control-github/src/shared/definition.test.tsindex 3aadd4697b6..924ab317168 100644--- a/packages/source-control-github/src/shared/definition.test.ts+++ b/packages/source-control-github/src/shared/definition.test.ts@@ -132,6 +132,7 @@ describe("GitHub media URLs", () => {fetchUrl: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",fileName: "1a1842fb-6383-492f-873c-57aa0033fa6c",kind: "video",+ immutable: true,});expect(media("https://github.com/owner/repo/blob/main/docs/shot.png")).toEqual({fetchUrl: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",@@ -147,6 +148,24 @@ describe("GitHub media URLs", () => {expect(media("https://raw.githubusercontent.com/o/r/main/100%.png")?.fileName).toBe("100%.png");});+ it("marks only uploads and files at a full commit SHA as immutable", () => {+ const sha = "0123456789abcdef0123456789abcdef01234567";+ for (const url of [+ "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",+ "https://github.com/owner/repo/assets/45952064/1a1842fb",+ `https://github.com/owner/repo/blob/${sha}/docs/shot.png`,+ `https://raw.githubusercontent.com/owner/repo/${sha}/docs/shot.png`,+ ]) {+ expect(media(url)?.immutable, url).toBe(true);+ }+ for (const url of [+ "https://raw.githubusercontent.com/owner/repo/0123456789ab/docs/shot.png",+ `https://media.githubusercontent.com/media/owner/repo/${sha}/a.mp4`,+ ]) {+ expect(media(url)?.immutable, url).toBeUndefined();+ }+ });+it("claims nothing a request without a credential loads just as well", () => {for (const url of ["https://example.com/shot.png",diff --git a/packages/source-control-github/src/shared/gitHubMedia.ts b/packages/source-control-github/src/shared/gitHubMedia.tsindex 0bcc126fd7c..eec80c071fd 100644--- a/packages/source-control-github/src/shared/gitHubMedia.ts+++ b/packages/source-control-github/src/shared/gitHubMedia.ts@@ -18,6 +18,8 @@ const ATTACHMENT_PATH_PATTERN = /^\/user-attachments\/assets\/[\w-]+$/u;const LEGACY_ATTACHMENT_PATH_PATTERN = /^\/[^/]+\/[^/]+\/assets\/\d+\/[\w-]+$/u;/** `blob` and `raw` both address file bytes; `raw` is the one the token is honoured on. */const REPOSITORY_FILE_PATTERN = /^\/([^/]+)\/([^/]+)\/(?:raw|blob)\/(.*[^/])$/u;+/** GitHub rejects 40-hex branch and tag names, and serves no SHA-256 repositories. */+const COMMIT_SHA_PATTERN = /^[0-9a-f]{40}$/u;function fileName(fetchUrl: string): string {const segment = new URL(fetchUrl).pathname.split("/").pop() ?? "";@@ -31,26 +33,34 @@ function fileName(fetchUrl: string): string {return name.length > 0 ? name : "github-media";}-function media(fetchUrl: string, kind?: "video"): SourceControlMediaUrl {- return { fetchUrl, fileName: fileName(fetchUrl), ...(kind ? { kind } : {}) };+function media(+ fetchUrl: string,+ extra: Pick<SourceControlMediaUrl, "kind" | "immutable"> = {},+): SourceControlMediaUrl {+ return { fetchUrl, fileName: fileName(fetchUrl), ...extra };+}++/** A branch or tag can move; a raw file is fixed only when read at a full commit SHA. */+function rawFile(fetchUrl: string): SourceControlMediaUrl {+ const ref = new URL(fetchUrl).pathname.split("/")[3] ?? "";+ return media(fetchUrl, COMMIT_SHA_PATTERN.test(ref) ? { immutable: true } : {});}export function gitHubMediaUrl(url: URL): SourceControlMediaUrl | null {if (url.protocol !== "https:") return null;const host = url.hostname.toLowerCase();- if (host === RAW_HOST || host === LFS_HOST) {- return media(`https://${host}${url.pathname}${url.search}`);- }+ if (host === RAW_HOST) return rawFile(`https://${host}${url.pathname}${url.search}`);+ if (host === LFS_HOST) return media(`https://${host}${url.pathname}${url.search}`);if (!WEB_HOSTS.has(host)) return null;// GitHub links an uploaded video bare, with no extension, and an image as markdown.if (ATTACHMENT_PATH_PATTERN.test(url.pathname)) {- return media(`https://github.com${url.pathname}`, "video");+ return media(`https://github.com${url.pathname}`, { kind: "video", immutable: true });}if (LEGACY_ATTACHMENT_PATH_PATTERN.test(url.pathname)) {- return media(`https://github.com${url.pathname}`);+ return media(`https://github.com${url.pathname}`, { immutable: true });}const repositoryFile = REPOSITORY_FILE_PATTERN.exec(url.pathname);return repositoryFile- ? media(`https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`)+ ? rawFile(`https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`): null;}