feat(webui): remove original-file display fallbacks, use proxies only (#273)

* feat(webui): remove original-file display fallbacks, use proxies only

WebUI now never uses the raw original file for display. All viewers
(image, video, compare, pdf) render exclusively from transcoded proxies;
when no proxy exists the viewer shows an unavailable placeholder instead
of falling back to media.original.

- getBestTranscode: drop the isRaw fallback candidates
- video-viewer / compare-video-pane: remove the synthetic 'Original'
  resolution entry and the original.downloadUrl hasMedia gate
- image-viewer / compare-image-pane: remove original.downloadUrl default
- pdf-viewer: require pdfTranscode.url (no original fallback)
- download menus (video-control-bar, breadcrumb-nav): use
  media.original.key for the 'Original' download option instead of the
  isRaw transcode marker entry

Backend:
- transcode-video workflow no longer pushes the isRaw:true marker entry
  into videoTranscodes (it pointed at the original file key)
- remove media.original.downloadUrl from the DTO, asset service mapping,
  MediaInfo DB type, and transcode workflows/activities (it was only
  consumed by the removed display fallbacks; downloads already use key
  via the download-url endpoints)

Tests/fixtures updated; docs updated to state the proxy-only display
policy.

* refactor: remove isRaw field via data migration, clean legacy media JSON

Add a Prisma data migration that cleans legacy media JSONB on both
assets and watermark_files:
- drop the raw-original marker entries (isRaw: true) from
  videoTranscodes / imageTranscodes — they pointed at the original file
  key and were only used by the removed display fallbacks / download
  menus, which now use media.original.key directly
- strip the isRaw field from remaining transcode entries
- drop original.downloadUrl (removed from the AssetInfo DTO)

The migration is generated via prisma migrate dev --create-only and
applied automatically by migrate deploy in production. It is guarded by
a test (packages/db/src/clean-media-migration.test.ts) that seeds legacy
media JSON, runs the migration SQL, and asserts the transform on both
tables.

With the data cleaned, remove the isRaw field entirely from the codebase:
- DTO schemas + ImageTranscode/VideoTranscode interfaces
- PrismaJson MediaInfo transcode types
- watermark activity isRaw skip (and its test), watermark proxy mapping,
  agent-embedding transcode selection, webui transcode filters, and all
  test fixtures

AGENTS.md: clarify that the no-manual-migration rule applies to DDL;
data migrations (pure SQL transforms, no schema change) are allowed
inside a --create-only generated migration and must be tested.
This commit is contained in:
Yiling-J
2026-08-07 22:40:06 +08:00
committed by GitHub
parent 03aea2cb36
commit 624a3a6a54
31 changed files with 277 additions and 315 deletions
+2 -1
View File
@@ -321,7 +321,8 @@ We use `prisma-json-types-generator` to enforce strict type-safety for Prisma `J
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
- Production: Use `bun --bun run prisma migrate deploy` to apply pending migrations in production environments.
- **No Manual Migration Creation**: Never create migration SQL files or directories manually by hand. Always use Prisma CLI commands (e.g. `bun --bun run prisma migrate dev --create-only` to generate a migration template, or `bun --bun run prisma migrate dev`) so Prisma correctly tracks migration metadata and checksums.
- **No Manual DDL Creation**: Never hand-write **schema (DDL) migration** files or directories. Always generate them with Prisma CLI (`bun --bun run prisma migrate dev --create-only` to create a template, then edit it if needed, or `bun --bun run prisma migrate dev` to apply) so Prisma correctly tracks migration metadata and checksums.
- **Data Migrations Are Allowed**: Pure **data migration** SQL (no schema change) may be written by hand, but it MUST live inside a migration generated via `bun --bun run prisma migrate dev --create-only` so it is tracked and applied automatically.
- **No Automatic Dev DB Reset**: Do not run `prisma migrate reset --force` or commands that force-reset the database automatically. If migrations become out of sync or a reset is required, stop executing, report the situation to the user, and present suggested manual cleanup/reset steps for the user to execute.
### Commands
@@ -186,7 +186,7 @@ describe('Agent Embedding Workflow', () => {
mediaType: 'image/png',
storageKey: { key: 'test.png' },
media: {
imageTranscodes: [{ key: 'test-transcoded.webp', isRaw: false, format: 'webp' }],
imageTranscodes: [{ key: 'test-transcoded.webp', format: 'webp' }],
},
},
chunkDuration: 60.0,
@@ -220,7 +220,7 @@ describe('Agent Embedding Workflow', () => {
storageKey: { key: 'test.mp4' },
media: {
duration: 150.0,
videoTranscodes: [{ key: 'test-transcoded.mp4', isRaw: false }],
videoTranscodes: [{ key: 'test-transcoded.mp4' }],
},
},
chunkDuration: 60.0,
@@ -91,20 +91,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const media = asset.media as any
if (isVideo) {
if (media.videoTranscodes && media.videoTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.videoTranscodes.find((t: PrismaJson.VideoTranscode) => !t.isRaw) ||
media.videoTranscodes[0]
const transcode = media.videoTranscodes[0] as PrismaJson.VideoTranscode
if (transcode?.key) {
embeddingKey = transcode.key
}
}
} else if (isImage) {
if (media.imageTranscodes && media.imageTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.imageTranscodes.find((t: PrismaJson.ImageTranscode) => !t.isRaw) ||
media.imageTranscodes[0]
const transcode = media.imageTranscodes[0] as PrismaJson.ImageTranscode
if (transcode?.key) {
embeddingKey = transcode.key
if (transcode.format) {
-2
View File
@@ -54,7 +54,6 @@ async function applyWatermarkToAssetMedia(
width: vt.width ?? 0,
height: vt.height ?? 0,
size: 0,
isRaw: false,
})),
)
: []
@@ -69,7 +68,6 @@ async function applyWatermarkToAssetMedia(
width: it.width ?? 0,
height: it.height ?? 0,
size: 0,
isRaw: false,
})),
)
: []
+5 -12
View File
@@ -71,7 +71,6 @@ function watermarkMediaInfo(overrides: Partial<PrismaJson.MediaInfo> = {}): Pris
},
original: {
key: 'files/orig.mp4',
downloadUrl: 'u',
filesizeInBytes: 100,
codec: '',
},
@@ -245,11 +244,10 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 1,
isRaw: false,
},
],
imageTranscodes: [],
original: { downloadUrl: 'u', key: 'files/orig.mp4' },
original: { key: 'files/orig.mp4' },
},
},
{
@@ -270,11 +268,10 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 1,
isRaw: false,
},
],
imageTranscodes: [],
original: { downloadUrl: 'u', key: 'files/orig.mp4' },
original: { key: 'files/orig.mp4' },
},
},
{
@@ -290,7 +287,7 @@ describe('Share API', () => {
pdfTranscode: { url: 'u', key: 'files/doc.pdf' },
videoTranscodes: [],
imageTranscodes: [],
original: { downloadUrl: 'u', key: 'files/doc.pdf' },
original: { key: 'files/doc.pdf' },
},
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -326,7 +323,6 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 0,
isRaw: false,
},
])
// Pending item → original transcodes emptied
@@ -368,11 +364,10 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 100,
isRaw: false,
},
],
imageTranscodes: [],
original: { downloadUrl: 'http://s3/original', key: 'files/original.mp4' },
original: { key: 'files/original.mp4' },
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
@@ -411,7 +406,6 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 0,
isRaw: false,
},
])
expect(body.media.imageTranscodes).toEqual([])
@@ -447,7 +441,7 @@ describe('Share API', () => {
pdfTranscode: { url: 'http://s3/doc', key: 'files/doc.pdf' },
videoTranscodes: [],
imageTranscodes: [],
original: { downloadUrl: 'http://s3/doc-original', key: 'files/doc.pdf' },
original: { key: 'files/doc.pdf' },
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
@@ -495,7 +489,6 @@ describe('Share API', () => {
width: 640,
height: 360,
size: 100,
isRaw: false,
},
])
expect(wfSpy).not.toHaveBeenCalled()
-8
View File
@@ -853,13 +853,6 @@ export class AssetService {
t.url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', t.key, 'GET')
}
}
if (info.media.original?.key) {
info.media.original.downloadUrl = await s3Service.presign(
process.env.S3_BUCKET || 'shumai',
info.media.original.key,
'GET',
)
}
}
return info
@@ -1732,7 +1725,6 @@ export class AssetService {
}
media.original = {
key,
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
filesizeInBytes: Number(latestVersion.sizeByte),
codec: '',
}
@@ -290,7 +290,7 @@ describe('WatermarkService', () => {
},
finishedAt: new Date().toISOString(),
metadata: null,
original: { key: 'files/gc/original.mp4', downloadUrl: '', filesizeInBytes: 0, codec: '' },
original: { key: 'files/gc/original.mp4', filesizeInBytes: 0, codec: '' },
}
}
@@ -0,0 +1,86 @@
-- Data cleanup: remove legacy media JSON fields that are no longer used.
--
-- WebUI now displays transcoded proxies only and never falls back to the raw
-- original file:
-- 1. Drop the raw-original marker entries (`isRaw: true`) from
-- videoTranscodes / imageTranscodes. They pointed at the original file
-- key and were only consumed by the removed display fallbacks and the
-- download-menu entries, which now use media.original.key directly.
-- 2. Strip the now-removed `isRaw` field from remaining transcode entries.
-- 3. Drop `original.downloadUrl` (removed from the AssetInfo DTO; downloads
-- resolve a fresh presigned URL from `key` via the download-url APIs).
UPDATE "assets"
SET "media" = jsonb_set(
jsonb_set(
CASE WHEN jsonb_typeof("media"->'original') = 'object'
THEN "media" #- '{original,downloadUrl}'
ELSE "media" END,
'{videoTranscodes}',
COALESCE(
(SELECT jsonb_agg(elem - 'isRaw')
FROM jsonb_array_elements("media"->'videoTranscodes') elem
WHERE jsonb_typeof(elem) = 'object'
AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
'[]'::jsonb
)
),
'{imageTranscodes}',
COALESCE(
(SELECT jsonb_agg(elem - 'isRaw')
FROM jsonb_array_elements("media"->'imageTranscodes') elem
WHERE jsonb_typeof(elem) = 'object'
AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
'[]'::jsonb
)
)
WHERE "media" IS NOT NULL
AND (
(jsonb_typeof("media"->'original') = 'object' AND "media"->'original' ? 'downloadUrl')
OR EXISTS (
SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'videoTranscodes', '[]'::jsonb)) e
WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
)
OR EXISTS (
SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'imageTranscodes', '[]'::jsonb)) e
WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
)
);
-- Same cleanup for watermarked proxy media.
UPDATE "watermark_files"
SET "media" = jsonb_set(
jsonb_set(
CASE WHEN jsonb_typeof("media"->'original') = 'object'
THEN "media" #- '{original,downloadUrl}'
ELSE "media" END,
'{videoTranscodes}',
COALESCE(
(SELECT jsonb_agg(elem - 'isRaw')
FROM jsonb_array_elements("media"->'videoTranscodes') elem
WHERE jsonb_typeof(elem) = 'object'
AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
'[]'::jsonb
)
),
'{imageTranscodes}',
COALESCE(
(SELECT jsonb_agg(elem - 'isRaw')
FROM jsonb_array_elements("media"->'imageTranscodes') elem
WHERE jsonb_typeof(elem) = 'object'
AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
'[]'::jsonb
)
)
WHERE "media" IS NOT NULL
AND (
(jsonb_typeof("media"->'original') = 'object' AND "media"->'original' ? 'downloadUrl')
OR EXISTS (
SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'videoTranscodes', '[]'::jsonb)) e
WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
)
OR EXISTS (
SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'imageTranscodes', '[]'::jsonb)) e
WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
)
);
-3
View File
@@ -74,7 +74,6 @@ declare global {
width: number
height: number
resolution?: string
isRaw?: boolean
}
export interface ImageTranscode {
@@ -84,7 +83,6 @@ declare global {
height: number
quality: number
format: string
isRaw?: boolean
}
export interface SpriteInfo {
@@ -117,7 +115,6 @@ declare global {
export interface OriginalInfo {
key: string
downloadUrl: string
filesizeInBytes: number
codec: string
}
+1 -5
View File
@@ -77,7 +77,7 @@ export const assetInfoSchema = z.object({
media: z
.object({
original: z.object({ downloadUrl: z.string(), key: z.string().optional() }).optional(),
original: z.object({ key: z.string().optional() }).optional(),
videoTranscodes: z
.array(
z.object({
@@ -87,7 +87,6 @@ export const assetInfoSchema = z.object({
width: z.number(),
height: z.number(),
size: z.number(),
isRaw: z.boolean(),
}),
)
.optional(),
@@ -100,7 +99,6 @@ export const assetInfoSchema = z.object({
width: z.number(),
height: z.number(),
size: z.number(),
isRaw: z.boolean(),
}),
)
.optional(),
@@ -285,7 +283,6 @@ export interface ImageTranscode {
width: number
height: number
size: number
isRaw: boolean
}
export interface VideoTranscode {
@@ -295,7 +292,6 @@ export interface VideoTranscode {
width: number
height: number
size: number
isRaw: boolean
}
export const postAttachmentRequestSchema = z.object({
@@ -123,7 +123,6 @@ describe.each(['local', 'temporal'] as const)(
},
original: {
key: storageKey.key,
downloadUrl: '',
filesizeInBytes: sampleBuffer.length,
codec: '',
},
@@ -232,12 +231,7 @@ describe.each(['local', 'temporal'] as const)(
frames: 30,
proxyType: 'video',
imageTranscodes: [],
videoTranscodes: [
{ key: storageKey.key, width: 640, height: 360, resolution: '360p' },
// Raw marker entry (as produced by transcodeVideoWorkflow) — must
// not be watermarked.
{ key: storageKey.key, width: 640, height: 360, isRaw: true },
],
videoTranscodes: [{ key: storageKey.key, width: 640, height: 360, resolution: '360p' }],
videoPreview: { width: 640, height: 360 },
finishedAt: new Date().toISOString(),
metadata: {
@@ -253,7 +247,6 @@ describe.each(['local', 'temporal'] as const)(
},
original: {
key: storageKey.key,
downloadUrl: '',
filesizeInBytes: videoBuffer.length,
codec: '',
},
@@ -313,8 +306,7 @@ describe.each(['local', 'temporal'] as const)(
expect(watermarkFile).toBeDefined()
expect(watermarkFile?.status).toBe(WatermarkFileStatus.completed)
expect(watermarkFile?.media).toBeDefined()
// Only the transcoded proxy should be watermarked — the raw marker entry
// (isRaw: true) must be skipped, so exactly one watermark proxy is produced.
// The transcoded proxy should be watermarked, producing exactly one proxy.
const mediaInfo = watermarkFile?.media as PrismaJson.MediaInfo | null
expect(mediaInfo?.videoTranscodes?.length).toBe(1)
expect(mediaInfo?.videoTranscodes?.[0].resolution).toBe('360p')
@@ -384,7 +376,6 @@ describe.each(['local', 'temporal'] as const)(
},
original: {
key,
downloadUrl: '',
filesizeInBytes: buffer.length,
codec: '',
},
@@ -75,7 +75,6 @@ export async function getMediaInfoActivity(params: {
metadata: null,
original: {
key: '', // Will be filled by caller or updated later
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
@@ -213,7 +213,6 @@ describe('Watermark Activities', () => {
},
original: {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
@@ -295,66 +294,6 @@ describe('Watermark Activities', () => {
fs.rmSync(outFilePath, { force: true })
})
it('skips the raw (isRaw) video transcode when generating watermark proxies', async () => {
const assetKey = 'files/e2e-wm/raw-video.mp4'
const asset = await seedAsset('raw-video.mp4', 'video/mp4', assetKey, 'video')
const config = await seedConfig()
// Simulate the media state produced by transcodeVideoWorkflow: a
// transcoded proxy plus a raw marker entry pointing at the original file.
await prisma.asset.update({
where: { id: asset.id },
data: {
media: {
...(asset.media as PrismaJson.MediaInfo),
videoTranscodes: [
{ key: assetKey, width: 100, height: 100, resolution: '100p' },
{ key: assetKey, width: 1920, height: 1080, isRaw: true },
],
},
},
})
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
bitRate: 1000,
frameRate: 30,
totalFrames: 300,
startTimecode: '00:00:00:00',
hasAudio: true,
mimeType: 'video/mp4',
})
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
// The ffmpeg execFile call is mocked, but the activity stats the output
// file afterwards, so pre-create both expected output paths.
const stem = 'raw-video'
const configId = config.id
const proxyOutFilePath = path.join('/tmp', `${stem}-watermark-${configId}-100p.mp4`)
const rawOutFilePath = path.join('/tmp', `${stem}-watermark-${configId}-1080p.mp4`)
fs.writeFileSync(proxyOutFilePath, Buffer.from('fake mp4'))
fs.writeFileSync(rawOutFilePath, Buffer.from('fake mp4'))
try {
const media = await transcodeWatermarkMediaActivity({
assetId: asset.id,
watermarkConfigId: config.id,
})
expect(media.proxyType).toBe('video')
// Only the transcoded proxy should be watermarked, never the raw original.
expect(transcodeService.transcodeVideo).toHaveBeenCalledTimes(1)
expect(media.videoTranscodes).toHaveLength(1)
expect(media.videoTranscodes?.[0].resolution).toBe('100p')
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
} finally {
fs.rmSync(proxyOutFilePath, { force: true })
fs.rmSync(rawOutFilePath, { force: true })
}
})
it('produces a watermarked mp4 proxy for a video asset (ffmpeg path)', async () => {
const assetKey = 'files/e2e-wm/video.mp4'
const asset = await seedAsset('video.mp4', 'video/mp4', assetKey, 'video')
@@ -435,7 +374,6 @@ describe('Watermark Activities', () => {
},
original: {
key: 'files/x/original.png',
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
@@ -246,7 +246,6 @@ export async function transcodeWatermarkMediaActivity(
},
original: {
key: assetKey,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
@@ -302,10 +301,6 @@ export async function transcodeWatermarkMediaActivity(
for (let i = 0; i < originalTranscodes.length; i++) {
const vt = originalTranscodes[i]
// Skip the raw marker entry (points at the original file) — it is not a
// transcoded proxy, so there is nothing to watermark (and transcoding
// the original at full resolution would be needlessly expensive).
if (vt.isRaw) continue
const targetWidth = vt.width || originalWidth
const targetHeight = vt.height || originalHeight
const resolution = vt.resolution || `${targetHeight}p`
@@ -49,7 +49,6 @@ export async function transcodeImageWorkflow(task: WorkflowTask): Promise<void>
mediaInfo.original = {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
}
@@ -60,7 +60,6 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
mediaInfo.original = {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
}
@@ -210,7 +210,6 @@ describe('transcodeVideoWorkflow', () => {
},
original: {
key: 'audio.wav',
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
},
@@ -54,7 +54,6 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
mediaInfo.original = {
key,
downloadUrl: '',
filesizeInBytes: 0,
codec: '',
}
@@ -94,13 +93,6 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
mediaInfo.videoTranscodes.push(videoTranscode)
}
}
mediaInfo.videoTranscodes.push({
key: mediaInfo.original?.key,
width: metadata.originalWidth,
height: metadata.originalHeight,
isRaw: true,
})
}
const isAudio = mediaInfo.proxyType === 'audio'
+21 -27
View File
@@ -71,7 +71,6 @@ interface BreadcrumbNavProps {
key: string
width: number
height: number
isRaw?: boolean
}>
}
versions?: Array<{
@@ -159,10 +158,7 @@ export function BreadcrumbNav({
}
const isAudio = currentAsset.proxyType === 'audio'
const hasVideoTranscodes =
!isAudio &&
downloadInfo?.videoTranscodes &&
downloadInfo.videoTranscodes.filter((t) => !t.isRaw).length > 0
const hasVideoTranscodes = !isAudio && (downloadInfo?.videoTranscodes?.length ?? 0) > 0
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
? [
@@ -244,28 +240,26 @@ export function BreadcrumbNav({
<DropdownMenuPortal>
<DropdownMenuSubContent className="w-48">
<DropdownMenuLabel>{m.download()}</DropdownMenuLabel>
{downloadInfo?.videoTranscodes
?.filter((t) => !t.isRaw)
.map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return (
<DropdownMenuItem
key={resolution}
onClick={() => handleDownload(t.key)}
className="flex items-center justify-between"
>
<span>{resolution}</span>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
})}
{downloadInfo?.videoTranscodes?.map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return (
<DropdownMenuItem
key={resolution}
onClick={() => handleDownload(t.key)}
className="flex items-center justify-between"
>
<span>{resolution}</span>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
})}
{downloadInfo?.originalKey && (
<>
<DropdownMenuSeparator />
@@ -425,7 +425,6 @@ export function PublicShareManager({
key: t.key,
width: t.width,
height: t.height,
isRaw: t.isRaw,
})),
}
: undefined,
@@ -111,11 +111,7 @@ export const CompareImagePane = forwardRef<ComparePaneHandle, CompareImagePanePr
})
}, [baseScale, conW, conH, imgW, imgH])
let bestUrl = file.media?.original?.downloadUrl
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
if (bestTranscode?.url) {
bestUrl = bestTranscode.url
}
const bestUrl = getBestTranscode(file.media?.imageTranscodes, screenWidth)?.url ?? ''
const handleDownload = useCallback(async () => {
const key = file.media?.original?.key
@@ -96,12 +96,7 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
setPan({ x, y })
}
let bestUrl = file.media?.original?.downloadUrl
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
if (bestTranscode?.url) {
bestUrl = bestTranscode.url
}
const bestUrl = getBestTranscode(file.media?.imageTranscodes, screenWidth)?.url ?? ''
const handleDownload = async () => {
const key = file.media?.original?.key
@@ -184,24 +179,30 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{children}
<div ref={containerRef} className="flex-1 relative overflow-hidden">
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{
width: imgW,
height: imgH,
}}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={setPan}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
{bestUrl ? (
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{
width: imgW,
height: imgH,
}}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={setPan}
className="absolute inset-0 z-0"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
) : (
<div className="flex h-full w-full items-center justify-center">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)}
</div>
</div>
<ImageControlBar
@@ -132,7 +132,7 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}, [])
const fileUrl = file.media?.pdfTranscode?.url || file.media?.original?.downloadUrl
const fileUrl = file.media?.pdfTranscode?.url
// Load PDF Document
useEffect(() => {
@@ -30,20 +30,9 @@ interface CompareVideoPaneProps {
}
function computeResolutions(file: AssetInfo): DisplayTranscode[] {
const original: DisplayTranscode | null = file.media?.original?.downloadUrl
? {
id: 'original',
url: file.media.original.downloadUrl,
key: file.media.original.key ?? '',
width: file.media?.metadata?.originalWidth ?? 0,
height: file.media?.metadata?.originalHeight ?? 0,
size: 0,
isRaw: true,
resolution: 'Original',
}
: null
const transcodes: DisplayTranscode[] = (file.media?.videoTranscodes ?? []).map((t) => {
// Only transcoded proxy versions are ever displayed; the raw original file
// is never used as a playback source.
return (file.media?.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
@@ -52,14 +41,8 @@ function computeResolutions(file: AssetInfo): DisplayTranscode[] {
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return { ...t, resolution: t.isRaw ? 'Original' : resolution }
return { ...t, resolution }
})
const hasOriginalTranscode = transcodes.some((t) => t.isRaw)
if (!hasOriginalTranscode && original) {
return [...transcodes, original]
}
return transcodes
}
export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPaneProps>(
@@ -113,9 +96,8 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const resolutions = computeResolutions(file)
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const initialRes = previewResolutions[0] ?? resolutions[0]
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? 'Original')
const initialRes = resolutions[0]
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? '')
const currentSrcRef = useRef(initialRes?.url)
const isAudio = file.proxyType === 'audio'
@@ -155,7 +137,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
// if the parent renders this pane without a per-asset `key`. Runs before the
// video.js init effect below (declaration order) so the ref is fresh.
useEffect(() => {
setCurrentResolution(initialRes?.resolution ?? 'Original')
setCurrentResolution(initialRes?.resolution ?? '')
currentSrcRef.current = initialRes?.url
}, [file.id])
@@ -421,7 +403,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
onRequestTogglePlay?.()
}, [isActive, onActivate, onRequestTogglePlay])
if (!file.media?.original?.downloadUrl || !metadata) {
if (!file.media?.metadata || resolutions.length === 0) {
return (
<div className="flex h-full w-full items-center justify-center bg-black">
<p className="text-muted-foreground">Media is not available.</p>
@@ -23,6 +23,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '../../ui/dropdown-menu'
import { Slider } from '../../ui/slider'
@@ -115,7 +116,6 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
const overlay = state.isFullScreen && floatOverlayInFullScreen
const isAudio = data.proxyType === 'audio'
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const startTimecode = data.media?.metadata?.startTimecode
const displayTotalFrames = Math.max(0, totalFrames - 1)
@@ -311,7 +311,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
</DropdownMenu>
{/* Settings / Resolution */}
{!isAudio && previewResolutions.length > 0 && (
{!isAudio && resolutions.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-1 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
@@ -326,7 +326,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
<DropdownMenuContent>
<DropdownMenuLabel>{m.quality()}</DropdownMenuLabel>
{previewResolutions.map((res) => (
{resolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => changeResolution(res)}
@@ -372,12 +372,24 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{res.resolution === 'Original' ? m.original() : res.resolution}</span>
<span className="text-xs text-muted-foreground">
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
</span>
<span>{res.resolution}</span>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
))}
{data.media?.original?.key && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(data.media?.original?.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{m.original()}</span>
<span className="text-xs text-muted-foreground">
{data.name?.split('.').pop()?.toUpperCase() || 'RAW'}
</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
@@ -18,9 +18,67 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
) => {
const localPlayerRef = useRef<Player | null>(null)
const playerRef = localPlayerRef
const hasMedia = !!data.media?.original?.downloadUrl && !!data.media?.metadata
const resolutions: DisplayTranscode[] = (data.media?.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return {
...t,
resolution,
}
})
// Only transcoded proxy versions are ever displayed; the raw original file
// is never used as a playback source.
const hasMedia = resolutions.length > 0 && !!data.media?.metadata
// We use a container ref to manually append the video element
const videoContainerRef = useRef<HTMLDivElement>(null)
// Logic to select best resolution based on screen size
const getInitialResolution = (): DisplayTranscode | null => {
if (resolutions.length === 0) return null
if (typeof window === 'undefined') return resolutions[0]
// Use device pixel ratio for high DPI screens
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
// 1. Sort by width ascending
const sortedResolutions = [...resolutions].sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
return wA - wB
})
// 2. Find first one >= screenWidth
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
// 3. If found, return it. If not (all are smaller), return the last one (largest).
return bestFit || sortedResolutions[sortedResolutions.length - 1]
}
const initialRes = getInitialResolution()
// State
const [state, setState] = useState<PlayerState>({
isPlaying: false,
progress: 0,
currentTime: 0,
duration: data.media?.metadata?.duration || 0,
volume: 1,
isMuted: false,
isLooping: false,
playbackRate: 1,
isFullScreen: false,
showFrames: false,
currentResolution: initialRes?.resolution ?? '',
currentSrc: initialRes?.url ?? '',
})
const containerRef = useRef<HTMLDivElement>(null)
const rootRef = useRef<HTMLDivElement>(null)
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -113,76 +171,6 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}, [])
// Initial resolution setup
const originalRes: DisplayTranscode = {
id: 'original',
url: data.media?.original?.downloadUrl || '',
key: data.media?.original?.key ?? '',
width: data.media?.metadata?.originalWidth ?? 0,
height: data.media?.metadata?.originalHeight ?? 0,
size: 0,
isRaw: true,
resolution: 'Original',
}
const resolutions: DisplayTranscode[] = (data.media?.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return {
...t,
resolution: t.isRaw ? 'Original' : resolution,
}
})
const previewResolutions = resolutions.filter((r) => !r.isRaw)
// Logic to select best resolution based on screen size
const getInitialResolution = (): DisplayTranscode => {
if (previewResolutions.length === 0) return originalRes
if (typeof window === 'undefined') return previewResolutions[0]
// Use device pixel ratio for high DPI screens
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
// 1. Sort by width ascending
const sortedResolutions = [...previewResolutions].sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
return wA - wB
})
// 2. Find first one >= screenWidth
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
// 3. If found, return it. If not (all are smaller), return the last one (largest).
return bestFit || sortedResolutions[sortedResolutions.length - 1]
}
const initialRes = getInitialResolution()
// State
const [state, setState] = useState<PlayerState>({
isPlaying: false,
progress: 0,
currentTime: 0,
duration: data.media?.metadata?.duration || 0,
volume: 1,
isMuted: false,
isLooping: false,
playbackRate: 1,
isFullScreen: false,
showFrames: false,
currentResolution: initialRes?.resolution || 'Original',
currentSrc: initialRes?.url || '',
})
const [buffered, setBuffered] = useState(0)
const [isControlsVisible, setIsControlsVisible] = useState(true)
const [isPlayerReady, setIsPlayerReady] = useState(false)
+9 -2
View File
@@ -4,6 +4,13 @@ The **File Viewer Registry** is a modular, type-safe system that makes it easy f
By registering a file type, the detail pages (`FileViewer`), split-screen comparison interfaces (`CompareViewer`), and sidebars automatically adapt to the content, control schemes, and comment features of that file type.
> **Display policy**: Viewers must **only ever display transcoded proxies**
> (`imageTranscodes`, `videoTranscodes`, `pdfTranscode`). The raw original file
> (`media.original`) is **never** used as a display source — there is no fallback
> to the original when no transcode exists. `media.original.key` is used solely
> for the download flow (via the `download-url` API endpoints);
> `media.original.downloadUrl` no longer exists.
---
## 1. Core Architecture
@@ -115,7 +122,7 @@ export const AudioViewer = React.forwardRef<MediaController, FileViewerProps>(
<div className="flex-1 flex items-center justify-center">
<audio
ref={audioEl}
src={file.media?.original?.downloadUrl}
src={file.media?.videoTranscodes?.[0]?.url}
onPlay={onPlay}
onTimeUpdate={(e) => onTimeUpdate?.((e.target as HTMLAudioElement).currentTime)}
controls
@@ -148,7 +155,7 @@ export const CompareAudioPane = forwardRef<ComparePaneHandle, CompareAudioPanePr
return (
<div onClick={onActivate} className="flex-1 flex flex-col items-center justify-center">
<audio ref={audioEl} src={file.media?.original?.downloadUrl} />
<audio ref={audioEl} src={file.media?.videoTranscodes?.[0]?.url} />
</div>
)
}
+30 -4
View File
@@ -37,9 +37,18 @@ export const sampleVideoAsset: AssetInfo = {
media: {
proxyType: 'video',
original: {
downloadUrl: SAMPLE_VIDEO_URL,
key: 'sample.mp4',
},
videoTranscodes: [
{
id: 'sample-proxy',
url: SAMPLE_VIDEO_URL,
key: 'sample.mp4',
width: SAMPLE_WIDTH,
height: SAMPLE_HEIGHT,
size: 6170,
},
],
metadata: {
duration: SAMPLE_DURATION,
originalWidth: SAMPLE_WIDTH,
@@ -84,7 +93,6 @@ export const containerLongerVideoAsset: AssetInfo = {
media: {
...sampleVideoAsset.media,
original: {
downloadUrl: SAMPLE_VIDEO_URL,
key: 'sample.mp4',
},
metadata: {
@@ -127,9 +135,18 @@ export const longAudioVideoAsset: AssetInfo = {
media: {
...sampleVideoAsset.media,
original: {
downloadUrl: LONG_AUDIO_VIDEO_URL,
key: 'sample-long-audio.mp4',
},
videoTranscodes: [
{
id: 'long-audio-proxy',
url: LONG_AUDIO_VIDEO_URL,
key: 'sample-long-audio.mp4',
width: SAMPLE_WIDTH,
height: SAMPLE_HEIGHT,
size: 6170,
},
],
metadata: {
duration: LONG_AUDIO_DURATION,
originalWidth: SAMPLE_WIDTH,
@@ -154,9 +171,18 @@ export const sampleAudioAsset: AssetInfo = {
media: {
proxyType: 'audio',
original: {
downloadUrl: SAMPLE_AUDIO_URL,
key: 'sample-audio.mp4',
},
videoTranscodes: [
{
id: 'sample-audio-proxy',
url: SAMPLE_AUDIO_URL,
key: 'sample-audio.mp4',
width: 0,
height: 0,
size: 0,
},
],
metadata: {
duration: SAMPLE_AUDIO_DURATION,
originalWidth: 0,
+3 -13
View File
@@ -10,20 +10,11 @@ export function getBestTranscode(
return null
}
// Filter out raw versions unless they are the only option
const nonRaw = transcodes.filter((t) => !t.isRaw)
const candidates = nonRaw.length > 0 ? nonRaw : transcodes
// Sort by width descending to easily find largest available
// If widths are equal, prefer the one that is NOT raw (transcoded optimized version)
const sorted = [...candidates].sort((a, b) => {
const sorted = [...transcodes].sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
if (wA !== wB) {
return wB - wA // Descending width
}
// If widths equal, prefer non-raw (optimized)
return (a.isRaw ? 1 : 0) - (b.isRaw ? 1 : 0)
return wB - wA // Descending width
})
// Find smallest width that is >= screenWidth
@@ -34,8 +25,7 @@ export function getBestTranscode(
suitable.sort((a, b) => {
const wA = a.width ?? 0
const wB = b.width ?? 0
if (wA !== wB) return wA - wB // Ascending
return (a.isRaw ? 1 : 0) - (b.isRaw ? 1 : 0) // Non-raw first
return wA - wB // Ascending
})
return suitable[0]
}
@@ -171,7 +171,6 @@ function FileViewPage() {
key: t.key,
width: t.width,
height: t.height,
isRaw: t.isRaw,
})),
},
versions: versionsDataList,
-1
View File
@@ -20,7 +20,6 @@ export interface TopNavProjectState {
key: string
width: number
height: number
isRaw?: boolean
}>
}
versions?: Array<{