Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

feat(video-download): support link queues, cover downloads, and Reddit

Joshua Yin Junxib91281c3498d
diff --git a/apps/daemon/src/api/routes.creator-thumbnail.ts b/apps/daemon/src/api/routes.creator-thumbnail.ts
new file mode 100644
index 00000000..58a342df
--- /dev/null
+++ b/apps/daemon/src/api/routes.creator-thumbnail.ts
@@ -0,0 +1,38 @@
+import type { CreatorServicesConfig } from '@opencreator/protocol';
+import type { FastifyInstance } from 'fastify';
+import sharp from 'sharp';
+import { downloadThumbnail } from '../creator/cover/executor.js';
+import type { CreatorService } from '../creator/service.js';
+import { apiError } from './errors.js';
+
+export async function registerCreatorThumbnailRoutes(
+ server: FastifyInstance,
+ service: Pick<CreatorService, 'getJob'>,
+ readServicesConfig?: () => Promise<CreatorServicesConfig>
+): Promise<void> {
+ server.get('/creator/jobs/:id/artifacts/:artifactId/thumbnail', async (request, reply) => {
+ const { id, artifactId } = request.params as { id: string; artifactId: string };
+ const job = service.getJob(id);
+ if (job === undefined) return reply.code(404).send(apiError('creator_job_not_found', 'Creator job not found'));
+ const probe = job.artifacts.find(artifact => artifact.id === artifactId
+ && artifact.kind === 'download_probe' && artifact.status === 'completed');
+ const url = probe?.metadata.thumbnailUrl;
+ if (typeof url !== 'string' || !url.trim()) {
+ return reply.code(404).send(apiError('creator_artifact_not_found', 'Video thumbnail not found'));
+ }
+ try {
+ const config = await readServicesConfig?.();
+ const thumbnail = await downloadThumbnail(url, config?.proxy ?? '', AbortSignal.timeout(30_000));
+ const image = sharp(thumbnail.content);
+ const metadata = await image.metadata();
+ const content = metadata.format === 'jpeg' ? thumbnail.content
+ : await image.rotate().flatten({ background: '#ffffff' }).jpeg({ quality: 95 }).toBuffer();
+ return reply.type('image/jpeg')
+ .header('Content-Disposition', 'attachment; filename="thumbnail.jpg"')
+ .header('Cache-Control', 'private, no-store')
+ .send(content);
+ } catch {
+ return reply.code(502).send(apiError('VIDEO_METADATA_UNAVAILABLE', 'Could not download the video thumbnail. Try again.'));
+ }
+ });
+}
diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.ts
index 648ca89d..60246855 100644
--- a/apps/daemon/src/api/routes.creator.ts
+++ b/apps/daemon/src/api/routes.creator.ts
@@ -88,6 +88,7 @@ import { createCreatorPresetDetails } from '../creator/presets/presentation.js';
import { readCodexImageConfiguration } from '../image-generation/codex-runtime.js';
import type { CodexNativeImageRuntime } from '../image-generation/provider.js';
import type { CreatorIssueService } from '../creator/issues.js';
+import { registerCreatorThumbnailRoutes } from './routes.creator-thumbnail.js';
export async function registerCreatorRoutes(
server: FastifyInstance,
@@ -116,6 +117,7 @@ export async function registerCreatorRoutes(
issueService?: CreatorIssueService;
}
): Promise<void> {
+ await registerCreatorThumbnailRoutes(server, service, options.readServicesConfig);
if (options.stickmanVisualAssets !== undefined) {
server.get('/creator/visual-assets', async (request, reply) => {
try {
diff --git a/apps/daemon/src/creator/cover/executor.ts b/apps/daemon/src/creator/cover/executor.ts
index 59843d33..55f58570 100644
--- a/apps/daemon/src/creator/cover/executor.ts
+++ b/apps/daemon/src/creator/cover/executor.ts
@@ -228,7 +228,7 @@ function runYtDlp(
});
}
-async function downloadThumbnail(
+export async function downloadThumbnail(
url: string,
proxy: string,
signal: AbortSignal
diff --git a/apps/daemon/src/creator/download/executor.ts b/apps/daemon/src/creator/download/executor.ts
index 35547a5b..45ba67e7 100644
--- a/apps/daemon/src/creator/download/executor.ts
+++ b/apps/daemon/src/creator/download/executor.ts
@@ -67,7 +67,7 @@ export function createDownloadExecutor(
if (!isSupported(url)) {
throw new CreatorExecutorError(
'unsupported_source',
- 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, and Pinterest video URLs are supported'
+ 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, and Reddit video URLs are supported'
);
}
const proxy = (await input.configStore.read()).proxy.trim();
diff --git a/apps/daemon/src/creator/download/probe-parser.ts b/apps/daemon/src/creator/download/probe-parser.ts
index 9b770dad..70afd0e4 100644
--- a/apps/daemon/src/creator/download/probe-parser.ts
+++ b/apps/daemon/src/creator/download/probe-parser.ts
@@ -3,6 +3,7 @@ import type {
DownloadProbe,
DownloadProbeFormat
} from '@opencreator/protocol';
+import { supportedVideoSourcePlatform } from '@opencreator/protocol';
import { z } from 'zod';
const formatSchema = z.object({
@@ -78,7 +79,8 @@ export function parseDownloadProbe(
function parseSingleDownloadProbe(value: unknown, requestedUrl: string): DownloadProbe {
const parsed = probeSchema.parse(value);
const extractor = parsed.extractor_key ?? '';
- const platform = /^https:\/\/(?:v|www)\.douyin\.com\//i.test(requestedUrl)
+ const platform = supportedVideoSourcePlatform(requestedUrl) === 'reddit' || /^reddit(?::|$)/i.test(extractor) ? 'reddit'
+ : /^https:\/\/(?:v|www)\.douyin\.com\//i.test(requestedUrl)
|| /^douyin(?::|$)/i.test(extractor) ? 'douyin'
: /bilibili/i.test(extractor) ? 'bilibili'
: /^(twitter|x)(?::|$)/i.test(extractor) ? 'x'
diff --git a/apps/daemon/src/creator/templates/video-download.ts b/apps/daemon/src/creator/templates/video-download.ts
index 11676f4d..d0b7e653 100644
--- a/apps/daemon/src/creator/templates/video-download.ts
+++ b/apps/daemon/src/creator/templates/video-download.ts
@@ -84,7 +84,7 @@ export function createVideoDownloadTemplate(): CreatorTemplateDefinition {
{ kind: 'source_audio', required: false }
],
agentGuidance: [
- '支持公开的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书和 Pinterest 视频链接,可下载视频或提取音频。',
+ '支持公开的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 和 Reddit 视频链接,可下载视频或提取音频。',
'先设置 sourceUrl 并运行 probe,再读取最新 download_probe.options;只选择其中与用户请求的 video 或 audio 对应的 option.id。',
'更新 selectedOptionId 和 mediaType 后运行 download;不得自行构造或写入 formatId。若 probe 没有对应选项,再说明该链接无法提供所需媒体。'
].join(' ')
diff --git a/apps/daemon/src/creator/templates/video-translation-actions.ts b/apps/daemon/src/creator/templates/video-translation-actions.ts
index 24aa0ed8..054ee73b 100644
--- a/apps/daemon/src/creator/templates/video-translation-actions.ts
+++ b/apps/daemon/src/creator/templates/video-translation-actions.ts
@@ -166,7 +166,7 @@ function validateSource(job: CreatorJob): void {
}
const value = job.state.sourceUrl;
if (typeof value !== 'string' || !isSupportedVideoUrl(value)) {
- throw new VideoTranslationWorkflowError('unsupported_source', 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, and Pinterest video URLs are supported');
+ throw new VideoTranslationWorkflowError('unsupported_source', 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, and Reddit video URLs are supported');
}
}
diff --git a/apps/daemon/test/unit/creator-download-executor.test.ts b/apps/daemon/test/unit/creator-download-executor.test.ts
index b6e229c0..4be43c54 100644
--- a/apps/daemon/test/unit/creator-download-executor.test.ts
+++ b/apps/daemon/test/unit/creator-download-executor.test.ts
@@ -51,7 +51,8 @@ describe('creator download executor', () => {
'https://www.instagram.com/reel/abc123/', 'https://www.douyin.com/video/123',
'https://www.facebook.com/watch/?v=123',
'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D',
- 'https://www.pinterest.com/pin/123/'
+ 'https://www.pinterest.com/pin/123/',
+ 'https://www.reddit.com/r/claude/s/R5I7tDfJ0h'
])('prepares saved translation previews from the added platform: %s', async sourceUrl => {
const executor = createDownloadExecutor(await fakeBinaries());
const workdir = join(tempDir, 'preview');
@@ -142,6 +143,33 @@ describe('creator download executor', () => {
}
});
+ it.each(['Reddit', 'Youtube'])('keeps Reddit attribution for a post resolved by %s and sends share links to the downloader', async extractor => {
+ const sourceUrl = 'https://www.reddit.com/r/claude/s/R5I7tDfJ0h';
+ const canonicalUrl = 'https://www.reddit.com/r/claude/comments/1x1qhlj/i_made_with_opus_55/';
+ const probe = parseDownloadProbe({
+ id: 'reddit-video', title: 'Reddit video', extractor_key: extractor,
+ webpage_url: canonicalUrl,
+ formats: [
+ { format_id: 'dash-video', ext: 'mp4', width: 1280, height: 720, vcodec: 'h264', acodec: 'none' },
+ { format_id: 'dash-audio', ext: 'm4a', vcodec: 'none', acodec: 'aac' }
+ ]
+ }, sourceUrl);
+ expect(probe).toMatchObject({ platform: 'reddit', requestedUrl: sourceUrl, url: canonicalUrl });
+ const option = probe.options.find(option => option.mediaType === 'video' && option.videoFormatId === 'dash-video');
+ expect(option).toMatchObject({ videoFormatId: 'dash-video', audioFormatId: 'dash-audio' });
+ const executor = createDownloadExecutor(await fakeBinaries());
+ const workdir = join(tempDir, 'reddit');
+ await mkdir(workdir);
+ await executor.run(stageInput({ workdir, stageId: 'probe', state: { sourceUrl } }));
+ expect(JSON.parse(await readFile(join(workdir, 'args.json'), 'utf8'))).toContain(sourceUrl);
+ const probeArtifact = await writeProbeArtifact(workdir, probe);
+ const result = await executor.run(stageInput({
+ workdir, stageId: 'download', state: { sourceUrl, selectedOptionId: option!.id, mediaType: 'video' }, inputArtifacts: [probeArtifact]
+ }));
+ expect(JSON.parse(await readFile(join(workdir, 'args.json'), 'utf8'))).toContain(sourceUrl);
+ expect(result.outputs[0]?.metadata).toMatchObject({ platform: 'reddit', requestedUrl: sourceUrl });
+ });
+
it('recognizes a Xiaohongshu video note and its downloadable formats', () => {
const sourceUrl = 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D&xsec_source=pc_feed';
const probe = parseDownloadProbe({
diff --git a/apps/daemon/test/unit/creator-thumbnail-routes.test.ts b/apps/daemon/test/unit/creator-thumbnail-routes.test.ts
new file mode 100644
index 00000000..5b8b0707
--- /dev/null
+++ b/apps/daemon/test/unit/creator-thumbnail-routes.test.ts
@@ -0,0 +1,88 @@
+import type { CreatorArtifact, CreatorJob } from '@opencreator/protocol';
+import Fastify, { type FastifyInstance } from 'fastify';
+import sharp from 'sharp';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { registerCreatorThumbnailRoutes } from '../../src/api/routes.creator-thumbnail.js';
+
+let server: FastifyInstance | undefined;
+afterEach(async () => { await server?.close(); vi.unstubAllGlobals(); });
+
+describe('creator video thumbnail download', () => {
+ it.each(['jpeg', 'png', 'webp'] as const)('saves a %s thumbnail as JPG at its original dimensions', async format => {
+ const bytes = await sharp({ create: { width: 16, height: 9, channels: 3, background: '#cc4433' } }).toFormat(format).toBuffer();
+ const fetch = vi.fn(async () => new Response(bytes, { headers: { 'content-type': `image/${format}` } }));
+ vi.stubGlobal('fetch', fetch);
+ await setup(job());
+ const response = await server!.inject('/creator/jobs/job/artifacts/probe/thumbnail');
+ expect(response.statusCode).toBe(200);
+ expect(response.headers['content-type']).toBe('image/jpeg');
+ expect(response.headers['content-disposition']).toBe('attachment; filename="thumbnail.jpg"');
+ expect(await sharp(response.rawPayload).metadata()).toMatchObject({ format: 'jpeg', width: 16, height: 9 });
+ if (format === 'jpeg') expect(response.rawPayload).toEqual(bytes);
+ expect(fetch).toHaveBeenCalledWith(new URL('https://i.ytimg.com/vi/demo/hqdefault.jpg'), expect.objectContaining({ method: 'GET', signal: expect.any(AbortSignal) }));
+ });
+
+ it('uses a white background for transparent thumbnails saved as JPG', async () => {
+ const bytes = await sharp({ create: { width: 16, height: 9, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } }).png().toBuffer();
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes, { headers: { 'content-type': 'image/png' } })));
+ await setup(job());
+ const response = await server!.inject('/creator/jobs/job/artifacts/probe/thumbnail');
+ expect(response.statusCode).toBe(200);
+ const { data, info } = await sharp(response.rawPayload).raw().toBuffer({ resolveWithObject: true });
+ expect(info.channels).toBe(3);
+ expect([...data.subarray(0, 3)]).toEqual([255, 255, 255]);
+ });
+
+ it('rejects missing jobs and probes that do not belong to the requested job', async () => {
+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
+ await setup(job());
+ expect((await server!.inject('/creator/jobs/other/artifacts/probe/thumbnail')).statusCode).toBe(404);
+ expect((await server!.inject('/creator/jobs/job/artifacts/other/thumbnail')).statusCode).toBe(404);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { kind: 'source_video' }, { status: 'draft' }, { metadata: {} }
+ ] satisfies Partial<CreatorArtifact>[])('rejects artifacts that cannot supply a thumbnail: %j', async patch => {
+ const current = job(); current.artifacts[0] = { ...current.artifacts[0]!, ...patch };
+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
+ await setup(current);
+ expect((await server!.inject('/creator/jobs/job/artifacts/probe/thumbnail')).statusCode).toBe(404);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ () => new Response('unavailable', { status: 403 }),
+ () => new Response('<html>error</html>', { headers: { 'content-type': 'text/html' } }),
+ () => new Response('invalid image', { headers: { 'content-type': 'image/jpeg' } })
+ ])('returns a retryable error when the platform does not return an image', async upstream => {
+ vi.stubGlobal('fetch', vi.fn(async () => upstream()));
+ await setup(job());
+ const response = await server!.inject('/creator/jobs/job/artifacts/probe/thumbnail');
+ expect(response.statusCode).toBe(502);
+ expect(response.json().error.code).toBe('VIDEO_METADATA_UNAVAILABLE');
+ });
+
+ it('rejects non-HTTP thumbnail URLs without requesting them', async () => {
+ const current = job(); current.artifacts[0]!.metadata.thumbnailUrl = 'file:///private/image.png';
+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
+ await setup(current);
+ expect((await server!.inject('/creator/jobs/job/artifacts/probe/thumbnail')).statusCode).toBe(502);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
+
+async function setup(current: CreatorJob) {
+ server = Fastify();
+ await registerCreatorThumbnailRoutes(server, { getJob: id => id === current.id ? current : undefined });
+}
+
+function job(): CreatorJob {
+ const createdAt = '2026-10-12T00:00:00Z';
+ return { id: 'job', projectId: 'project', templateId: 'video-download', templateVersion: 2,
+ status: 'draft', revision: 0, presetOrigin: null, state: {}, agentThreadId: null,
+ stages: [], providerRequests: [], activities: [], createdAt, updatedAt: createdAt,
+ artifacts: [{ id: 'probe', jobId: 'job', kind: 'download_probe', version: 1, status: 'completed',
+ path: '/tmp/probe.json', scopeKey: null, inputFingerprint: null, sha256: null,
+ sourceArtifactIds: [], createdAt, metadata: { thumbnailUrl: 'https://i.ytimg.com/vi/demo/hqdefault.jpg' } }] };
+}
diff --git a/apps/web/e2e/video-download-layout.spec.ts b/apps/web/e2e/video-download-layout.spec.ts
index db0e0e5d..0e748f53 100644
--- a/apps/web/e2e/video-download-layout.spec.ts
+++ b/apps/web/e2e/video-download-layout.spec.ts
@@ -1,7 +1,7 @@
import type { CreatorJob } from '@opencreator/protocol';
import { expect, test } from './fixtures/runtime.js';
-test('video download platforms stay centered and wrap within translation-sized settings', async ({ page, runtime }) => {
+test('video download platforms stay centered and wrap within the full workspace width', async ({ page, runtime }) => {
const { job } = await runtime.api<{ job: CreatorJob }>('POST', '/creator/jobs', {
projectId: runtime.projectId,
templateId: 'video-download',
@@ -27,7 +27,11 @@ test('video download platforms stay centered and wrap within translation-sized s
loadedIcons: [...element.querySelectorAll<HTMLImageElement>('img')].every(image => image.naturalWidth > 0)
};
});
- expect(await stack.evaluate(element => element.getBoundingClientRect().width)).toBeCloseTo(960, 0);
+ const contentWidth = await page.locator('.video-download-workspace-page .creator-workspace-content').evaluate(element => {
+ const style = getComputedStyle(element);
+ return element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
+ });
+ expect(await stack.evaluate(element => element.getBoundingClientRect().width)).toBeCloseTo(contentWidth, 0);
expect(wide.rowTops).toHaveLength(1);
expect(Math.abs(wide.itemsCenter - wide.listCenter)).toBeLessThan(2);
expect(wide.loadedIcons).toBe(true);
diff --git a/apps/web/public/platforms/reddit.png b/apps/web/public/platforms/reddit.png
new file mode 100644
index 00000000..197279c1
Binary files /dev/null and b/apps/web/public/platforms/reddit.png differ
diff --git a/apps/web/src/features/dashboard/CreatorToolShell.tsx b/apps/web/src/features/dashboard/CreatorToolShell.tsx
index 500508c5..d3c2bd59 100644
--- a/apps/web/src/features/dashboard/CreatorToolShell.tsx
+++ b/apps/web/src/features/dashboard/CreatorToolShell.tsx
@@ -13,6 +13,8 @@ export default function CreatorToolShell(props: {
titleIcon?: ReactNode;
subtitle: string;
context: string;
+ taskSummary?: ReactNode;
+ headerActions?: ReactNode;
initialMessage?: string;
suggestions: string[];
placeholder: string;
@@ -43,7 +45,7 @@ export default function CreatorToolShell(props: {
<CreatorResizableLayout
className="creator-workspace-layout"
workspace={<section className="creator-workspace-main" aria-label={`${props.title} ${l('操作区', 'workspace')}`}>
- <header className={`creator-workspace-header${props.titleIcon === undefined ? '' : ' has-title-icon'}`}>
+ <header className={`creator-workspace-header${props.titleIcon === undefined ? '' : ' has-title-icon'}${props.headerActions === undefined ? '' : ' has-actions'}`}>
<button type="button" onClick={props.onBack} aria-label={l('返回', 'Back')}>
<ArrowLeft size={18} strokeWidth={1.8} aria-hidden="true" />
</button>
@@ -54,6 +56,7 @@ export default function CreatorToolShell(props: {
<h1>{props.title}</h1>
<p>{props.subtitle}</p>
</div>
+ {props.headerActions === undefined ? null : <div className="creator-workspace-header-actions">{props.headerActions}</div>}
</header>
<div className={`creator-workspace-content${props.contentClassName ? ` ${props.contentClassName}` : ''}`}>{props.children}</div>
</section>}
@@ -61,6 +64,7 @@ export default function CreatorToolShell(props: {
adapter={adapter}
stepLabel={props.stepLabel ?? props.title}
contextSummary={props.context}
+ taskSummary={props.taskSummary}
promptHint={props.placeholder}
currentIssue={props.currentIssue}
quickActions={quickActions}
diff --git a/apps/web/src/features/dashboard/DashboardPage.tsx b/apps/web/src/features/dashboard/DashboardPage.tsx
index 4ed02c2e..8de6a5fc 100644
--- a/apps/web/src/features/dashboard/DashboardPage.tsx
+++ b/apps/web/src/features/dashboard/DashboardPage.tsx
@@ -31,7 +31,7 @@ import SmartDubbingWorkspace from './SmartDubbingWorkspace.js';
import XiaohongshuPostWorkspace from './XiaohongshuPostWorkspace.js';
import WechatArticleWorkspace from './WechatArticleWorkspace.js';
import StickmanVideoWorkspace from './StickmanVideoWorkspace.js';
-import VideoDownloadWorkspace from './VideoDownloadWorkspace.js';
+import VideoDownloadBatchWorkspace from './VideoDownloadBatchWorkspace.js';
import VideoTranslationWorkspace from './VideoTranslationWorkspace.js';
import VideoGenerationWorkspace from './VideoGenerationWorkspace.js';
import type { CreatorWebService } from '../../services/creator-service.js';
@@ -368,7 +368,8 @@ export default function DashboardPage(props: {
if (activeWorkspace === 'video-download') {
return renderCreatorWorkspace('video-download', (
- <VideoDownloadWorkspace
+ <VideoDownloadBatchWorkspace
+ service={props.creatorService!}
promptHint={activePromptHint}
runtimeDependencies={props.runtimeDependencies}
onOpenRuntimeComponents={props.onOpenRuntimeComponents}
diff --git a/apps/web/src/features/dashboard/SupportedVideoSources.tsx b/apps/web/src/features/dashboard/SupportedVideoSources.tsx
index 27e3e171..c99031c8 100644
--- a/apps/web/src/features/dashboard/SupportedVideoSources.tsx
+++ b/apps/web/src/features/dashboard/SupportedVideoSources.tsx
@@ -1,19 +1,19 @@
import { useId, useState } from 'react';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
-export default function SupportedVideoSources(props: { compact?: boolean }) {
+export default function SupportedVideoSources(props: { compact?: boolean; label?: string }) {
const l = useLocalizedCopy();
const tooltipId = useId();
const [activePlatform, setActivePlatform] = useState<string>();
return (
<div className={`video-download-platform-section${props.compact ? ' video-source-platforms-compact' : ''}`}>
- <span>{props.compact ? l('支持平台', 'Supported platforms')
- : l('支持的视频来源(支持单个公开视频链接)', 'Supported video sources (one public video link)')}</span>
+ <span>{props.label ?? (props.compact ? l('支持平台', 'Supported platforms')
+ : l('支持的视频来源(支持单个公开视频链接)', 'Supported video sources (one public video link)'))}</span>
<ul className="video-download-platforms" aria-label={l('支持的平台', 'Supported platforms')}>
{([
['youtube', 'YouTube'], ['bilibili', 'Bilibili'], ['x', 'X'],
['tiktok', 'TikTok'], ['instagram', 'Instagram'], ['douyin', l('抖音', 'Douyin')],
- ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest']
+ ['facebook', 'Facebook'], ['xiaohongshu', l('小红书', 'Xiaohongshu')], ['pinterest', 'Pinterest'], ['reddit', 'Reddit']
] as const).map(([platform, name]) => (
<li
key={platform}
diff --git a/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.test.tsx
new file mode 100644
index 00000000..05b83e66
--- /dev/null
+++ b/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.test.tsx
@@ -0,0 +1,298 @@
+import type { CreateCreatorJobRequest, CreatorActionRequest, CreatorArtifact, CreatorEventEnvelope, CreatorJob, CreatorJson, CreatorStageRun } from '@opencreator/protocol';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { LanguageProvider } from '../../i18n/LanguageProvider.js';
+import type { CreatorWebService } from '../../services/creator-service.js';
+import { CreatorSessionProvider } from './creator-session-store.js';
+import VideoDownloadBatchWorkspace from './VideoDownloadBatchWorkspace.js';
+import { DOWNLOAD_BATCH_HIDDEN, DOWNLOAD_BATCH_PARENT, parseDownloadLink } from './video-download-batch.js';
+
+const firstUrl = 'https://www.youtube.com/watch?v=first';
+type CreateDownloadJobRequest = Extract<CreateCreatorJobRequest, { templateId: string }>;
+const secondUrl = 'https://www.youtube.com/watch?v=second';
+const thirdUrl = 'https://www.youtube.com/watch?v=third';
+const createObjectURL = vi.fn(() => 'blob:batch-test');
+const revokeObjectURL = vi.fn();
+beforeEach(() => {
+ createObjectURL.mockClear(); revokeObjectURL.mockClear();
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL });
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL });
+});
+
+describe('video download link batches', () => {
+ it('accepts one URL or Douyin share text and rejects multiple or unsupported URLs', () => {
+ expect(parseDownloadLink(` ${firstUrl} `)).toEqual({ url: firstUrl });
+ expect(parseDownloadLink('https://www.reddit.com/r/claude/s/R5I7tDfJ0h')).toEqual({ url: 'https://www.reddit.com/r/claude/s/R5I7tDfJ0h' });
+ expect(parseDownloadLink('分享\nhttps://v.douyin.com/example/\n复制链接')).toEqual({ url: 'https://v.douyin.com/example/' });
+ for (const separator of ['\n', ' ', '']) {
+ expect(parseDownloadLink(`${firstUrl}${separator}${secondUrl}`)).toEqual({ error: 'multiple' });
+ }
+ expect(parseDownloadLink(`${firstUrl}\n${firstUrl}`)).toEqual({ error: 'multiple' });
+ expect(parseDownloadLink('分享 https://v.douyin.com/example/ 和 https://example.com')).toEqual({ error: 'multiple' });
+ for (const value of ['', 'ftp://example.com/video', 'https://example.com']) {
+ expect(parseDownloadLink(value)).toEqual({ error: 'invalid' });
+ }
+ });
+
+ it('rejects multiple pasted links before the single-line input strips newlines', async () => {
+ const harness = setup(makeJob('pending:project:video-download'));
+ const input = screen.getByRole('textbox', { name: '视频链接' });
+ expect(input.tagName).toBe('INPUT');
+ for (const separator of ['\n', ' ']) {
+ expect(fireEvent.paste(input, { clipboardData: { getData: () => `${firstUrl}${separator}${secondUrl}` } })).toBe(false);
+ expect(screen.getByRole('alert')).toHaveTextContent('每次只能添加一个链接');
+ expect(input).toHaveValue('');
+ }
+ expect(harness.ensureJob).not.toHaveBeenCalled();
+ expect(harness.service.createJob).not.toHaveBeenCalled();
+ fireEvent.paste(input, { clipboardData: { getData: () => '分享\nhttps://v.douyin.com/example/\n复制链接' } });
+ expect(input).toHaveValue('https://v.douyin.com/example/');
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('adds independent jobs and selects existing duplicates without starting another analysis', async () => {
+ const harness = setup(readyJob('root', firstUrl));
+ await addLinks(secondUrl);
+ await addLinks(thirdUrl);
+ await waitFor(() => expect(harness.service.createJob).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(harness.probes()).toHaveLength(2));
+ const created = harness.service.createJob.mock.calls.map(([request]) => request);
+ expect(created.every(request => request.state?.[DOWNLOAD_BATCH_PARENT] === 'root')).toBe(true);
+ expect(await screen.findByRole('heading', { name: 'Video third' })).toBeInTheDocument();
+ expect(screen.getAllByRole('complementary', { name: 'OpenCreator' })).toHaveLength(1);
+ await addLinks('https://youtu.be/first?t=20');
+ expect(harness.service.createJob).toHaveBeenCalledTimes(2);
+ expect(harness.probes()).toHaveLength(2);
+ expect(await screen.findByRole('heading', { name: 'Video first' })).toBeInTheDocument();
+ });
+
+ it('persists the first pending job before linking more jobs to it', async () => {
+ const harness = setup(makeJob('pending:project:video-download'));
+ await addLinks(firstUrl);
+ await addLinks(secondUrl);
+ await addLinks(thirdUrl);
+ await waitFor(() => expect(harness.service.createJob).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(harness.probes()).toHaveLength(3));
+ expect(harness.ensureJob).toHaveBeenCalledTimes(1);
+ expect(harness.service.createJob.mock.calls.every(([request]) => request.state?.[DOWNLOAD_BATCH_PARENT] === 'persisted-root')).toBe(true);
+ expect(within(screen.getByRole('list', { name: '视频链接列表' })).getAllByRole('listitem')).toHaveLength(3);
+ });
+
+ it('keeps the blank-page input visible while typing and analyzes an existing pending URL', async () => {
+ const harness = setup(makeJob('pending:project:video-download'));
+ const input = screen.getByRole('textbox', { name: '视频链接' });
+ expect(within(screen.getByRole('list', { name: '支持的平台' })).getAllByRole('listitem')).toHaveLength(10);
+ fireEvent.change(input, { target: { value: 'h' } });
+ expect(screen.getByRole('textbox', { name: '视频链接' })).toHaveValue('h');
+ await addLinks(firstUrl);
+ await screen.findByRole('heading', { name: 'Video first' });
+ expect(harness.probes()).toHaveLength(1);
+ expect(harness.service.createJob).not.toHaveBeenCalled();
+ harness.view.unmount();
+ const pending = makeJob('pending:project:video-download');
+ pending.state.sourceUrl = firstUrl;
+ const existing = setup(pending);
+ await addLinks(firstUrl);
+ await addLinks(secondUrl);
+ await waitFor(() => expect(existing.probes()).toHaveLength(2));
+ expect(existing.service.createJob.mock.calls[0]![0].state?.[DOWNLOAD_BATCH_PARENT]).toBe('persisted-root');
+ });
+
+ it('continues adding other links when one analysis fails and retries only that source', async () => {
+ const harness = setup(readyJob('root', firstUrl));
+ const apply = harness.service.applyAction.getMockImplementation()!;
+ let failed = false;
+ harness.service.applyAction.mockImplementation(async (id, request) => {
+ if (id === 'child-1' && request.input.stageId === 'probe' && !failed) {
+ failed = true;
+ throw new Error('analysis unavailable');
+ }
+ return apply(id, request);
+ });
+ await addLinks(secondUrl);
+ await addLinks(thirdUrl);
+ await screen.findByRole('button', { name: `重试 ${secondUrl}` });
+ expect(screen.getByRole('button', { name: /^Video third/ })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: `重试 ${secondUrl}` }));
+ await screen.findByRole('button', { name: /^Video second/ });
+ expect(harness.probes().filter(([id]) => id === 'child-2')).toHaveLength(1);
+ expect(harness.service.createJob).toHaveBeenCalledTimes(2);
+ });
+
+ it('restores only members of this project and batch, preserves subscriptions while switching, and opens files through the owner', async () => {
+ const child = readyJob('child', secondUrl, 'root');
+ child.artifacts.push(fileArtifact(child));
+ const harness = setup(readyJob('root', firstUrl), [child,
+ readyJob('other-batch', thirdUrl, 'another-root'),
+ { ...readyJob('other-project', thirdUrl, 'root'), projectId: 'other-project' }]);
+ const list = await screen.findByRole('list', { name: '视频链接列表' });
+ await waitFor(() => expect(within(list).getAllByRole('listitem')).toHaveLength(2));
+ fireEvent.click(screen.getByRole('button', { name: '下载 1080p' }));
+ await waitFor(() => expect(harness.jobs.get('root')?.stages.at(-1)?.status).toBe('running'));
+ fireEvent.click(screen.getByRole('tab', { name: '下载规格' }));
+ fireEvent.click(within(screen.getByRole('list', { name: '视频链接列表' })).getByRole('button', { name: /^Video second/ }));
+ expect(await screen.findByRole('heading', { name: 'Video second' })).toBeInTheDocument();
+ expect(harness.unsubscribe).not.toHaveBeenCalled();
+ fireEvent.click(within(screen.getByRole('list', { name: '视频链接列表' })).getByRole('button', { name: /^Video first/ }));
+ fireEvent.click(screen.getByRole('tab', { name: '作品' }));
+ expect(screen.queryByRole('list', { name: '视频链接列表' })).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Video first' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Video second' })).toBeInTheDocument();
+ expect(screen.getByRole('progressbar', { name: '下载进度 30%' })).toBeInTheDocument();
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
+ fireEvent.click(screen.getByRole('button', { name: '保存到本机 child.mp4' }));
+ await waitFor(() => expect(harness.service.openArtifact).toHaveBeenCalledWith('child', 'child-file'));
+ expect(click).toHaveBeenCalled();
+ click.mockRestore();
+ fireEvent.click(screen.getByRole('tab', { name: '下载规格' }));
+ expect(within(screen.getByRole('list', { name: '视频链接列表' })).getAllByRole('listitem')).toHaveLength(2);
+ });
+
+ it('retries a failed link independently and soft removes it without deleting its files', async () => {
+ const child = readyJob('child', secondUrl, 'root');
+ child.stages.push(stage(child, 'download', 'failed'));
+ const harness = setup(readyJob('root', firstUrl), [child]);
+ await screen.findByRole('button', { name: '重试 Video second' });
+ fireEvent.click(screen.getByRole('button', { name: '重试 Video second' }));
+ await waitFor(() => expect(harness.service.applyAction).toHaveBeenCalledWith('child', expect.objectContaining({
+ action: 'run-stage', input: { stageId: 'download', optionId: 'video-1080', mediaType: 'video', sourceUrl: secondUrl }
+ })));
+ expect(harness.probes()).toHaveLength(0);
+ expect(screen.getByRole('button', { name: '移除链接 Video second' })).toBeDisabled();
+ const completed = { ...harness.jobs.get('child')!, revision: 5, stages: [stage(child, 'download', 'succeeded')], artifacts: [...child.artifacts, fileArtifact(child)] };
+ await act(async () => harness.publish(completed));
+ await waitFor(() => expect(screen.getByRole('button', { name: '移除链接 Video second' })).toBeEnabled());
+ fireEvent.click(screen.getByRole('button', { name: '移除链接 Video second' }));
+ await waitFor(() => expect(screen.queryByRole('button', { name: '移除链接 Video second' })).not.toBeInTheDocument());
+ expect(harness.jobs.get('root')?.state[DOWNLOAD_BATCH_HIDDEN]).toEqual(['child']);
+ fireEvent.click(screen.getByRole('tab', { name: '作品' }));
+ expect(screen.getByText('child.mp4')).toBeInTheDocument();
+ await addLinks(secondUrl);
+ await screen.findByRole('button', { name: '移除链接 Video second' });
+ expect(harness.service.createJob).not.toHaveBeenCalled();
+ expect(harness.jobs.get('root')?.state[DOWNLOAD_BATCH_HIDDEN]).toEqual([]);
+ });
+
+ it('keeps successfully added jobs when a later creation fails and retries with the same creation key', async () => {
+ const harness = setup(readyJob('root', firstUrl));
+ const realCreate = harness.service.createJob.getMockImplementation()!;
+ let failedKey = '';
+ harness.service.createJob.mockImplementation(async request => {
+ if (request.state?.sourceUrl === thirdUrl && !failedKey) {
+ failedKey = request.creationKey!;
+ await realCreate(request);
+ throw new Error('connection lost');
+ }
+ return realCreate(request);
+ });
+ await addLinks(secondUrl);
+ await addLinks(thirdUrl);
+ expect(await screen.findByRole('alert')).toHaveTextContent('connection lost');
+ expect(screen.getByRole('textbox', { name: '视频链接' })).toHaveValue(thirdUrl);
+ fireEvent.click(screen.getByRole('button', { name: '添加并解析' }));
+ await waitFor(() => expect(harness.probes()).toHaveLength(2));
+ expect(harness.service.createJob.mock.calls[2]![0].creationKey).toBe(failedKey);
+ expect(harness.jobs.size).toBe(3);
+ });
+
+ it('restores hidden sources without showing their old formats, while keeping Works available', async () => {
+ const root = readyJob('root', firstUrl);
+ root.state[DOWNLOAD_BATCH_HIDDEN] = ['root'];
+ root.artifacts.push(fileArtifact(root));
+ setup(root);
+ await waitFor(() => expect(screen.queryByText('正在加载链接列表')).not.toBeInTheDocument());
+ expect(screen.queryByRole('heading', { name: 'Video first' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: '下载 1080p' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('tab', { name: '作品' }));
+ expect(screen.getByText('root.mp4')).toBeInTheDocument();
+ });
+});
+
+async function addLinks(value: string) {
+ await waitFor(() => expect(screen.queryByText('正在加载链接列表')).not.toBeInTheDocument());
+ if (screen.queryByRole('textbox', { name: '视频链接' }) === null) fireEvent.click(screen.getByRole('button', { name: '添加链接' }));
+ fireEvent.change(screen.getByRole('textbox', { name: '视频链接' }), { target: { value } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: '添加并解析' })); });
+}
+
+function setup(root: CreatorJob, members: CreatorJob[] = []) {
+ const jobs = new Map([root, ...members].map(job => [job.id, job]));
+ const subscriptions = new Map<string, (event: CreatorEventEnvelope) => void>();
+ const creationKeys = new Map<string, CreatorJob>();
+ const unsubscribe = vi.fn();
+ const service = {
+ getJob: vi.fn(async (id: string) => ({ job: jobs.get(id)! })),
+ subscribeJobEvents: vi.fn((id: string, onEvent: (event: CreatorEventEnvelope) => void) => {
+ subscriptions.set(id, onEvent);
+ return { close: () => { unsubscribe(id); subscriptions.delete(id); } };
+ }),
+ listJobs: vi.fn(async () => ({ jobs: [...jobs.values()] })),
+ createJob: vi.fn(async (request: CreateDownloadJobRequest) => {
+ const existing = creationKeys.get(request.creationKey!);
+ if (existing) return { job: jobs.get(existing.id)! };
+ const job = { ...makeJob(`child-${creationKeys.size + 1}`), state: request.state ?? {} };
+ jobs.set(job.id, job); creationKeys.set(request.creationKey!, job);
+ return { job };
+ }),
+ applyAction: vi.fn(async (id: string, request: CreatorActionRequest) => {
+ let next = jobs.get(id)!;
+ if (request.action === 'update-settings') next = { ...next, state: { ...next.state, ...(request.input.patch as Record<string, CreatorJson>) } };
+ if (request.action === 'run-stage') {
+ if (request.input.stageId === 'probe') next = { ...next, artifacts: [...next.artifacts, probeArtifact(next)], stages: [...next.stages, stage(next, 'probe', 'succeeded')] };
+ else next = { ...next, stages: [...next.stages, stage(next, 'download', 'running')] };
+ }
+ next = { ...next, revision: next.revision + 1 };
+ jobs.set(id, next);
+ return { job: next, receipt: { actor: 'user' as const, action: request.action, summary: request.action, affectedArtifacts: [], newRevision: next.revision, createdAt: next.updatedAt } };
+ }),
+ openArtifact: vi.fn(async () => new Response(new Blob(['file'], { type: 'video/mp4' }))),
+ runAgentTurn: vi.fn()
+ };
+ const ensureJob = vi.fn(async (state: Record<string, CreatorJson>) => {
+ const next = { ...makeJob('persisted-root'), state };
+ jobs.delete(root.id); jobs.set(next.id, next);
+ return next;
+ });
+ const view = render(<LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider initialJob={root} service={service} ensureJob={ensureJob}>
+ <VideoDownloadBatchWorkspace service={service as unknown as CreatorWebService} onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>);
+ return { service, ensureJob, jobs, unsubscribe, view,
+ probes: () => service.applyAction.mock.calls.filter(([, request]) => request.action === 'run-stage' && request.input.stageId === 'probe'),
+ publish: (job: CreatorJob) => { jobs.set(job.id, job); subscriptions.get(job.id)?.({ id: `${job.id}-${job.revision}`, jobId: job.id, revision: job.revision, kind: 'snapshot_changed', payload: {}, createdAt: job.updatedAt }); }
+ };
+}
+
+function makeJob(id: string): CreatorJob {
+ return { id, projectId: 'project', templateId: 'video-download', templateVersion: 2,
+ status: 'draft', revision: 0, presetOrigin: null, state: {}, agentThreadId: null,
+ stages: [], artifacts: [], providerRequests: [], activities: [], createdAt: '2026-10-12T00:00:00Z', updatedAt: '2026-10-12T00:00:00Z' };
+}
+
+function readyJob(id: string, url: string, parent?: string): CreatorJob {
+ const job = makeJob(id);
+ job.state = { sourceUrl: url, ...(parent ? { [DOWNLOAD_BATCH_PARENT]: parent } : {}) };
+ job.artifacts = [probeArtifact(job)];
+ return job;
+}
+
+function probeArtifact(job: CreatorJob): CreatorArtifact {
+ const url = String(job.state.sourceUrl);
+ return { id: `${job.id}-probe`, jobId: job.id, kind: 'download_probe', version: 1,
+ status: 'completed', path: '/tmp/probe.json', scopeKey: null, inputFingerprint: null, sha256: null, sourceArtifactIds: [], createdAt: job.createdAt,
+ metadata: { id: job.id, title: `Video ${url.split('v=')[1]}`, url, requestedUrl: url, platform: 'youtube', duration: 120, formats: [],
+ options: [{ id: 'video-1080', mediaType: 'video', container: 'mp4', height: 1080, videoFormatId: '399', audioFormatId: '140' }] } };
+}
+
+function fileArtifact(job: CreatorJob): CreatorArtifact {
+ return { ...probeArtifact(job), id: `${job.id}-file`, kind: 'source_video', path: `/tmp/${job.id}.mp4`, sourceArtifactIds: [`${job.id}-probe`],
+ metadata: { fileName: `${job.id}.mp4`, optionId: 'video-1080', mediaType: 'video', requestedUrl: job.state.sourceUrl!, mimeType: 'video/mp4' } };
+}
+
+function stage(job: CreatorJob, stageId: string, status: CreatorStageRun['status']): CreatorStageRun {
+ return { id: `${job.id}-${stageId}-${job.revision}`, jobId: job.id, stageId, executor: 'download', status,
+ dispatchStatus: 'claimed', claimOwner: 'test', claimExpiresAt: null, attempt: 1, idempotencyKey: null, scopeKey: null, inputFingerprint: null,
+ progress: stageId === 'probe' ? {} : { optionId: 'video-1080', mediaType: 'video', sourceUrl: job.state.sourceUrl!, probeArtifactId: `${job.id}-probe`, percent: 30 },
+ errorCode: null, errorMessage: null, startedAt: job.createdAt, finishedAt: null };
+}
diff --git a/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.tsx
new file mode 100644
index 00000000..7e7fc5ac
--- /dev/null
+++ b/apps/web/src/features/dashboard/VideoDownloadBatchWorkspace.tsx
@@ -0,0 +1,322 @@
+import type { CreatorJob } from '@opencreator/protocol';
+import { FileVideo, LoaderCircle, Plus, RefreshCw, X } from 'lucide-react';
+import { useCallback, useEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react';
+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
+import type { CreatorWebService } from '../../services/creator-service.js';
+import {
+ CreatorSessionProvider,
+ useCreatorSession,
+ type CreatorSessionContextValue
+} from './creator-session-store.js';
+import VideoDownloadWorkspace from './VideoDownloadWorkspace.js';
+import SupportedVideoSources from './SupportedVideoSources.js';
+import VideoDownloadThumbnail from './VideoDownloadThumbnail.js';
+import {
+ DOWNLOAD_BATCH_HIDDEN,
+ DOWNLOAD_BATCH_PARENT,
+ downloadSourceForJob,
+ downloadSourceIdentity,
+ hiddenDownloadJobIds,
+ parseDownloadLink,
+ type DownloadSource
+} from './video-download-batch.js';
+
+export type VideoDownloadBatchView = {
+ jobs: CreatorJob[];
+ hasSelectedSource: boolean;
+ toolbarActions: ReactNode;
+ editor: ReactNode;
+ sourceList: ReactNode;
+ resolveSession(jobId: string): CreatorSessionContextValue | undefined;
+};
+
+const ROOT = 'root';
+
+export default function VideoDownloadBatchWorkspace(props: ComponentProps<typeof VideoDownloadWorkspace> & {
+ service: CreatorWebService;
+}) {
+ const root = useCreatorSession();
+ const l = useLocalizedCopy();
+ const [jobs, setJobs] = useState<CreatorJob[]>([]);
+ const [selectedId, setSelectedId] = useState(ROOT);
+ const [editorOpen, setEditorOpen] = useState(() => downloadSourceForJob({ ...root.job, state: root.state }) === undefined);
+ const [linksText, setLinksText] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [restoreAttempt, setRestoreAttempt] = useState(0);
+ const [error, setError] = useState('');
+ const [restoreError, setRestoreError] = useState('');
+ const [jobErrors, setJobErrors] = useState<Record<string, string>>({});
+ const [retryingIds, setRetryingIds] = useState<ReadonlySet<string>>(() => new Set());
+ const retryingIdsRef = useRef(new Set<string>());
+ const sessionsRef = useRef(new Map<string, CreatorSessionContextValue>());
+ const rootRef = useRef(root);
+ const jobsRef = useRef(jobs);
+ const busyRef = useRef(false);
+ const needsProbeRef = useRef(new Set<string>());
+ const startedProbeRef = useRef(new Set<string>());
+ const inputRef = useRef<HTMLInputElement>(null);
+ rootRef.current = root;
+ jobsRef.current = jobs;
+
+ const rootSource = downloadSourceForJob({ ...root.job, state: root.state });
+ const hiddenIds = hiddenDownloadJobIds({ ...root.job, state: root.state });
+ const allJobs = [root.job, ...jobs];
+ const sources = [rootSource, ...jobs.map(downloadSourceForJob)]
+ .filter((source): source is DownloadSource => source !== undefined && !hiddenIds.includes(source.id));
+ const activeJobId = selectedId === ROOT ? root.job.id : selectedId;
+
+ useEffect(() => {
+ if (editorOpen) inputRef.current?.focus();
+ }, [editorOpen]);
+
+ useEffect(() => {
+ if (root.job.id.startsWith('pending:') || props.service.listJobs === undefined) return;
+ let canceled = false;
+ setLoading(true);
+ void props.service.listJobs(root.job.projectId).then(response => {
+ if (canceled) return;
+ const members = response.jobs.filter(job => job.templateId === 'video-download'
+ && job.projectId === root.job.projectId && job.state[DOWNLOAD_BATCH_PARENT] === root.job.id);
+ setJobs(current => {
+ const merged = new Map(current.map(job => [job.id, job]));
+ for (const job of members) if ((merged.get(job.id)?.revision ?? -1) <= job.revision) merged.set(job.id, job);
+ return [...merged.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
+ });
+ setRestoreError('');
+ }).catch(cause => {
+ if (!canceled) setRestoreError(errorMessage(cause, l('链接列表加载失败,请重试', 'Could not load links. Try again.')));
+ }).finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [root.job.id, root.job.projectId, props.service, restoreAttempt]);
+
+ useEffect(() => {
+ if (sources.some(source => source.id === activeJobId)) return;
+ if (sources.length > 0) setSelectedId(sources[0]!.id === root.job.id ? ROOT : sources[0]!.id);
+ else if (selectedId !== ROOT) setSelectedId(ROOT);
+ }, [activeJobId, root.job.id, selectedId, sources.map(source => source.id).join(':')]);
+
+ const registerSession = useCallback((session: CreatorSessionContextValue) => {
+ sessionsRef.current.set(session.job.id, session);
+ setJobs(current => {
+ const previous = current.find(job => job.id === session.job.id);
+ if (previous === undefined || previous === session.job || previous.revision > session.job.revision) return current;
+ const next = current.map(job => job.id === session.job.id ? session.job : job);
+ jobsRef.current = next;
+ return next;
+ });
+ if (!needsProbeRef.current.has(session.job.id) || startedProbeRef.current.has(session.job.id)) return;
+ startedProbeRef.current.add(session.job.id);
+ void session.applyAction({ actor: 'user', action: 'run-stage', input: { stageId: 'probe' } })
+ .catch(cause => setJobErrors(current => ({ ...current, [session.job.id]: errorMessage(cause, l('解析未完成', 'Analysis did not complete')) })))
+ .finally(() => { needsProbeRef.current.delete(session.job.id); });
+ }, [l]);
+
+ const unregisterSession = useCallback((jobId: string) => { sessionsRef.current.delete(jobId); }, []);
+
+ function resolveSession(jobId: string) {
+ return rootRef.current.job.id === jobId ? rootRef.current : sessionsRef.current.get(jobId);
+ }
+
+ async function unhide(jobId: string) {
+ const hidden = hiddenDownloadJobIds({ ...rootRef.current.job, state: rootRef.current.state });
+ if (!hidden.includes(jobId)) return;
+ rootRef.current.updateDraft({ [DOWNLOAD_BATCH_HIDDEN]: hidden.filter(id => id !== jobId) });
+ await rootRef.current.flush();
+ }
+
+ function linkError(error: 'multiple' | 'invalid') {
+ return error === 'multiple'
+ ? l('每次只能添加一个链接', 'Add one link at a time.')
+ : l('请输入支持的公开视频链接', 'Enter a supported public video URL.');
+ }
+
+ async function addLink() {
+ if (busyRef.current || loading) return;
+ const parsed = parseDownloadLink(linksText);
+ if (parsed.error) {
+ setError(linkError(parsed.error));
+ return;
+ }
+ const url = parsed.url;
+ busyRef.current = true;
+ setBusy(true);
+ setError('');
+ try {
+ let rootJob = { ...rootRef.current.job, state: rootRef.current.state };
+ let parentId = rootJob.id;
+ let selected: string;
+ const currentRoot = rootRef.current;
+ const existing = [downloadSourceForJob(rootJob), ...jobsRef.current.map(downloadSourceForJob)]
+ .find(source => source !== undefined && downloadSourceIdentity(source.url) === downloadSourceIdentity(url));
+ if (existing !== undefined) {
+ const isRoot = existing.id === rootJob.id;
+ if (isRoot && parentId.startsWith('pending:')) {
+ rootJob = await currentRoot.applyAction({ actor: 'user', action: 'update-settings', input: { patch: { sourceUrl: url }, activityMode: 'draft' } });
+ parentId = rootJob.id;
+ void currentRoot.applyAction({ actor: 'user', action: 'run-stage', input: { stageId: 'probe' } })
+ .catch(cause => setJobErrors(current => ({ ...current, [parentId]: errorMessage(cause, l('解析未完成', 'Analysis did not complete')) })));
+ }
+ await unhide(existing.id);
+ selected = isRoot ? ROOT : existing.id;
+ } else if (typeof rootJob.state.sourceUrl !== 'string' || !rootJob.state.sourceUrl.trim()) {
+ currentRoot.updateDraft({ sourceUrl: url, selectedOptionId: null }, { semantic: true });
+ rootJob = await currentRoot.applyAction({ actor: 'user', action: 'update-settings', input: { patch: { sourceUrl: url }, activityMode: 'draft' } });
+ parentId = rootJob.id;
+ void currentRoot.applyAction({ actor: 'user', action: 'run-stage', input: { stageId: 'probe' } })
+ .catch(cause => setJobErrors(current => ({ ...current, [parentId]: errorMessage(cause, l('解析未完成', 'Analysis did not complete')) })));
+ selected = ROOT;
+ } else {
+ if (parentId.startsWith('pending:')) {
+ rootJob = await currentRoot.applyAction({ actor: 'user', action: 'update-settings', input: { patch: { sourceUrl: rootJob.state.sourceUrl }, activityMode: 'draft' } });
+ parentId = rootJob.id;
+ }
+ const { job } = await props.service.createJob({
+ projectId: currentRoot.job.projectId, templateId: 'video-download', templateVersion: 2,
+ creationKey: `download-link:${parentId}:${downloadSourceIdentity(url)}`,
+ state: { sourceUrl: url, [DOWNLOAD_BATCH_PARENT]: parentId }
+ });
+ if (job.projectId !== currentRoot.job.projectId || job.templateId !== 'video-download'
+ || job.state[DOWNLOAD_BATCH_PARENT] !== parentId) throw new Error('Download task does not belong to this link list');
+ if (!job.stages.some(stage => stage.stageId === 'probe')) needsProbeRef.current.add(job.id);
+ jobsRef.current = [...jobsRef.current.filter(member => member.id !== job.id), job];
+ setJobs(jobsRef.current);
+ selected = job.id;
+ }
+ setSelectedId(selected);
+ setLinksText('');
+ setEditorOpen(false);
+ } catch (cause) {
+ setError(errorMessage(cause, l('添加链接未完成,请重试', 'Could not add the link. Try again.')));
+ } finally {
+ busyRef.current = false;
+ setBusy(false);
+ }
+ }
+
+ async function retrySource(source: DownloadSource) {
+ const session = resolveSession(source.id);
+ if (session === undefined || retryingIdsRef.current.has(source.id)
+ || session.job.stages.some(stage => stage.status === 'queued' || stage.status === 'running')) return;
+ retryingIdsRef.current.add(source.id);
+ setRetryingIds(new Set(retryingIdsRef.current));
+ setJobErrors(current => { const next = { ...current }; delete next[source.id]; return next; });
+ try {
+ session.clearError();
+ const latest = session.job.stages.at(-1);
+ if ((latest?.status === 'canceled' || latest?.status === 'interrupted') && source.job.artifacts.some(artifact => artifact.kind === 'download_probe')) {
+ await session.resumeJob();
+ } else if (latest?.status === 'failed' && latest.stageId === 'download'
+ && typeof latest.progress.optionId === 'string'
+ && (latest.progress.mediaType === 'video' || latest.progress.mediaType === 'audio')) {
+ await session.applyAction({ actor: 'user', action: 'run-stage', input: {
+ stageId: 'download', optionId: latest.progress.optionId,
+ mediaType: latest.progress.mediaType, sourceUrl: latest.progress.sourceUrl ?? source.url
+ } });
+ } else {
+ await session.applyAction({ actor: 'user', action: 'run-stage', input: { stageId: 'probe' } });
+ }
+ } catch (cause) {
+ setJobErrors(current => ({ ...current, [source.id]: errorMessage(cause, l('解析未完成,请重试', 'Analysis did not complete. Try again.')) }));
+ } finally {
+ retryingIdsRef.current.delete(source.id);
+ setRetryingIds(new Set(retryingIdsRef.current));
+ }
+ }
+
+ async function removeSource(source: DownloadSource) {
+ if (busyRef.current || retryingIdsRef.current.has(source.id) || source.status === 'analyzing' || source.status === 'downloading') return;
+ busyRef.current = true;
+ setBusy(true);
+ try {
+ const hidden = hiddenDownloadJobIds({ ...rootRef.current.job, state: rootRef.current.state });
+ rootRef.current.updateDraft({ [DOWNLOAD_BATCH_HIDDEN]: [...new Set([...hidden, source.id])] });
+ await rootRef.current.flush();
+ if (activeJobId === source.id) {
+ const next = sources.find(member => member.id !== source.id);
+ setSelectedId(next === undefined || next.id === root.job.id ? ROOT : next.id);
+ if (next === undefined) setEditorOpen(true);
+ }
+ } catch (cause) {
+ setError(errorMessage(cause, l('移除链接未完成,请重试', 'Could not remove the link. Try again.')));
+ } finally { busyRef.current = false; setBusy(false); }
+ }
+
+ const sourceList = sources.length === 0 ? null : (
+ <ul className="video-download-source-list" aria-label={l('视频链接列表', 'Video links')}>
+ {sources.map(source => {
+ const active = source.status === 'analyzing' || source.status === 'downloading' || retryingIds.has(source.id);
+ const failed = source.status === 'failed' || jobErrors[source.id] !== undefined;
+ const status = failed ? l('失败', 'Failed') : {
+ waiting: l('待解析', 'Waiting'), analyzing: l('解析中', 'Analyzing'), ready: l('可下载', 'Ready'),
+ downloading: l('下载中', 'Downloading'), completed: l('已完成', 'Completed'), failed: l('失败', 'Failed'), canceled: l('已停止', 'Stopped')
+ }[source.status];
+ return <li key={source.id} data-selected={source.id === activeJobId}>
+ <button className="video-download-source-select" type="button" aria-pressed={source.id === activeJobId}
+ onClick={() => setSelectedId(source.id === root.job.id ? ROOT : source.id)} title={jobErrors[source.id] ?? source.url}>
+ {source.thumbnail ? <VideoDownloadThumbnail key={source.thumbnailArtifactId} src={source.thumbnail} alt=""
+ load={source.thumbnailArtifactId ? () => props.service.openDownloadThumbnail(source.id, source.thumbnailArtifactId!) : undefined} /> : <FileVideo size={24} aria-hidden="true" />}
+ <span><strong>{source.title}</strong><small>{status}{source.percent === undefined ? '' : ` · ${Math.round(source.percent)}%`}</small></span>
+ </button>
+ {failed || source.status === 'waiting' || source.status === 'canceled' ? <button className="video-download-source-action" type="button"
+ disabled={busy || active} onClick={() => void retrySource(source)} aria-label={`${l('重试', 'Retry')} ${source.title}`} title={l('重试', 'Retry')}>
+ <RefreshCw size={15} aria-hidden="true" />
+ </button> : null}
+ <button className="video-download-source-action" type="button" disabled={busy || active}
+ onClick={() => void removeSource(source)} aria-label={`${l('移除链接', 'Remove link')} ${source.title}`} title={l('移除链接', 'Remove link')}>
+ <X size={15} aria-hidden="true" />
+ </button>
+ </li>;
+ })}
+ </ul>
+ );
+ const editor = <>
+ {editorOpen ? <form className="video-download-add-form" onSubmit={event => { event.preventDefault(); void addLink(); }}>
+ {sources.length === 0 ? <SupportedVideoSources label={l('支持的视频来源', 'Supported video sources')} /> : null}
+ <label htmlFor="video-download-add-links">{l('视频链接', 'Video URL')}</label>
+ <input id="video-download-add-links" ref={inputRef} value={linksText} disabled={busy} type="text" inputMode="url"
+ onChange={event => { setLinksText(event.target.value); setError(''); }}
+ onPaste={event => {
+ const pasted = event.clipboardData.getData('text');
+ const input = event.currentTarget;
+ const combined = linksText.slice(0, input.selectionStart ?? 0) + pasted + linksText.slice(input.selectionEnd ?? linksText.length);
+ const parsed = parseDownloadLink(combined);
+ if (parsed.error === 'multiple' || /[\r\n]/.test(pasted)) {
+ event.preventDefault();
+ if (parsed.error) setError(linkError(parsed.error));
+ else { setLinksText(parsed.url); setError(''); }
+ }
+ }}
+ placeholder={l('粘贴一个视频链接', 'Paste a video URL')} />
+ <div className="video-download-add-form-actions"><button type="button" disabled={busy} onClick={() => { setEditorOpen(false); setError(''); }}>{l('取消', 'Cancel')}</button>
+ <button type="submit" disabled={busy || loading || !linksText.trim()}>{busy ? <LoaderCircle size={15} className="smart-dubbing-spinner" /> : <Plus size={15} />}{l('添加并解析', 'Add and analyze')}</button></div>
+ </form> : null}
+ {loading ? <p className="creator-tool-notice" role="status">{l('正在加载链接列表', 'Loading links')}</p> : null}
+ {error ? <div className="video-download-batch-error" role="alert">{error}</div> : null}
+ {restoreError ? <div className="video-download-batch-error" role="alert">{restoreError}<button type="button" onClick={() => setRestoreAttempt(value => value + 1)}><RefreshCw size={15} />{l('重试', 'Retry')}</button></div> : null}
+ </>;
+ const batch: VideoDownloadBatchView = {
+ jobs: allJobs, hasSelectedSource: sources.some(source => source.id === activeJobId), sourceList, editor,
+ resolveSession,
+ toolbarActions: <button type="button" className="video-download-add-button" disabled={busy} onClick={() => setEditorOpen(value => !value)} aria-expanded={editorOpen} aria-controls={editorOpen ? 'video-download-add-links' : undefined}><Plus size={16} aria-hidden="true" />{l('添加链接', 'Add link')}</button>
+ };
+ const workspace = <VideoDownloadWorkspace {...props} batch={batch} />;
+ return <>
+ {selectedId === ROOT ? workspace : null}
+ {jobs.map(job => <CreatorSessionProvider key={job.id} initialJob={job} service={props.service}>
+ <DownloadJobObserver onSession={registerSession} onUnmount={unregisterSession} />
+ {selectedId === job.id ? workspace : null}
+ </CreatorSessionProvider>)}
+ </>;
+}
+
+function DownloadJobObserver(props: { onSession(session: CreatorSessionContextValue): void; onUnmount(jobId: string): void }) {
+ const session = useCreatorSession();
+ useEffect(() => { props.onSession(session); }, [session, props.onSession]);
+ useEffect(() => () => props.onUnmount(session.job.id), [session.job.id, props.onUnmount]);
+ return null;
+}
+
+function errorMessage(cause: unknown, fallback: string): string {
+ return cause instanceof Error && cause.message ? cause.message : fallback;
+}
diff --git a/apps/web/src/features/dashboard/VideoDownloadThumbnail.test.tsx b/apps/web/src/features/dashboard/VideoDownloadThumbnail.test.tsx
new file mode 100644
index 00000000..4d5db7a3
--- /dev/null
+++ b/apps/web/src/features/dashboard/VideoDownloadThumbnail.test.tsx
@@ -0,0 +1,54 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, expect, it, vi } from 'vitest';
+import VideoDownloadThumbnail from './VideoDownloadThumbnail.js';
+
+const createObjectURL = vi.fn(() => 'blob:local-thumbnail');
+const revokeObjectURL = vi.fn();
+const source = 'http://sns-webpic-qc.xhscdn.com/signed-cover.jpg';
+beforeEach(() => {
+ createObjectURL.mockClear(); revokeObjectURL.mockClear();
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL });
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL });
+});
+
+it('recovers a rejected CDN image through the local transport and releases its URL', async () => {
+ const load = vi.fn(async () => new Response('image', { headers: { 'content-type': 'image/jpeg' } }));
+ const view = render(<VideoDownloadThumbnail src={source} alt="Cover" load={load} />);
+ expect(screen.getByRole('img')).toHaveAttribute('src', source);
+ expect(load).not.toHaveBeenCalled();
+ fireEvent.error(screen.getByRole('img'));
+ await waitFor(() => expect(screen.getByRole('img')).toHaveAttribute('src', 'blob:local-thumbnail'));
+ expect(load).toHaveBeenCalledTimes(1);
+ view.unmount();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:local-thumbnail');
+});
+
+it.each([502, 200])('shows a placeholder if recovery returns an error or invalid image (%s)', async status => {
+ const load = vi.fn(async () => new Response('error', { status, headers: { 'content-type': 'text/html' } }));
+ render(<VideoDownloadThumbnail src={source} alt="Cover" load={load} />);
+ fireEvent.error(screen.getByRole('img'));
+ await waitFor(() => expect(screen.getByRole('img')).toHaveClass('video-download-image-placeholder'));
+ expect(screen.getByRole('img').tagName).toBe('SPAN');
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(createObjectURL).not.toHaveBeenCalled();
+});
+
+it('does not replace a newer source with an old recovery result', async () => {
+ let finish!: (response: Response) => void;
+ const load = vi.fn(() => new Promise<Response>(resolve => { finish = resolve; }));
+ const view = render(<VideoDownloadThumbnail src={source} alt="Cover" load={load} />);
+ fireEvent.error(screen.getByRole('img'));
+ view.rerender(<VideoDownloadThumbnail src="https://example.com/new.jpg" alt="New cover" load={load} />);
+ await act(async () => finish(new Response('old image', { headers: { 'content-type': 'image/jpeg' } })));
+ expect(screen.getByRole('img')).toHaveAttribute('src', 'https://example.com/new.jpg');
+ expect(createObjectURL).not.toHaveBeenCalled();
+});
+
+it('does not create an object URL if unmounted during recovery', async () => {
+ let finish!: (response: Response) => void;
+ const view = render(<VideoDownloadThumbnail src={source} alt="Cover" load={() => new Promise<Response>(resolve => { finish = resolve; })} />);
+ fireEvent.error(screen.getByRole('img'));
+ view.unmount();
+ await act(async () => finish(new Response('image', { headers: { 'content-type': 'image/jpeg' } })));
+ expect(createObjectURL).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/dashboard/VideoDownloadThumbnail.tsx b/apps/web/src/features/dashboard/VideoDownloadThumbnail.tsx
new file mode 100644
index 00000000..836fbe26
--- /dev/null
+++ b/apps/web/src/features/dashboard/VideoDownloadThumbnail.tsx
@@ -0,0 +1,51 @@
+import { FileVideo, LoaderCircle } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+
+export default function VideoDownloadThumbnail(props: {
+ src: string;
+ alt: string;
+ load?(): Promise<Response>;
+}) {
+ const [preview, setPreview] = useState<{ source: string; url?: string; loading?: boolean; failed?: boolean }>();
+ const attempted = useRef(false);
+ const generation = useRef(0);
+ const objectUrl = useRef<string>();
+
+ useEffect(() => {
+ attempted.current = false;
+ return () => {
+ ++generation.current;
+ if (objectUrl.current) URL.revokeObjectURL(objectUrl.current);
+ objectUrl.current = undefined;
+ };
+ }, [props.src]);
+
+ async function recover() {
+ if (attempted.current || !props.load) {
+ setPreview({ source: props.src, failed: true });
+ return;
+ }
+ attempted.current = true;
+ const request = generation.current;
+ setPreview({ source: props.src, loading: true });
+ try {
+ const response = await props.load();
+ if (!response.ok) throw new Error('Thumbnail unavailable');
+ const blob = await response.blob();
+ if (!blob.size || !['image/jpeg', 'image/png', 'image/webp'].includes(blob.type)) throw new Error('Invalid thumbnail');
+ if (request !== generation.current) return;
+ const url = URL.createObjectURL(blob);
+ objectUrl.current = url;
+ setPreview({ source: props.src, url });
+ } catch {
+ if (request === generation.current) setPreview({ source: props.src, failed: true });
+ }
+ }
+
+ const current = preview?.source === props.src ? preview : undefined;
+ return current?.loading || current?.failed
+ ? <span className="video-download-image-placeholder" role="img" aria-label={props.alt} aria-busy={current.loading || undefined}>
+ {current.loading ? <LoaderCircle size={24} className="smart-dubbing-spinner" aria-hidden="true" /> : <FileVideo size={24} aria-hidden="true" />}
+ </span>
+ : <img src={current?.url ?? props.src} alt={props.alt} onError={() => void recover()} />;
+}
diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
index 0ca6b428..68f9454d 100644
--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.test.tsx
@@ -46,14 +46,54 @@ afterEach(() => {
});
describe('VideoDownloadWorkspace', () => {
+ it('downloads the current thumbnail as an image and disables repeated clicks until it is ready', async () => {
+ const current = job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probeArtifact()] });
+ let finish!: (response: Response) => void;
+ const openDownloadThumbnail = vi.fn(() => new Promise<Response>(resolve => { finish = resolve; }));
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function(this: HTMLAnchorElement) {
+ expect(this.download).toBe('Creator Download-thumbnail.webp');
+ });
+ createObjectURL.mockReturnValue('blob:thumbnail');
+ renderWorkspace(current, { applyAction: vi.fn(), openDownloadThumbnail });
+ const button = await screen.findByRole('button', { name: '下载封面' });
+ fireEvent.click(button);
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+ expect(openDownloadThumbnail).toHaveBeenCalledTimes(1);
+ expect(openDownloadThumbnail).toHaveBeenCalledWith(current.id, 'probe_artifact');
+ expect(screen.queryByText('封面下载已开始')).not.toBeInTheDocument();
+ await act(async () => finish(new Response('image', { headers: { 'content-type': 'image/webp' } })));
+ await waitFor(() => expect(click).toHaveBeenCalledTimes(1));
+ expect(screen.getByText('封面下载已开始')).toBeInTheDocument();
+ expect(button).toBeEnabled();
+ click.mockRestore();
+ });
+
+ it('reports thumbnail download failures without announcing a saved file', async () => {
+ const current = job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probeArtifact()] });
+ renderWorkspace(current, { applyAction: vi.fn(), openDownloadThumbnail: vi.fn(async () => new Response('unavailable', { status: 502 })) });
+ fireEvent.click(await screen.findByRole('button', { name: '下载封面' }));
+ await waitFor(() => expect(screen.getAllByText('封面下载失败,请稍后重试').length).toBeGreaterThan(0));
+ expect(createObjectURL).not.toHaveBeenCalled();
+ expect(screen.queryByText('封面下载已开始')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: '下载封面' })).toBeEnabled();
+ });
+
+ it('does not offer thumbnail download when the video has no thumbnail', async () => {
+ const probe = probeArtifact(); probe.metadata.thumbnailUrl = null;
+ renderWorkspace(job({ state: { sourceUrl: 'https://www.youtube.com/watch?v=demo' }, artifacts: [probe] }), { applyAction: vi.fn() });
+ await screen.findByRole('heading', { name: 'Creator Download' });
+ expect(screen.queryByRole('button', { name: '下载封面' })).not.toBeInTheDocument();
+ });
+
it('shows labeled icons for every supported platform', () => {
renderWorkspace(job(), { applyAction: vi.fn() });
expect(screen.getByText('支持的视频来源(支持单个公开视频链接)')).toBeInTheDocument();
expect(screen.getAllByText(/支持单个公开视频链接/)).toHaveLength(1);
const platforms = screen.getByRole('list', { name: '支持的平台' });
const items = within(platforms).getAllByRole('listitem');
- expect(items).toHaveLength(9);
- for (const [index, name] of ['YouTube', 'Bilibili', 'X', 'TikTok', 'Instagram', '抖音', 'Facebook', '小红书', 'Pinterest'].entries()) {
+ expect(items).toHaveLength(10);
+ for (const [index, name] of ['YouTube', 'Bilibili', 'X', 'TikTok', 'Instagram', '抖音', 'Facebook', '小红书', 'Pinterest', 'Reddit'].entries()) {
const item = items[index]!;
expect(item).toHaveTextContent(name);
expect(item.querySelector('img')).toHaveAttribute('src', expect.stringMatching(/^\/platforms\//));
@@ -170,10 +210,18 @@ describe('VideoDownloadWorkspace', () => {
applyAction: vi.fn()
});
- expect(await screen.findByRole('tab', { name: '视频信息' })).toBeInTheDocument();
- fireEvent.click(screen.getByRole('tab', { name: '视频信息' }));
+ expect(await screen.findByRole('tab', { name: '下载规格' })).toHaveAttribute('aria-selected', 'true');
+ expect(screen.queryByRole('tab', { name: '视频信息' })).not.toBeInTheDocument();
expect(screen.getByText('Creator Download')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('tab', { name: '下载规格' }));
+ expect(screen.getByRole('button', { name: '更换链接' })).toBeInTheDocument();
+ const panel = screen.getByRole('complementary', { name: 'OpenCreator' });
+ const summary = within(panel).getByRole('complementary', { name: '任务摘要' });
+ expect(screen.getAllByRole('complementary', { name: '任务摘要' })).toHaveLength(1);
+ expect(summary.querySelector('details')).not.toHaveAttribute('open');
+ fireEvent.click(within(summary).getByText('任务摘要'));
+ expect(summary.querySelector('details')).toHaveAttribute('open');
+ expect(summary).toHaveTextContent('https://www.youtube.com/watch?v=demo');
+ expect(summary).toHaveTextContent('当前选择1080p');
expect(screen.getAllByText('1080p')).toHaveLength(2);
expect(screen.getByText('MP4 · 1920 x 1080 · 30 FPS · 84 MB')).toBeInTheDocument();
expect(screen.getByLabelText('已完成 1080p')).toBeInTheDocument();
@@ -528,7 +576,7 @@ describe('VideoDownloadWorkspace', () => {
.not.toHaveAttribute('aria-valuenow');
});
- it('accepts X, Twitter, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, and Pinterest video URLs for analysis', async () => {
+ it('accepts supported platform video URLs and Reddit share links for analysis', async () => {
for (const url of [
'https://x.com/creator/status/123',
'https://twitter.com/creator/status/123',
@@ -543,7 +591,9 @@ describe('VideoDownloadWorkspace', () => {
'https://www.facebook.com/reel/123',
'https://fb.watch/abc123/',
'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D&xsec_source=pc_feed',
- 'https://www.pinterest.com/pin/6544361954284154/'
+ 'https://www.pinterest.com/pin/6544361954284154/',
+ 'https://www.reddit.com/r/claude/s/R5I7tDfJ0h',
+ 'https://www.reddit.com/r/claude/comments/1x1qhlj/i_made_with_opus_55/'
]) {
let current = job();
const applyAction = vi.fn(async (
@@ -588,7 +638,7 @@ describe('VideoDownloadWorkspace', () => {
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -601,7 +651,7 @@ describe('VideoDownloadWorkspace', () => {
});
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -614,7 +664,7 @@ describe('VideoDownloadWorkspace', () => {
});
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -627,7 +677,7 @@ describe('VideoDownloadWorkspace', () => {
});
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -640,7 +690,7 @@ describe('VideoDownloadWorkspace', () => {
});
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -653,7 +703,7 @@ describe('VideoDownloadWorkspace', () => {
});
fireEvent.click(screen.getByRole('button', { name: '解析链接' }));
expect(screen.getByRole('alert')).toHaveTextContent(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接'
);
expect(applyAction).not.toHaveBeenCalled();
});
@@ -816,6 +866,7 @@ function renderWorkspace(
input: {
applyAction: ReturnType<typeof vi.fn>;
openArtifact?: ReturnType<typeof vi.fn>;
+ openDownloadThumbnail?: ReturnType<typeof vi.fn>;
runtimeDependencies?: Partial<RuntimeDependenciesController>;
onOpenRuntimeComponents?: () => void;
onSnapshot?: (callback: (next: CreatorJob) => void) => void;
@@ -836,6 +887,7 @@ function renderWorkspace(
service={{
applyAction: input.applyAction,
openArtifact: input.openArtifact,
+ openDownloadThumbnail: input.openDownloadThumbnail,
runAgentTurn: vi.fn()
} as never}
>
diff --git a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
index 1e25d772..c270e9ae 100644
--- a/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
+++ b/apps/web/src/features/dashboard/VideoDownloadWorkspace.tsx
@@ -25,21 +25,25 @@ import {
Video,
XCircle
} from 'lucide-react';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
import NativeSelect from '../../components/forms/NativeSelect.js';
import CreatorTaskSummary from './CreatorTaskSummary.js';
import CreatorToolShell from './CreatorToolShell.js';
import SupportedVideoSources from './SupportedVideoSources.js';
+import VideoDownloadThumbnail from './VideoDownloadThumbnail.js';
import {
createCreatorArtifactObjectUrl,
useOptionalCreatorSession
} from './creator-session-store.js';
import type { RuntimeDependenciesController } from '../../app/use-runtime-dependencies.js';
+import type { VideoDownloadBatchView } from './VideoDownloadBatchWorkspace.js';
type DownloadStep = 0 | 1;
-type DownloadResultTab = 'info' | 'formats' | 'outputs';
+type DownloadResultTab = 'formats' | 'outputs';
type DownloadHistoryItem = {
+ ownerJobId?: string;
+ sourceTitle?: string;
option?: DownloadOption;
stage?: CreatorStageRun;
artifact?: CreatorArtifact;
@@ -55,6 +59,7 @@ export default function VideoDownloadWorkspace(props: {
promptHint?: string;
runtimeDependencies?: RuntimeDependenciesController;
onOpenRuntimeComponents?(): void;
+ batch?: VideoDownloadBatchView;
}) {
const l = useLocalizedCopy();
const session = useOptionalCreatorSession();
@@ -69,6 +74,8 @@ export default function VideoDownloadWorkspace(props: {
const [resultTab, setResultTab] = useState<DownloadResultTab>('formats');
const [notice, setNotice] = useState('');
const [error, setError] = useState('');
+ const [thumbnailDownloading, setThumbnailDownloading] = useState(false);
+ const thumbnailDownloadPendingRef = useRef(false);
const [submittingOptionIds, setSubmittingOptionIds] = useState<ReadonlySet<string>>(
() => new Set()
);
@@ -88,10 +95,10 @@ export default function VideoDownloadWorkspace(props: {
[session?.job.artifacts, url]
);
const probe = useMemo(
- () => probeArtifact === undefined
+ () => probeArtifact === undefined || props.batch?.hasSelectedSource === false
? undefined
: readDownloadProbe(probeArtifact.metadata),
- [probeArtifact]
+ [probeArtifact, props.batch?.hasSelectedSource]
);
const legacy = (session?.job.templateVersion ?? 2) < 2;
const options = useMemo(() => (
@@ -152,14 +159,23 @@ export default function VideoDownloadWorkspace(props: {
const hasActiveDownloads = activeDownloadStages.length > 0
|| submittingOptionIds.size > 0;
const historyItems = useMemo(
- () => downloadHistoryItems(
+ () => props.batch === undefined ? downloadHistoryItems(
options,
downloadStages,
downloadArtifacts,
probeArtifact,
probe
- ),
- [downloadArtifacts, downloadStages, options, probe, probeArtifact]
+ ) : props.batch.jobs.flatMap(job => {
+ const sourceUrl = readString(job.state.sourceUrl) ?? '';
+ const sourceProbeArtifact = latestMatchingProbe(job.artifacts, sourceUrl);
+ const sourceProbe = sourceProbeArtifact === undefined ? undefined : readDownloadProbe(sourceProbeArtifact.metadata);
+ const artifacts = job.artifacts.filter(artifact => artifact.status === 'completed'
+ && (artifact.kind === 'source_video' || artifact.kind === 'source_audio')).sort(compareArtifactFreshness);
+ return downloadHistoryItems(sourceProbe?.options ?? [],
+ job.stages.filter(stage => stage.stageId === 'download'), artifacts, sourceProbeArtifact, sourceProbe)
+ .map(item => ({ ...item, ownerJobId: job.id, sourceTitle: sourceProbe?.title ?? sourceUrl }));
+ }),
+ [downloadArtifacts, downloadStages, options, probe, probeArtifact, props.batch?.jobs]
);
const latestTaskStage = session?.job.stages.at(-1);
const resumableStage = latestTaskStage?.status === 'canceled'
@@ -182,7 +198,8 @@ export default function VideoDownloadWorkspace(props: {
: probe.platform === 'douyin' ? l('抖音', 'Douyin')
: probe.platform === 'facebook' ? 'Facebook'
: probe.platform === 'xiaohongshu' ? l('小红书', 'Xiaohongshu')
- : probe.platform === 'pinterest' ? 'Pinterest' : 'YouTube';
+ : probe.platform === 'pinterest' ? 'Pinterest'
+ : probe.platform === 'reddit' ? 'Reddit' : 'YouTube';
const context = probe === undefined
? validUrl
? `${platform} · ${probing ? l('正在解析', 'Analyzing') : l('待解析', 'Waiting to analyze')}`
@@ -290,8 +307,8 @@ export default function VideoDownloadWorkspace(props: {
if (probing || hasActiveDownloads) return;
if (!validUrl) {
setError(l(
- '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接',
- 'Enter a valid public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, or Pinterest video URL'
+ '请输入有效的 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接',
+ 'Enter a valid public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, or Reddit video URL'
));
return;
}
@@ -405,11 +422,40 @@ export default function VideoDownloadWorkspace(props: {
downloadSubmissionTailRef.current = work;
}
+ async function downloadThumbnail() {
+ if (session === null || probeArtifact === undefined || probe?.thumbnailUrl == null || thumbnailDownloadPendingRef.current) return;
+ thumbnailDownloadPendingRef.current = true;
+ setThumbnailDownloading(true);
+ setError('');
+ try {
+ const response = await session.openDownloadThumbnail(probeArtifact.id);
+ if (!response.ok) throw new Error('thumbnail_download_failed');
+ const blob = await response.blob();
+ if (!blob.size || !['image/jpeg', 'image/png', 'image/webp'].includes(blob.type)) throw new Error('thumbnail_download_failed');
+ const extension = blob.type === 'image/jpeg' ? 'jpg' : blob.type === 'image/webp' ? 'webp' : 'png';
+ const title = probe.title.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim().slice(0, 120) || 'thumbnail';
+ const objectUrl = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = objectUrl;
+ link.download = `${title}-thumbnail.${extension}`;
+ link.click();
+ window.setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
+ setNotice(l('封面下载已开始', 'Thumbnail download started'));
+ } catch (cause) {
+ const message = l('封面下载失败,请稍后重试', 'Could not download the thumbnail. Try again.');
+ session.captureCreatorFailure('video-download.download-thumbnail', cause, message);
+ setError(message);
+ } finally {
+ thumbnailDownloadPendingRef.current = false;
+ setThumbnailDownloading(false);
+ }
+ }
+
async function downloadArtifact(artifact: CreatorArtifact) {
- if (session === null) return;
try {
+ const owner = artifactSession(artifact);
const objectUrl = await createCreatorArtifactObjectUrl(
- session,
+ owner,
artifact.id,
'video-download.download-artifact',
l('文件下载失败,请稍后重试。', 'The file download failed. Try again later.')
@@ -425,6 +471,12 @@ export default function VideoDownloadWorkspace(props: {
}
}
+ function artifactSession(artifact: CreatorArtifact) {
+ const owner = props.batch === undefined ? session : props.batch.resolveSession(artifact.jobId);
+ if (owner === null || owner === undefined) throw new Error(l('文件所属任务尚未加载,请稍后重试', 'The file task is still loading. Try again shortly.'));
+ return owner;
+ }
+
function releaseArtifactPreviewUrl() {
if (artifactPreviewUrlRef.current === undefined) return;
URL.revokeObjectURL(artifactPreviewUrlRef.current);
@@ -445,16 +497,9 @@ export default function VideoDownloadWorkspace(props: {
artifactId: artifact.id,
status: 'loading'
});
- if (session === null) {
- setArtifactPreview({
- artifactId: artifact.id,
- status: 'failed'
- });
- return;
- }
try {
const objectUrl = await createCreatorArtifactObjectUrl(
- session,
+ artifactSession(artifact),
artifact.id,
'video-download.load-artifact-preview',
l('文件预览加载失败,请稍后重试。', 'The file preview failed to load. Try again later.')
@@ -469,8 +514,9 @@ export default function VideoDownloadWorkspace(props: {
status: 'ready',
objectUrl
});
- } catch {
+ } catch (caught) {
if (artifactPreviewRequestRef.current !== requestId) return;
+ setError(formatDownloadError(caught, l));
setArtifactPreview({
artifactId: artifact.id,
status: 'failed'
@@ -486,9 +532,10 @@ export default function VideoDownloadWorkspace(props: {
void openArtifactPreview(artifact);
}
- function handleArtifactPreviewError(artifactId: string) {
+ function handleArtifactPreviewError(artifact: CreatorArtifact) {
+ const artifactId = artifact.id;
if (artifactPreview?.artifactId !== artifactId) return;
- session?.captureCreatorFailure(
+ artifactSession(artifact).captureCreatorFailure(
'video-download.play-artifact-preview',
new Error('artifact_preview_playback_failed'),
l('文件预览播放失败,可重新加载或保存到本机。', 'The preview could not play. Reload it or save the file locally.')
@@ -597,6 +644,22 @@ export default function VideoDownloadWorkspace(props: {
setResultTab('outputs');
}
+ const resultToolbar = (
+ <div className="video-result-toolbar video-download-result-toolbar">
+ <div className="video-result-tabs" role="tablist" aria-label={l('下载结果类型', 'Download result types')}>
+ <button type="button" role="tab" aria-selected={resultTab === 'formats'} onClick={() => setResultTab('formats')}>
+ <Download size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('下载规格', 'Formats')}
+ </button>
+ <button type="button" role="tab" aria-selected={resultTab === 'outputs'} onClick={() => setResultTab('outputs')}>
+ <PackageOpen size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('作品', 'Works')}
+ </button>
+ </div>
+ {props.batch?.toolbarActions}
+ </div>
+ );
+
return (
<CreatorToolShell
title={l('视频下载', 'Video Downloader')}
@@ -606,12 +669,29 @@ export default function VideoDownloadWorkspace(props: {
'Analyze a public link and save video or audio to the project'
)}
context={context}
+ taskSummary={probe === undefined ? undefined : <CreatorTaskSummary
+ sourceIcon={Link2}
+ sourceLabel={l('视频链接', 'Video link')}
+ sourceValue={url}
+ items={[
+ { label: l('来源平台', 'Platform'), value: platform },
+ { label: l('可用规格', 'Formats'), value: String(options.length) },
+ {
+ label: l('当前选择', 'Selected'),
+ value: selectedOption === undefined
+ ? l('未选择', 'Not selected')
+ : optionLabel(selectedOption, l)
+ },
+ { label: l('作品', 'Works'), value: String(downloadArtifacts.length) }
+ ]}
+ compactSummary={`${platform} · ${selectedOption === undefined ? l('未选择', 'Not selected') : optionLabel(selectedOption, l)}`}
+ />}
suggestions={probe === undefined
? [l('这个链接支持哪些规格', 'Which formats are available?')]
: [l('下载最高画质视频', 'Download the highest-quality video'), l('提取 MP3 音频', 'Extract MP3 audio')]}
placeholder={props.promptHint ?? l(
- '粘贴 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书或 Pinterest 公开视频链接',
- 'Paste a public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, or Pinterest video URL'
+ '粘贴 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 或 Reddit 公开视频链接',
+ 'Paste a public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, or Reddit video URL'
)}
stepLabel={activeStage?.stageId === 'probe'
? l('解析视频信息', 'Analyze video information')
@@ -638,7 +718,10 @@ export default function VideoDownloadWorkspace(props: {
onBack={props.onBack}
>
<div className="creator-tool-stack">
- <nav
+ {props.batch === undefined ? null : resultToolbar}
+ {props.batch?.editor}
+ {props.batch !== undefined && resultTab === 'formats' && probe === undefined ? props.batch.sourceList : null}
+ {props.batch === undefined ? <nav
className="video-translation-steps creator-tool-steps creator-tool-steps-two"
aria-label={l('视频下载流程', 'Video download steps')}
>
@@ -666,10 +749,10 @@ export default function VideoDownloadWorkspace(props: {
);
})}
</ol>
- </nav>
+ </nav> : null}
- {currentStep === 0 ? (
+ {currentStep === 0 && props.batch === undefined ? (
<section
className="creator-tool-panel"
aria-labelledby="video-download-source-title"
@@ -705,222 +788,194 @@ export default function VideoDownloadWorkspace(props: {
</section>
) : null}
- {currentStep === 1 && probe !== undefined ? (
+ {(props.batch === undefined ? currentStep === 1 && probe !== undefined
+ : props.batch.hasSelectedSource || historyItems.length > 0 || resultTab === 'outputs') ? (
<section
className="video-result-workspace download-result-workspace"
aria-label={l('视频下载结果', 'Video download results')}
>
- <div className="video-result-toolbar">
- <div
- className="video-result-tabs"
- role="tablist"
- aria-label={l('下载结果类型', 'Download result types')}
- >
- <button
- type="button"
- role="tab"
- aria-selected={resultTab === 'info'}
- onClick={() => setResultTab('info')}
- >
- <Video size={15} strokeWidth={1.8} aria-hidden="true" />
- {l('视频信息', 'Video info')}
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={resultTab === 'formats'}
- onClick={() => setResultTab('formats')}
- >
- <Download size={15} strokeWidth={1.8} aria-hidden="true" />
- {l('下载规格', 'Formats')}
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={resultTab === 'outputs'}
- onClick={() => setResultTab('outputs')}
- >
- <PackageOpen size={15} strokeWidth={1.8} aria-hidden="true" />
- {l('作品', 'Works')}
- </button>
- </div>
- </div>
+ {props.batch === undefined ? resultToolbar : null}
<div className="creator-result-layout">
- {resultTab === 'info' ? (
- <div className="video-result-pane">
- <header className="video-result-pane-heading">
- <div>
- <h2>{l('视频信息', 'Video information')}</h2>
- <p>{l('来自真实链接解析结果', 'From the live URL analysis')}</p>
+ {resultTab === 'formats' && probe !== undefined ? (
+ <div className="video-result-pane video-download-formats-pane">
+ <div className="video-download-formats-layout">
+ <div className="video-download-source-column">
+ {props.batch?.sourceList}
+ <div className="video-download-preview">
+ {probe.thumbnailUrl
+ ? <div className="video-download-thumbnail">
+ <VideoDownloadThumbnail key={probeArtifact?.id} src={probe.thumbnailUrl} alt={probe.title}
+ load={session && probeArtifact ? () => session.openDownloadThumbnail(probeArtifact.id) : undefined} />
+ <button type="button" className="video-download-thumbnail-button"
+ disabled={thumbnailDownloading || session === null}
+ aria-busy={thumbnailDownloading}
+ aria-label={l('下载封面', 'Download thumbnail')}
+ title={l('下载封面', 'Download thumbnail')}
+ onClick={() => void downloadThumbnail()}>
+ {thumbnailDownloading ? <LoaderCircle size={16} className="smart-dubbing-spinner" aria-hidden="true" />
+ : <Download size={16} aria-hidden="true" />}
+ <span>{l('下载封面', 'Thumbnail')}</span>
+ </button>
+ </div>
+ : (
+ <span className="video-download-preview-placeholder">
+ <FileVideo size={30} strokeWidth={1.5} />
+ </span>
+ )}
+ <div>
+ <span>{platform}</span>
+ <h2>{probe.title}</h2>
+ <p>
+ {[
+ probe.uploader,
+ formatDuration(probe.duration),
+ formatDimensions(probe.width, probe.height)
+ ].filter(Boolean).join(' · ')}
+ </p>
+ </div>
</div>
- <button type="button" onClick={() => setCurrentStep(0)}>
- <Link2 size={15} strokeWidth={1.8} aria-hidden="true" />
- {l('更换链接', 'Change link')}
- </button>
- </header>
- <div className="video-download-preview">
- {probe.thumbnailUrl
- ? <img src={probe.thumbnailUrl} alt={probe.title} />
- : (
- <span className="video-download-preview-placeholder">
- <FileVideo size={30} strokeWidth={1.5} />
- </span>
- )}
- <div>
- <span>{platform}</span>
- <h2>{probe.title}</h2>
- <p>
- {[
- probe.uploader,
- formatDuration(probe.duration),
- formatDimensions(probe.width, probe.height)
- ].filter(Boolean).join(' · ')}
- </p>
</div>
- </div>
- </div>
- ) : null}
-
- {resultTab === 'formats' ? (
- <div className="video-result-pane">
- <header className="video-result-pane-heading">
- <div>
- <h2>{l('下载规格', 'Download formats')}</h2>
- <p>
- {legacy
- ? l('旧版任务仅支持视频下载', 'Legacy jobs support video downloads only')
- : l('选择视频清晰度或提取 MP3 音频', 'Choose video quality or extract MP3 audio')}
- </p>
- </div>
- </header>
- <div
- className="creator-tool-segmented"
- role="tablist"
- aria-label={l('下载格式', 'Download format')}
- >
- <button
- type="button"
- role="tab"
- aria-selected={mediaType === 'video'}
- disabled={!options.some(option => option.mediaType === 'video')}
- onClick={() => selectMediaType('video')}
- >
- <Video size={15} strokeWidth={1.8} aria-hidden="true" />
- MP4 {l('视频', 'video')}
- </button>
- {!legacy ? (
- <button
- type="button"
- role="tab"
- aria-selected={mediaType === 'audio'}
- disabled={!options.some(option => option.mediaType === 'audio')}
- onClick={() => selectMediaType('audio')}
+ <div className="video-download-format-list">
+ <header className="video-result-pane-heading">
+ <h2>{l('下载规格', 'Download formats')}</h2>
+ {props.batch === undefined ? <button type="button" onClick={() => setCurrentStep(0)}>
+ <Link2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('更换链接', 'Change link')}
+ </button> : null}
+ </header>
+ <div
+ className="creator-tool-segmented"
+ role="tablist"
+ aria-label={l('下载格式', 'Download format')}
>
- <Music2 size={15} strokeWidth={1.8} aria-hidden="true" />
- MP3 {l('音频', 'audio')}
- </button>
- ) : null}
- </div>
- {audioLanguages.length > 1 && selectedAudioLanguage !== undefined ? (
- <label className="creator-tool-field video-download-language-field">
- <span>{l('音频语言', 'Audio language')}</span>
- <NativeSelect
- aria-label={l('音频语言', 'Audio language')}
- value={selectedAudioLanguage}
- onChange={event => selectAudioLanguage(event.target.value)}
- >
- {audioLanguages.map(language => (
- <option key={language} value={language}>
- {audioLanguageLabel(language, l)}
- </option>
- ))}
- </NativeSelect>
- </label>
- ) : null}
- {visibleOptions.length > 0 ? (
- <div className="video-download-options">
- {visibleOptions.map((option, index) => {
- const downloaded = downloadedOptionIds.has(option.id);
- const stage = latestDownloadStageByOption.get(option.id);
- const submitting = submittingOptionIds.has(option.id);
- const queued = submitting || stage?.status === 'queued';
- const running = stage?.status === 'running';
- const normalizing = running
- && stage.progress.phase === 'normalizing_media';
- const inProgress = queued || running;
- return (
- <label
- key={option.id}
- data-downloaded={downloaded}
- data-status={downloaded
- ? 'completed'
- : inProgress
- ? 'active'
- : stage?.status}
+ <button
+ type="button"
+ role="tab"
+ aria-selected={mediaType === 'video'}
+ disabled={!options.some(option => option.mediaType === 'video')}
+ onClick={() => selectMediaType('video')}
+ >
+ <Video size={15} strokeWidth={1.8} aria-hidden="true" />
+ MP4 {l('视频', 'video')}
+ </button>
+ {!legacy ? (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={mediaType === 'audio'}
+ disabled={!options.some(option => option.mediaType === 'audio')}
+ onClick={() => selectMediaType('audio')}
>
- <input
- type="radio"
- name="download-option"
- checked={selectedOptionId === option.id}
- onChange={() => selectOption(option)}
- />
- <span>
- <strong>{optionLabel(option, l)}</strong>
- <small>{optionDetail(option, l)}</small>
- </span>
- {index === 0
- ? <small>{l('推荐', 'Recommended')}</small>
- : null}
- {downloaded ? (
- <span
- className="video-download-option-complete"
- aria-label={`${l('已完成', 'Completed')} ${optionLabel(option, l)}`}
- >
- <CheckCircle2 size={16} strokeWidth={1.9} aria-hidden="true" />
- {l('已完成', 'Completed')}
- </span>
- ) : (
- <button
- type="button"
- disabled={probing || inProgress}
- onClick={() => startDownload(option)}
- aria-label={`${l('下载', 'Download')} ${optionLabel(option, l)}`}
+ <Music2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ MP3 {l('音频', 'audio')}
+ </button>
+ ) : null}
+ </div>
+ {audioLanguages.length > 1 && selectedAudioLanguage !== undefined ? (
+ <label className="creator-tool-field video-download-language-field">
+ <span>{l('音频语言', 'Audio language')}</span>
+ <NativeSelect
+ aria-label={l('音频语言', 'Audio language')}
+ value={selectedAudioLanguage}
+ onChange={event => selectAudioLanguage(event.target.value)}
+ >
+ {audioLanguages.map(language => (
+ <option key={language} value={language}>
+ {audioLanguageLabel(language, l)}
+ </option>
+ ))}
+ </NativeSelect>
+ </label>
+ ) : null}
+ {visibleOptions.length > 0 ? (
+ <div className="video-download-options">
+ {visibleOptions.map(option => {
+ const downloaded = downloadedOptionIds.has(option.id);
+ const stage = latestDownloadStageByOption.get(option.id);
+ const submitting = submittingOptionIds.has(option.id);
+ const queued = submitting || stage?.status === 'queued';
+ const running = stage?.status === 'running';
+ const normalizing = running
+ && stage.progress.phase === 'normalizing_media';
+ const inProgress = queued || running;
+ return (
+ <label
+ key={option.id}
+ data-downloaded={downloaded}
+ data-status={downloaded
+ ? 'completed'
+ : inProgress
+ ? 'active'
+ : stage?.status}
>
- {inProgress
- ? <LoaderCircle className="smart-dubbing-spinner" size={16} />
- : <Download size={16} strokeWidth={1.8} aria-hidden="true" />}
- {normalizing
- ? l('转换中', 'Converting')
- : running
- ? l('下载中', 'Downloading')
- : queued
- ? l('排队中', 'Queued')
- : l('下载', 'Download')}
- </button>
- )}
- </label>
- );
- })}
- </div>
- ) : (
- <div className="video-result-empty">
- <AlertCircle size={26} strokeWidth={1.5} aria-hidden="true" />
- <strong>{l('当前没有可用规格', 'No formats are available')}</strong>
- <button type="button" onClick={() => setCurrentStep(0)}>
- {l('重新解析', 'Analyze again')}
- </button>
+ <input
+ type="radio"
+ name="download-option"
+ checked={selectedOptionId === option.id}
+ onChange={() => selectOption(option)}
+ />
+ <span>
+ <strong>{optionLabel(option, l)}</strong>
+ <small>{optionDetail(option, l)}</small>
+ </span>
+ {downloaded ? (
+ <span
+ className="video-download-option-complete"
+ aria-label={`${l('已完成', 'Completed')} ${optionLabel(option, l)}`}
+ >
+ <CheckCircle2 size={16} strokeWidth={1.9} aria-hidden="true" />
+ {l('已完成', 'Completed')}
+ </span>
+ ) : (
+ <button
+ type="button"
+ disabled={probing || inProgress}
+ onClick={() => startDownload(option)}
+ aria-label={`${l('下载', 'Download')} ${optionLabel(option, l)}`}
+ >
+ {inProgress
+ ? <LoaderCircle className="smart-dubbing-spinner" size={16} />
+ : <Download size={16} strokeWidth={1.8} aria-hidden="true" />}
+ {normalizing
+ ? l('转换中', 'Converting')
+ : running
+ ? l('下载中', 'Downloading')
+ : queued
+ ? l('排队中', 'Queued')
+ : l('下载', 'Download')}
+ </button>
+ )}
+ </label>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="video-result-empty">
+ <AlertCircle size={26} strokeWidth={1.5} aria-hidden="true" />
+ <strong>{l('当前没有可用规格', 'No formats are available')}</strong>
+ <button type="button" disabled={probing || hasActiveDownloads} onClick={() => props.batch === undefined ? setCurrentStep(0) : void analyze()}>
+ {l('重新解析', 'Analyze again')}
+ </button>
+ </div>
+ )}
</div>
- )}
+ </div>
</div>
) : null}
+ {resultTab === 'formats' && probe === undefined && props.batch !== undefined ? <div className="video-result-empty" role="status">
+ {probing ? <LoaderCircle size={26} className="smart-dubbing-spinner" /> : <FileVideo size={26} />}
+ <strong>{probing ? l('正在解析视频', 'Analyzing video') : props.batch.hasSelectedSource
+ ? l('尚无可用规格', 'No formats available yet') : l('添加视频链接', 'Add a video link')}</strong>
+ </div> : null}
+
{resultTab === 'outputs' ? (
<div className="video-result-pane">
<header className="video-result-pane-heading">
<div>
<h2>{l('作品', 'Works')}</h2>
<p>
- {hasActiveDownloads
+ {props.batch !== undefined ? l('所有链接的下载结果', 'Downloads from all links') : hasActiveDownloads
? l('各规格会按队列依次下载,并在这里显示进度', 'Formats download in order and show progress here')
: l('当前任务保存的真实下载产物', 'Downloaded artifacts saved by this job')}
</p>
@@ -942,6 +997,9 @@ export default function VideoDownloadWorkspace(props: {
? undefined
: artifactFileName(artifact);
return (
+ <Fragment key={`${item.ownerJobId ?? ''}:${artifact?.id ?? stage?.id ?? `${option?.id ?? 'download'}-${index}`}`}>
+ {item.ownerJobId !== undefined && historyItems[index - 1]?.ownerJobId !== item.ownerJobId
+ ? <h3 className="video-download-work-source">{item.sourceTitle}</h3> : null}
<div
className="video-result-file-row video-download-progress-row"
data-status={status}
@@ -953,7 +1011,7 @@ export default function VideoDownloadWorkspace(props: {
<div>
<strong>
{artifact === undefined
- ? downloadPendingTitle(probe.title, option, l)
+ ? downloadPendingTitle(item.sourceTitle ?? probe?.title ?? url, option, l)
: artifactFileName(artifact)}
</strong>
<small>
@@ -1075,7 +1133,7 @@ export default function VideoDownloadWorkspace(props: {
preload="metadata"
src={artifactPreview.objectUrl}
aria-label={`${l('音频播放', 'Audio playback')} ${fileName}`}
- onError={() => handleArtifactPreviewError(artifact.id)}
+ onError={() => handleArtifactPreviewError(artifact)}
/>
) : (
<video
@@ -1087,12 +1145,13 @@ export default function VideoDownloadWorkspace(props: {
preload="metadata"
src={artifactPreview.objectUrl}
aria-label={`${l('视频预览', 'Video preview')} ${fileName}`}
- onError={() => handleArtifactPreviewError(artifact.id)}
+ onError={() => handleArtifactPreviewError(artifact)}
/>
)}
</div>
) : null}
</div>
+ </Fragment>
);
})}
</div>
@@ -1108,28 +1167,6 @@ export default function VideoDownloadWorkspace(props: {
</div>
) : null}
- <CreatorTaskSummary
- sourceIcon={Link2}
- sourceLabel={l('视频链接', 'Video link')}
- sourceValue={url}
- items={[
- { label: l('来源平台', 'Platform'), value: platform },
- {
- label: l('可用规格', 'Formats'),
- value: String(options.length)
- },
- {
- label: l('当前选择', 'Selected'),
- value: selectedOption === undefined
- ? l('未选择', 'Not selected')
- : optionLabel(selectedOption, l)
- },
- {
- label: l('作品', 'Works'),
- value: String(downloadArtifacts.length)
- }
- ]}
- />
</div>
</section>
) : null}
@@ -1169,7 +1206,7 @@ function readDownloadProbe(
|| typeof metadata.title !== 'string'
|| typeof metadata.requestedUrl !== 'string'
|| typeof metadata.url !== 'string'
- || (metadata.platform !== 'youtube' && metadata.platform !== 'bilibili' && metadata.platform !== 'x' && metadata.platform !== 'tiktok' && metadata.platform !== 'instagram' && metadata.platform !== 'douyin' && metadata.platform !== 'facebook' && metadata.platform !== 'xiaohongshu' && metadata.platform !== 'pinterest')
+ || (metadata.platform !== 'youtube' && metadata.platform !== 'bilibili' && metadata.platform !== 'x' && metadata.platform !== 'tiktok' && metadata.platform !== 'instagram' && metadata.platform !== 'douyin' && metadata.platform !== 'facebook' && metadata.platform !== 'xiaohongshu' && metadata.platform !== 'pinterest' && metadata.platform !== 'reddit')
|| !Array.isArray(metadata.formats)
|| !Array.isArray(metadata.options)
) {
@@ -1577,6 +1614,7 @@ function platformFor(
if (/^https:\/\/(?:www\.|m\.)?facebook\.com\//i.test(value) || /^https:\/\/fb\.watch\//i.test(value)) return 'Facebook';
if (/^https:\/\/(?:www\.)?xiaohongshu\.com\//i.test(value)) return l('小红书', 'Xiaohongshu');
if (/^https:\/\/(?:www\.)?pinterest\.com\//i.test(value)) return 'Pinterest';
+ if (supportedVideoSourcePlatform(value) === 'reddit') return 'Reddit';
return l('公开视频', 'Public video');
}
@@ -1595,8 +1633,8 @@ function formatDownloadError(
const message = caught instanceof Error ? caught.message : String(caught);
if (/unsupported_source/i.test(message)) {
return l(
- '当前仅支持 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书和 Pinterest 公开视频',
- 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, and Pinterest videos are supported'
+ '当前仅支持 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 和 Reddit 公开视频',
+ 'Only public YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, and Reddit videos are supported'
);
}
if (/download_probe_stale/i.test(message)) {
diff --git a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
index 2f6cba90..e56b6221 100644
--- a/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
+++ b/apps/web/src/features/dashboard/VideoTranslationWorkspace.tsx
@@ -3970,7 +3970,7 @@ function creatorErrorMessage(cause: unknown, l: LocalizeCopy): string {
return l('已开启配音,请先配置配音服务。', 'Dubbing is enabled. Configure a TTS service first.');
}
if (code === 'unsupported_source') {
- return l('请使用 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest 的单个公开视频链接或已上传的本地视频。', 'Use a single public video link from YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, or Pinterest, or an uploaded local video.');
+ return l('请使用 YouTube、Bilibili、X、TikTok、Instagram、抖音、Facebook、小红书、Pinterest、Reddit 的单个公开视频链接或已上传的本地视频。', 'Use a single public video link from YouTube, Bilibili, X, TikTok, Instagram, Douyin, Facebook, Xiaohongshu, Pinterest, or Reddit, or an uploaded local video.');
}
return l('启动翻译失败,请在 Agent 区域查看诊断后重试。', 'Failed to start translation. Review the diagnosis in the Agent panel and retry.');
}
diff --git a/apps/web/src/features/dashboard/creator-session-store.tsx b/apps/web/src/features/dashboard/creator-session-store.tsx
index cb854392..6df7e7d2 100644
--- a/apps/web/src/features/dashboard/creator-session-store.tsx
+++ b/apps/web/src/features/dashboard/creator-session-store.tsx
@@ -71,6 +71,7 @@ export type CreatorSessionContextValue = {
uploadArticleImage(file: File): Promise<CreatorArtifact>;
uploadSourceDocument(file: File): Promise<void>;
openArtifact(artifactId: string): Promise<Response>;
+ openDownloadThumbnail(probeArtifactId: string): Promise<Response>;
openArtifactJson<T = unknown>(artifactId: string): Promise<T>;
agentSession: CreatorAgentSession | null;
turns: CreatorAgentTurn[];
@@ -166,6 +167,7 @@ export function CreatorSessionProvider(props: {
| 'listIssues'
| 'reportClientIssue'
| 'openArtifact'
+ | 'openDownloadThumbnail'
| 'uploadReferenceImage'
| 'uploadArticleImage'
| 'uploadSourceVideo'
@@ -824,6 +826,11 @@ export function CreatorSessionProvider(props: {
}
}, [captureCreatorFailure, props.service]);
+ const openDownloadThumbnail = useCallback(async (probeArtifactId: string) => {
+ if (props.service.openDownloadThumbnail === undefined) throw new Error('Video thumbnail transport is unavailable');
+ return await props.service.openDownloadThumbnail(confirmedRef.current.id, probeArtifactId);
+ }, [props.service]);
+
const openArtifactJson = useCallback(<T,>(artifactId: string): Promise<T> => {
const cached = artifactJsonCacheRef.current.get(artifactId);
if (cached !== undefined) return cached as Promise<T>;
@@ -992,6 +999,7 @@ export function CreatorSessionProvider(props: {
uploadSourceVideo,
uploadArticleImage,
openArtifact,
+ openDownloadThumbnail,
openArtifactJson,
agentSession,
turns,
@@ -1002,7 +1010,7 @@ export function CreatorSessionProvider(props: {
steerAgentTurn,
interruptAgentTurn,
respondAgentApproval
- }), [connection, reconnect, agentBusy, agentSession, askPendingIssue, applyAction, applyRemoteSnapshot, approvals, cancelJob, captureCreatorFailure, clearError, confirmedJob, conflictedFields, draft, error, flush, focusIssue, focusedIssue, interruptAgentTurn, issues, items, openArtifact, openArtifactJson, preflight, repairIssue, respondAgentApproval, resumeJob, runAgentTurn, runPreflight, steerAgentTurn, turns, updateDraft, uploadArticleImage, uploadReferenceImage, uploadSourceDocument, uploadSourceVideo]);
+ }), [connection, reconnect, agentBusy, agentSession, askPendingIssue, applyAction, applyRemoteSnapshot, approvals, cancelJob, captureCreatorFailure, clearError, confirmedJob, conflictedFields, draft, error, flush, focusIssue, focusedIssue, interruptAgentTurn, issues, items, openArtifact, openDownloadThumbnail, openArtifactJson, preflight, repairIssue, respondAgentApproval, resumeJob, runAgentTurn, runPreflight, steerAgentTurn, turns, updateDraft, uploadArticleImage, uploadReferenceImage, uploadSourceDocument, uploadSourceVideo]);
return (
<CreatorSessionContext.Provider value={value}>
diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.css
index 28d29958..6275ace0 100644
--- a/apps/web/src/features/dashboard/dashboard.css
+++ b/apps/web/src/features/dashboard/dashboard.css
@@ -1827,6 +1827,19 @@
grid-template-columns: 34px 36px minmax(0, 1fr);
}
+.creator-workspace-header.has-actions {
+ grid-template-columns: 34px minmax(0, 1fr) auto;
+}
+
+.creator-workspace-header.has-title-icon.has-actions {
+ grid-template-columns: 34px 36px minmax(0, 1fr) auto;
+}
+
+.creator-workspace-header-actions {
+ display: flex;
+ align-items: center;
+}
+
.creator-workspace-title-icon {
width: 36px;
height: 36px;
@@ -1890,7 +1903,11 @@
}
.video-download-workspace-page .creator-tool-stack {
- width: min(960px, 100%);
+ width: 100%;
+}
+
+.video-download-workspace-page .creator-workspace-layout {
+ --creator-workspace-pane-width: calc(80% - 3.5px);
}
.auto-clip-tool-stack {
@@ -7493,23 +7510,287 @@
font-size: 13px;
}
-.video-download-preview {
+.video-download-formats-pane {
+ container: video-download-formats / inline-size;
+}
+
+.video-download-source-column {
+ min-width: 0;
display: grid;
- grid-template-columns: 180px minmax(0, 1fr);
+ gap: 18px;
+}
+
+.video-download-result-toolbar {
+ gap: 8px;
+}
+
+.video-download-result-toolbar .video-result-tabs > button {
+ padding-inline: 8px;
+}
+
+.video-download-result-toolbar .video-download-add-button {
+ flex: none;
+ min-height: 38px;
+ padding-inline: 8px;
+ font-size: 12px;
+ white-space: nowrap;
+}
+
+.video-download-add-button,
+.video-download-add-form button,
+.video-download-batch-error button {
+ display: inline-flex;
align-items: center;
- gap: 16px;
- margin-bottom: 16px;
+ justify-content: center;
+ gap: 6px;
+ min-height: 34px;
+ padding: 6px 10px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--surface);
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ cursor: pointer;
+}
+
+.video-download-add-button:hover,
+.video-download-add-form button:hover,
+.video-download-source-action:hover {
+ background: var(--surface-2);
+}
+
+.video-download-add-form {
+ display: grid;
+ gap: 8px;
+}
+
+.video-download-add-form label {
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.video-download-add-form input {
+ box-sizing: border-box;
+ width: 100%;
+ height: 44px;
+ padding: 10px 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--conversation-bg);
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ line-height: 1.6;
+}
+
+.video-download-add-form-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+}
+
+.video-download-add-form button[type='submit'] {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: var(--on-accent);
+}
+
+.video-download-add-form button:disabled,
+.video-download-source-action:disabled {
+ opacity: .5;
+ cursor: default;
+}
+
+.video-download-batch-error {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ color: var(--danger, #c93434);
+ font-size: 13px;
+ overflow-wrap: anywhere;
+}
+
+.video-download-source-list {
+ display: grid;
+ gap: 4px;
+ max-height: 260px;
+ overflow-y: auto;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.video-download-source-list li {
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ padding: 4px;
+ border: 1px solid transparent;
+ border-radius: 6px;
+}
+
+.video-download-source-list li[data-selected='true'] {
+ border-color: var(--border);
+ background: var(--surface-2);
+}
+
+.video-download-source-select {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ min-width: 0;
+ gap: 8px;
+ min-height: 44px;
+ padding: 2px;
+ border: 0;
+ background: transparent;
+ color: var(--text);
+ text-align: left;
+ cursor: pointer;
+}
+
+.video-download-source-select > img,
+.video-download-source-select > .video-download-image-placeholder,
+.video-download-source-select > svg {
+ flex: none;
+ width: 40px;
+ height: 30px;
+ object-fit: cover;
+ border-radius: 4px;
+ color: var(--muted);
+}
+
+.video-download-source-select > span {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.video-download-source-select strong {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.video-download-source-select small {
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.video-download-source-action {
+ display: grid;
+ place-items: center;
+ flex: none;
+ width: 30px;
+ height: 32px;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--muted);
+ cursor: pointer;
+}
+
+.video-download-work-source {
+ margin: 12px 0 4px;
+ font-size: 13px;
+ font-weight: 600;
+ overflow-wrap: anywhere;
+}
+
+@media (max-width: 540px) {
+ .video-download-workspace-page .creator-workspace-header {
+ padding-inline: 12px;
+ gap: 8px;
+ }
+
+ .video-download-workspace-page .creator-workspace-header p {
+ display: none;
+ }
+}
+
+.video-download-formats-layout {
+ display: grid;
+ grid-template-columns: minmax(180px, 30%) minmax(0, 1fr);
+ align-items: start;
+ gap: 24px;
+}
+
+.video-download-preview,
+.video-download-preview > div,
+.video-download-format-list {
+ min-width: 0;
}
.video-download-preview img {
- width: 180px;
+ width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
border-radius: 7px;
}
+.video-download-preview > .video-download-thumbnail {
+ position: relative;
+ margin-top: 0;
+}
+
+.video-download-thumbnail img {
+ display: block;
+}
+
+.video-download-image-placeholder {
+ display: grid;
+ place-items: center;
+ background: var(--surface);
+ color: var(--muted);
+}
+
+.video-download-thumbnail > .video-download-image-placeholder {
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ border-radius: 7px;
+}
+
+.video-download-thumbnail-button {
+ position: absolute;
+ right: 8px;
+ bottom: 8px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ min-height: 30px;
+ padding: 5px 10px;
+ border: 1px solid rgb(255 255 255 / 30%);
+ border-radius: 6px;
+ background: rgb(20 20 20 / 88%);
+ color: #fff;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.video-download-thumbnail-button:hover {
+ background: #141414;
+}
+
+.video-download-thumbnail-button:disabled {
+ opacity: .65;
+ cursor: default;
+}
+
+@container video-download-formats (max-width: 560px) {
+ .video-download-thumbnail-button { right: 4px; bottom: 4px; width: 28px; min-height: 28px; padding: 0; }
+ .video-download-thumbnail-button > span { display: none; }
+}
+
.video-download-preview-placeholder {
- width: 180px;
+ width: 100%;
aspect-ratio: 16 / 9;
display: grid;
place-items: center;
@@ -7519,7 +7800,7 @@
color: var(--muted);
}
-.video-download-preview span {
+.video-download-preview > div > span {
color: var(--accent);
font-size: 11px;
font-weight: 650;
@@ -7527,12 +7808,27 @@
.video-download-preview h2 {
margin-top: 5px;
+ font-size: 17px;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
}
.video-download-preview p {
margin-top: 6px;
color: var(--muted);
font-size: 12px;
+ overflow-wrap: anywhere;
+}
+
+.video-download-preview > div {
+ margin-top: 12px;
+}
+
+@container video-download-formats (max-width: 560px) {
+ .video-download-formats-layout { grid-template-columns: minmax(0, 1fr); gap: 20px; }
+ .video-download-preview { display: grid; grid-template-columns: 100px minmax(0, 1fr); align-items: start; gap: 12px; }
+ .video-download-preview > div { margin-top: 0; }
+ .video-download-format-list > .video-result-pane-heading { flex-wrap: wrap; }
}
.video-download-options {
@@ -7549,7 +7845,7 @@
.video-download-options > label {
min-height: 56px;
display: grid;
- grid-template-columns: 18px minmax(0, 1fr) auto auto;
+ grid-template-columns: 18px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
padding: 8px 10px 8px 13px;
@@ -7574,10 +7870,6 @@
font-size: 11px;
}
-.video-download-options > label > small {
- color: var(--accent);
-}
-
.video-download-options > label[data-downloaded="true"] {
background: color-mix(in srgb, var(--success) 5%, transparent);
}
@@ -7621,6 +7913,10 @@
min-height: 480px;
}
+.download-result-workspace .creator-result-layout {
+ grid-template-columns: minmax(0, 1fr);
+}
+
.download-record-list {
display: grid;
gap: 8px;
diff --git a/apps/web/src/features/dashboard/video-download-batch.ts b/apps/web/src/features/dashboard/video-download-batch.ts
new file mode 100644
index 00000000..e68dcedd
--- /dev/null
+++ b/apps/web/src/features/dashboard/video-download-batch.ts
@@ -0,0 +1,65 @@
+import {
+ normalizeVideoSourceUrl,
+ supportedVideoSourcePlatform,
+ videoSourceIdentity,
+ type CreatorJob
+} from '@opencreator/protocol';
+
+export const DOWNLOAD_BATCH_PARENT = 'downloadBatchId';
+export const DOWNLOAD_BATCH_HIDDEN = 'downloadBatchHiddenJobIds';
+
+export type DownloadSource = {
+ id: string;
+ job: CreatorJob;
+ url: string;
+ title: string;
+ thumbnail?: string;
+ thumbnailArtifactId?: string;
+ status: 'waiting' | 'analyzing' | 'ready' | 'downloading' | 'completed' | 'failed' | 'canceled';
+ percent?: number;
+};
+
+export function downloadSourceIdentity(value: string): string {
+ const normalized = normalizeVideoSourceUrl(value);
+ return videoSourceIdentity(normalized) ?? normalized;
+}
+
+export function parseDownloadLink(value: string): { url: string; error?: never } | { error: 'multiple' | 'invalid'; url?: never } {
+ // Check before normalization, which can extract a single URL from share text.
+ if ((value.match(/[a-z][a-z\d+.-]*:\/\//gi) ?? []).length > 1) return { error: 'multiple' };
+ const url = normalizeVideoSourceUrl(value);
+ return supportedVideoSourcePlatform(url) === null ? { error: 'invalid' } : { url };
+}
+
+export function downloadSourceForJob(job: CreatorJob): DownloadSource | undefined {
+ const url = typeof job.state.sourceUrl === 'string' ? job.state.sourceUrl.trim() : '';
+ if (!url) return undefined;
+ const probe = [...job.artifacts].reverse().find(artifact => (
+ artifact.kind === 'download_probe'
+ && artifact.status === 'completed'
+ && typeof artifact.metadata.requestedUrl === 'string'
+ && downloadSourceIdentity(artifact.metadata.requestedUrl) === downloadSourceIdentity(url)
+ ));
+ const active = job.stages.filter(stage => stage.status === 'queued' || stage.status === 'running');
+ const downloading = active.find(stage => stage.stageId === 'download');
+ const latest = job.stages.at(-1);
+ const completed = job.artifacts.some(artifact => artifact.status === 'completed'
+ && (artifact.kind === 'source_video' || artifact.kind === 'source_audio'));
+ return {
+ id: job.id, job, url,
+ title: typeof probe?.metadata.title === 'string' ? probe.metadata.title : url,
+ ...(typeof probe?.metadata.thumbnailUrl === 'string' ? { thumbnail: probe.metadata.thumbnailUrl, thumbnailArtifactId: probe.id } : {}),
+ status: downloading !== undefined ? 'downloading'
+ : active.some(stage => stage.stageId === 'probe') ? 'analyzing'
+ : latest?.status === 'failed' ? 'failed'
+ : latest?.status === 'canceled' || latest?.status === 'interrupted' ? 'canceled'
+ : completed ? 'completed' : probe !== undefined ? 'ready' : 'waiting',
+ ...(typeof downloading?.progress.percent === 'number'
+ ? { percent: Math.min(100, Math.max(0, downloading.progress.percent)) } : {})
+ };
+}
+
+export function hiddenDownloadJobIds(job: CreatorJob): string[] {
+ const value = job.state[DOWNLOAD_BATCH_HIDDEN];
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
+}
diff --git a/apps/web/src/features/issues/issue-catalog.test.ts b/apps/web/src/features/issues/issue-catalog.test.ts
index c74eb250..d8ac055a 100644
--- a/apps/web/src/features/issues/issue-catalog.test.ts
+++ b/apps/web/src/features/issues/issue-catalog.test.ts
@@ -6,6 +6,24 @@ const raw = '后台原文:操作无法完成';
const issue = normalizePageIssue('runtime', 'creator.prepare', new Error(raw), raw);
describe('localized issue copy', () => {
+ it.each(['zh-CN', 'en-US', 'sv-SE'] as const)('explains video platform access failures without model permission guidance in %s', language => {
+ const next = { ...issue, code: 'download_http_error', publicFacts: {
+ kind: 'unauthorized' as const, provider: 'yt-dlp', httpStatus: 403,
+ upstreamMessage: 'The video platform returned HTTP 403 to yt-dlp.'
+ } };
+ const text = issueConversationText(next, language);
+ expect(text.message).toContain('HTTP 403');
+ expect(text.message).toContain('yt-dlp');
+ expect(text.message).not.toMatch(/模型访问权限|model access permissions|modellbehörigheter/);
+ expect(text.nextStep).toMatch(/浏览器|browser|webbläsaren/);
+ expect(text.nextStep).toMatch(/代理|proxy/);
+ if (language === 'en-US') expect(text.message).toContain('The video platform denied access');
+ });
+
+ it('preserves model permission guidance for AI provider authorization failures', () => {
+ const next = { ...issue, publicFacts: { kind: 'unauthorized' as const, provider: 'seedance', httpStatus: 403 } };
+ expect(issueConversationText(next, 'en-US').nextStep).toContain('model access permissions');
+ });
it.each([
['audio_no_speech', '音频为静音或音量过低', '检查原音频和音量'],
['audio_transcription_empty', '尚不能确认音频是否含有语音', '换一个语音识别模型核验'],
diff --git a/apps/web/src/features/issues/issue-catalog.ts b/apps/web/src/features/issues/issue-catalog.ts
index a4a35183..58de8c83 100644
--- a/apps/web/src/features/issues/issue-catalog.ts
+++ b/apps/web/src/features/issues/issue-catalog.ts
@@ -134,9 +134,12 @@ export function publicErrorReason(input: PublicErrorFacts, language: AppLanguage
unavailable: { zh: '服务返回服务器错误', en: 'The service returned a server error' },
unknown: { zh: '尚未取得更细的原因', en: 'A more specific cause is not available' }
};
+ const reason = facts.provider === 'yt-dlp' && facts.kind === 'unauthorized'
+ ? localize('视频平台拒绝了访问请求', 'The video platform denied access', 'Videoplattformen nekade åtkomst')
+ : localize(reasons[facts.kind].zh, reasons[facts.kind].en, reasons[facts.kind].sv);
const parts = facts.kind === 'unknown'
? []
- : [localize(reasons[facts.kind].zh, reasons[facts.kind].en, reasons[facts.kind].sv)];
+ : [reason];
if (facts.provider !== undefined && safePublicErrorCode(facts.provider) !== undefined) {
parts.push(`provider: ${safeIdentifier(facts.provider)}`);
}
@@ -188,7 +191,9 @@ export function issueConversationText(
: issue.publicFacts?.kind === 'http-rejected' || issue.publicFacts?.kind === 'provider-failed'
? localize('请根据服务返回的原因调整输入或请求参数后重试;仍有疑问时,可提供请求编号向服务方查询。', 'Review the provider reason and adjust the input or request parameters before retrying. Use the request ID to ask the provider for details if needed.', 'Läs leverantörens felorsak och justera indata eller parametrarna innan du försöker igen. Använd begärans-ID för att fråga leverantören vid behov.')
: issue.publicFacts?.kind === 'unauthorized'
- ? issue.publicFacts.provider === 'codex-native'
+ ? issue.publicFacts.provider === 'yt-dlp'
+ ? localize('请先确认视频可以在浏览器打开,再检查代理和地区限制。部分平台需要有效的浏览器登录态,直接重试可能仍被拒绝。', 'Confirm that the video opens in your browser, then check the proxy and region restrictions. Some platforms require a valid browser session; retrying alone may still be denied.', 'Kontrollera att videon går att öppna i webbläsaren och kontrollera sedan proxy och regionbegränsningar. Vissa plattformar kräver en giltig webbläsarsession; enbart ett nytt försök kan fortfarande nekas.')
+ : issue.publicFacts.provider === 'codex-native'
? localize('请在本机 Codex 中重新登录 ChatGPT 后重试。', 'Sign in to ChatGPT again in local Codex, then retry.', 'Logga in på ChatGPT igen i lokala Codex och försök igen.')
: localize('请检查服务凭据和模型访问权限后重试。', 'Check the provider credentials and model access permissions before retrying.', 'Kontrollera leverantörens autentiseringsuppgifter och modellbehörigheter innan du försöker igen.')
: issue.publicFacts?.kind === 'rate-limited'
diff --git a/apps/web/src/services/creator-service.test.ts b/apps/web/src/services/creator-service.test.ts
index 184ebff1..3ef91300 100644
--- a/apps/web/src/services/creator-service.test.ts
+++ b/apps/web/src/services/creator-service.test.ts
@@ -78,6 +78,8 @@ describe('creator web service', () => {
});
await service.openProjectCover('job_1');
await service.openArtifact('job_1', 'artifact 1');
+ await service.openDownloadThumbnail('job 1', 'probe 1');
+ expect(client.rawGet).toHaveBeenCalledWith('/creator/jobs/job%201/artifacts/probe%201/thumbnail');
await service.deleteJob('job 1');
await service.deleteJob('job 2', { deleteFiles: true });
await service.listVisualAssets('stickman-video', 'style');
diff --git a/apps/web/src/services/creator-service.ts b/apps/web/src/services/creator-service.ts
index 7e3c1ace..3878a5ab 100644
--- a/apps/web/src/services/creator-service.ts
+++ b/apps/web/src/services/creator-service.ts
@@ -51,6 +51,10 @@ export function createCreatorService(client: ClientLike) {
const lastEventIdByJob = new Map<string, string>();
const consumedEventIds = new Map<string, Set<string>>();
return {
+ openDownloadThumbnail(jobId: string, probeArtifactId: string): Promise<Response> {
+ if (client.rawGet === undefined) throw new Error('Video thumbnail transport is unavailable');
+ return client.rawGet(`/creator/jobs/${encodeURIComponent(jobId)}/artifacts/${encodeURIComponent(probeArtifactId)}/thumbnail`);
+ },
listTemplates(): Promise<CreatorTemplateListResponse> {
return client.get('/creator/templates') as Promise<CreatorTemplateListResponse>;
},
diff --git a/packages/protocol/src/creator-download.ts b/packages/protocol/src/creator-download.ts
index ac11c6ad..b6ae7e1d 100644
--- a/packages/protocol/src/creator-download.ts
+++ b/packages/protocol/src/creator-download.ts
@@ -1,4 +1,4 @@
-export type DownloadPlatform = 'youtube' | 'bilibili' | 'x' | 'tiktok' | 'instagram' | 'douyin' | 'facebook' | 'xiaohongshu' | 'pinterest';
+export type DownloadPlatform = 'youtube' | 'bilibili' | 'x' | 'tiktok' | 'instagram' | 'douyin' | 'facebook' | 'xiaohongshu' | 'pinterest' | 'reddit';
export function extractDouyinShareUrl(value: string): string {
const trimmed = value.trim();
@@ -34,6 +34,7 @@ export function supportedVideoSourcePlatform(value: string): DownloadPlatform |
if (isFacebookVideoUrl(url)) return 'facebook';
if (isXiaohongshuVideoUrl(url)) return 'xiaohongshu';
if (isPinterestVideoUrl(url)) return 'pinterest';
+ if (isRedditVideoUrl(url)) return 'reddit';
} catch {
return null;
}
@@ -81,6 +82,14 @@ function isPinterestVideoUrl(url: URL): boolean {
return ['pinterest.com', 'www.pinterest.com'].includes(url.hostname.toLowerCase()) && /^\/pin\/\d+\/?$/.test(url.pathname);
}
+function isRedditVideoUrl(url: URL): boolean {
+ const host = url.hostname.toLowerCase();
+ if (host === 'redd.it' || host === 'v.redd.it') return /^\/[a-z0-9]+\/?$/i.test(url.pathname);
+ return ['reddit.com', 'www.reddit.com', 'old.reddit.com', 'np.reddit.com', 'm.reddit.com'].includes(host)
+ && (/^\/(?:(?:r|user)\/[\w-]+\/)?comments\/[a-z0-9]+(?:\/.*)?$/i.test(url.pathname)
+ || /^\/r\/[\w-]+\/s\/[a-z0-9]+\/?$/i.test(url.pathname));
+}
+
export type DownloadMediaType = 'video' | 'audio';
export type DownloadContainer = 'mp4' | 'mp3' | 'm4a' | 'webm';
diff --git a/packages/protocol/test/video-source-platforms.test.ts b/packages/protocol/test/video-source-platforms.test.ts
index 80aaf407..b1a583b6 100644
--- a/packages/protocol/test/video-source-platforms.test.ts
+++ b/packages/protocol/test/video-source-platforms.test.ts
@@ -17,7 +17,13 @@ describe('shared public video sources', () => {
['facebook', 'https://www.facebook.com/watch/?v=123'],
['facebook', 'https://fb.watch/abc123/'],
['xiaohongshu', 'https://www.xiaohongshu.com/explore/6a9149f3000000001f01d20a?xsec_token=sample%3D'],
- ['pinterest', 'https://www.pinterest.com/pin/123/']
+ ['pinterest', 'https://www.pinterest.com/pin/123/'],
+ ['reddit', 'https://www.reddit.com/r/claude/s/R5I7tDfJ0h'],
+ ['reddit', 'https://www.reddit.com/r/claude/comments/1x1qhlj/i_made_with_opus_55/'],
+ ['reddit', 'https://old.reddit.com/comments/1x1qhlj'],
+ ['reddit', 'https://www.reddit.com/user/creator/comments/abc123/video/'],
+ ['reddit', 'https://redd.it/1x1qhlj'],
+ ['reddit', 'https://v.redd.it/demo123/']
])('accepts %s videos and identifies them for saved previews: %s', (platform, url) => {
expect(supportedVideoSourcePlatform(url)).toBe(platform);
expect(videoSourceIdentity(url)).not.toBeNull();
@@ -38,6 +44,10 @@ describe('shared public video sources', () => {
'https://www.douyin.com/user/123', 'https://www.facebook.com/creator/',
'https://www.xiaohongshu.com/user/profile/123', 'https://www.pinterest.com/creator/',
'https://notpinterest.com/pin/123/', 'https://instagram.com.example.com/reel/abc/',
+ 'https://www.reddit.com/r/claude/', 'https://www.reddit.com/user/creator/',
+ 'https://www.reddit.com/r/claude/s/', 'https://www.reddit.com/comments/',
+ 'https://reddit.com.example.com/r/claude/s/R5I7tDfJ0h', 'https://notreddit.com/comments/123',
+ 'https://redd.it/', 'https://v.redd.it.example.com/demo123/',
'http://www.instagram.com/reel/abc/', 'file:///tmp/video.mp4', 'not a URL'
])('rejects unsupported links: %s', url => {
expect(supportedVideoSourcePlatform(url)).toBeNull();