Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(settings): split Settings and the scheduling guide into sections
spacesdrive2c54ce41f6c5
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex fd92fd0..d753712 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -85,8 +85,15 @@ frontend/src/│ │ ├── publishConstants.js <- Content types, statuses, intervals, caption limit│ │ └── publishHelpers.js, scheduleHelpers.js, queueHelpers.js <- Pure helpers with *.test.js│ ├── settings/-│ │ ├── Settings.jsx <- Theme, server keys, scheduling, platform requirements, links-│ │ └── SchedulingSetupGuide.jsx <- Optional GitHub backup scheduler steps for administrators+│ │ ├── Settings.jsx <- Page: loads server settings, then renders each section; keeps the #hash scroll+│ │ ├── SettingsSection.jsx, AppearanceSection.jsx, ServerKeysSection.jsx, SchedulingSection.jsx+│ │ ├── PlatformRequirementsSection.jsx, UsefulLinksSection.jsx+│ │ ├── SchedulingSetupGuide.jsx <- Optional GitHub backup scheduler steps for administrators+│ │ ├── SchedulingSetupSteps.jsx, SetupStep.jsx, GithubRepoForm.jsx, CopyChip.jsx, GuideLinkButton.jsx, RepoLinkButton.jsx+│ │ ├── useServerSettings.js <- Loads keys and the saved repository; saves the repository+│ │ ├── useApiHealthCheck.js <- Runs api.health() for the server keys section+│ │ ├── settingsData.js <- Pure load sequence (api injected), links, health text (settingsData.test.js)+│ │ └── schedulingProgress.js <- Pure guide progress in localStorage (schedulingProgress.test.js)│ ├── analytics/videos/│ │ ├── VideoExplorer.jsx <- Page: YouTube video library with filtering│ │ ├── VideoFilters.jsx, LayoutToggle.jsx, VideoListTable.jsx, VideoSortHeader.jsx, VideoGrid.jsxdiff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdindex a8afbdc..5d1ffd1 100644--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -109,7 +109,7 @@ frontend/src/accounts/AccountManager.jsx Add/remove/refresh accounts (page; dialog, cards, hooks and helpers beside it)settings/- Settings.jsx API keys status + GitHub config+ Settings.jsx API keys status + GitHub config (page; sections, setup guide, hooks and helpers beside it)```## Naming Conventionsdiff --git a/frontend/src/features/settings/AppearanceSection.jsx b/frontend/src/features/settings/AppearanceSection.jsxnew file mode 100644index 0000000..c9c363a--- /dev/null+++ b/frontend/src/features/settings/AppearanceSection.jsx@@ -0,0 +1,26 @@+import React from 'react';+import { Monitor, Moon, Sun } from 'lucide-react';+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';+import SurfaceBox from '@/components/SurfaceBox';+import { FieldRow } from '@/components/DetailPanel';+import { useSmoothTheme } from '@/hooks/use-smooth-theme';+import SettingsSection from './SettingsSection';++export default function AppearanceSection() {+ const { theme, setTheme } = useSmoothTheme();+ return (+ <SettingsSection id="appearance" title="Appearance" description="Choose a theme or follow your system setting.">+ <SurfaceBox>+ <FieldRow label="Theme" hint="Dusk is the dark theme, Paper the light one.">+ <Tabs value={theme ?? 'system'} onValueChange={setTheme}>+ <TabsList variant="segmented" className="w-full sm:w-fit">+ <TabsTrigger value="light"><Sun />Light</TabsTrigger>+ <TabsTrigger value="dark"><Moon />Dark</TabsTrigger>+ <TabsTrigger value="system"><Monitor />System</TabsTrigger>+ </TabsList>+ </Tabs>+ </FieldRow>+ </SurfaceBox>+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/CopyChip.jsx b/frontend/src/features/settings/CopyChip.jsxnew file mode 100644index 0000000..04c6781--- /dev/null+++ b/frontend/src/features/settings/CopyChip.jsx@@ -0,0 +1,28 @@+import React, { useState } from 'react';+import { Check, Copy } from 'lucide-react';++export default function CopyChip({ text }) {+ const [copied, setCopied] = useState(false);++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ setCopied(false);+ }+ };++ return (+ <button+ type="button"+ onClick={handleCopy}+ className="inline-flex h-7 items-center gap-1.5 rounded-control border border-line-control bg-surface px-2.5 font-mono text-small text-ink transition-colors hover:bg-surface-hover"+ aria-label={copied ? `${text} copied` : `Copy ${text}`}+ >+ {text}+ {copied ? <Check className="size-3.5 text-success" /> : <Copy className="size-3.5 text-ink-faint" />}+ </button>+ );+}diff --git a/frontend/src/features/settings/GithubRepoForm.jsx b/frontend/src/features/settings/GithubRepoForm.jsxnew file mode 100644index 0000000..98fbbfc--- /dev/null+++ b/frontend/src/features/settings/GithubRepoForm.jsx@@ -0,0 +1,28 @@+import React from 'react';+import { Save } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Spinner } from '@/components/ui/spinner';++export default function GithubRepoForm({ owner, repo, onOwnerChange, onRepoChange, onSave, saving, canSave }) {+ return (+ <form onSubmit={onSave} className="flex flex-col gap-2 rounded-field bg-surface-sunken/60 p-4">+ <label htmlFor="gh-user" className="text-sm font-medium text-ink">Your GitHub username</label>+ <p className="text-caption text-ink-faint">Type it once and every button below opens the right page in your GitHub.</p>+ <div className="flex flex-wrap gap-2">+ <Input id="gh-user" value={owner} onChange={e => onOwnerChange(e.target.value)} placeholder="your-github-username" autoComplete="off" className="max-w-xs flex-1 bg-surface-raised" />+ <Button type="submit" variant="outline" disabled={saving || !canSave}>+ {saving ? <Spinner className="size-4" /> : <Save data-icon="inline-start" />}+ Save+ </Button>+ </div>+ <details className="text-caption text-ink-faint">+ <summary className="cursor-pointer select-none">Renamed your copy?</summary>+ <div className="mt-2 flex items-center gap-2">+ <label htmlFor="gh-repo" className="shrink-0">Repository name</label>+ <Input id="gh-repo" value={repo} onChange={e => onRepoChange(e.target.value)} placeholder="twiligent" autoComplete="off" className="h-(--control-h-sm) max-w-48 bg-surface-raised" />+ </div>+ </details>+ </form>+ );+}diff --git a/frontend/src/features/settings/GuideLinkButton.jsx b/frontend/src/features/settings/GuideLinkButton.jsxnew file mode 100644index 0000000..dc284f8--- /dev/null+++ b/frontend/src/features/settings/GuideLinkButton.jsx@@ -0,0 +1,15 @@+import React from 'react';+import { ExternalLink } from 'lucide-react';+import { Button } from '@/components/ui/button';++export default function GuideLinkButton({ href, children, disabled, variant = 'outline' }) {+ if (disabled) {+ return <Button variant={variant} size="sm" disabled>{children}</Button>;+ }+ return (+ <Button variant={variant} size="sm" render={<a href={href} target="_blank" rel="noopener noreferrer" />}>+ {children}+ <ExternalLink data-icon="inline-end" />+ </Button>+ );+}diff --git a/frontend/src/features/settings/PlatformRequirementsSection.jsx b/frontend/src/features/settings/PlatformRequirementsSection.jsxnew file mode 100644index 0000000..49e9768--- /dev/null+++ b/frontend/src/features/settings/PlatformRequirementsSection.jsx@@ -0,0 +1,31 @@+import React from 'react';+import SurfaceBox from '@/components/SurfaceBox';+import InstagramTesterNotice from '@/components/InstagramTesterNotice';+import SettingsSection from './SettingsSection';++export default function PlatformRequirementsSection() {+ return (+ <SettingsSection id="platforms" title="Platform requirements" description="What each platform needs before it can be added.">+ <SurfaceBox content={false} className="divide-y divide-divider">+ <div className="flex flex-col gap-1 px-5 py-4">+ <p className="text-sm font-medium text-ink">YouTube</p>+ <p className="text-sm text-ink-muted">Add a channel link or @handle in Accounts. The API key is already set on the server.</p>+ </div>+ <div className="flex flex-col gap-2 px-5 py-4">+ <p className="text-sm font-medium text-ink">Instagram</p>+ <ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">+ <li>The account must be an Instagram Business or Creator account.</li>+ <li>Get tester access from the administrator and accept the invite (below).</li>+ <li>In Accounts, choose Add account, then Instagram account, then Continue to Instagram.</li>+ <li>Approve the requested permissions. Instagram sends you back here automatically.</li>+ </ol>+ <InstagramTesterNotice className="mt-2" />+ </div>+ <div className="flex flex-col gap-1 px-5 py-4">+ <p className="text-sm font-medium text-ink">Cloudinary</p>+ <p className="text-sm text-ink-muted">Instagram needs every file at a public URL before publishing. Cloudinary hosts uploads for that; its cloud name and upload preset are set on the server.</p>+ </div>+ </SurfaceBox>+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/RepoLinkButton.jsx b/frontend/src/features/settings/RepoLinkButton.jsxnew file mode 100644index 0000000..cb65b19--- /dev/null+++ b/frontend/src/features/settings/RepoLinkButton.jsx@@ -0,0 +1,11 @@+import React from 'react';+import GuideLinkButton from './GuideLinkButton';++// links into the user's own copy stay disabled until a GitHub username is entered+export default function RepoLinkButton({ base, path, label }) {+ return (+ <GuideLinkButton href={base ? `${base}${path}` : ''} disabled={!base}>+ {base ? label : 'Enter your GitHub username first'}+ </GuideLinkButton>+ );+}diff --git a/frontend/src/features/settings/SchedulingSection.jsx b/frontend/src/features/settings/SchedulingSection.jsxnew file mode 100644index 0000000..76fdcc7--- /dev/null+++ b/frontend/src/features/settings/SchedulingSection.jsx@@ -0,0 +1,78 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { ArrowRight, Clock, Server, Users } from 'lucide-react';+import SurfaceBox from '@/components/SurfaceBox';+import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';+import SettingsSection from './SettingsSection';+import SchedulingSetupGuide from './SchedulingSetupGuide';++const HOW_IT_WORKS = [+ { title: 'Schedule a post', body: 'In Publish, choose an account, the content type and the file, write the caption, pick Schedule, then a date and time, and choose Schedule post. The file uploads straight away.' },+ { title: 'The server publishes it', body: 'Within 15 minutes after the time you picked, the server publishes the post. Your browser can be closed and your computer can be off.' },+ { title: 'Keep the account connected', body: 'The post uses the Instagram account you picked. If that account is removed or its access expires before the time, the post fails and shows the reason under Publish, Scheduled posts. Refresh the account in Accounts if Instagram asks you to reconnect.' },+];++function Steps({ steps }) {+ return (+ <ol className="flex flex-col gap-4">+ {steps.map((step, i) => (+ <li key={step.title} className="flex gap-3">+ <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-surface-sunken font-mono text-caption font-medium text-ink-muted">{i + 1}</span>+ <div className="flex min-w-0 flex-1 flex-col gap-1 pt-0.5">+ <p className="text-sm font-medium text-ink">{step.title}</p>+ <div className="text-sm text-ink-muted [&_a]:font-medium [&_a]:text-brand-text [&_a]:underline-offset-4 [&_a:hover]:underline [&_strong]:font-semibold [&_strong]:text-ink">{step.body}</div>+ {step.extra}+ </div>+ </li>+ ))}+ </ol>+ );+}++export default function SchedulingSection({ github }) {+ const pendingStep = {+ title: 'If a post stays Pending',+ body: <>A post still Pending 30 minutes after its time means the scheduler on this server is not running. Email the administrator at <a href={adminMailto('Scheduled posts are not publishing on Twiligent')}>{ADMIN_EMAIL}</a> with the time of the post. You can edit or delete a Pending post at any time.</>,+ };++ return (+ <SettingsSection+ id="scheduling"+ title="Scheduled publishing"+ description="How scheduled Instagram posts go out, and who needs to set anything up."+ >+ <SurfaceBox title="Who needs to set this up">+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="flex flex-col gap-2 rounded-field border border-line p-4">+ <p className="flex items-center gap-2 text-sm font-semibold text-ink"><Users className="size-4 stroke-[1.75] text-ink-faint" />You sign in to this Twiligent</p>+ <p className="text-sm text-ink-muted">Nothing to set up. The server publishes your scheduled posts. You do not need GitHub, Supabase or any keys.</p>+ </div>+ <div className="flex flex-col gap-2 rounded-field border border-line p-4">+ <p className="flex items-center gap-2 text-sm font-semibold text-ink"><Server className="size-4 stroke-[1.75] text-ink-faint" />You run your own Twiligent</p>+ <p className="text-sm text-ink-muted">Deploying the backend is enough; scheduling starts with it. The GitHub backup below is optional.</p>+ <Link to="/docs/self-host" className="mt-auto inline-flex items-center gap-1 text-sm font-medium text-brand-text underline-offset-4 hover:underline">+ Self-hosting guide<ArrowRight className="size-3.5" />+ </Link>+ </div>+ </div>+ </SurfaceBox>++ <SurfaceBox title="How it works for you">+ <Steps steps={[...HOW_IT_WORKS, pendingStep]} />+ <div className="mt-5 flex flex-wrap items-center gap-3 rounded-control bg-surface-sunken/60 px-3 py-2.5 text-small text-ink-muted">+ <Clock className="size-4 shrink-0 stroke-[1.75] text-ink-faint" />+ Instagram allows up to 100 posts per account in any 24 hours, including scheduled ones.+ </div>+ </SurfaceBox>++ <SchedulingSetupGuide+ owner={github.owner}+ repo={github.repo}+ onOwnerChange={github.setOwner}+ onRepoChange={github.setRepo}+ onSave={github.handleSave}+ saving={github.saving}+ />+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/SchedulingSetupGuide.jsx b/frontend/src/features/settings/SchedulingSetupGuide.jsxindex d717668..259339d 100644--- a/frontend/src/features/settings/SchedulingSetupGuide.jsx+++ b/frontend/src/features/settings/SchedulingSetupGuide.jsx@@ -1,100 +1,38 @@import React, { useEffect, useState } from 'react';import { Link } from 'react-router-dom';-import { GitFork, KeyRound, Lock, Power, PlayCircle, Check, Copy, ExternalLink, Save, ChevronDown, BookOpen } from 'lucide-react';+import { BookOpen, ChevronDown } from 'lucide-react';import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Spinner } from '@/components/ui/spinner';import SurfaceBox from '@/components/SurfaceBox';import { cn } from '@/lib/utils';+import { browserStorage, completedSteps, readProgress, repoBaseUrl, saveProgress } from './schedulingProgress';+import GithubRepoForm from './GithubRepoForm';+import SchedulingSetupSteps from './SchedulingSetupSteps';-const UPSTREAM_REPO = 'spacesdrive/twiligent';-const SUPABASE_KEYS_URL = 'https://supabase.com/dashboard/project/_/settings/api-keys';-const SUPABASE_URL_PAGE = 'https://supabase.com/dashboard/project/_/integrations/data_api/overview';-const PROGRESS_KEY = 'twiligent.schedulingSetup.done';--function readProgress() {- try { return JSON.parse(localStorage.getItem(PROGRESS_KEY)) || {}; } catch { return {}; }-}--function CopyChip({ text }) {- const [copied, setCopied] = useState(false);+function SetupNotes() {return (- <button- type="button"- onClick={async () => {- try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch { setCopied(false); }- }}- className="inline-flex h-7 items-center gap-1.5 rounded-control border border-line-control bg-surface px-2.5 font-mono text-small text-ink transition-colors hover:bg-surface-hover"- aria-label={copied ? `${text} copied` : `Copy ${text}`}- >- {text}- {copied ? <Check className="size-3.5 text-success" /> : <Copy className="size-3.5 text-ink-faint" />}- </button>- );-}--function LinkButton({ href, children, disabled, variant = 'outline' }) {- if (disabled) {- return <Button variant={variant} size="sm" disabled>{children}</Button>;- }- return (- <Button variant={variant} size="sm" render={<a href={href} target="_blank" rel="noopener noreferrer" />}>- {children}- <ExternalLink data-icon="inline-end" />- </Button>- );-}--function Step({ number, icon, title, done, onToggle, children, check }) {- const Icon = icon;- return (- <li className={cn('flex gap-4 rounded-card border p-4 transition-colors', done ? 'border-success/30 bg-success-soft/40' : 'border-line')}>- <div className="flex flex-col items-center gap-2">- <span className={cn(- 'flex size-9 shrink-0 items-center justify-center rounded-full',- done ? 'bg-success text-ink-inverse' : 'bg-surface-sunken text-ink-muted',- )}>- {done ? <Check className="size-4" strokeWidth={2.5} /> : <Icon className="size-4 stroke-[1.75]" />}- </span>- </div>- <div className="flex min-w-0 flex-1 flex-col gap-3">- <div className="flex flex-wrap items-start justify-between gap-2">- <p className="text-sm font-semibold text-ink"><span className="text-ink-faint">Step {number}. </span>{title}</p>- <label className="flex cursor-pointer items-center gap-2 text-small text-ink-muted select-none">- <input type="checkbox" checked={done} onChange={onToggle} className="size-4 accent-[var(--brand)]" />- Done- </label>- </div>- <div className="flex flex-col gap-3 text-sm text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{children}</div>- {check && (- <p className="flex items-start gap-1.5 text-small text-success">- <Check className="mt-0.5 size-3.5 shrink-0" />- <span><span className="font-semibold">It worked if</span> {check}</span>- </p>- )}- </div>- </li>+ <div className="flex flex-col gap-2 rounded-field border border-line p-4">+ <p className="text-sm font-semibold text-ink">That is it</p>+ <p className="text-sm text-ink-muted">GitHub now checks every 15 minutes. You do not need to keep anything open. Two things to know:</p>+ <ul className="flex list-disc flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">+ <li>If nothing changes in your copy for 60 days, GitHub pauses the schedule and emails you. Repeat step 4 to switch it back on.</li>+ <li>If you made your copy private, GitHub's free minutes run out. Keep it public, or change the schedule in <code className="font-mono text-small text-ink">.github/workflows/publish-scheduled.yml</code> to every 30 minutes.</li>+ </ul>+ </div>);}export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRepoChange, onSave, saving }) {- const [done, setDone] = useState(readProgress);+ const [done, setDone] = useState(() => readProgress(browserStorage));useEffect(() => {- try {- localStorage.setItem(PROGRESS_KEY, JSON.stringify(done));- } catch {- // saved progress is a convenience, the guide works without it- return;- }+ saveProgress(browserStorage, done);}, [done]);const toggle = key => () => setDone(prev => ({ ...prev, [key]: !prev[key] }));const user = owner.trim();- const name = (repo || 'twiligent').trim();- const base = user ? `https://github.com/${user}/${name}` : null;- const completed = ['fork', 'supabase', 'secrets', 'enable', 'test'].filter(k => done[k]).length;- // Members never need these steps, so the guide stays folded unless someone has already started it.+ const base = repoBaseUrl(owner, repo);+ const completed = completedSteps(done);+ // members never need these steps, so the guide stays folded unless someone has already started itconst [open, setOpen] = useState(() => completed > 0 || Boolean(user));return (@@ -102,7 +40,7 @@ export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onReptitle="Backup scheduler on GitHub"subheader="Optional, for administrators running their own Twiligent. About 5 minutes."secondary={(- <Button variant="ghost" size="sm" onClick={() => setOpen(o => !o)} aria-expanded={open} aria-controls="gh-guide-steps">+ <Button variant="ghost" size="sm" onClick={() => setOpen(isOpen => !isOpen)} aria-expanded={open} aria-controls="gh-guide-steps">{open ? 'Hide steps' : 'Show steps'}<ChevronDown data-icon="inline-end" className={cn('transition-transform duration-(--duration-base)', open && 'rotate-180')} /></Button>@@ -121,108 +59,19 @@ export default function SchedulingSetupGuide({ owner, repo, onOwnerChange, onRep</div>{open && (- <div id="gh-guide-steps" className="flex flex-col gap-5">-- <form onSubmit={onSave} className="flex flex-col gap-2 rounded-field bg-surface-sunken/60 p-4">- <label htmlFor="gh-user" className="text-sm font-medium text-ink">Your GitHub username</label>- <p className="text-caption text-ink-faint">Type it once and every button below opens the right page in your GitHub.</p>- <div className="flex flex-wrap gap-2">- <Input id="gh-user" value={owner} onChange={e => onOwnerChange(e.target.value)} placeholder="your-github-username" autoComplete="off" className="max-w-xs flex-1 bg-surface-raised" />- <Button type="submit" variant="outline" disabled={saving || !user}>- {saving ? <Spinner className="size-4" /> : <Save data-icon="inline-start" />}- Save- </Button>+ <div id="gh-guide-steps" className="flex flex-col gap-5">+ <GithubRepoForm+ owner={owner}+ repo={repo}+ onOwnerChange={onOwnerChange}+ onRepoChange={onRepoChange}+ onSave={onSave}+ saving={saving}+ canSave={Boolean(user)}+ />+ <SchedulingSetupSteps done={done} toggle={toggle} base={base} />+ <SetupNotes /></div>- <details className="text-caption text-ink-faint">- <summary className="cursor-pointer select-none">Renamed your copy?</summary>- <div className="mt-2 flex items-center gap-2">- <label htmlFor="gh-repo" className="shrink-0">Repository name</label>- <Input id="gh-repo" value={repo} onChange={e => onRepoChange(e.target.value)} placeholder="twiligent" autoComplete="off" className="h-(--control-h-sm) max-w-48 bg-surface-raised" />- </div>- </details>- </form>-- <ol className="flex flex-col gap-3">- <Step- number={1}- icon={GitFork}- title="Make your own copy of Twiligent on GitHub"- done={!!done.fork}- onToggle={toggle('fork')}- check="you see the twiligent repository under your own GitHub username."- >- <p>Open the Twiligent repository and choose <strong>Fork</strong>, then <strong>Create fork</strong>. Keep it public: GitHub runs public repositories for free.</p>- <div><LinkButton href={`https://github.com/${UPSTREAM_REPO}/fork`}>Fork on GitHub</LinkButton></div>- </Step>-- <Step- number={2}- icon={KeyRound}- title="Copy two values from Supabase"- done={!!done.supabase}- onToggle={toggle('supabase')}- check="you have the project URL and the secret key ready to paste."- >- <p><strong>Project URL.</strong> In Supabase, open your project, then <strong>Integrations, Data API</strong>. It looks like <code className="font-mono text-small text-ink">https://abcdefgh.supabase.co</code>.</p>- <p><strong>Secret key.</strong> Open <strong>Settings, API Keys</strong> and copy a secret key (it starts with <code className="font-mono text-small text-ink">sb_secret_</code>). If your project only shows legacy keys, copy <strong>service_role</strong> instead.</p>- <p className="flex items-start gap-1.5 text-small text-warning"><Lock className="mt-0.5 size-3.5 shrink-0" />The secret key can read and change all your data. Paste it only into GitHub secrets in the next step, never into code, chat or email.</p>- <div className="flex flex-wrap gap-2">- <LinkButton href={SUPABASE_URL_PAGE}>Open Data API</LinkButton>- <LinkButton href={SUPABASE_KEYS_URL}>Open API Keys</LinkButton>- </div>- </Step>-- <Step- number={3}- icon={Lock}- title="Save the two values as secrets in your copy"- done={!!done.secrets}- onToggle={toggle('secrets')}- check="both names appear in the Repository secrets list."- >- <p>On the secrets page choose <strong>New repository secret</strong>. Type the name exactly as shown, paste the value, and choose <strong>Add secret</strong>. Do it twice:</p>- <div className="flex flex-col gap-2">- <div className="flex flex-wrap items-center gap-2"><CopyChip text="SUPABASE_URL" /><span className="text-small">with the project URL</span></div>- <div className="flex flex-wrap items-center gap-2"><CopyChip text="SUPABASE_SERVICE_KEY" /><span className="text-small">with the secret key</span></div>- </div>- <div><LinkButton href={base ? `${base}/settings/secrets/actions` : ''} disabled={!base}>{base ? 'Open secrets page' : 'Enter your GitHub username first'}</LinkButton></div>- </Step>-- <Step- number={4}- icon={Power}- title="Switch on the publisher"- done={!!done.enable}- onToggle={toggle('enable')}- check="Instagram Scheduled Publisher is listed on the left with no disabled warning."- >- <p>GitHub switches workflows off in new copies. Open the <strong>Actions</strong> tab and choose <strong>I understand my workflows, go ahead and enable them</strong>. Then choose <strong>Instagram Scheduled Publisher</strong> in the list on the left, and if a yellow banner says it is disabled, choose <strong>Enable workflow</strong>.</p>- <div><LinkButton href={base ? `${base}/actions` : ''} disabled={!base}>{base ? 'Open Actions' : 'Enter your GitHub username first'}</LinkButton></div>- </Step>-- <Step- number={5}- icon={PlayCircle}- title="Run it once to test"- done={!!done.test}- onToggle={toggle('test')}- check="the run shows a green tick after about a minute. The log saying “No posts due for publishing” is fine."- >- <p>On the publisher page choose <strong>Run workflow</strong>, then the green <strong>Run workflow</strong> button. Refresh the page after a few seconds and open the new run.</p>- <p>A red cross with <strong>Missing SUPABASE_URL or SUPABASE_SERVICE_KEY</strong> means a secret name is misspelled; fix it in step 3. Any other red cross usually means the secret key was pasted incompletely.</p>- <div><LinkButton href={base ? `${base}/actions/workflows/publish-scheduled.yml` : ''} disabled={!base}>{base ? 'Open the publisher' : 'Enter your GitHub username first'}</LinkButton></div>- </Step>- </ol>-- <div className="flex flex-col gap-2 rounded-field border border-line p-4">- <p className="text-sm font-semibold text-ink">That is it</p>- <p className="text-sm text-ink-muted">GitHub now checks every 15 minutes. You do not need to keep anything open. Two things to know:</p>- <ul className="flex list-disc flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">- <li>If nothing changes in your copy for 60 days, GitHub pauses the schedule and emails you. Repeat step 4 to switch it back on.</li>- <li>If you made your copy private, GitHub's free minutes run out. Keep it public, or change the schedule in <code className="font-mono text-small text-ink">.github/workflows/publish-scheduled.yml</code> to every 30 minutes.</li>- </ul>- </div>- </div>)}</div></SurfaceBox>diff --git a/frontend/src/features/settings/SchedulingSetupSteps.jsx b/frontend/src/features/settings/SchedulingSetupSteps.jsxnew file mode 100644index 0000000..a543c7d--- /dev/null+++ b/frontend/src/features/settings/SchedulingSetupSteps.jsx@@ -0,0 +1,86 @@+import React from 'react';+import { GitFork, KeyRound, Lock, PlayCircle, Power } from 'lucide-react';+import CopyChip from './CopyChip';+import GuideLinkButton from './GuideLinkButton';+import RepoLinkButton from './RepoLinkButton';+import SetupStep from './SetupStep';++const UPSTREAM_REPO = 'spacesdrive/twiligent';+const SUPABASE_KEYS_URL = 'https://supabase.com/dashboard/project/_/settings/api-keys';+const SUPABASE_URL_PAGE = 'https://supabase.com/dashboard/project/_/integrations/data_api/overview';++export default function SchedulingSetupSteps({ done, toggle, base }) {+ return (+ <ol className="flex flex-col gap-3">+ <SetupStep+ number={1}+ icon={GitFork}+ title="Make your own copy of Twiligent on GitHub"+ done={!!done.fork}+ onToggle={toggle('fork')}+ check="you see the twiligent repository under your own GitHub username."+ >+ <p>Open the Twiligent repository and choose <strong>Fork</strong>, then <strong>Create fork</strong>. Keep it public: GitHub runs public repositories for free.</p>+ <div><GuideLinkButton href={`https://github.com/${UPSTREAM_REPO}/fork`}>Fork on GitHub</GuideLinkButton></div>+ </SetupStep>++ <SetupStep+ number={2}+ icon={KeyRound}+ title="Copy two values from Supabase"+ done={!!done.supabase}+ onToggle={toggle('supabase')}+ check="you have the project URL and the secret key ready to paste."+ >+ <p><strong>Project URL.</strong> In Supabase, open your project, then <strong>Integrations, Data API</strong>. It looks like <code className="font-mono text-small text-ink">https://abcdefgh.supabase.co</code>.</p>+ <p><strong>Secret key.</strong> Open <strong>Settings, API Keys</strong> and copy a secret key (it starts with <code className="font-mono text-small text-ink">sb_secret_</code>). If your project only shows legacy keys, copy <strong>service_role</strong> instead.</p>+ <p className="flex items-start gap-1.5 text-small text-warning"><Lock className="mt-0.5 size-3.5 shrink-0" />The secret key can read and change all your data. Paste it only into GitHub secrets in the next step, never into code, chat or email.</p>+ <div className="flex flex-wrap gap-2">+ <GuideLinkButton href={SUPABASE_URL_PAGE}>Open Data API</GuideLinkButton>+ <GuideLinkButton href={SUPABASE_KEYS_URL}>Open API Keys</GuideLinkButton>+ </div>+ </SetupStep>++ <SetupStep+ number={3}+ icon={Lock}+ title="Save the two values as secrets in your copy"+ done={!!done.secrets}+ onToggle={toggle('secrets')}+ check="both names appear in the Repository secrets list."+ >+ <p>On the secrets page choose <strong>New repository secret</strong>. Type the name exactly as shown, paste the value, and choose <strong>Add secret</strong>. Do it twice:</p>+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2"><CopyChip text="SUPABASE_URL" /><span className="text-small">with the project URL</span></div>+ <div className="flex flex-wrap items-center gap-2"><CopyChip text="SUPABASE_SERVICE_KEY" /><span className="text-small">with the secret key</span></div>+ </div>+ <div><RepoLinkButton base={base} path="/settings/secrets/actions" label="Open secrets page" /></div>+ </SetupStep>++ <SetupStep+ number={4}+ icon={Power}+ title="Switch on the publisher"+ done={!!done.enable}+ onToggle={toggle('enable')}+ check="Instagram Scheduled Publisher is listed on the left with no disabled warning."+ >+ <p>GitHub switches workflows off in new copies. Open the <strong>Actions</strong> tab and choose <strong>I understand my workflows, go ahead and enable them</strong>. Then choose <strong>Instagram Scheduled Publisher</strong> in the list on the left, and if a yellow banner says it is disabled, choose <strong>Enable workflow</strong>.</p>+ <div><RepoLinkButton base={base} path="/actions" label="Open Actions" /></div>+ </SetupStep>++ <SetupStep+ number={5}+ icon={PlayCircle}+ title="Run it once to test"+ done={!!done.test}+ onToggle={toggle('test')}+ check="the run shows a green tick after about a minute. The log saying “No posts due for publishing” is fine."+ >+ <p>On the publisher page choose <strong>Run workflow</strong>, then the green <strong>Run workflow</strong> button. Refresh the page after a few seconds and open the new run.</p>+ <p>A red cross with <strong>Missing SUPABASE_URL or SUPABASE_SERVICE_KEY</strong> means a secret name is misspelled; fix it in step 3. Any other red cross usually means the secret key was pasted incompletely.</p>+ <div><RepoLinkButton base={base} path="/actions/workflows/publish-scheduled.yml" label="Open the publisher" /></div>+ </SetupStep>+ </ol>+ );+}diff --git a/frontend/src/features/settings/ServerKeysSection.jsx b/frontend/src/features/settings/ServerKeysSection.jsxnew file mode 100644index 0000000..8824821--- /dev/null+++ b/frontend/src/features/settings/ServerKeysSection.jsx@@ -0,0 +1,59 @@+import React from 'react';+import { Activity, AlertTriangle, CheckCircle2, RefreshCw } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Alert, AlertDescription } from '@/components/ui/alert';+import { Badge } from '@/components/ui/badge';+import { Spinner } from '@/components/ui/spinner';+import SurfaceBox from '@/components/SurfaceBox';+import { cn } from '@/lib/utils';+import SettingsSection from './SettingsSection';+import { useApiHealthCheck } from './useApiHealthCheck';++function StatusRow({ label, ok, hint }) {+ return (+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div className="min-w-0">+ <p className="text-sm font-medium text-ink">{label}</p>+ {hint && <p className="text-caption text-ink-faint">{hint}</p>}+ </div>+ {ok ? (+ <Badge variant="success"><CheckCircle2 />Configured</Badge>+ ) : (+ <Badge variant="warning"><AlertTriangle />Not set</Badge>+ )}+ </div>+ );+}++export default function ServerKeysSection({ serverStatus, refreshAll, refreshingAll }) {+ const { testing, testResult, handleTest } = useApiHealthCheck();+ return (+ <SettingsSection+ id="server-keys"+ title="Server API keys"+ description="YouTube, Instagram and Cloudinary credentials are environment variables on the server, shared by everyone on this instance."+ >+ <SurfaceBox content={false} className="divide-y divide-divider">+ <StatusRow label="YouTube" hint="Channel and video analytics" ok={serverStatus?.youtube?.configured} />+ <StatusRow label="Instagram" hint="Account connection and publishing" ok={serverStatus?.instagram?.configured} />+ <StatusRow label="Cloudinary" hint="Media hosting for publishing" ok={serverStatus?.cloudinary?.configured} />+ </SurfaceBox>+ <div className="flex flex-wrap items-center gap-2">+ <Button variant="outline" onClick={handleTest} disabled={testing}>+ {testing ? <Spinner className="size-4" /> : <Activity data-icon="inline-start" />}+ {testing ? 'Checking API' : 'Check API health'}+ </Button>+ <Button variant="outline" onClick={refreshAll} disabled={refreshingAll}>+ <RefreshCw data-icon="inline-start" className={cn(refreshingAll && 'animate-spin')} />+ {refreshingAll ? 'Refreshing accounts' : 'Refresh all accounts'}+ </Button>+ </div>+ {testResult && (+ <Alert variant={testResult.success ? 'success' : 'destructive'}>+ {testResult.success ? <CheckCircle2 /> : <AlertTriangle />}+ <AlertDescription>{testResult.success ? '' : 'Error: '}{testResult.message}</AlertDescription>+ </Alert>+ )}+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/Settings.jsx b/frontend/src/features/settings/Settings.jsxindex 4784f85..1dcd74c 100644--- a/frontend/src/features/settings/Settings.jsx+++ b/frontend/src/features/settings/Settings.jsx@@ -1,158 +1,28 @@-import React, { useEffect, useState } from 'react';-import { useSmoothTheme } from '@/hooks/use-smooth-theme';-import { Link, useLocation } from 'react-router-dom';-import {- RefreshCw, CheckCircle2, AlertTriangle, ExternalLink, Sun, Moon, Monitor, Activity, Clock, Users, Server, BookOpen, ArrowRight,-} from 'lucide-react';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Alert, AlertDescription } from '@/components/ui/alert';-import { Badge } from '@/components/ui/badge';+import React, { useEffect } from 'react';+import { useLocation } from 'react-router-dom';import { Skeleton } from '@/components/ui/skeleton';-import { Spinner } from '@/components/ui/spinner';-import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import PageHeader from '@/components/PageHeader';-import SurfaceBox from '@/components/SurfaceBox';-import { FieldRow } from '@/components/DetailPanel';-import InstagramTesterNotice from '@/components/InstagramTesterNotice';-import SchedulingSetupGuide from './SchedulingSetupGuide';-import { ADMIN_EMAIL, adminMailto } from '@/lib/contact';import { useAppContext } from '../../context/AppContext';-import { api } from '../../services/api';-import { cn } from '@/lib/utils';--const DOC_LINKS = [- { label: 'Using Twiligent', to: '/docs/use/getting-started' },- { label: 'Run your own Twiligent', to: '/docs/self-host' },- { label: 'Environment variables', to: '/docs/reference/environment' },-];--const LINKS = [- { label: 'Supabase API keys', href: 'https://supabase.com/dashboard/project/_/settings/api-keys' },- { label: 'Cloudinary console', href: 'https://cloudinary.com/console' },- { label: 'Google Cloud credentials', href: 'https://console.cloud.google.com/apis/credentials' },- { label: 'Meta app dashboard', href: 'https://developers.facebook.com/apps' },- { label: 'Cloudflare dashboard', href: 'https://dash.cloudflare.com' },-];--function Steps({ steps }) {- return (- <ol className="flex flex-col gap-4">- {steps.map((step, i) => (- <li key={step.title} className="flex gap-3">- <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-surface-sunken font-mono text-caption font-medium text-ink-muted">{i + 1}</span>- <div className="flex min-w-0 flex-1 flex-col gap-1 pt-0.5">- <p className="text-sm font-medium text-ink">{step.title}</p>- <div className="text-sm text-ink-muted [&_a]:font-medium [&_a]:text-brand-text [&_a]:underline-offset-4 [&_a:hover]:underline [&_strong]:font-semibold [&_strong]:text-ink">{step.body}</div>- {step.extra}- </div>- </li>- ))}- </ol>- );-}--function SettingsSection({ id, title, description, children }) {- return (- <section id={id} aria-labelledby={`${id}-title`} className="grid scroll-mt-20 grid-cols-1 gap-4 border-t border-line pt-8 first:border-t-0 first:pt-0 lg:grid-cols-[16rem_1fr] lg:gap-10">- <div className="flex flex-col gap-1">- <h2 id={`${id}-title`} className="font-heading text-section font-semibold text-ink">{title}</h2>- {description && <p className="text-small text-ink-muted">{description}</p>}- </div>- <div className="flex min-w-0 flex-col gap-4">{children}</div>- </section>- );-}--function StatusRow({ label, ok, hint }) {- return (- <div className="flex items-center justify-between gap-4 px-4 py-3">- <div className="min-w-0">- <p className="text-sm font-medium text-ink">{label}</p>- {hint && <p className="text-caption text-ink-faint">{hint}</p>}- </div>- {ok ? (- <Badge variant="success"><CheckCircle2 />Configured</Badge>- ) : (- <Badge variant="warning"><AlertTriangle />Not set</Badge>- )}- </div>- );-}+import { useServerSettings } from './useServerSettings';+import SettingsSection from './SettingsSection';+import AppearanceSection from './AppearanceSection';+import ServerKeysSection from './ServerKeysSection';+import SchedulingSection from './SchedulingSection';+import PlatformRequirementsSection from './PlatformRequirementsSection';+import UsefulLinksSection from './UsefulLinksSection';export default function Settings() {const { showToast, refreshAll, loading: refreshingAll } = useAppContext();- const { theme, setTheme } = useSmoothTheme();-- const [serverStatus, setServerStatus] = useState(null);- const [testing, setTesting] = useState(false);- const [testResult, setTestResult] = useState(null);- const [loading, setLoading] = useState(true);-+ const { serverStatus, loading, github } = useServerSettings(showToast);const location = useLocation();- const [ghRepoOwner, setGhRepoOwner] = useState('');- const [ghRepoName, setGhRepoName] = useState('');- const [ghSaving, setGhSaving] = useState(false);- useEffect(() => {- let cancelled = false;- (async () => {- try {- const [keys, gh] = await Promise.all([api.getKeys(), api.getGithubSettings()]);- if (cancelled) return;- setServerStatus(keys);- setGhRepoOwner(gh.repoOwner || '');- setGhRepoName(gh.repoName || '');- } catch {- try {- const keys = await api.getKeys();- if (!cancelled) setServerStatus(keys);- } catch {- // status is informational, the page still renders- return;- }- } finally {- if (!cancelled) setLoading(false);- }- })();- return () => { cancelled = true; };- }, []);-- // Links such as /settings#scheduling jump to their section once the page has loaded+ // links such as /settings#scheduling jump to their section once the page has loadeduseEffect(() => {if (loading || !location.hash) return;document.getElementById(location.hash.slice(1))?.scrollIntoView({ block: 'start' });}, [loading, location.hash]);- // Only the repository is kept: it fills in the direct links in the setup guide. No token is needed.- const handleSaveGithub = async e => {- e.preventDefault();- setGhSaving(true);- try {- await api.saveGithubSettings({ repoOwner: ghRepoOwner.trim(), repoName: (ghRepoName || 'twiligent').trim(), branch: 'main' });- showToast('GitHub username saved. The buttons in the guide now open your copy.');- } catch (err) {- showToast(`Couldn't save the repository. ${err.message}`, 'error');- } finally {- setGhSaving(false);- }- };-- const handleTest = async () => {- setTesting(true);- setTestResult(null);- try {- const res = await api.health();- setTestResult(res.status === 'ok'- ? { success: true, message: 'The API is reachable and healthy.' }- : { success: false, message: `The API answered with status "${res.status}". Check the Worker logs.` });- } catch (err) {- setTestResult({ success: false, message: `The API could not be reached: ${err.message}. Check VITE_API_URL and that the Worker is deployed.` });- } finally {- setTesting(false);- }- };-+ // the setup guide decides once, at mount, whether to start open, so it mounts after loadingif (loading) {return (<div className="flex flex-col gap-8">@@ -167,145 +37,11 @@ export default function Settings() {<PageHeader title="Settings" description="Appearance, connections and setup guides" /><div className="flex flex-col gap-8">- <SettingsSection id="appearance" title="Appearance" description="Choose a theme or follow your system setting.">- <SurfaceBox>- <FieldRow label="Theme" hint="Dusk is the dark theme, Paper the light one.">- <Tabs value={theme ?? 'system'} onValueChange={setTheme}>- <TabsList variant="segmented" className="w-full sm:w-fit">- <TabsTrigger value="light"><Sun />Light</TabsTrigger>- <TabsTrigger value="dark"><Moon />Dark</TabsTrigger>- <TabsTrigger value="system"><Monitor />System</TabsTrigger>- </TabsList>- </Tabs>- </FieldRow>- </SurfaceBox>- </SettingsSection>-- <SettingsSection- id="server-keys"- title="Server API keys"- description="YouTube, Instagram and Cloudinary credentials are environment variables on the server, shared by everyone on this instance."- >- <SurfaceBox content={false} className="divide-y divide-divider">- <StatusRow label="YouTube" hint="Channel and video analytics" ok={serverStatus?.youtube?.configured} />- <StatusRow label="Instagram" hint="Account connection and publishing" ok={serverStatus?.instagram?.configured} />- <StatusRow label="Cloudinary" hint="Media hosting for publishing" ok={serverStatus?.cloudinary?.configured} />- </SurfaceBox>- <div className="flex flex-wrap items-center gap-2">- <Button variant="outline" onClick={handleTest} disabled={testing}>- {testing ? <Spinner className="size-4" /> : <Activity data-icon="inline-start" />}- {testing ? 'Checking API' : 'Check API health'}- </Button>- <Button variant="outline" onClick={refreshAll} disabled={refreshingAll}>- <RefreshCw data-icon="inline-start" className={cn(refreshingAll && 'animate-spin')} />- {refreshingAll ? 'Refreshing accounts' : 'Refresh all accounts'}- </Button>- </div>- {testResult && (- <Alert variant={testResult.success ? 'success' : 'destructive'}>- {testResult.success ? <CheckCircle2 /> : <AlertTriangle />}- <AlertDescription>{testResult.success ? '' : 'Error: '}{testResult.message}</AlertDescription>- </Alert>- )}- </SettingsSection>-- <SettingsSection- id="scheduling"- title="Scheduled publishing"- description="How scheduled Instagram posts go out, and who needs to set anything up."- >- <SurfaceBox title="Who needs to set this up">- <div className="grid gap-3 sm:grid-cols-2">- <div className="flex flex-col gap-2 rounded-field border border-line p-4">- <p className="flex items-center gap-2 text-sm font-semibold text-ink"><Users className="size-4 stroke-[1.75] text-ink-faint" />You sign in to this Twiligent</p>- <p className="text-sm text-ink-muted">Nothing to set up. The server publishes your scheduled posts. You do not need GitHub, Supabase or any keys.</p>- </div>- <div className="flex flex-col gap-2 rounded-field border border-line p-4">- <p className="flex items-center gap-2 text-sm font-semibold text-ink"><Server className="size-4 stroke-[1.75] text-ink-faint" />You run your own Twiligent</p>- <p className="text-sm text-ink-muted">Deploying the backend is enough; scheduling starts with it. The GitHub backup below is optional.</p>- <Link to="/docs/self-host" className="mt-auto inline-flex items-center gap-1 text-sm font-medium text-brand-text underline-offset-4 hover:underline">- Self-hosting guide<ArrowRight className="size-3.5" />- </Link>- </div>- </div>- </SurfaceBox>-- <SurfaceBox title="How it works for you">- <Steps steps={[- { title: 'Schedule a post', body: 'In Publish, choose an account, the content type and the file, write the caption, pick Schedule, then a date and time, and choose Schedule post. The file uploads straight away.' },- { title: 'The server publishes it', body: 'Within 15 minutes after the time you picked, the server publishes the post. Your browser can be closed and your computer can be off.' },- { title: 'Keep the account connected', body: 'The post uses the Instagram account you picked. If that account is removed or its access expires before the time, the post fails and shows the reason under Publish, Scheduled posts. Refresh the account in Accounts if Instagram asks you to reconnect.' },- {- title: 'If a post stays Pending',- body: <>A post still Pending 30 minutes after its time means the scheduler on this server is not running. Email the administrator at <a href={adminMailto('Scheduled posts are not publishing on Twiligent')}>{ADMIN_EMAIL}</a> with the time of the post. You can edit or delete a Pending post at any time.</>,- },- ]} />- <div className="mt-5 flex flex-wrap items-center gap-3 rounded-control bg-surface-sunken/60 px-3 py-2.5 text-small text-ink-muted">- <Clock className="size-4 shrink-0 stroke-[1.75] text-ink-faint" />- Instagram allows up to 100 posts per account in any 24 hours, including scheduled ones.- </div>- </SurfaceBox>-- <SchedulingSetupGuide- owner={ghRepoOwner}- repo={ghRepoName}- onOwnerChange={setGhRepoOwner}- onRepoChange={setGhRepoName}- onSave={handleSaveGithub}- saving={ghSaving}- />- </SettingsSection>-- <SettingsSection id="platforms" title="Platform requirements" description="What each platform needs before it can be added.">- <SurfaceBox content={false} className="divide-y divide-divider">- <div className="flex flex-col gap-1 px-5 py-4">- <p className="text-sm font-medium text-ink">YouTube</p>- <p className="text-sm text-ink-muted">Add a channel link or @handle in Accounts. The API key is already set on the server.</p>- </div>- <div className="flex flex-col gap-2 px-5 py-4">- <p className="text-sm font-medium text-ink">Instagram</p>- <ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-ink-muted marker:text-ink-faint">- <li>The account must be an Instagram Business or Creator account.</li>- <li>Get tester access from the administrator and accept the invite (below).</li>- <li>In Accounts, choose Add account, then Instagram account, then Continue to Instagram.</li>- <li>Approve the requested permissions. Instagram sends you back here automatically.</li>- </ol>- <InstagramTesterNotice className="mt-2" />- </div>- <div className="flex flex-col gap-1 px-5 py-4">- <p className="text-sm font-medium text-ink">Cloudinary</p>- <p className="text-sm text-ink-muted">Instagram needs every file at a public URL before publishing. Cloudinary hosts uploads for that; its cloud name and upload preset are set on the server.</p>- </div>- </SurfaceBox>- </SettingsSection>-- <SettingsSection id="links" title="Useful links">- <SurfaceBox content={false} className="divide-y divide-divider">- {DOC_LINKS.map(({ label, to }) => (- <Link- key={label}- to={to}- className="flex items-center justify-between gap-2 px-5 py-3 text-sm text-ink transition-colors duration-(--duration-fast) hover:bg-surface-hover"- >- <span className="flex items-center gap-2"><BookOpen className="size-4 shrink-0 stroke-[1.75] text-ink-faint" />{label}</span>- <ArrowRight className="size-4 shrink-0 text-ink-faint" />- </Link>- ))}- {LINKS.map(({ label, href }) => (- <a- key={label}- href={href}- target="_blank"- rel="noreferrer"- className="flex items-center justify-between gap-2 px-5 py-3 text-sm text-ink transition-colors duration-(--duration-fast) hover:bg-surface-hover"- >- {label}- <ExternalLink className="size-4 shrink-0 text-ink-faint" />- </a>- ))}- </SurfaceBox>- </SettingsSection>-+ <AppearanceSection />+ <ServerKeysSection serverStatus={serverStatus} refreshAll={refreshAll} refreshingAll={refreshingAll} />+ <SchedulingSection github={github} />+ <PlatformRequirementsSection />+ <UsefulLinksSection /><SettingsSection id="about" title="About Twiligent" description="Analytics and publishing for YouTube, Instagram and Reddit, run on your own infrastructure." /></div></div>diff --git a/frontend/src/features/settings/SettingsSection.jsx b/frontend/src/features/settings/SettingsSection.jsxnew file mode 100644index 0000000..f9948b4--- /dev/null+++ b/frontend/src/features/settings/SettingsSection.jsx@@ -0,0 +1,13 @@+import React from 'react';++export default function SettingsSection({ id, title, description, children }) {+ return (+ <section id={id} aria-labelledby={`${id}-title`} className="grid scroll-mt-20 grid-cols-1 gap-4 border-t border-line pt-8 first:border-t-0 first:pt-0 lg:grid-cols-[16rem_1fr] lg:gap-10">+ <div className="flex flex-col gap-1">+ <h2 id={`${id}-title`} className="font-heading text-section font-semibold text-ink">{title}</h2>+ {description && <p className="text-small text-ink-muted">{description}</p>}+ </div>+ <div className="flex min-w-0 flex-col gap-4">{children}</div>+ </section>+ );+}diff --git a/frontend/src/features/settings/SetupStep.jsx b/frontend/src/features/settings/SetupStep.jsxnew file mode 100644index 0000000..d0bb8b7--- /dev/null+++ b/frontend/src/features/settings/SetupStep.jsx@@ -0,0 +1,35 @@+import React from 'react';+import { Check } from 'lucide-react';+import { cn } from '@/lib/utils';++export default function SetupStep({ number, icon, title, done, onToggle, children, check }) {+ const Icon = icon;+ return (+ <li className={cn('flex gap-4 rounded-card border p-4 transition-colors', done ? 'border-success/30 bg-success-soft/40' : 'border-line')}>+ <div className="flex flex-col items-center gap-2">+ <span className={cn(+ 'flex size-9 shrink-0 items-center justify-center rounded-full',+ done ? 'bg-success text-ink-inverse' : 'bg-surface-sunken text-ink-muted',+ )}>+ {done ? <Check className="size-4" strokeWidth={2.5} /> : <Icon className="size-4 stroke-[1.75]" />}+ </span>+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-3">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <p className="text-sm font-semibold text-ink"><span className="text-ink-faint">Step {number}. </span>{title}</p>+ <label className="flex cursor-pointer items-center gap-2 text-small text-ink-muted select-none">+ <input type="checkbox" checked={done} onChange={onToggle} className="size-4 accent-[var(--brand)]" />+ Done+ </label>+ </div>+ <div className="flex flex-col gap-3 text-sm text-ink-muted [&_strong]:font-semibold [&_strong]:text-ink">{children}</div>+ {check && (+ <p className="flex items-start gap-1.5 text-small text-success">+ <Check className="mt-0.5 size-3.5 shrink-0" />+ <span><span className="font-semibold">It worked if</span> {check}</span>+ </p>+ )}+ </div>+ </li>+ );+}diff --git a/frontend/src/features/settings/UsefulLinksSection.jsx b/frontend/src/features/settings/UsefulLinksSection.jsxnew file mode 100644index 0000000..e841d3a--- /dev/null+++ b/frontend/src/features/settings/UsefulLinksSection.jsx@@ -0,0 +1,37 @@+import React from 'react';+import { Link } from 'react-router-dom';+import { ArrowRight, BookOpen, ExternalLink } from 'lucide-react';+import SurfaceBox from '@/components/SurfaceBox';+import SettingsSection from './SettingsSection';+import { DOC_LINKS, EXTERNAL_LINKS } from './settingsData';++export default function UsefulLinksSection() {+ return (+ <SettingsSection id="links" title="Useful links">+ <SurfaceBox content={false} className="divide-y divide-divider">+ {DOC_LINKS.map(({ label, to }) => (+ <Link+ key={label}+ to={to}+ className="flex items-center justify-between gap-2 px-5 py-3 text-sm text-ink transition-colors duration-(--duration-fast) hover:bg-surface-hover"+ >+ <span className="flex items-center gap-2"><BookOpen className="size-4 shrink-0 stroke-[1.75] text-ink-faint" />{label}</span>+ <ArrowRight className="size-4 shrink-0 text-ink-faint" />+ </Link>+ ))}+ {EXTERNAL_LINKS.map(({ label, href }) => (+ <a+ key={label}+ href={href}+ target="_blank"+ rel="noreferrer"+ className="flex items-center justify-between gap-2 px-5 py-3 text-sm text-ink transition-colors duration-(--duration-fast) hover:bg-surface-hover"+ >+ {label}+ <ExternalLink className="size-4 shrink-0 text-ink-faint" />+ </a>+ ))}+ </SurfaceBox>+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/schedulingProgress.js b/frontend/src/features/settings/schedulingProgress.jsnew file mode 100644index 0000000..4e3e985--- /dev/null+++ b/frontend/src/features/settings/schedulingProgress.js@@ -0,0 +1,32 @@+export const PROGRESS_KEY = 'twiligent.schedulingSetup.done';+export const SETUP_STEP_KEYS = ['fork', 'supabase', 'secrets', 'enable', 'test'];++export const browserStorage = () => localStorage;++// getStorage runs inside the try: reading localStorage itself throws when site data is blocked+export function readProgress(getStorage) {+ try {+ return JSON.parse(getStorage().getItem(PROGRESS_KEY)) || {};+ } catch {+ return {};+ }+}++export function saveProgress(getStorage, done) {+ try {+ getStorage().setItem(PROGRESS_KEY, JSON.stringify(done));+ } catch {+ // saved progress is a convenience, the guide works without it+ return;+ }+}++export function completedSteps(done) {+ return SETUP_STEP_KEYS.filter(key => done[key]).length;+}++export function repoBaseUrl(owner, repo) {+ const user = owner.trim();+ const name = (repo || 'twiligent').trim();+ return user ? `https://github.com/${user}/${name}` : null;+}diff --git a/frontend/src/features/settings/schedulingProgress.test.js b/frontend/src/features/settings/schedulingProgress.test.jsnew file mode 100644index 0000000..43e82af--- /dev/null+++ b/frontend/src/features/settings/schedulingProgress.test.js@@ -0,0 +1,55 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { PROGRESS_KEY, readProgress, saveProgress, completedSteps, repoBaseUrl } from './schedulingProgress.js';++function fakeStorage(initial = {}) {+ const items = { ...initial };+ return {+ items,+ getItem: key => (key in items ? items[key] : null),+ setItem: (key, value) => { items[key] = String(value); },+ };+}++const throwingStorage = {+ getItem: () => { throw new Error('blocked'); },+ setItem: () => { throw new Error('quota'); },+};++test('saved progress is read back', () => {+ const storage = fakeStorage({ [PROGRESS_KEY]: '{"fork":true}' });+ assert.deepEqual(readProgress(() => storage), { fork: true });+});++test('missing, null or broken progress reads as nothing done', () => {+ assert.deepEqual(readProgress(() => fakeStorage()), {});+ assert.deepEqual(readProgress(() => fakeStorage({ [PROGRESS_KEY]: 'null' })), {});+ assert.deepEqual(readProgress(() => fakeStorage({ [PROGRESS_KEY]: '{oops' })), {});+});++test('blocked storage reads as nothing done', () => {+ assert.deepEqual(readProgress(() => throwingStorage), {});+ assert.deepEqual(readProgress(() => { throw new Error('SecurityError'); }), {});+});++test('progress is saved as JSON under one key', () => {+ const storage = fakeStorage();+ saveProgress(() => storage, { fork: true, test: false });+ assert.equal(storage.items[PROGRESS_KEY], '{"fork":true,"test":false}');+});++test('saving to blocked storage is silent', () => {+ assert.doesNotThrow(() => saveProgress(() => throwingStorage, { fork: true }));+ assert.doesNotThrow(() => saveProgress(() => { throw new Error('SecurityError'); }, {}));+});++test('only the five setup steps count as completed', () => {+ assert.equal(completedSteps({}), 0);+ assert.equal(completedSteps({ fork: true, supabase: false, test: true, other: true }), 2);+});++test('repository links need a username and default to twiligent', () => {+ assert.equal(repoBaseUrl(' ', 'x'), null);+ assert.equal(repoBaseUrl(' me ', ''), 'https://github.com/me/twiligent');+ assert.equal(repoBaseUrl('me', ' copy '), 'https://github.com/me/copy');+});diff --git a/frontend/src/features/settings/settingsData.js b/frontend/src/features/settings/settingsData.jsnew file mode 100644index 0000000..13a03ca--- /dev/null+++ b/frontend/src/features/settings/settingsData.js@@ -0,0 +1,51 @@+export const DOC_LINKS = [+ { label: 'Using Twiligent', to: '/docs/use/getting-started' },+ { label: 'Run your own Twiligent', to: '/docs/self-host' },+ { label: 'Environment variables', to: '/docs/reference/environment' },+];++export const EXTERNAL_LINKS = [+ { label: 'Supabase API keys', href: 'https://supabase.com/dashboard/project/_/settings/api-keys' },+ { label: 'Cloudinary console', href: 'https://cloudinary.com/console' },+ { label: 'Google Cloud credentials', href: 'https://console.cloud.google.com/apis/credentials' },+ { label: 'Meta app dashboard', href: 'https://developers.facebook.com/apps' },+ { label: 'Cloudflare dashboard', href: 'https://dash.cloudflare.com' },+];++async function retryKeys(apiClient, isCancelled, applyKeys) {+ try {+ const keys = await apiClient.getKeys();+ if (!isCancelled()) applyKeys(keys);+ } catch {+ // status is informational, the page still renders+ return;+ }+}++// a failure after applyKeys keeps those keys: the retry only replaces them when it succeeds+export async function loadServerSettings(apiClient, { isCancelled, applyKeys, applyGithub, finish }) {+ try {+ const [keys, github] = await Promise.all([apiClient.getKeys(), apiClient.getGithubSettings()]);+ if (isCancelled()) return;+ applyKeys(keys);+ applyGithub(github.repoOwner || '', github.repoName || '');+ } catch {+ await retryKeys(apiClient, isCancelled, applyKeys);+ } finally {+ if (!isCancelled()) finish();+ }+}++// only the repository is kept: it fills in the direct links in the setup guide, no token needed+export function githubSettingsPayload(owner, repo) {+ return { repoOwner: owner.trim(), repoName: (repo || 'twiligent').trim(), branch: 'main' };+}++export function healthCheckResult(response) {+ if (response.status === 'ok') return { success: true, message: 'The API is reachable and healthy.' };+ return { success: false, message: `The API answered with status "${response.status}". Check the Worker logs.` };+}++export function healthCheckFailure(err) {+ return { success: false, message: `The API could not be reached: ${err.message}. Check VITE_API_URL and that the Worker is deployed.` };+}diff --git a/frontend/src/features/settings/settingsData.test.js b/frontend/src/features/settings/settingsData.test.jsnew file mode 100644index 0000000..f7b5cfd--- /dev/null+++ b/frontend/src/features/settings/settingsData.test.js@@ -0,0 +1,85 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ loadServerSettings, githubSettingsPayload, healthCheckResult, healthCheckFailure,+} from './settingsData.js';++function fakeApi({ keys = [], github }) {+ const calls = [];+ const queue = [...keys];+ return {+ calls,+ getKeys: async () => {+ calls.push('getKeys');+ const next = queue.shift();+ if (next instanceof Error) throw next;+ return next;+ },+ getGithubSettings: async () => {+ calls.push('getGithubSettings');+ if (github instanceof Error) throw github;+ return github;+ },+ };+}++async function run(apiClient, { cancelled = false } = {}) {+ const state = { keys: [], github: null, finished: false };+ await loadServerSettings(apiClient, {+ isCancelled: () => cancelled,+ applyKeys: keys => state.keys.push(keys),+ applyGithub: (owner, name) => { state.github = { owner, name }; },+ finish: () => { state.finished = true; },+ });+ return state;+}++test('loads keys and the saved repository together', async () => {+ const apiClient = fakeApi({ keys: [{ youtube: 1 }], github: { repoOwner: 'me', repoName: 'copy' } });+ const state = await run(apiClient);+ assert.deepEqual(apiClient.calls, ['getKeys', 'getGithubSettings']);+ assert.deepEqual(state, { keys: [{ youtube: 1 }], github: { owner: 'me', name: 'copy' }, finished: true });+});++test('missing repository fields become empty strings', async () => {+ const state = await run(fakeApi({ keys: [{}], github: {} }));+ assert.deepEqual(state.github, { owner: '', name: '' });+});++test('a failed GitHub request retries the keys alone', async () => {+ const apiClient = fakeApi({ keys: [{ first: true }, { second: true }], github: new Error('down') });+ const state = await run(apiClient);+ assert.deepEqual(apiClient.calls, ['getKeys', 'getGithubSettings', 'getKeys']);+ assert.deepEqual(state.keys, [{ second: true }]);+ assert.equal(state.github, null);+ assert.equal(state.finished, true);+});++test('an empty GitHub answer keeps the keys already applied when the retry fails', async () => {+ const state = await run(fakeApi({ keys: [{ first: true }, new Error('down')], github: null }));+ assert.deepEqual(state.keys, [{ first: true }]);+ assert.equal(state.github, null);+ assert.equal(state.finished, true);+});++test('when both attempts fail the page still finishes loading', async () => {+ const state = await run(fakeApi({ keys: [new Error('a'), new Error('b')], github: {} }));+ assert.deepEqual(state, { keys: [], github: null, finished: true });+});++test('a cancelled load applies nothing', async () => {+ const state = await run(fakeApi({ keys: [{}], github: {} }), { cancelled: true });+ assert.deepEqual(state, { keys: [], github: null, finished: false });+});++test('the saved repository is trimmed and defaults to twiligent', () => {+ assert.deepEqual(githubSettingsPayload(' me ', ''), { repoOwner: 'me', repoName: 'twiligent', branch: 'main' });+ assert.deepEqual(githubSettingsPayload('me', ' copy '), { repoOwner: 'me', repoName: 'copy', branch: 'main' });+});++test('health results explain what to check', () => {+ assert.deepEqual(healthCheckResult({ status: 'ok' }), { success: true, message: 'The API is reachable and healthy.' });+ assert.equal(healthCheckResult({ status: 'degraded' }).message, 'The API answered with status "degraded". Check the Worker logs.');+ assert.equal(healthCheckFailure(new Error('timeout')).success, false);+ assert.ok(healthCheckFailure(new Error('timeout')).message.startsWith('The API could not be reached: timeout.'));+});diff --git a/frontend/src/features/settings/useApiHealthCheck.js b/frontend/src/features/settings/useApiHealthCheck.jsnew file mode 100644index 0000000..f7039b1--- /dev/null+++ b/frontend/src/features/settings/useApiHealthCheck.js@@ -0,0 +1,23 @@+import { useState } from 'react';+import { api } from '../../services/api';+import { healthCheckFailure, healthCheckResult } from './settingsData';++export function useApiHealthCheck() {+ const [testing, setTesting] = useState(false);+ const [testResult, setTestResult] = useState(null);++ const handleTest = async () => {+ setTesting(true);+ setTestResult(null);+ try {+ const res = await api.health();+ setTestResult(healthCheckResult(res));+ } catch (err) {+ setTestResult(healthCheckFailure(err));+ } finally {+ setTesting(false);+ }+ };++ return { testing, testResult, handleTest };+}diff --git a/frontend/src/features/settings/useServerSettings.js b/frontend/src/features/settings/useServerSettings.jsnew file mode 100644index 0000000..1875d19--- /dev/null+++ b/frontend/src/features/settings/useServerSettings.js@@ -0,0 +1,50 @@+import { useEffect, useState } from 'react';+import { api } from '../../services/api';+import { githubSettingsPayload, loadServerSettings } from './settingsData';++function useGithubRepoSave({ owner, repo, showToast }) {+ const [saving, setSaving] = useState(false);++ const handleSave = async e => {+ e.preventDefault();+ setSaving(true);+ try {+ await api.saveGithubSettings(githubSettingsPayload(owner, repo));+ showToast('GitHub username saved. The buttons in the guide now open your copy.');+ } catch (err) {+ showToast(`Couldn't save the repository. ${err.message}`, 'error');+ } finally {+ setSaving(false);+ }+ };++ return { saving, handleSave };+}++export function useServerSettings(showToast) {+ const [serverStatus, setServerStatus] = useState(null);+ const [loading, setLoading] = useState(true);+ const [ghRepoOwner, setGhRepoOwner] = useState('');+ const [ghRepoName, setGhRepoName] = useState('');++ useEffect(() => {+ let cancelled = false;+ loadServerSettings(api, {+ isCancelled: () => cancelled,+ applyKeys: setServerStatus,+ applyGithub: (owner, name) => {+ setGhRepoOwner(owner);+ setGhRepoName(name);+ },+ finish: () => setLoading(false),+ });+ return () => { cancelled = true; };+ }, []);++ const { saving, handleSave } = useGithubRepoSave({ owner: ghRepoOwner, repo: ghRepoName, showToast });++ return {+ serverStatus, loading,+ github: { owner: ghRepoOwner, repo: ghRepoName, setOwner: setGhRepoOwner, setRepo: setGhRepoName, saving, handleSave },+ };+}