Skip to content
TypeScript

fix(assets): preserve the PR repository for GitHub media (#21631)

Julius Marmingee4b98f9d3967
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
index f08b5c48468..a067af12d1e 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
@@ -57,7 +57,9 @@ export function PullRequestMarkdownRepository(props: {
projectId: target.input.projectId,
});
const cwd = project?.workspaceRoot;
- const media = cwd ? { environmentId: target.environmentId, cwd } : null;
+ const media = cwd
+ ? { environmentId: target.environmentId, cwd, repository: target.input.repository }
+ : null;
return (
<AutolinksContext value={autolinks}>
<LineBreaksContext value={lineBreaks}>
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
index 54d3a822277..3fcfbceb842 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
@@ -1,12 +1,10 @@
import { createContext, useContext, useState } from "react";
-import { pullRequestMediaSource, pullRequestImageSource } from "./pullRequestMediaSource";
-import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
-import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import {
- SOURCE_CONTROL_MEDIA_ASSET,
- type AssetResource,
- type EnvironmentId,
-} from "@t3tools/contracts";
+ pullRequestMediaSource,
+ pullRequestImageSource,
+ type PullRequestMediaLocation,
+} from "./pullRequestMediaSource";
+import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
import { videoMimeType } from "@t3tools/shared/video";
import { Pressable, View } from "react-native";
import { Image } from "expo-image";
@@ -25,25 +23,19 @@ import {
export const PullRequestMediaVisibleContext = createContext(true);
-export const PullRequestMediaContext = createContext<{
- readonly environmentId: EnvironmentId;
- readonly cwd: string;
-} | null>(null);
+export const PullRequestMediaContext = createContext<PullRequestMediaLocation | null>(null);
export function usePullRequestMediaUrl(url: string) {
const context = useContext(PullRequestMediaContext);
- const fetchUrl = sourceControlClients.mediaUrl(url)?.fetchUrl;
- const resource: AssetResource | null =
- context && fetchUrl
- ? { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: context.cwd, url: fetchUrl }
- : null;
+ const source = pullRequestMediaSource(url, context);
+ const resource = "resource" in source ? (source.resource ?? null) : null;
const asset = useAssetUrlState(context?.environmentId ?? null, resource);
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),
+ source,
resolvePlaybackUri: resource ? async () => (await refresh()) ?? null : undefined,
};
}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts
index 3651b284023..52ee08d3a60 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts
@@ -3,7 +3,11 @@ import { EnvironmentId } from "@t3tools/contracts";
import { filePreviewGallery } from "../../lib/filePreviewGallery";
import { pullRequestImageSource } from "./pullRequestMediaSource";
-const location = { environmentId: EnvironmentId.make("test"), cwd: "/repo" };
+const location = {
+ environmentId: EnvironmentId.make("test"),
+ cwd: "/repo",
+ repository: "enterprise/private",
+};
const url = "https://github.com/user-attachments/assets/abc-123";
describe("PR media previews", () => {
@@ -13,6 +17,9 @@ describe("PR media previews", () => {
const selected = { ...second, sourceIdentifier: "tapped" };
const gallery = filePreviewGallery(selected, [first, second]);
expect(gallery).toEqual([first, selected]);
- expect(gallery.every((item) => "resource" in item)).toBe(true);
+ expect(gallery).toMatchObject([
+ { resource: { url, repository: location.repository } },
+ { resource: { url: `${url}-second`, repository: location.repository } },
+ ]);
});
});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
index 075eccfc38d..d20bbeac638 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
@@ -5,6 +5,7 @@ import type { FilePreviewItem } from "../../components/FilePreviewModal.types";
export interface PullRequestMediaLocation {
readonly environmentId: EnvironmentId;
readonly cwd: string;
+ readonly repository?: string;
}
/** Keep the original resource identity so previewers can resolve and renew its capability. */
@@ -13,7 +14,12 @@ export function pullRequestMediaSource(url: string, location: PullRequestMediaLo
return location && fetchUrl
? {
environmentId: location.environmentId,
- resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: location.cwd, url: fetchUrl },
+ resource: {
+ _tag: SOURCE_CONTROL_MEDIA_ASSET,
+ cwd: location.cwd,
+ url: fetchUrl,
+ ...(location.repository ? { repository: location.repository } : {}),
+ },
}
: { uri: url };
}
diff --git a/apps/mobile/src/lib/videoPreviewSource.ts b/apps/mobile/src/lib/videoPreviewSource.ts
index 837b4fbb0ae..c6688359b23 100644
--- a/apps/mobile/src/lib/videoPreviewSource.ts
+++ b/apps/mobile/src/lib/videoPreviewSource.ts
@@ -63,6 +63,7 @@ export function mediaVideoThumbnailKey(source: MediaVideoPreviewSource): string
source.environmentId,
source.resource.cwd,
source.resource.url,
+ source.resource.repository ?? "",
]
: [
"media-video",
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index cc423a14f96..b983a431d79 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -1471,6 +1471,31 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect("preserves the change request repository through RPC decoding and signed media", () =>
+ Effect.gen(function* () {
+ const decodeAssetCreateUrlInput = Schema.decodeEffect(AssetCreateUrlInput);
+ const resource = {
+ _tag: SOURCE_CONTROL_MEDIA_ASSET,
+ cwd: "/personal-fork",
+ url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
+ repository: "enterprise/private",
+ };
+ const input = yield* decodeAssetCreateUrlInput({ resource });
+ const issued = yield* issueAssetUrl(input);
+ const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const resolved = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
+
+ expect(resolved).toEqual({
+ kind: "source-control-media",
+ url: resource.url,
+ cwd: resource.cwd,
+ repository: resource.repository,
+ expiresAt: issued.expiresAt,
+ });
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("serves a host's credentialed media through that host's driver", () => {
const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index bbaa3f5c1f8..ecf7180b13e 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -169,6 +169,7 @@ const AssetClaimsSchema = Schema.Union([
/** A host's `fetchUrl`, narrowed at mint time; the signature is what keeps it there. */
url: Schema.String,
cwd: Schema.String,
+ repository: Schema.optionalKey(Schema.String),
expiresAt: Schema.Number,
}),
]);
@@ -197,6 +198,7 @@ export type ResolvedAsset =
readonly kind: "source-control-media";
readonly url: string;
readonly cwd: string;
+ readonly repository?: string;
readonly expiresAt: number;
};
@@ -830,11 +832,12 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (media === null) {
return yield* new AssetSourceControlMediaUrlValidationError({});
}
+ const { _tag, ...resource } = input.resource;
claims = {
version: 1,
kind: SOURCE_CONTROL_MEDIA_ASSET,
+ ...resource,
url: media.fetchUrl,
- cwd: input.resource.cwd,
expiresAt,
};
fileName = media.fileName;
@@ -944,12 +947,8 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
- return {
- kind: "source-control-media",
- url: claims.url,
- cwd: claims.cwd,
- expiresAt: claims.expiresAt,
- } satisfies ResolvedAsset;
+ const { version: _version, ...media } = claims;
+ return { ...media, kind: "source-control-media" } satisfies ResolvedAsset;
}
if (claims.kind === "tool-output-image") {
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 2f2cfea67fd..5e3c7ca96fd 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -248,6 +248,8 @@ interface ChatMarkdownProps {
/** Loads media a source control host keeps behind a credential through the server, which holds
`cwd`'s; without it a private repository's uploads load unauthenticated and 404. */
sourceControlMedia?: boolean | undefined;
+ /** The change request's repository, when it can differ from the checkout at `cwd`. */
+ sourceControlMediaRepository?: string | undefined;
headingLevelOffset?: number | undefined;
}
@@ -494,6 +496,7 @@ function useChatMarkdownState({
renderContextReference,
headingLevelOffset = 0,
sourceControlMedia = false,
+ sourceControlMediaRepository,
}: ChatMarkdownProps) {
const resolvedTheme = useRenderedAppearance();
const markdownRef = useRef<HTMLElement>(null);
@@ -891,6 +894,7 @@ function useChatMarkdownState({
expandMedia,
fileLinkChip,
sourceControlMedia,
+ sourceControlMediaRepository,
renderContextReference,
headingLevelOffset,
imageBaseDir,
@@ -1365,6 +1369,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
cwd,
environmentId,
sourceControlMedia,
+ sourceControlMediaRepository,
imageBaseDir,
threadRef,
workspaceMutationId,
@@ -1451,7 +1456,12 @@ const CHAT_MARKDOWN_COMPONENTS = {
return (
<ChatMarkdownAssetImage
environmentId={environmentId}
- resource={{ _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd, url: hostMediaUrl }}
+ resource={{
+ _tag: SOURCE_CONTROL_MEDIA_ASSET,
+ cwd,
+ url: hostMediaUrl,
+ ...(sourceControlMediaRepository ? { repository: sourceControlMediaRepository } : {}),
+ }}
alt={altText}
kind={kind}
copyMarkdown={copyMarkdown}
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index 4c8e1e2acbc..c70a424ed1a 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -236,13 +236,14 @@ function resolvePullRequestReference(
}
function pullRequestMarkdownContext(
- detail: Pick<PullRequestDetail, "provider" | "url"> | null,
+ detail: Pick<PullRequestDetail, "provider" | "url" | "repository"> | null,
threadRef: ScopedThreadRef | null,
) {
return {
remarkPlugins: pullRequestAutolinkPlugins(detail),
lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false,
threadRef,
+ repository: detail?.repository ?? null,
};
}
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx
index 6bbfcdadd54..fae5270d271 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx
@@ -1,23 +1,41 @@
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
-import { EnvironmentId } from "@t3tools/contracts";
-import { expect, it } from "vite-plus/test";
+import { type AssetResource, EnvironmentId } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
import { render } from "../../../test/render";
import { PullRequestMarkdown, PullRequestMarkdownContext } from "./PullRequestMarkdown";
-async function renderBody(host: string, options: { lineBreaks?: boolean } = {}) {
+const requested = vi.hoisted(() => [] as Array<AssetResource | null>);
+vi.mock(import("~/assets/assetUrls"), async (original) => ({
+ ...(await original()),
+ useAssetUrlState: (_environmentId, resource) => {
+ requested.push(resource);
+ return { _tag: "Loading" };
+ },
+}));
+
+function setup() {
+ requested.length = 0;
+}
+
+async function renderBody(
+ host: string,
+ options: { lineBreaks?: boolean; repository?: string; text?: string } = {},
+) {
+ const { repository = null, text = "first line\nsecond line", ...props } = options;
const context = {
remarkPlugins: [],
lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false,
threadRef: null,
+ repository,
};
return render(
<PullRequestMarkdownContext value={context}>
<PullRequestMarkdown
- text={"first line\nsecond line"}
+ text={text}
cwd="/repo"
environmentId={EnvironmentId.make("local")}
- {...options}
+ {...props}
/>
</PullRequestMarkdownContext>,
);
@@ -43,3 +61,29 @@ it("lets text the host did not write opt out of the host's breaks", async () =>
await expect.element(screen.getByText(/first line/)).toBeInTheDocument();
expect(screen.container.querySelectorAll("p br")).toHaveLength(0);
});
+
+it("loads the body's host media in the pull request's repository, not the checkout's", async () => {
+ setup();
+ const image = "https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422";
+ const video = "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
+ await using _screen = await renderBody("github", {
+ repository: "enterprise/private",
+ text: `![shot](${image})\n\n${video}`,
+ });
+ await vi.waitFor(() =>
+ expect(requested).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ cwd: "/repo",
+ url: expect.stringContaining("7195f963"),
+ repository: "enterprise/private",
+ }),
+ expect.objectContaining({
+ cwd: "/repo",
+ url: expect.stringContaining("2f8c1a90"),
+ repository: "enterprise/private",
+ }),
+ ]),
+ ),
+ );
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index 68d354f1758..00f7a5d0bd1 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -23,6 +23,8 @@ export const PullRequestMarkdownContext = createContext<{
remarkPlugins: PluggableList;
lineBreaks: boolean;
threadRef: ScopedThreadRef | null;
+ /** The change request's `owner/name`, which can differ from the checkout the body renders in. */
+ repository: string | null;
} | null>(null);
function PullRequestHostVideo({
@@ -30,13 +32,20 @@ function PullRequestHostVideo({
cwd,
url,
fetchUrl,
+ repository,
}: {
environmentId: EnvironmentId;
cwd: string;
url: string;
fetchUrl: string;
+ repository: string | undefined;
}) {
- const resource: AssetResource = { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd, url: fetchUrl };
+ const resource: AssetResource = {
+ _tag: SOURCE_CONTROL_MEDIA_ASSET,
+ cwd,
+ url: fetchUrl,
+ ...(repository ? { repository } : {}),
+ };
const assetUrl = useAssetUrlState(environmentId, resource);
const refreshAssetUrl = useAssetUrlRefresh(environmentId, resource);
const src =
@@ -73,6 +82,7 @@ export function PullRequestMarkdown({
}) {
const segments = splitPullRequestBody(text);
const context = useContext(PullRequestMarkdownContext);
+ const repository = context?.repository ?? undefined;
const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
return (
<div
@@ -95,6 +105,7 @@ export function PullRequestMarkdown({
{...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
sourceControlMedia
+ sourceControlMediaRepository={repository}
onTaskListChange={
onTaskListChange && segment.kind === "markdown"
? ({ markerOffset, checked }) =>
@@ -116,6 +127,7 @@ export function PullRequestMarkdown({
cwd={cwd}
url={segment.url}
fetchUrl={hostMedia.fetchUrl}
+ repository={repository}
/>
);
}
diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts
index da3eb0e4206..77bb94b99be 100644
--- a/packages/contracts/src/assets.ts
+++ b/packages/contracts/src/assets.ts
@@ -54,10 +54,12 @@ export const AssetResource = Schema.Union([
}),
// Media a change request body points at on its host. A private repository serves these only
// to a request that carries a credential, which the client has none of, so the server fetches
- // them with the credential the host's driver holds for the repository at `cwd`.
+ // them with the credential the host's driver holds for the repository at `cwd`. `repository`
+ // names the change request's repository, which can differ from the checkout at `cwd`.
Schema.TaggedStruct(SOURCE_CONTROL_MEDIA_ASSET, {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
url: TrimmedNonEmptyString.check(Schema.isMaxLength(2048)),
+ repository: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(512))),
}),
]);
export type AssetResource = typeof AssetResource.Type;