Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(youtube): add YouTube uploads to the dashboard

spacesdrive012cc02e324a
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 9ebcbdf..e375a33 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -19,6 +19,7 @@ const VideoExplorer = lazy(() => import('./features/analytics/videos/VideoE
const ShortsExplorer = lazy(() => import('./features/analytics/shorts/ShortsExplorer'));
const ReelsExplorer = lazy(() => import('./features/analytics/reels/ReelsExplorer'));
const UploadContent = lazy(() => import('./features/publishing/UploadContent'));
+const YouTubeUploads = lazy(() => import('./features/youtube/YouTubeUploads'));
const Automations = lazy(() => import('./features/automations/Automations'));
const RuleEditorPage = lazy(() => import('./features/automations/RuleEditorPage'));
const AccountManager = lazy(() => import('./features/accounts/AccountManager'));
@@ -61,6 +62,7 @@ const router = createBrowserRouter([
{ path: 'reels', element: <RedirectWithQuery to="/instagram" /> },
{ path: 'publish', element: <UploadContent /> },
{ path: 'upload', element: <RedirectWithQuery to="/publish" /> },
+ { path: 'youtube-uploads', element: <YouTubeUploads /> },
{ path: 'automations', element: <Automations /> },
{ path: 'automations/rules/new', element: <RuleEditorPage /> },
{ path: 'automations/rules/:id', element: <RuleEditorPage /> },
diff --git a/frontend/src/features/accounts/AccountManager.tsx b/frontend/src/features/accounts/AccountManager.tsx
index 9e34b81..6594a34 100644
--- a/frontend/src/features/accounts/AccountManager.tsx
+++ b/frontend/src/features/accounts/AccountManager.tsx
@@ -14,6 +14,7 @@ import { useInstagramOAuthReturn } from './useInstagramOAuthReturn';
import AccountsEmptyState from './AccountsEmptyState';
import AccountSection from './AccountSection';
import AddAccountDialog from './AddAccountDialog';
+import YouTubePublishingSection from './YouTubePublishingSection';
export default function AccountManager() {
const { accounts, showToast, loadAccounts } = useAppContext();
@@ -62,6 +63,8 @@ export default function AccountManager() {
))
)}
+ <YouTubePublishingSection />
+
<AddAccountDialog flow={addFlow} />
<ConfirmDialog
diff --git a/frontend/src/features/accounts/YouTubePublishingSection.tsx b/frontend/src/features/accounts/YouTubePublishingSection.tsx
new file mode 100644
index 0000000..43f224a
--- /dev/null
+++ b/frontend/src/features/accounts/YouTubePublishingSection.tsx
@@ -0,0 +1,97 @@
+import React, { useState } from 'react';
+import { CheckCircle2, Link2, Trash2, TriangleAlert } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Spinner } from '@/components/ui/spinner';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import RelativeTime from '@/components/RelativeTime';
+import RowAction from '@/components/RowAction';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState, ErrorState } from '@/components/StateViews';
+import { useAppContext } from '../../context/AppContext';
+import { useYouTubeConnections } from './useYouTubeConnections';
+import type { YouTubeConnectionSummary } from '@shared/types/youtubePublishing.ts';
+
+export default function YouTubePublishingSection() {
+ const { showToast } = useAppContext();
+ const youtube = useYouTubeConnections(showToast);
+ const [pending, setPending] = useState<YouTubeConnectionSummary | null>(null);
+
+ const connectButton = (
+ <Button variant="outline" onClick={() => { void youtube.connect(); }} disabled={youtube.connecting || !youtube.configured}>
+ {youtube.connecting ? <Spinner className="size-4" /> : <Link2 data-icon="inline-start" />}
+ {youtube.connecting ? 'Opening Google' : 'Connect a channel'}
+ </Button>
+ );
+
+ return (
+ <section id="youtube-publishing" aria-labelledby="youtube-publishing-title" className="flex scroll-mt-20 flex-col gap-3">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div className="flex flex-col gap-1">
+ <h2 id="youtube-publishing-title" className="font-heading text-section font-semibold text-ink">YouTube publishing</h2>
+ <p className="max-w-prose text-body text-ink-muted">
+ Connect a channel with Google to upload videos to it. Twiligent asks only to upload and to read the channel, never to change or delete what is there.
+ </p>
+ </div>
+ {youtube.connections.length > 0 && connectButton}
+ </div>
+
+ {youtube.loading ? (
+ <Skeleton className="h-24 rounded-card" />
+ ) : youtube.error ? (
+ <SurfaceBox><ErrorState title="YouTube connections could not load" description={youtube.error} onRetry={() => { void youtube.reload(); }} /></SurfaceBox>
+ ) : !youtube.configured ? (
+ <SurfaceBox>
+ <EmptyState compact icon={<TriangleAlert />} title="Not set up on this server" description="The owner needs to add a Google OAuth client and TOKEN_ENCRYPTION_KEY before channels can be connected." />
+ </SurfaceBox>
+ ) : youtube.connections.length === 0 ? (
+ <SurfaceBox>
+ <EmptyState compact icon={<Link2 />} title="No channel connected for publishing" description="Analytics work without this; publishing needs the channel owner to sign in once." action={connectButton} />
+ </SurfaceBox>
+ ) : (
+ <SurfaceBox content={false}>
+ <ul className="divide-y divide-divider">
+ {youtube.connections.map(connection => (
+ <li key={connection.id} className="flex items-center justify-between gap-4 px-4 py-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="truncate text-sm font-medium text-ink">{connection.channelTitle || connection.channelId}</p>
+ {connection.status === 'active'
+ ? <Badge variant="success"><CheckCircle2 />Connected</Badge>
+ : <Badge variant="warning"><TriangleAlert />Needs a new sign-in</Badge>}
+ </div>
+ <p className="text-caption text-ink-muted"><RelativeTime date={connection.createdAt} prefix="Connected " /></p>
+ </div>
+ <div className="flex items-center gap-2">
+ {connection.status !== 'active' && (
+ <Button variant="outline" size="sm" onClick={() => { void youtube.connect(); }} disabled={youtube.connecting} aria-label={`Sign in again: ${connection.channelTitle}`}>
+ Sign in again
+ </Button>
+ )}
+ <RowAction label="Disconnect" target={connection.channelTitle || connection.channelId} onClick={() => setPending(connection)} danger>
+ <Trash2 />
+ </RowAction>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </SurfaceBox>
+ )}
+
+ <ConfirmDialog
+ open={pending !== null}
+ onOpenChange={open => { if (!open) setPending(null); }}
+ title={`Disconnect ${pending?.channelTitle || 'this channel'}?`}
+ description="Google is told to drop Twiligent's access, and this channel's upload queue and history are removed. Videos already on YouTube stay there. Its analytics are not affected."
+ confirmLabel="Disconnect"
+ busyLabel="Disconnecting"
+ busy={pending !== null && youtube.removingId === pending.id}
+ onConfirm={() => {
+ if (pending) void youtube.disconnect(pending).then(done => { if (done) setPending(null); });
+ }}
+ hold
+ />
+ </section>
+ );
+}
diff --git a/frontend/src/features/accounts/useYouTubeConnections.ts b/frontend/src/features/accounts/useYouTubeConnections.ts
new file mode 100644
index 0000000..e5a4917
--- /dev/null
+++ b/frontend/src/features/accounts/useYouTubeConnections.ts
@@ -0,0 +1,87 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import { api } from '../../services/api';
+import { readYouTubeReturn, youtubeReturnError } from '../youtube/youtubeUploadData';
+import type { AppContextValue } from '../../context/AppContext';
+import type { YouTubeConnectionSummary } from '@shared/types/youtubePublishing.ts';
+
+type ShowToast = AppContextValue['showToast'];
+
+export function useYouTubeConnections(showToast: ShowToast) {
+ const [connections, setConnections] = useState<YouTubeConnectionSummary[]>([]);
+ const [configured, setConfigured] = useState(true);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [connecting, setConnecting] = useState(false);
+ const [removingId, setRemovingId] = useState<string | null>(null);
+ const [searchParams, setSearchParams] = useSearchParams();
+ // the code works once, so a second run of the effect must not send it again
+ const completing = useRef(false);
+
+ const load = useCallback(async () => {
+ setError(null);
+ try {
+ const answer = await api.getYouTubeConnections();
+ setConnections(answer.connections);
+ setConfigured(answer.configured);
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { void load(); }, [load]);
+
+ // a finished Google sign-in: the server connects the channel only if this person started it
+ useEffect(() => {
+ const returned = readYouTubeReturn(window.location.hash);
+ if (!returned || completing.current) return;
+ completing.current = true;
+ // out of the address at once, so a reload or a shared link never carries the code
+ window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search);
+ api.completeYouTubeConnection(returned.code, returned.state)
+ .then(({ outcome, connection }) => {
+ showToast(`${connection.channelTitle || 'YouTube channel'} ${outcome === 'reconnected' ? 'reconnected' : 'connected'} for publishing`);
+ void load();
+ })
+ .catch((err: unknown) => showToast(`Couldn't connect YouTube. ${(err as Error).message}`, 'error'));
+ }, [showToast, load]);
+
+ useEffect(() => {
+ const message = youtubeReturnError(searchParams);
+ if (!message) return;
+ showToast(message, 'error');
+ const next = new URLSearchParams(searchParams);
+ next.delete('yt_error');
+ setSearchParams(next, { replace: true });
+ }, [searchParams, setSearchParams, showToast]);
+
+ const connect = async () => {
+ setConnecting(true);
+ try {
+ const { url } = await api.getYouTubeAuthUrl();
+ window.location.assign(url);
+ } catch (err) {
+ showToast(`Couldn't start connecting YouTube. ${(err as Error).message}`, 'error');
+ setConnecting(false);
+ }
+ };
+
+ const disconnect = async (connection: YouTubeConnectionSummary): Promise<boolean> => {
+ setRemovingId(connection.id);
+ try {
+ await api.deleteYouTubeConnection(connection.id);
+ setConnections(current => current.filter(item => item.id !== connection.id));
+ showToast(`${connection.channelTitle || 'YouTube channel'} disconnected`);
+ return true;
+ } catch (err) {
+ showToast(`Couldn't disconnect the channel. ${(err as Error).message}`, 'error');
+ return false;
+ } finally {
+ setRemovingId(null);
+ }
+ };
+
+ return { connections, configured, loading, error, reload: load, connecting, connect, removingId, disconnect };
+}
diff --git a/frontend/src/features/youtube/YouTubeComposer.tsx b/frontend/src/features/youtube/YouTubeComposer.tsx
new file mode 100644
index 0000000..79fa700
--- /dev/null
+++ b/frontend/src/features/youtube/YouTubeComposer.tsx
@@ -0,0 +1,217 @@
+import React, { useState } from 'react';
+import { Upload } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Input } from '@/components/ui/input';
+import { Progress } from '@/components/ui/progress';
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Spinner } from '@/components/ui/spinner';
+import { Switch } from '@/components/ui/switch';
+import { Textarea } from '@/components/ui/textarea';
+import SegmentedChoice from '@/components/SegmentedChoice';
+import SurfaceBox from '@/components/SurfaceBox';
+import { FieldRow } from '@/components/DetailPanel';
+import { api } from '../../services/api';
+import { CATEGORY_OPTIONS, PRIVACY_OPTIONS, TITLE_MAX, composerProblem, parseTags } from './youtubeUploadData';
+import type { CloudinaryUploadConfig, CloudinaryUpload } from '../../services/api';
+import type { ComposerField } from './youtubeUploadData';
+import type { YouTubeConnectionSummary, YouTubePrivacy, YouTubeUploadRequest } from '@shared/types/youtubePublishing.ts';
+
+export interface YouTubeComposerProps {
+ connections: YouTubeConnectionSummary[];
+ cloudConfig: CloudinaryUploadConfig | null;
+ onQueue: (request: YouTubeUploadRequest) => Promise<boolean>;
+ showError: (message: string) => void;
+}
+
+type KidsChoice = 'yes' | 'no' | '';
+const KIDS_OPTIONS: { value: KidsChoice; label: string }[] = [{ value: 'no', label: 'No' }, { value: 'yes', label: 'Yes' }];
+// YouTube takes custom thumbnails up to 2 MB
+const THUMBNAIL_MAX_BYTES = 2 * 1024 * 1024;
+
+const FIELD_IDS: Record<ComposerField, string> = {
+ connection: 'yt-channel', video: 'yt-video', title: 'yt-title', madeForKids: 'yt-kids', schedule: 'yt-publish-at',
+};
+
+async function register(upload: CloudinaryUpload, label: string): Promise<string> {
+ const { media } = await api.registerMedia({ ...upload, label });
+ return media.id;
+}
+
+export default function YouTubeComposer({ connections, cloudConfig, onQueue, showError }: YouTubeComposerProps) {
+ const active = connections.filter(connection => connection.status === 'active');
+ const [connectionId, setConnectionId] = useState(active.length === 1 ? active[0].id : '');
+ const [video, setVideo] = useState<File | null>(null);
+ const [thumbnail, setThumbnail] = useState<File | null>(null);
+ const [title, setTitle] = useState('');
+ const [description, setDescription] = useState('');
+ const [tags, setTags] = useState('');
+ const [categoryId, setCategoryId] = useState('22');
+ const [privacy, setPrivacy] = useState<YouTubePrivacy>('private');
+ const [scheduled, setScheduled] = useState(false);
+ const [publishAt, setPublishAt] = useState('');
+ const [kids, setKids] = useState<KidsChoice>('');
+ const [synthetic, setSynthetic] = useState(false);
+ const [notify, setNotify] = useState(true);
+ const [tried, setTried] = useState(false);
+ const [working, setWorking] = useState<string | null>(null);
+ const [progress, setProgress] = useState(0);
+
+ const values = { connectionId, hasVideo: video !== null, title, madeForKids: kids === '' ? null : kids === 'yes', scheduled, publishAt };
+ const problem = tried ? composerProblem(values, new Date()) : null;
+ const errorFor = (field: ComposerField) => (problem?.field === field ? problem.message : undefined);
+ const titleLength = [...title].length;
+
+ function reset() {
+ setVideo(null);
+ setThumbnail(null);
+ setTitle('');
+ setDescription('');
+ setTags('');
+ setScheduled(false);
+ setPublishAt('');
+ setKids('');
+ setSynthetic(false);
+ setTried(false);
+ }
+
+ async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
+ e.preventDefault();
+ if (working) return;
+ setTried(true);
+ const found = composerProblem(values, new Date());
+ if (found) {
+ document.getElementById(FIELD_IDS[found.field])?.focus();
+ return;
+ }
+ if (!cloudConfig || !video) return;
+ if (thumbnail && thumbnail.size > THUMBNAIL_MAX_BYTES) {
+ showError('Couldn\'t queue the video. The thumbnail is larger than 2 MB, which YouTube does not accept.');
+ return;
+ }
+ try {
+ setWorking('Uploading the video');
+ setProgress(0);
+ const uploadedVideo = await api.uploadWithDetails(video, cloudConfig, { onProgress: setProgress });
+ setWorking('Saving it to your media');
+ const mediaId = await register(uploadedVideo, title.trim());
+ let thumbnailMediaId: string | null = null;
+ if (thumbnail) {
+ setWorking('Uploading the thumbnail');
+ thumbnailMediaId = await register(await api.uploadWithDetails(thumbnail, cloudConfig), `${title.trim()} thumbnail`);
+ }
+ setWorking('Queueing the upload');
+ const queued = await onQueue({
+ connectionId,
+ mediaId,
+ thumbnailMediaId,
+ title: title.trim(),
+ description,
+ tags: parseTags(tags),
+ categoryId,
+ privacy: scheduled ? 'private' : privacy,
+ publishAt: scheduled ? new Date(publishAt).toISOString() : null,
+ madeForKids: kids === 'yes',
+ syntheticMedia: synthetic,
+ notifySubscribers: notify,
+ // one id per press, so a repeated request never queues the video twice
+ clientRequestId: crypto.randomUUID(),
+ });
+ if (queued) reset();
+ } catch (err) {
+ showError(`Couldn't queue the video. ${(err as Error).message}`);
+ } finally {
+ setWorking(null);
+ }
+ }
+
+ return (
+ <SurfaceBox title="New upload" headingLevel="h2" subheader="The video goes to Cloudinary first, then to YouTube over the next runs, every 15 minutes.">
+ <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-5">
+ <FieldRow label="Channel" htmlFor="yt-channel" error={errorFor('connection')}>
+ <Select value={connectionId} onValueChange={value => setConnectionId(String(value))} items={active.map(item => ({ value: item.id, label: item.channelTitle || item.channelId }))}>
+ <SelectTrigger id="yt-channel" className="w-full max-w-sm"><SelectValue placeholder="Choose a channel" /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {active.map(item => <SelectItem key={item.id} value={item.id}>{item.channelTitle || item.channelId}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FieldRow>
+
+ <FieldRow label="Video" htmlFor="yt-video" hint="MP4 or MOV. A vertical or square video of up to three minutes becomes a Short. Your Cloudinary plan sets the largest size (100 MB on the free plan)." error={errorFor('video')}>
+ <input id="yt-video" type="file" accept="video/*" onChange={e => setVideo(e.target.files?.[0] ?? null)} className="block w-full max-w-sm text-body text-ink file:mr-3 file:rounded-control file:border file:border-line-control file:bg-surface file:px-3 file:py-1.5 file:text-sm file:text-ink" />
+ </FieldRow>
+
+ <FieldRow label="Title" htmlFor="yt-title" hint={`${titleLength} of ${TITLE_MAX} characters.`} error={errorFor('title')}>
+ <Input id="yt-title" value={title} onChange={e => setTitle(e.target.value)} maxLength={TITLE_MAX + 20} required />
+ </FieldRow>
+
+ <FieldRow label="Description" htmlFor="yt-description" optional>
+ <Textarea id="yt-description" value={description} onChange={e => setDescription(e.target.value)} rows={5} />
+ </FieldRow>
+
+ <FieldRow label="Tags" htmlFor="yt-tags" optional hint="Separate them with commas.">
+ <Input id="yt-tags" value={tags} onChange={e => setTags(e.target.value)} />
+ </FieldRow>
+
+ <FieldRow label="Category" htmlFor="yt-category">
+ <Select value={categoryId} onValueChange={value => setCategoryId(String(value))} items={CATEGORY_OPTIONS}>
+ <SelectTrigger id="yt-category" className="w-full max-w-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {CATEGORY_OPTIONS.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </FieldRow>
+
+ <FieldRow label="Made for kids" htmlFor="yt-kids" group hint="YouTube requires an answer for every video." error={errorFor('madeForKids')}>
+ <SegmentedChoice<KidsChoice> name="yt-kids" id="yt-kids" options={KIDS_OPTIONS} value={kids} onChange={setKids} />
+ </FieldRow>
+
+ <FieldRow label="Publish later" htmlFor="yt-schedule" hint={scheduled ? 'The video stays private until this time, then YouTube makes it public.' : 'Off: the video gets the visibility below as soon as it is processed.'}>
+ <Switch id="yt-schedule" checked={scheduled} onCheckedChange={setScheduled} />
+ </FieldRow>
+
+ {scheduled ? (
+ <FieldRow label="Publish at" htmlFor="yt-publish-at" hint="In your own time zone." error={errorFor('schedule')}>
+ <Input id="yt-publish-at" type="datetime-local" value={publishAt} onChange={e => setPublishAt(e.target.value)} className="max-w-sm" />
+ </FieldRow>
+ ) : (
+ <FieldRow label="Visibility" htmlFor="yt-privacy" group>
+ <SegmentedChoice<YouTubePrivacy> name="yt-privacy" id="yt-privacy" options={PRIVACY_OPTIONS} value={privacy} onChange={setPrivacy} />
+ </FieldRow>
+ )}
+
+ <FieldRow label="Thumbnail" htmlFor="yt-thumbnail" optional hint="JPEG or PNG up to 2 MB. Custom thumbnails need a verified channel.">
+ <input id="yt-thumbnail" type="file" accept="image/jpeg,image/png" onChange={e => setThumbnail(e.target.files?.[0] ?? null)} className="block w-full max-w-sm text-body text-ink file:mr-3 file:rounded-control file:border file:border-line-control file:bg-surface file:px-3 file:py-1.5 file:text-sm file:text-ink" />
+ </FieldRow>
+
+ <div className="flex flex-col gap-3">
+ <label htmlFor="yt-synthetic" className="flex items-start gap-2 text-body text-ink">
+ <Checkbox id="yt-synthetic" checked={synthetic} onCheckedChange={checked => setSynthetic(checked === true)} className="mt-1" />
+ <span>Contains realistic content made or changed with AI</span>
+ </label>
+ <label htmlFor="yt-notify" className="flex items-start gap-2 text-body text-ink">
+ <Checkbox id="yt-notify" checked={notify} onCheckedChange={checked => setNotify(checked === true)} className="mt-1" />
+ <span>Tell subscribers about the new video</span>
+ </label>
+ </div>
+
+ {working && (
+ <div role="status" className="flex flex-col gap-2">
+ <p className="text-sm text-ink-muted">{working}</p>
+ {working === 'Uploading the video' && <Progress value={progress} aria-label="Video upload progress" />}
+ </div>
+ )}
+
+ <Button type="submit" className="self-start" disabled={working !== null || !cloudConfig}>
+ {working ? <Spinner className="size-4" /> : <Upload data-icon="inline-start" />}
+ {working ? 'Queueing' : 'Queue upload'}
+ </Button>
+ {!cloudConfig && <p className="text-sm text-ink-muted">Uploads need Cloudinary, which is not set up on this server.</p>}
+ </form>
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/youtube/YouTubeUploadList.tsx b/frontend/src/features/youtube/YouTubeUploadList.tsx
new file mode 100644
index 0000000..7f7b558
--- /dev/null
+++ b/frontend/src/features/youtube/YouTubeUploadList.tsx
@@ -0,0 +1,107 @@
+import React, { useState } from 'react';
+import { ExternalLink, RotateCcw, Upload, X } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Progress } from '@/components/ui/progress';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import RelativeTime from '@/components/RelativeTime';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState } from '@/components/StateViews';
+import { STATE_DISPLAY, uploadPercent } from './youtubeUploadData';
+import type { StateTone } from './youtubeUploadData';
+import type { YouTubeUploadState, YouTubeUploadSummary } from '@shared/types/youtubePublishing.ts';
+
+export interface YouTubeUploadListProps {
+ uploads: YouTubeUploadSummary[];
+ busyId: string | null;
+ onCancel: (id: string) => Promise<void>;
+ onRetry: (id: string) => Promise<void>;
+}
+
+const BADGE: Record<StateTone, 'secondary' | 'success' | 'warning' | 'destructive' | 'outline'> = {
+ secondary: 'secondary', info: 'outline', success: 'success', warning: 'warning', danger: 'destructive',
+};
+const CANCELLABLE: YouTubeUploadState[] = ['queued', 'uploading', 'waiting_quota', 'needs_reconnect', 'failed', 'needs_review'];
+const RETRYABLE: YouTubeUploadState[] = ['failed', 'needs_review'];
+
+function UploadRow({ upload, busy, onAskCancel, onRetry }: { upload: YouTubeUploadSummary; busy: boolean; onAskCancel: () => void; onRetry: () => void }) {
+ const display = STATE_DISPLAY[upload.state];
+ const percent = uploadPercent(upload);
+ return (
+ <li className="flex flex-col gap-2 px-4 py-3">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="truncate text-sm font-medium text-ink">{upload.title}</p>
+ <Badge variant={BADGE[display.tone]}>{display.label}</Badge>
+ {upload.isShort && <Badge variant="outline">Short</Badge>}
+ <Badge variant="outline">{upload.publishAt ? 'Scheduled' : upload.privacy[0].toUpperCase() + upload.privacy.slice(1)}</Badge>
+ </div>
+ <p className="text-caption text-ink-muted">
+ <RelativeTime date={upload.createdAt} prefix="Queued " />
+ {upload.publishAt && <> <span aria-hidden="true">·</span><span className="sr-only">,</span> <RelativeTime date={upload.publishAt} prefix="publishes " /></>}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {upload.videoId && (
+ <Button variant="outline" size="sm" render={<a href={`https://www.youtube.com/watch?v=${encodeURIComponent(upload.videoId)}`} target="_blank" rel="noopener noreferrer" />}>
+ <ExternalLink data-icon="inline-start" />
+ Open on YouTube<span className="sr-only"> (opens in a new tab)</span>
+ </Button>
+ )}
+ {RETRYABLE.includes(upload.state) && (
+ <Button variant="outline" size="sm" onClick={onRetry} disabled={busy} aria-label={`Try again: ${upload.title}`}>
+ <RotateCcw data-icon="inline-start" />
+ Try again
+ </Button>
+ )}
+ {CANCELLABLE.includes(upload.state) && (
+ <Button variant="ghost" size="sm" onClick={onAskCancel} disabled={busy} aria-label={`Cancel upload: ${upload.title}`}>
+ <X data-icon="inline-start" />
+ Cancel
+ </Button>
+ )}
+ </div>
+ </div>
+ {upload.state === 'uploading' && <Progress value={percent} aria-label={`Upload progress for ${upload.title}: ${percent} percent`} />}
+ <p className="max-w-prose text-sm text-ink-muted">{upload.lastError ?? display.help}</p>
+ </li>
+ );
+}
+
+export default function YouTubeUploadList({ uploads, busyId, onCancel, onRetry }: YouTubeUploadListProps) {
+ const [pending, setPending] = useState<YouTubeUploadSummary | null>(null);
+
+ return (
+ <SurfaceBox title="Your uploads" headingLevel="h2" content={false}>
+ {uploads.length === 0 ? (
+ <EmptyState compact icon={<Upload />} title="No uploads yet" description="Queue a video above; it appears here with its progress." />
+ ) : (
+ <ul className="divide-y divide-divider">
+ {uploads.map(upload => (
+ <UploadRow
+ key={upload.id}
+ upload={upload}
+ busy={busyId === upload.id}
+ onAskCancel={() => setPending(upload)}
+ onRetry={() => { void onRetry(upload.id); }}
+ />
+ ))}
+ </ul>
+ )}
+ <ConfirmDialog
+ open={pending !== null}
+ onOpenChange={open => { if (!open) setPending(null); }}
+ title={`Cancel ${pending?.title ?? 'this upload'}?`}
+ description="YouTube has not finished the video, so nothing appears on the channel. Queue it again later if you change your mind."
+ confirmLabel="Cancel upload"
+ cancelLabel="Keep it"
+ busyLabel="Cancelling"
+ busy={pending !== null && busyId === pending.id}
+ onConfirm={() => {
+ if (pending) void onCancel(pending.id).then(() => setPending(null));
+ }}
+ />
+ </SurfaceBox>
+ );
+}
diff --git a/frontend/src/features/youtube/YouTubeUploads.tsx b/frontend/src/features/youtube/YouTubeUploads.tsx
new file mode 100644
index 0000000..f6aed0b
--- /dev/null
+++ b/frontend/src/features/youtube/YouTubeUploads.tsx
@@ -0,0 +1,68 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { AlertCircle, Link2 } from 'lucide-react';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import PageHeader from '@/components/PageHeader';
+import SurfaceBox from '@/components/SurfaceBox';
+import { EmptyState, ErrorState } from '@/components/StateViews';
+import { docsUrl } from '@/lib/docs';
+import { useAppContext } from '../../context/AppContext';
+import { useCloudinaryConfig } from '../../hooks/use-cloudinary-config';
+import YouTubeComposer from './YouTubeComposer';
+import YouTubeUploadList from './YouTubeUploadList';
+import { useYouTubePublishing } from './useYouTubePublishing';
+
+const DESCRIPTION = 'Upload videos and Shorts to your connected YouTube channels.';
+
+export default function YouTubeUploads() {
+ const { accounts, showToast } = useAppContext();
+ const cloudConfig = useCloudinaryConfig(accounts);
+ const youtube = useYouTubePublishing(showToast);
+ const active = youtube.connections.filter(connection => connection.status === 'active');
+
+ if (youtube.loading) {
+ return (
+ <div role="status" className="flex flex-col gap-6">
+ <PageHeader title="YouTube uploads" description={DESCRIPTION} />
+ <span className="sr-only">Loading YouTube uploads</span>
+ <Skeleton className="h-64 rounded-card" />
+ <Skeleton className="h-40 rounded-card" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <PageHeader title="YouTube uploads" description={DESCRIPTION} />
+
+ {youtube.error ? (
+ <SurfaceBox><ErrorState title="YouTube uploads could not load" description={youtube.error} onRetry={() => { void youtube.reload(); }} /></SurfaceBox>
+ ) : !youtube.configured ? (
+ <Alert variant="warning">
+ <AlertCircle />
+ <AlertDescription>
+ YouTube publishing is not set up on this server. The owner needs to add a Google OAuth client and <code>TOKEN_ENCRYPTION_KEY</code>.{' '}
+ <a href={docsUrl('/self-host/youtube-publishing')} target="_blank" rel="noopener noreferrer" className="font-semibold underline underline-offset-4">How to set it up<span className="sr-only"> (opens in a new tab)</span></a>
+ </AlertDescription>
+ </Alert>
+ ) : active.length === 0 ? (
+ <SurfaceBox>
+ <EmptyState
+ icon={<Link2 />}
+ title={youtube.connections.length > 0 ? 'Your channel needs a new sign-in' : 'Connect a YouTube channel first'}
+ description="Connecting signs in with Google and lets Twiligent upload videos to the channel. It cannot change or delete videos already there."
+ action={<Button render={<Link to="/accounts#youtube-publishing" />}>Go to Accounts</Button>}
+ />
+ </SurfaceBox>
+ ) : (
+ <YouTubeComposer connections={youtube.connections} cloudConfig={cloudConfig} onQueue={youtube.queue} showError={message => showToast(message, 'error')} />
+ )}
+
+ {!youtube.error && youtube.configured && (
+ <YouTubeUploadList uploads={youtube.uploads} busyId={youtube.busyId} onCancel={youtube.cancel} onRetry={youtube.retry} />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/features/youtube/useYouTubePublishing.ts b/frontend/src/features/youtube/useYouTubePublishing.ts
new file mode 100644
index 0000000..29711cb
--- /dev/null
+++ b/frontend/src/features/youtube/useYouTubePublishing.ts
@@ -0,0 +1,72 @@
+import { useCallback, useEffect, useState } from 'react';
+import { api } from '../../services/api';
+import { anyActive } from './youtubeUploadData';
+import type { AppContextValue } from '../../context/AppContext';
+import type { YouTubeConnectionSummary, YouTubeUploadRequest, YouTubeUploadSummary } from '@shared/types/youtubePublishing.ts';
+
+type ShowToast = AppContextValue['showToast'];
+
+// uploads move on the server's 15 minute runs, so checking every half minute is plenty and costs one request
+const ACTIVE_REFRESH_MS = 30 * 1000;
+
+export function useYouTubePublishing(showToast: ShowToast) {
+ const [connections, setConnections] = useState<YouTubeConnectionSummary[]>([]);
+ const [configured, setConfigured] = useState(true);
+ const [uploads, setUploads] = useState<YouTubeUploadSummary[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [busyId, setBusyId] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ setError(null);
+ try {
+ const [connected, queued] = await Promise.all([api.getYouTubeConnections(), api.getYouTubeUploads()]);
+ setConnections(connected.connections);
+ setConfigured(connected.configured);
+ setUploads(queued.uploads);
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { void load(); }, [load]);
+
+ const active = anyActive(uploads);
+ useEffect(() => {
+ if (!active) return undefined;
+ const timer = setInterval(() => { void load(); }, ACTIVE_REFRESH_MS);
+ return () => clearInterval(timer);
+ }, [active, load]);
+
+ const queue = async (request: YouTubeUploadRequest): Promise<boolean> => {
+ try {
+ const { upload } = await api.createYouTubeUpload(request);
+ setUploads(current => [upload, ...current.filter(item => item.id !== upload.id)]);
+ showToast('Video queued. It uploads over the next runs, every 15 minutes.');
+ return true;
+ } catch (err) {
+ showToast(`Couldn't queue the video. ${(err as Error).message}`, 'error');
+ return false;
+ }
+ };
+
+ const act = async (id: string, action: 'cancel' | 'retry') => {
+ setBusyId(id);
+ try {
+ const { upload } = action === 'cancel' ? await api.cancelYouTubeUpload(id) : await api.retryYouTubeUpload(id);
+ setUploads(current => current.map(item => (item.id === id ? upload : item)));
+ showToast(action === 'cancel' ? 'Upload cancelled' : 'Upload queued again');
+ } catch (err) {
+ showToast(`Couldn't ${action === 'cancel' ? 'cancel' : 'retry'} the upload. ${(err as Error).message}`, 'error');
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ return {
+ connections, configured, uploads, loading, error, reload: load, busyId,
+ queue, cancel: (id: string) => act(id, 'cancel'), retry: (id: string) => act(id, 'retry'),
+ };
+}
diff --git a/frontend/src/features/youtube/youtubeUploadData.ts b/frontend/src/features/youtube/youtubeUploadData.ts
new file mode 100644
index 0000000..c6ce18c
--- /dev/null
+++ b/frontend/src/features/youtube/youtubeUploadData.ts
@@ -0,0 +1,122 @@
+import type { YouTubePrivacy, YouTubeUploadState, YouTubeUploadSummary } from '@shared/types/youtubePublishing.ts';
+
+export type StateTone = 'secondary' | 'info' | 'success' | 'warning' | 'danger';
+
+export interface StateDisplay {
+ label: string;
+ tone: StateTone;
+ // the page checks again while a job is moving
+ active: boolean;
+ help: string;
+}
+
+export const STATE_DISPLAY: Record<YouTubeUploadState, StateDisplay> = {
+ queued: { label: 'Queued', tone: 'secondary', active: true, help: 'Waits for the next upload run, every 15 minutes.' },
+ uploading: { label: 'Uploading', tone: 'info', active: true, help: 'Sent to YouTube in parts over the next runs.' },
+ processing: { label: 'Processing', tone: 'info', active: true, help: 'YouTube has the video and is processing it.' },
+ finalizing: { label: 'Setting thumbnail', tone: 'info', active: true, help: 'The video is up; the thumbnail is being set.' },
+ done: { label: 'On YouTube', tone: 'success', active: false, help: 'The video is on the channel.' },
+ waiting_quota: { label: 'Waiting for quota', tone: 'warning', active: true, help: 'YouTube\'s daily allowance is used up; the upload continues after midnight Pacific time.' },
+ needs_reconnect: { label: 'Needs sign-in', tone: 'warning', active: false, help: 'Connect YouTube again on the Accounts page; the upload then continues.' },
+ needs_review: { label: 'Check your channel', tone: 'warning', active: false, help: 'YouTube may already have this video. Look on your channel before trying again.' },
+ failed: { label: 'Failed', tone: 'danger', active: false, help: 'The upload stopped. Read the reason, then try again.' },
+ cancelled: { label: 'Cancelled', tone: 'secondary', active: false, help: 'Stopped before YouTube had the video.' },
+};
+
+export const PRIVACY_OPTIONS: { value: YouTubePrivacy; label: string }[] = [
+ { value: 'private', label: 'Private' },
+ { value: 'unlisted', label: 'Unlisted' },
+ { value: 'public', label: 'Public' },
+];
+
+// YouTube's own category numbers for the categories most channels use
+export const CATEGORY_OPTIONS: { value: string; label: string }[] = [
+ { value: '22', label: 'People and blogs' },
+ { value: '1', label: 'Film and animation' },
+ { value: '2', label: 'Autos and vehicles' },
+ { value: '10', label: 'Music' },
+ { value: '15', label: 'Pets and animals' },
+ { value: '17', label: 'Sports' },
+ { value: '19', label: 'Travel and events' },
+ { value: '20', label: 'Gaming' },
+ { value: '23', label: 'Comedy' },
+ { value: '24', label: 'Entertainment' },
+ { value: '25', label: 'News and politics' },
+ { value: '26', label: 'How-to and style' },
+ { value: '27', label: 'Education' },
+ { value: '28', label: 'Science and technology' },
+ { value: '29', label: 'Nonprofits and activism' },
+];
+
+export const TITLE_MAX = 100;
+
+export function uploadPercent(upload: Pick<YouTubeUploadSummary, 'bytesConfirmed' | 'sourceBytes'>): number {
+ if (upload.sourceBytes <= 0) return 0;
+ return Math.min(100, Math.round((upload.bytesConfirmed / upload.sourceBytes) * 100));
+}
+
+export function anyActive(uploads: Pick<YouTubeUploadSummary, 'state'>[]): boolean {
+ return uploads.some(upload => STATE_DISPLAY[upload.state].active);
+}
+
+// accepts commas or new lines, trims, and keeps each tag once
+export function parseTags(text: string): string[] {
+ return [...new Set(text.split(/[,\n]/).map(tag => tag.trim()).filter(Boolean))];
+}
+
+export type ComposerField = 'connection' | 'video' | 'title' | 'madeForKids' | 'schedule';
+
+export interface ComposerValues {
+ connectionId: string;
+ hasVideo: boolean;
+ title: string;
+ madeForKids: boolean | null;
+ scheduled: boolean;
+ publishAt: string;
+}
+
+export interface ComposerProblem {
+ field: ComposerField;
+ message: string;
+}
+
+// the first thing missing, next to its field; the server checks the same and the rest of YouTube's rules
+export function composerProblem(values: ComposerValues, now: Date): ComposerProblem | null {
+ if (!values.connectionId) return { field: 'connection', message: 'Choose the YouTube channel to upload to.' };
+ if (!values.hasVideo) return { field: 'video', message: 'Choose the video file to upload.' };
+ if (!values.title.trim()) return { field: 'title', message: 'Give the video a title.' };
+ if ([...values.title].length > TITLE_MAX) return { field: 'title', message: `Keep the title to ${TITLE_MAX} characters.` };
+ if (/[<>]/.test(values.title)) return { field: 'title', message: 'YouTube does not accept < or > in a title.' };
+ if (values.madeForKids === null) return { field: 'madeForKids', message: 'Say whether the video is made for kids. YouTube requires an answer.' };
+ if (values.scheduled) {
+ const when = new Date(values.publishAt);
+ if (!values.publishAt || Number.isNaN(when.getTime())) return { field: 'schedule', message: 'Set the date and time to publish.' };
+ if (when <= now) return { field: 'schedule', message: 'Pick a time in the future.' };
+ }
+ return null;
+}
+
+export interface YouTubeOAuthReturn {
+ code: string;
+ state: string;
+}
+
+// the callback hands the code back in the fragment, which never reaches a server
+export function readYouTubeReturn(hash: string): YouTubeOAuthReturn | null {
+ const params = new URLSearchParams(hash.replace(/^#/, ''));
+ const code = params.get('yt_code');
+ const state = params.get('yt_state');
+ return code && state ? { code, state } : null;
+}
+
+const RETURN_ERRORS: Record<string, string> = {
+ access_denied: 'YouTube was not connected: the sign-in was cancelled.',
+ invalid_state: 'YouTube was not connected: the sign-in link expired or was changed. Try again.',
+ cancelled: 'YouTube was not connected: the sign-in was cancelled.',
+};
+
+export function youtubeReturnError(search: URLSearchParams): string | null {
+ const error = search.get('yt_error');
+ if (!error) return null;
+ return RETURN_ERRORS[error] ?? `YouTube was not connected (${error}). Try again.`;
+}
diff --git a/frontend/src/layout/navigation.ts b/frontend/src/layout/navigation.ts
index bc99aeb..48c0280 100644
--- a/frontend/src/layout/navigation.ts
+++ b/frontend/src/layout/navigation.ts
@@ -1,5 +1,5 @@
import {
- LayoutDashboard, PlaySquare, Scissors, Clapperboard, Bookmark, Send, MessageSquareReply, Users, Settings,
+ LayoutDashboard, PlaySquare, Scissors, Clapperboard, Bookmark, Send, CloudUpload, MessageSquareReply, Users, Settings,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { activeNavPath, routeTitle as titleForRoute } from './routes';
@@ -34,6 +34,7 @@ export const NAV_GROUPS: NavGroup[] = [
label: 'Publishing',
items: [
{ path: '/publish', label: 'Publish', icon: Send },
+ { path: '/youtube-uploads', label: 'YouTube uploads', icon: CloudUpload },
{ path: '/automations', label: 'Automations', icon: MessageSquareReply },
],
},
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 6fc271b..e0f9f29 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -24,6 +24,11 @@ import type {
McpAccessTokenCreateRequest, McpAccessTokenCreateResponse, McpAccessTokenListResponse, McpClientApprovalRequest,
McpClientGrantListResponse, McpServerInfoResponse,
} from '@shared/types/mcp.ts';
+import type { MediaListResponse, MediaRegistrationRequest, MediaResponse } from '@shared/types/media.ts';
+import type {
+ YouTubeAuthUrlResponse, YouTubeConnectCompleteResponse, YouTubeConnectionListResponse, YouTubeUploadListResponse, YouTubeUploadRequest,
+ YouTubeUploadResponse, YouTubeUploadUpdateRequest,
+} from '@shared/types/youtubePublishing.ts';
const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';
@@ -66,9 +71,26 @@ export interface UploadOptions {
// the parts of a Cloudinary upload response the client reads
interface CloudinaryUploadBody {
secure_url?: string;
+ public_id?: string;
+ resource_type?: string;
+ format?: string;
+ width?: number;
+ height?: number;
+ duration?: number;
error?: { message?: string };
}
+// what a finished upload tells the media library
+export interface CloudinaryUpload {
+ url: string;
+ publicId: string;
+ resourceType: 'image' | 'video';
+ format: string | null;
+ width: number | null;
+ height: number | null;
+ durationSeconds: number | null;
+}
+
const UPLOAD_ERROR_MESSAGES: Record<UploadErrorReason, string> = {
network: 'The upload lost its network connection',
rejected: 'Upload failed',
@@ -88,13 +110,17 @@ function readUploadError(responseText: string): UploadErrorDetails {
}
// the browser posts straight to Cloudinary so the Worker never handles binaries
-function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<string> {
+function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, options: UploadOptions = {}): Promise<string> {
+ return uploadWithDetails(file, cloudConfig, options).then(upload => upload.url);
+}
+
+function uploadWithDetails(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<CloudinaryUpload> {
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', cloudConfig.uploadPreset);
const type = file.type.startsWith('video/') ? 'video' : 'image';
const xhr = new XMLHttpRequest();
- return new Promise<string>((resolve, reject) => {
+ return new Promise<CloudinaryUpload>((resolve, reject) => {
if (onProgress) {
xhr.upload.addEventListener('progress', e => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
@@ -102,7 +128,16 @@ function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { o
}
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
- resolve((JSON.parse(xhr.responseText) as CloudinaryUploadBody).secure_url as string);
+ const body = JSON.parse(xhr.responseText) as CloudinaryUploadBody;
+ resolve({
+ url: body.secure_url ?? '',
+ publicId: body.public_id ?? '',
+ resourceType: body.resource_type === 'video' ? 'video' : 'image',
+ format: body.format ?? null,
+ width: body.width ?? null,
+ height: body.height ?? null,
+ durationSeconds: body.duration ?? null,
+ });
return;
}
reject(uploadError('rejected', readUploadError(xhr.responseText)));
@@ -191,4 +226,20 @@ export const api = {
getMcpClients: () => request<McpClientGrantListResponse>('/mcp/clients'),
approveMcpClient: (data: McpClientApprovalRequest) => request<SuccessResponse>('/mcp/clients', { method: 'POST', body: JSON.stringify(data) }),
revokeMcpClient: (id: string) => request<SuccessResponse>(`/mcp/clients/${id}`, { method: 'DELETE' }),
+
+ // the person's media library on the instance's Cloudinary account; a browser upload is registered after Cloudinary answers
+ getMedia: () => request<MediaListResponse>('/media'),
+ registerMedia: (data: MediaRegistrationRequest) => request<MediaResponse>('/media', { method: 'POST', body: JSON.stringify(data) }),
+ uploadWithDetails,
+
+ // YouTube publishing: connecting a channel with Google, then upload jobs the scheduled runs move
+ getYouTubeConnections: () => request<YouTubeConnectionListResponse>('/youtube/connections'),
+ getYouTubeAuthUrl: () => request<YouTubeAuthUrlResponse>('/auth/youtube/url'),
+ completeYouTubeConnection: (code: string, state: string) => request<YouTubeConnectCompleteResponse>('/auth/youtube/complete', { method: 'POST', body: JSON.stringify({ code, state }) }),
+ deleteYouTubeConnection: (id: string) => request<SuccessResponse>(`/youtube/connections/${id}`, { method: 'DELETE' }),
+ getYouTubeUploads: () => request<YouTubeUploadListResponse>('/youtube/uploads'),
+ createYouTubeUpload: (data: YouTubeUploadRequest) => request<YouTubeUploadResponse>('/youtube/uploads', { method: 'POST', body: JSON.stringify(data) }),
+ updateYouTubeUpload: (id: string, data: YouTubeUploadUpdateRequest) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
+ cancelYouTubeUpload: (id: string) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}/cancel`, { method: 'POST' }),
+ retryYouTubeUpload: (id: string) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}/retry`, { method: 'POST' }),
};
diff --git a/frontend/tests/features/youtube/youtubeUploadData.test.ts b/frontend/tests/features/youtube/youtubeUploadData.test.ts
new file mode 100644
index 0000000..52ce94d
--- /dev/null
+++ b/frontend/tests/features/youtube/youtubeUploadData.test.ts
@@ -0,0 +1,47 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ STATE_DISPLAY, anyActive, composerProblem, parseTags, readYouTubeReturn, uploadPercent, youtubeReturnError,
+} from '../../../src/features/youtube/youtubeUploadData.ts';
+import type { ComposerValues } from '../../../src/features/youtube/youtubeUploadData.ts';
+
+const NOW = new Date('2026-11-05T12:00:00Z');
+const READY: ComposerValues = { connectionId: 'c1', hasVideo: true, title: 'Launch', madeForKids: false, scheduled: false, publishAt: '' };
+
+test('every state has a word, a tone and a line of help, so status is never shown by colour alone', () => {
+ for (const display of Object.values(STATE_DISPLAY)) {
+ assert.ok(display.label.length > 0);
+ assert.ok(display.help.length > 0);
+ }
+ assert.equal(anyActive([{ state: 'done' }, { state: 'failed' }]), false);
+ assert.equal(anyActive([{ state: 'done' }, { state: 'uploading' }]), true);
+});
+
+test('progress is the share of bytes YouTube confirmed', () => {
+ assert.equal(uploadPercent({ bytesConfirmed: 25, sourceBytes: 100 }), 25);
+ assert.equal(uploadPercent({ bytesConfirmed: 0, sourceBytes: 0 }), 0);
+ assert.equal(uploadPercent({ bytesConfirmed: 150, sourceBytes: 100 }), 100);
+});
+
+test('tags may be split by commas or lines, and repeats are dropped', () => {
+ assert.deepEqual(parseTags('launch, news\nlaunch, ,day one'), ['launch', 'news', 'day one']);
+});
+
+test('the composer names the first missing field, including YouTube\'s required kids answer', () => {
+ assert.equal(composerProblem(READY, NOW), null);
+ assert.equal(composerProblem({ ...READY, connectionId: '' }, NOW)?.field, 'connection');
+ assert.equal(composerProblem({ ...READY, hasVideo: false }, NOW)?.field, 'video');
+ assert.equal(composerProblem({ ...READY, title: 'x'.repeat(101) }, NOW)?.field, 'title');
+ assert.equal(composerProblem({ ...READY, title: 'a <b>' }, NOW)?.field, 'title');
+ assert.equal(composerProblem({ ...READY, madeForKids: null }, NOW)?.field, 'madeForKids');
+ assert.equal(composerProblem({ ...READY, scheduled: true, publishAt: '2026-11-05T11:00' }, NOW)?.message, 'Pick a time in the future.');
+ assert.equal(composerProblem({ ...READY, scheduled: true, publishAt: '2026-11-06T11:00' }, NOW), null);
+});
+
+test('the sign-in return is read from the fragment, and errors from the query', () => {
+ assert.deepEqual(readYouTubeReturn('#yt_code=abc&yt_state=s1'), { code: 'abc', state: 's1' });
+ assert.equal(readYouTubeReturn('#ig_code=abc'), null);
+ assert.match(youtubeReturnError(new URLSearchParams('yt_error=access_denied')) ?? '', /cancelled/);
+ assert.match(youtubeReturnError(new URLSearchParams('yt_error=weird')) ?? '', /weird/);
+ assert.equal(youtubeReturnError(new URLSearchParams('')), null);
+});