Skip to content

A motion design studio on your own machine: Claude makes the video step by step, you approve every stage. Bring your own Claude Code or API key.

Publish: post a delivered video to your social accounts, only when you say so

mutonby223c409e13d8
diff --git a/README.md b/README.md
index 419fee0..e9a6b5d 100644
--- a/README.md
+++ b/README.md
@@ -103,6 +103,7 @@ Mortiflix runs on your own accounts: there's nothing to sign up for. `mortiflix
```
Anthropic API key only for the anthropic-api backend (Claude Code uses your own login)
ElevenLabs API key only for ElevenLabs narration, sound effects and music
+Upload-Post API key only for `mortiflix publish` (optional; sessions never get it)
Other keys anything a pipeline's tools read from the environment, e.g. GEMINI_API_KEY
```
@@ -170,6 +171,23 @@ Everything goes into the studio folder, never system-wide. Full details: [docs/S
(MoGraph), Camera, Animate, Math, Circuits, Camera Flight for flying the camera yourself (`mortiflix blender`), and
**Nova FX**, Mortiflix's own particle engine (particles, fire, sparks, fireworks), which builds on Linux only for now.
+## Publishing (optional)
+
+Once you approve a final, the video is yours to download. If you'd rather post it straight from the studio, connect
+your accounts on [Upload-Post](https://upload-post.com), add its key with `mortiflix keys`, and:
+
+```sh
+mortiflix publish <project> # where the brief said (TikTok / Reels / Shorts), asks first
+mortiflix publish <project> --to linkedin,x --title "…" # somewhere else, with your own caption
+mortiflix publish <project> --at 2026-10-20T18:00 --timezone Europe/Madrid # scheduled
+mortiflix publish <project> --status # per platform, with the links once they're live
+```
+
+Only you publish: it's a command you run, never something a session can reach (`mfx` has no way to it), and only a
+delivered project's approved final goes out. It shows what goes where and asks before sending (`--yes` skips the
+question in scripts). Running it again never posts the same video twice. `--profile` is the Upload-Post profile your
+accounts are connected under; it's remembered after the first time.
+
## Make your own pipeline
```sh
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 3c27ae1..56b8497 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -124,6 +124,11 @@ work makes sound. `verifyKey` proves a key with a free, read-only call (`GET /v1
project that lacks a key for its next steps pauses with `NEEDS_YOU` instead of starting a session) all ask it. Other
keys for sessions go to `session.env` through `setSessionKey`; only their names are ever shown.
+The Upload-Post key is the studio's, not a session's: `publish.mjs` reads it (`keyValue`) when you run
+`mortiflix publish`, which takes a delivered project's approved video, shows the plan, asks, and posts it with an
+idempotency key (the same video to the same place and time is one post). It records the post in `project.json`
+(`published`) and the log (`PUBLISHED`).
+
## Narration (`src/voice/`)
`voice/index.mjs` holds the studio's choice (`config.json` › `voice`: `none`, `elevenlabs`, `qwen` or `own`) and hands a
diff --git a/src/cli.mjs b/src/cli.mjs
index e28ec6c..1f5c933 100644
--- a/src/cli.mjs
+++ b/src/cli.mjs
@@ -14,6 +14,7 @@ import * as setup from './setup.mjs';
import { costText } from './usage.mjs';
import * as booth from './booth.mjs';
import * as rec from './record.mjs';
+import * as pub from './publish.mjs';
const C = process.stdout.isTTY && !process.env.NO_COLOR
? { b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`, acc: (s) => `\x1b[38;5;208m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m` }
@@ -39,6 +40,12 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud
mortiflix reopen <project> <step> "what to change" send an approved step back (you changed your mind)
mortiflix pause|resume|cancel <project>
+ ${C.b('Publishing')}
+ mortiflix publish <project> [--to tiktok,instagram,youtube] [--profile <name>] [--title "…"] [--description "…"]
+ [--at 2026-10-20T18:00 [--timezone Europe/Madrid]] [--yes]
+ post a delivered video through Upload-Post (asks first)
+ mortiflix publish <project> --status how it went, per platform, with the links
+
${C.b('The web studio')}
mortiflix serve [--port 4646] [--host 127.0.0.1] the studio in your browser, with the runner
@@ -58,8 +65,8 @@ const HELP = `${C.b('mortiflix')}: a motion design studio on your machine. Claud
${C.b('Settings')}
mortiflix config [key [value]] show or change settings
- mortiflix keys set <anthropic|elevenlabs|NAME> set one key (typed hidden, or piped on stdin)
- mortiflix keys remove <anthropic|elevenlabs|NAME>
+ mortiflix keys set <anthropic|elevenlabs|uploadpost|NAME> set one key (typed hidden, or piped on stdin)
+ mortiflix keys remove <anthropic|elevenlabs|uploadpost|NAME>
mortiflix checks [approve|reject <id>] the error checklist sessions proposed
--studio <dir> works with every command.`;
@@ -106,6 +113,7 @@ export async function run(argv = process.argv.slice(2)) {
}
case 'resume': gates.resume(root, pick(root, rest[0])); return console.log('Resumed: it will run on the next `mortiflix run` (or right away under `serve`).');
case 'cancel': gates.cancel(root, pick(root, rest[0])); return console.log('Cancelled.');
+ case 'publish': return publishCmd(root, rest[0], a);
case 'serve': return serve(root, a);
case 'config': return config(root, rest);
case 'checks': return checks(root, rest);
@@ -326,6 +334,34 @@ function status(root, id) {
for (const e of readEvents(root, id, { limit: 12 })) console.log(C.dim(` ${e.t.slice(5, 16).replace('T', ' ')} ${e.event}${e.step ? ` ${e.step}${e.version ? ` v${e.version}` : ''}` : ''} ${e.details ? `· ${e.details.slice(0, 80)}` : ''}`));
}
+// Publishing: shows exactly what goes where, asks, then sends. Never runs on its own.
+async function publishCmd(root, given, a) {
+ const id = pick(root, given);
+ const opt = (k) => (typeof a[k] === 'string' ? a[k] : undefined);
+ if (a.status) {
+ const st = await pub.publishStatus(root, id);
+ console.log(`${C.b(st.status)}${st.message ? C.dim(` · ${st.message}`) : ''} ${C.dim(st.job_id ? `job ${st.job_id}` : `request ${st.request_id}`)}`);
+ for (const r of st.results) {
+ const icon = { completed: C.green('✔'), failed: C.red('✖') }[r.state] || C.acc('●');
+ console.log(` ${icon} ${r.platform.padEnd(10)} ${r.url || C.dim(r.message || r.state)}`);
+ }
+ if (!st.results.length) console.log(C.dim(st.scheduled_for ? ` Scheduled for ${st.scheduled_for}.` : ' Nothing back from the platforms yet.'));
+ return;
+ }
+ const plan = pub.publishPlan(root, id, { to: opt('to'), profile: opt('profile'), title: opt('title'), description: opt('description'), at: opt('at'), timezone: opt('timezone') });
+ console.log(`\n${C.b(plan.project)} ${C.dim(`${(plan.size / 1024 ** 2).toFixed(1)} MB`)}`);
+ console.log(` To ${plan.platforms.join(', ')}${plan.from_brief ? C.dim(' (from the brief; --to changes it)') : ''}`);
+ console.log(` Profile ${plan.profile}`);
+ console.log(` Title ${plan.title}`);
+ if (plan.description) console.log(` Text ${plan.description.slice(0, 200)}`);
+ console.log(` When ${plan.at ? `${plan.at} ${plan.timezone || 'UTC'}` : 'now'}\n`);
+ if (!a.yes && !process.stdin.isTTY) throw new Error('nothing sent: add --yes to post without being asked');
+ if (!a.yes && !(await confirm(`Post it${plan.at ? ' at that time' : ' now'}?`))) return console.log('Nothing sent.');
+ const sent = await pub.publish(root, plan);
+ console.log(`${C.green('✔')} ${plan.at ? 'Scheduled' : 'Sent'}. ${C.b(`mortiflix publish ${id} --status`)} shows how it went.`);
+ console.log(C.dim(` ${sent.job_id ? `job ${sent.job_id}` : `request ${sent.request_id}`} · also at https://app.upload-post.com`));
+}
+
// Review in the terminal: what was sent, then answers, notes and a decision.
async function review(root, given) {
needStudio(root);
diff --git a/src/keys.mjs b/src/keys.mjs
index f7b1c00..5b42230 100644
--- a/src/keys.mjs
+++ b/src/keys.mjs
@@ -23,6 +23,13 @@ export const KEYS = {
get: 'elevenlabs.io › Developers › API keys',
for: 'narration, sound effects and music with ElevenLabs. Not needed for local narration (Qwen3-TTS) or none.',
},
+ uploadpost: {
+ name: 'Upload-Post API key',
+ secret: 'upload_post_api_key',
+ env: 'UPLOAD_POST_API_KEY',
+ get: 'app.upload-post.com › API Keys',
+ for: 'publishing a delivered video to TikTok, Instagram, YouTube and others with `mortiflix publish`. Optional: nothing is ever posted on its own.',
+ },
};
// Where a key comes from: saved in this studio, session.env, the environment Mortiflix was started with, or nowhere.
@@ -36,6 +43,12 @@ export function keySource(root, id) {
return null;
}
+// The key itself, for the studio's own calls (publishing). Sessions never get this one.
+export function keyValue(root, id) {
+ const k = KEYS[id];
+ return readSecret(root, k.secret) || process.env[k.env] || null;
+}
+
// Which keys a project uses, given how the studio is set up. `steps` narrows it to the work that's about to run.
// anthropic: the project runs on the Claude API backend
// elevenlabs: the studio narrates with ElevenLabs and the work makes sound (voice, effects, music)
@@ -91,6 +104,12 @@ export async function verifyKey(root, id, value, { fetch = globalThis.fetch } =
if (res.status === 401 || res.status === 403) return { ok: false, detail: 'the Claude API refused it (check that you copied the whole key)' };
return { ok: null, detail: `couldn't check it (Claude API answered ${res.status})` };
}
+ if (id === 'uploadpost') {
+ const res = await fetch(`${process.env.UPLOAD_POST_API || 'https://api.upload-post.com'}/api/uploadposts/me`, { headers: { Authorization: `Apikey ${key}` } });
+ if (res.ok) { const me = await res.json().catch(() => ({})); return { ok: true, detail: me.plan ? `${me.plan} plan` : 'Upload-Post accepted it' }; }
+ if (res.status === 401 || res.status === 403) return { ok: false, detail: 'Upload-Post refused it (check that you copied the whole key)' };
+ return { ok: null, detail: `couldn't check it (Upload-Post answered ${res.status})` };
+ }
if (id === 'elevenlabs') {
const a = await new ElevenLabs({ key, server: voiceConfig(root).elevenlabs.server, fetch }).account();
const left = Number.isFinite(a.characters_left) ? ` · ${a.characters_left.toLocaleString()} credits left` : '';
diff --git a/src/publish.mjs b/src/publish.mjs
new file mode 100644
index 0000000..9778148
--- /dev/null
+++ b/src/publish.mjs
@@ -0,0 +1,96 @@
+// Publishing a delivered video to your social accounts, through Upload-Post (https://upload-post.com).
+//
+// Only you publish. It's reachable from the CLI, never from `mfx`, so a session can't post anything; and only a
+// delivered project's approved video goes out, never a version still in review. Nothing here runs on its own.
+import { createHash } from 'node:crypto';
+import { existsSync, openAsBlob, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { loadConfig, saveConfig, UserError } from './studio.mjs';
+import { loadProject, projectPaths, update, event, now } from './projects.mjs';
+import { keyValue } from './keys.mjs';
+
+// UPLOAD_POST_API moves it (e.g. to a staging server); the key is sent there.
+export const API = () => process.env.UPLOAD_POST_API || 'https://api.upload-post.com';
+
+export const PLATFORMS = ['tiktok', 'instagram', 'youtube', 'linkedin', 'x', 'facebook', 'threads', 'pinterest', 'bluesky'];
+
+// Where the brief said it will run (the social-short intake), as the accounts to post to.
+const FROM_BRIEF = { 'TikTok / Reels / Shorts': ['tiktok', 'instagram', 'youtube'], LinkedIn: ['linkedin'], X: ['x'] };
+
+// Everything a post needs, checked before anything is sent: what you see is what goes out.
+export function publishPlan(root, id, { to, profile, title, description, at, timezone } = {}) {
+ const p = loadProject(root, id);
+ if (p.state !== 'delivered') throw new UserError(`"${p.title}" isn't delivered yet (${p.state}): only an approved final is published`);
+ const video = p.deliverables.find((f) => f.kind === 'video');
+ if (!video) throw new UserError(`"${p.title}" delivered no video to publish`);
+ const file = join(projectPaths(root, id).state, video.file);
+ if (!existsSync(file)) throw new UserError(`the delivered video is missing from the record (${video.file})`);
+
+ const fromBrief = FROM_BRIEF[p.intake.answers.platform];
+ const platforms = to ? String(to).split(',').map((s) => s.trim().toLowerCase()).filter(Boolean) : fromBrief || [];
+ if (!platforms.length) throw new UserError(`where to? Pass --to with one or more of: ${PLATFORMS.join(', ')}`);
+ const unknown = platforms.filter((s) => !PLATFORMS.includes(s));
+ if (unknown.length) throw new UserError(`can't publish to ${unknown.join(', ')} (one or more of: ${PLATFORMS.join(', ')})`);
+
+ const who = String(profile || loadConfig(root).publish?.profile || '').trim();
+ if (!who) throw new UserError('which Upload-Post profile? Pass --profile with the name your accounts are connected under (it\'s remembered)');
+ const caption = String(title ?? p.title).trim();
+ if (!caption) throw new UserError('a post needs a title: pass --title');
+ if (timezone && !at) throw new UserError('--timezone only goes with --at');
+ if (at && Number.isNaN(Date.parse(at))) throw new UserError(`--at "${at}" isn't a date and time (e.g. 2026-10-20T18:00)`);
+
+ const st = statSync(file);
+ // The same video to the same place at the same time is the same post: a retry never posts it twice.
+ const key = createHash('sha256').update([id, video.file, st.size, who, platforms.join(','), at || '', timezone || ''].join('\n')).digest('hex').slice(0, 32);
+ return { id, project: p.title, file, size: st.size, platforms, profile: who, title: caption, description: description ? String(description) : null, at: at || null, timezone: timezone || null, key, from_brief: !to && Boolean(fromBrief) };
+}
+
+// Sends the plan. Returns Upload-Post's ids: `request_id` for a post that goes out now, `job_id` for a scheduled one.
+export async function publish(root, plan, { fetch = globalThis.fetch } = {}) {
+ const apiKey = keyValue(root, 'uploadpost');
+ if (!apiKey) throw new UserError('publishing needs your Upload-Post API key: add it with `mortiflix keys set uploadpost`');
+ const form = new FormData();
+ form.append('user', plan.profile);
+ for (const s of plan.platforms) form.append('platform[]', s);
+ form.append('title', plan.title);
+ if (plan.description) form.append('description', plan.description);
+ if (plan.at) form.append('scheduled_date', plan.at);
+ if (plan.timezone) form.append('timezone', plan.timezone);
+ form.append('async_upload', 'true');
+ form.append('video', await openAsBlob(plan.file, { type: 'video/mp4' }), `${plan.id}.mp4`);
+
+ let res;
+ try {
+ res = await fetch(`${API()}/api/upload`, { method: 'POST', body: form, headers: { Authorization: `Apikey ${apiKey}`, 'Idempotency-Key': plan.key } });
+ } catch (e) {
+ throw new UserError(`couldn't reach Upload-Post (${e.message}). Run it again: the same post is never sent twice`);
+ }
+ const body = await res.json().catch(() => ({}));
+ if (res.status === 401 || res.status === 403) throw new UserError('Upload-Post refused the API key (check it with `mortiflix keys`)');
+ if (!res.ok) throw new UserError(`Upload-Post didn't take it (${res.status}): ${body.message || body.error || 'no reason given'}`);
+
+ const sent = { request_id: body.request_id || null, job_id: body.job_id || null, platforms: plan.platforms, profile: plan.profile, scheduled_for: plan.at, sent_at: now() };
+ update(root, plan.id, (p) => { p.published = [...(p.published || []), sent]; });
+ event(root, plan.id, { event: 'PUBLISHED', actor: 'you', details: `${plan.platforms.join(', ')}${plan.at ? ` at ${plan.at}${plan.timezone ? ` ${plan.timezone}` : ''}` : ''}` });
+ if (loadConfig(root).publish?.profile !== plan.profile) saveConfig(root, { publish: { ...loadConfig(root).publish, profile: plan.profile } });
+ return sent;
+}
+
+// How the last post of a project is going, per platform, with the links once they're live.
+export async function publishStatus(root, id, { fetch = globalThis.fetch } = {}) {
+ const last = (loadProject(root, id).published || []).at(-1);
+ if (!last) throw new UserError('this project hasn\'t been published');
+ const apiKey = keyValue(root, 'uploadpost');
+ if (!apiKey) throw new UserError('checking needs your Upload-Post API key: add it with `mortiflix keys set uploadpost`');
+ const q = last.job_id ? `job_id=${encodeURIComponent(last.job_id)}` : `request_id=${encodeURIComponent(last.request_id)}`;
+ const res = await fetch(`${API()}/api/uploadposts/status?${q}`, { headers: { Authorization: `Apikey ${apiKey}` } });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new UserError(`Upload-Post couldn't say (${res.status}): ${body.message || body.error || 'no reason given'}`);
+ return {
+ ...last,
+ status: body.status || 'unknown',
+ message: body.message || null,
+ // Each platform: completed, failed, or still on its way (queued, processing…), as Upload-Post reports it.
+ results: (body.results || []).map((r) => ({ platform: r.platform, state: r.status || (r.success ? 'completed' : 'failed'), url: r.post_url || null, message: r.error_message || r.message || null })),
+ };
+}
diff --git a/src/studio.mjs b/src/studio.mjs
index ef52f58..a0868ed 100644
--- a/src/studio.mjs
+++ b/src/studio.mjs
@@ -2,7 +2,7 @@
//
// <studio>/
// config.json settings (backend, model, port...). No secrets.
-// secrets.json your Anthropic and ElevenLabs keys (mode 600), set with `mortiflix keys`. Never served, never logged.
+// secrets.json your Anthropic, ElevenLabs and Upload-Post keys (mode 600), set with `mortiflix keys`. Never served, never logged.
// session.env other keys handed to every session (e.g. GEMINI_API_KEY=...), mode 600, also set with `mortiflix keys`
// checks.json the studio's error checklist (grows from your feedback)
// pipelines/<slug>/ your own pipelines (override the built-in ones with the same slug)
diff --git a/test/publish.test.mjs b/test/publish.test.mjs
new file mode 100644
index 0000000..4541f18
--- /dev/null
+++ b/test/publish.test.mjs
@@ -0,0 +1,132 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tempStudio } from './helpers.mjs';
+import { loadConfig } from '../src/studio.mjs';
+import { createProject, projectPaths, update, loadProject, readEvents } from '../src/projects.mjs';
+import * as keys from '../src/keys.mjs';
+import { publishPlan, publish, publishStatus } from '../src/publish.mjs';
+
+delete process.env.UPLOAD_POST_API_KEY;
+delete process.env.UPLOAD_POST_API;
+
+// A social short that went through every gate: its approved final sits in the record.
+function delivered(root, answers = { message: 'Bikes are faster than you think', platform: 'TikTok / Reels / Shorts' }) {
+ const p = createProject(root, { pipeline: 'social-short', title: 'Fast bikes', answers });
+ const file = 'reviews/final/v2/files/final.mp4';
+ mkdirSync(join(projectPaths(root, p.id).state, 'reviews/final/v2/files'), { recursive: true });
+ writeFileSync(join(projectPaths(root, p.id).state, file), Buffer.alloc(2048));
+ update(root, p.id, (x) => { x.state = 'delivered'; x.deliverables = [{ label: 'Final', kind: 'video', file, size: 2048 }]; });
+ return p.id;
+}
+
+// A fake Upload-Post that records what it was sent.
+function fakeApi(reply) {
+ const calls = [];
+ const fetch = async (url, init = {}) => {
+ calls.push({ url, init, form: init.body instanceof FormData ? init.body : null });
+ const [status, body] = reply(url, init);
+ return new Response(JSON.stringify(body), { status });
+ };
+ return { calls, fetch };
+}
+
+test('publish: only a delivered video, to where the brief said, after the owner names a profile', (t) => {
+ const root = tempStudio(t);
+ const draft = createProject(root, { pipeline: 'social-short', title: 'Not yet', answers: { message: 'x' } });
+ assert.throws(() => publishPlan(root, draft.id, { profile: 'me' }), /isn't delivered yet \(draft\)/);
+
+ const id = delivered(root);
+ assert.throws(() => publishPlan(root, id), /which Upload-Post profile/);
+ const plan = publishPlan(root, id, { profile: 'me' });
+ assert.deepEqual(plan.platforms, ['tiktok', 'instagram', 'youtube']);
+ assert.equal(plan.from_brief, true);
+ assert.equal(plan.title, 'Fast bikes');
+ assert.equal(plan.size, 2048);
+ assert.deepEqual(publishPlan(root, id, { profile: 'me', to: 'LinkedIn, x' }).platforms, ['linkedin', 'x']);
+ assert.throws(() => publishPlan(root, id, { profile: 'me', to: 'myspace' }), /can't publish to myspace/);
+ assert.throws(() => publishPlan(root, id, { profile: 'me', timezone: 'Europe/Madrid' }), /only goes with --at/);
+ assert.throws(() => publishPlan(root, id, { profile: 'me', at: 'next tuesday' }), /isn't a date/);
+ // "Anywhere" names no platform: the owner says where.
+ const anywhere = delivered(root, { message: 'x', platform: 'Anywhere' });
+ assert.throws(() => publishPlan(root, anywhere, { profile: 'me' }), /where to\?/);
+ // The same post twice has the same key; a different time is a different post.
+ assert.equal(publishPlan(root, id, { profile: 'me' }).key, plan.key);
+ assert.notEqual(publishPlan(root, id, { profile: 'me', at: '2026-10-20T18:00' }).key, plan.key);
+});
+
+test('publish: sends the approved file with the key, records it, and remembers the profile', async (t) => {
+ const root = tempStudio(t);
+ const id = delivered(root);
+ const plan = publishPlan(root, id, { profile: 'studio', description: 'Link in bio', at: '2026-10-20T18:00', timezone: 'Europe/Madrid' });
+ await assert.rejects(publish(root, plan, { fetch: fakeApi(() => [200, {}]).fetch }), /needs your Upload-Post API key.*mortiflix keys set uploadpost/);
+
+ keys.saveKey(root, 'uploadpost', 'up-secret');
+ const api = fakeApi(() => [200, { success: true, job_id: 'job-1' }]);
+ const sent = await publish(root, plan, { fetch: api.fetch });
+ assert.equal(sent.job_id, 'job-1');
+ const [call] = api.calls;
+ assert.equal(call.url, 'https://api.upload-post.com/api/upload');
+ assert.equal(call.init.headers.Authorization, 'Apikey up-secret');
+ assert.equal(call.init.headers['Idempotency-Key'], plan.key);
+ assert.equal(call.form.get('user'), 'studio');
+ assert.deepEqual(call.form.getAll('platform[]'), ['tiktok', 'instagram', 'youtube']);
+ assert.equal(call.form.get('title'), 'Fast bikes');
+ assert.equal(call.form.get('description'), 'Link in bio');
+ assert.equal(call.form.get('scheduled_date'), '2026-10-20T18:00');
+ assert.equal(call.form.get('timezone'), 'Europe/Madrid');
+ assert.equal(call.form.get('video').size, 2048);
+
+ assert.equal(loadProject(root, id).published[0].job_id, 'job-1');
+ assert.equal(readEvents(root, id).at(-1).event, 'PUBLISHED');
+ assert.equal(loadConfig(root).publish.profile, 'studio');
+ assert.equal(publishPlan(root, id).profile, 'studio');
+});
+
+test('publish: a refused key and a refused post are sentences, and nothing is recorded', async (t) => {
+ const root = tempStudio(t);
+ const id = delivered(root);
+ keys.saveKey(root, 'uploadpost', 'up-secret');
+ const plan = publishPlan(root, id, { profile: 'me' });
+ await assert.rejects(publish(root, plan, { fetch: fakeApi(() => [401, { message: 'Invalid' }]).fetch }), /refused the API key/);
+ await assert.rejects(publish(root, plan, { fetch: fakeApi(() => [400, { message: 'No TikTok account connected' }]).fetch }), /didn't take it \(400\): No TikTok account connected/);
+ await assert.rejects(publish(root, plan, { fetch: async () => { throw new Error('offline'); } }), /couldn't reach Upload-Post.*never sent twice/);
+ assert.equal(loadProject(root, id).published, undefined);
+});
+
+test('publish: status asks about the last post and reads back each platform', async (t) => {
+ const root = tempStudio(t);
+ const id = delivered(root);
+ keys.saveKey(root, 'uploadpost', 'up-secret');
+ await assert.rejects(publishStatus(root, id), /hasn't been published/);
+ await publish(root, publishPlan(root, id, { profile: 'me', to: 'tiktok,youtube' }), { fetch: fakeApi(() => [200, { request_id: 'req-1' }]).fetch });
+ const api = fakeApi(() => [200, { status: 'completed', results: [
+ { platform: 'tiktok', status: 'completed', success: true, post_url: 'https://www.tiktok.com/@me/video/1' },
+ { platform: 'youtube', status: 'failed', success: false, error_message: 'Daily upload limit reached' },
+ { platform: 'x', status: 'queued', success: false },
+ ] }]);
+ const st = await publishStatus(root, id, { fetch: api.fetch });
+ assert.equal(api.calls[0].url, 'https://api.upload-post.com/api/uploadposts/status?request_id=req-1');
+ assert.equal(st.status, 'completed');
+ assert.deepEqual(st.results, [
+ { platform: 'tiktok', state: 'completed', url: 'https://www.tiktok.com/@me/video/1', message: null },
+ { platform: 'youtube', state: 'failed', url: null, message: 'Daily upload limit reached' },
+ // Not sent yet is not a failure.
+ { platform: 'x', state: 'queued', url: null, message: null },
+ ]);
+});
+
+test('keys: the Upload-Post key is checked with a free call and never handed to sessions', async (t) => {
+ const root = tempStudio(t);
+ const reply = (status, body = {}) => async () => new Response(JSON.stringify(body), { status });
+ const ok = await keys.verifyKey(root, 'uploadpost', 'k', { fetch: reply(200, { success: true, plan: 'Basic' }) });
+ assert.deepEqual(ok, { ok: true, detail: 'Basic plan' });
+ assert.equal((await keys.verifyKey(root, 'uploadpost', 'k', { fetch: reply(401) })).ok, false);
+ assert.equal((await keys.verifyKey(root, 'uploadpost', 'k', { fetch: reply(503) })).ok, null);
+ keys.saveKey(root, 'uploadpost', 'up-secret');
+ assert.equal(keys.keySource(root, 'uploadpost'), 'saved');
+ assert.ok(!JSON.stringify(keys.keyStatus(root)).includes('up-secret'));
+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', steps: [{ work: ['motion', 'audio'] }] }), []);
+ assert.throws(() => keys.setSessionKey(root, 'UPLOAD_POST_API_KEY', 'x'), /its own place/);
+});