Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(publishing): stop saying Cloudinary is not set up while its settings load or fail
spacesdrive652244a58fd0
diff --git a/backend/services/publishingService.ts b/backend/services/publishingService.tsindex 65e1da1..ac45162 100644--- a/backend/services/publishingService.ts+++ b/backend/services/publishingService.ts@@ -43,7 +43,7 @@ export function createPublishingService({ accounts, config, context }: Publishinreturn {cloudinaryConfig() {- if (!config.cloudinary) throw new NotConfiguredError('Cloudinary not configured on server');+ if (!config.cloudinary) throw new NotConfiguredError('Cloudinary is not set up on this server. The owner needs to set CLOUDINARY_CLOUD_NAME and CLOUDINARY_UPLOAD_PRESET.');return config.cloudinary;},diff --git a/backend/tests/routes/publishingRoutes.test.ts b/backend/tests/routes/publishingRoutes.test.tsindex cc23785..847e81e 100644--- a/backend/tests/routes/publishingRoutes.test.ts+++ b/backend/tests/routes/publishingRoutes.test.ts@@ -54,7 +54,7 @@ describe('publishing routes check the account before calling Instagram', () => {});test('a missing Cloudinary configuration is an error status, not a 200', async () => {- assert.deepEqual(await call('GET', '/cloudinary-config'), failure(503, 'NOT_CONFIGURED', 'Cloudinary not configured on server'));+ assert.deepEqual(await call('GET', '/cloudinary-config'), failure(503, 'NOT_CONFIGURED', 'Cloudinary is not set up on this server. The owner needs to set CLOUDINARY_CLOUD_NAME and CLOUDINARY_UPLOAD_PRESET.'));assert.deepEqual(await call('GET', '/cloudinary-config', undefined, { CLOUDINARY_CLOUD_NAME: 'cloud', CLOUDINARY_UPLOAD_PRESET: 'preset' }), {status: 200, body: { success: true, cloudName: 'cloud', uploadPreset: 'preset' },});diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.mdindex c678769..9b75c19 100644--- a/docs/architecture/frontend/CONTEXTS.md+++ b/docs/architecture/frontend/CONTEXTS.md@@ -127,10 +127,10 @@ Hooks used by more than one feature. Hooks used by a single feature live in that| `useIsMobile()` | `use-mobile.ts` | True below the mobile breakpoint || `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.ts` | Ctrl+K / Cmd+K toggle for the command palette || `useSmoothTheme()` | `use-smooth-theme.ts` | Theme switch as one cross-fade |-| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.ts` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |+| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.ts` | Loads `api.getCloudinaryConfig()`; returns `{ config, loading, error, retry }` || `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.ts` | Loads one account's analytics and refreshes it; used by Instagram analytics |-`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Instagram publishing page passes `accounts`.+`useCloudinaryConfig` keeps loading, ready and failed apart (`lib/cloudinaryConfigState.ts`), so a slow or failed request never reads as a server without Cloudinary. Loading shows no warning; a failed first load sets `error` to the server's reason, which the Instagram publishing and YouTube uploads pages show with Try again (`retry`); a failed refetch keeps the config already loaded. The request runs again whenever `reloadKey` changes: the Instagram publishing page passes `accounts`.`useAccountAnalytics` returns `{ loading, profile, analytics, refreshing, handleRefresh }`. Pass a stable `api` method (`api.getIGAnalytics`), never an inline arrow: the load is keyed on the account id and that method, so a background account refresh does not refetch analytics. `label` names the platform in the toasts (`Couldn't load Instagram analytics.`, `Instagram account refreshed`). `handleRefresh` calls `api.refreshAccount()` and then loads the analytics again.diff --git a/frontend/src/features/publishing/UploadContent.tsx b/frontend/src/features/publishing/UploadContent.tsxindex a332bcf..106c90a 100644--- a/frontend/src/features/publishing/UploadContent.tsx+++ b/frontend/src/features/publishing/UploadContent.tsx@@ -41,7 +41,8 @@ function stageAnnouncement(status: PublishStatus, uploading: boolean): string {export default function UploadContent() {const { accounts, showToast } = useAppContext();- const cloudConfig = useCloudinaryConfig(accounts);+ const cloudinary = useCloudinaryConfig(accounts);+ const cloudConfig = cloudinary.config;const [igAccounts, setIgAccounts] = useState<AppAccount[]>([]);const [uploadMode, setUploadMode] = useUrlChoice<UploadMode>('mode', UPLOAD_MODES, 'single');const schedule = useScheduledPosts();@@ -81,12 +82,13 @@ export default function UploadContent() {<PageHeader title="Instagram publishing" description="Post and schedule photos, Reels and Stories to Instagram." /><LiveStatus message={stageAnnouncement(publish.publishStatus, publish.uploading)} />- {!cloudConfig && (+ {cloudinary.error && (<Alert variant="warning"><AlertCircle /><AlertDescription>- Uploads need Cloudinary, which is not set up on the server. Instagram only accepts media from a public URL. Set the Cloudinary environment variables, then check the status in <Link to="/settings#server-keys" className="font-semibold underline underline-offset-4">Settings</Link>.+ Uploads can't start: the upload settings did not load. {cloudinary.error} The server status is in <Link to="/settings#server-keys" className="font-semibold underline underline-offset-4">Settings</Link>.</AlertDescription>+ <AlertAction><Button size="xs" variant="outline" onClick={cloudinary.retry} disabled={cloudinary.loading}>{cloudinary.loading ? 'Trying again' : 'Try again'}</Button></AlertAction></Alert>)}diff --git a/frontend/src/features/youtube/YouTubeComposer.tsx b/frontend/src/features/youtube/YouTubeComposer.tsxindex 79fa700..4e8c538 100644--- a/frontend/src/features/youtube/YouTubeComposer.tsx+++ b/frontend/src/features/youtube/YouTubeComposer.tsx@@ -20,6 +20,7 @@ import type { YouTubeConnectionSummary, YouTubePrivacy, YouTubeUploadRequest } fexport interface YouTubeComposerProps {connections: YouTubeConnectionSummary[];cloudConfig: CloudinaryUploadConfig | null;+ cloudLoading: boolean;onQueue: (request: YouTubeUploadRequest) => Promise<boolean>;showError: (message: string) => void;}@@ -38,7 +39,7 @@ async function register(upload: CloudinaryUpload, label: string): Promise<stringreturn media.id;}-export default function YouTubeComposer({ connections, cloudConfig, onQueue, showError }: YouTubeComposerProps) {+export default function YouTubeComposer({ connections, cloudConfig, cloudLoading, 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);@@ -210,7 +211,9 @@ export default function YouTubeComposer({ connections, cloudConfig, onQueue, sho{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>}+ {!cloudConfig && (+ <p className="text-sm text-ink-muted">{cloudLoading ? 'Checking the upload settings.' : 'Uploads can\'t start until the upload settings load. The reason is above the form.'}</p>+ )}</form></SurfaceBox>);diff --git a/frontend/src/features/youtube/YouTubeUploads.tsx b/frontend/src/features/youtube/YouTubeUploads.tsxindex 216012c..0787e76 100644--- a/frontend/src/features/youtube/YouTubeUploads.tsx+++ b/frontend/src/features/youtube/YouTubeUploads.tsx@@ -1,7 +1,7 @@import React from 'react';import { Link } from 'react-router-dom';import { AlertCircle, ShieldCheck } from 'lucide-react';-import { Alert, AlertDescription } from '@/components/ui/alert';+import { Alert, AlertAction, AlertDescription } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import PageHeader from '@/components/PageHeader';@@ -18,7 +18,7 @@ const DESCRIPTION = 'Upload videos and Shorts to your YouTube channels verifiedexport default function YouTubeUploads() {const { accounts, showToast } = useAppContext();- const cloudConfig = useCloudinaryConfig(accounts);+ const cloudinary = useCloudinaryConfig(accounts);const youtube = useYouTubePublishing(showToast);const active = youtube.connections.filter(connection => connection.status === 'active');@@ -57,7 +57,16 @@ export default function YouTubeUploads() {/></SurfaceBox>) : (- <YouTubeComposer connections={youtube.connections} cloudConfig={cloudConfig} onQueue={youtube.queue} showError={message => showToast(message, 'error')} />+ <>+ {cloudinary.error && (+ <Alert variant="warning">+ <AlertCircle />+ <AlertDescription>Uploads can't start: the upload settings did not load. {cloudinary.error}</AlertDescription>+ <AlertAction><Button size="xs" variant="outline" onClick={cloudinary.retry} disabled={cloudinary.loading}>{cloudinary.loading ? 'Trying again' : 'Try again'}</Button></AlertAction>+ </Alert>+ )}+ <YouTubeComposer connections={youtube.connections} cloudConfig={cloudinary.config} cloudLoading={cloudinary.loading} onQueue={youtube.queue} showError={message => showToast(message, 'error')} />+ </>)}{!youtube.error && youtube.configured && (diff --git a/frontend/src/hooks/use-cloudinary-config.ts b/frontend/src/hooks/use-cloudinary-config.tsindex bea3295..371e2e1 100644--- a/frontend/src/hooks/use-cloudinary-config.ts+++ b/frontend/src/hooks/use-cloudinary-config.ts@@ -1,27 +1,33 @@-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { api } from '../services/api';-import type { CloudinaryConfigResponse } from '@shared/types/instagram.ts';+import { CLOUDINARY_LOADING, nextCloudinaryState } from '../lib/cloudinaryConfigState';+import type { CloudinaryConfigResult, CloudinaryConfigState } from '../lib/cloudinaryConfigState';-async function fetchCloudinaryConfig(): Promise<CloudinaryConfigResponse | null> {+async function fetchCloudinaryConfig(): Promise<CloudinaryConfigResult> {try {- return await api.getCloudinaryConfig();- } catch {- // pages already show a missing config as an alert or a disabled upload field- return null;+ return { ok: true, config: await api.getCloudinaryConfig() };+ } catch (err) {+ return { ok: false, message: (err as Error).message };}}// reloadKey lets a page refetch the config when something it depends on changes-export function useCloudinaryConfig(reloadKey?: unknown): CloudinaryConfigResponse | null {- const [config, setConfig] = useState<CloudinaryConfigResponse | null>(null);+export function useCloudinaryConfig(reloadKey?: unknown): CloudinaryConfigState & { retry: () => void } {+ const [state, setState] = useState<CloudinaryConfigState>(CLOUDINARY_LOADING);useEffect(() => {- const loadConfig = async () => {- const nextConfig = await fetchCloudinaryConfig();- if (nextConfig) setConfig(nextConfig);- };- loadConfig();+ // an answer that arrives after the page left is dropped+ let current = true;+ void fetchCloudinaryConfig().then(result => {+ if (current) setState(previous => nextCloudinaryState(previous, result));+ });+ return () => { current = false; };}, [reloadKey]);- return config;+ const retry = useCallback(() => {+ setState(previous => ({ ...previous, loading: true }));+ void fetchCloudinaryConfig().then(result => setState(previous => nextCloudinaryState(previous, result)));+ }, []);++ return { ...state, retry };}diff --git a/frontend/src/lib/cloudinaryConfigState.ts b/frontend/src/lib/cloudinaryConfigState.tsnew file mode 100644index 0000000..c31bac6--- /dev/null+++ b/frontend/src/lib/cloudinaryConfigState.ts@@ -0,0 +1,19 @@+import type { CloudinaryConfigResponse } from '../../../shared/types/instagram.ts';++// loading, ready and failed are separate, so a slow or failed request never reads as a server without Cloudinary+export interface CloudinaryConfigState {+ config: CloudinaryConfigResponse | null;+ loading: boolean;+ error: string | null;+}++export const CLOUDINARY_LOADING: CloudinaryConfigState = { config: null, loading: true, error: null };++export type CloudinaryConfigResult = { ok: true; config: CloudinaryConfigResponse } | { ok: false; message: string };++// a refetch that fails keeps the config already loaded, since uploads still work with it+export function nextCloudinaryState(previous: CloudinaryConfigState, result: CloudinaryConfigResult): CloudinaryConfigState {+ if (result.ok) return { config: result.config, loading: false, error: null };+ if (previous.config) return { ...previous, loading: false };+ return { config: null, loading: false, error: result.message };+}diff --git a/frontend/tests/lib/cloudinaryConfigState.test.ts b/frontend/tests/lib/cloudinaryConfigState.test.tsnew file mode 100644index 0000000..1358a38--- /dev/null+++ b/frontend/tests/lib/cloudinaryConfigState.test.ts@@ -0,0 +1,20 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { CLOUDINARY_LOADING, nextCloudinaryState } from '../../src/lib/cloudinaryConfigState.ts';++const CONFIG = { success: true as const, cloudName: 'demo', uploadPreset: 'unsigned' };++test('the config starts loading with no error, so nothing claims the server lacks Cloudinary yet', () => {+ assert.deepEqual(CLOUDINARY_LOADING, { config: null, loading: true, error: null });+});++test('a loaded config is ready, and a failed first load keeps the reason to show', () => {+ assert.deepEqual(nextCloudinaryState(CLOUDINARY_LOADING, { ok: true, config: CONFIG }), { config: CONFIG, loading: false, error: null });+ assert.deepEqual(nextCloudinaryState(CLOUDINARY_LOADING, { ok: false, message: 'Network error' }), { config: null, loading: false, error: 'Network error' });+});++test('a failed refetch keeps the config already loaded, and a later success clears an earlier error', () => {+ const ready = { config: CONFIG, loading: true, error: null };+ assert.deepEqual(nextCloudinaryState(ready, { ok: false, message: 'Network error' }), { config: CONFIG, loading: false, error: null });+ assert.deepEqual(nextCloudinaryState({ config: null, loading: true, error: 'Network error' }, { ok: true, config: CONFIG }), { config: CONFIG, loading: false, error: null });+});