Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Release copy: keep hand-written posts, numbers and links through a redraft

Claude7fcf02037382
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsx
index e9c843881f..082ccb656c 100644
--- a/client/src/components/musicVideo/PublishKitPanel.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.jsx
@@ -84,7 +84,14 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets })
const [songUrl, setSongUrl] = useState(kit.links?.song || '');
const [include, setInclude] = useState({ ...DEFAULT_INCLUDE, ...(kit.draftOptions?.include || {}) });
const [length, setLength] = useState(kit.draftOptions?.length === 'full' ? 'full' : 'short');
- const lyricLines = (project?.lyricCues || []).filter((c) => typeof c?.text === 'string' && c.text.trim()).length;
+ // Same filter as the server's timedLines: only cues with text and a start time reach the writer.
+ const lyricLines = (project?.lyricCues || [])
+ .filter((c) => typeof c?.text === 'string' && c.text.trim() && typeof c.startSec === 'number' && Number.isFinite(c.startSec)).length;
+ const [confirmReplace, setConfirmReplace] = useState(false);
+ // Mirrors the server's copyEditedSinceDraft: a draft would replace posts written or edited by hand.
+ const editedAt = Date.parse(kit.copyEditedAt || '');
+ const draftedAt = Date.parse(kit.copyDraftedAt || '');
+ const editedSinceDraft = Number.isFinite(editedAt) && (!Number.isFinite(draftedAt) || editedAt > draftedAt);
const spend = projectSpend(project);
const includeRows = [
{ key: 'title', label: 'Song title', detail: project?.name ? `"${project.name}"` : 'no title yet', available: !!project?.name },
@@ -102,13 +109,15 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets })
...(/^https?:\/\//.test(youtubeUrl.trim()) ? { youtube: youtubeUrl.trim() } : {}),
...(/^https?:\/\//.test(songUrl.trim()) ? { song: songUrl.trim() } : {}),
};
- const draft = () => publishKit.draftCopy({
+ const draft = (replaceEdited = false) => publishKit.draftCopy({
...(selectedProviderId ? { providerId: selectedProviderId } : {}),
...(selectedModel ? { model: selectedModel } : {}),
notes, links,
include: Object.fromEntries(includeRows.map(({ key, available }) => [key, available && include[key]])),
length,
+ ...(replaceEdited ? { replaceEdited: true } : {}),
});
+ const onDraft = () => (editedSinceDraft ? setConfirmReplace(true) : draft());
return (
<div className="space-y-3">
@@ -232,11 +241,20 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets })
label="Writer" compact alwaysShowModel modelDisabled={availableModels.length === 0}
emptyProviderOption="Active provider (default)" emptyModelOption="Default model" disabled={publishKit.drafting} />
)}
- <button type="button" onClick={draft} disabled={publishKit.drafting || noPlatforms}
+ <button type="button" onClick={onDraft} disabled={publishKit.drafting || publishKit.saving || noPlatforms || confirmReplace}
className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
<Sparkles size={13} /> {publishKit.drafting ? 'Drafting…' : (kit.copy ? 'Redraft copy' : 'Draft copy')}
</button>
</div>
+ {confirmReplace && (
+ <div role="alert" className="flex flex-wrap items-center gap-2 rounded border border-port-warning/50 bg-port-warning/10 p-2">
+ <span className="flex-1 min-w-[12rem]">Drafting replaces the posts you wrote or edited below.</span>
+ <button type="button" onClick={() => { setConfirmReplace(false); draft(true); }}
+ className="bg-port-warning/20 text-port-warning rounded px-2 py-1.5 min-h-[44px] sm:min-h-0">Replace them</button>
+ <button type="button" onClick={() => setConfirmReplace(false)}
+ className="text-port-text-muted px-2 py-1.5 min-h-[44px] sm:min-h-0">Keep mine</button>
+ </div>
+ )}
{noPlatforms && <p className="text-port-text-muted">Turn on a platform under Where you post to draft its copy.</p>}
{!noPlatforms && (
<div className="space-y-3" key={kit.copyDraftedAt || 'copy'}>
diff --git a/client/src/components/musicVideo/PublishKitPanel.test.jsx b/client/src/components/musicVideo/PublishKitPanel.test.jsx
index bab76fae06..21e8f61ec5 100644
--- a/client/src/components/musicVideo/PublishKitPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.test.jsx
@@ -38,7 +38,7 @@ describe('PublishKitPanel (#9281)', () => {
it('drafts copy from the notes, only well-formed links and only what is ticked', () => {
const k = hook();
- const project = { id: 'mv-1', name: 'Example Song', renderHistoryId: 'rh-1', lyricCues: [{ text: 'a line', startSec: 1 }], productionRuns: [{ usage: { spentUsd: 4.5 } }] };
+ const project = { id: 'mv-1', name: 'Example Song', renderHistoryId: 'rh-1', lyricCues: [{ text: 'a line', startSec: 1 }, { text: 'untimed' }], productionRuns: [{ usage: { spentUsd: 4.5 } }] };
render(<PublishKitPanel project={project} publishKit={k} />);
fireEvent.change(screen.getByLabelText(/Making-of notes/), { target: { value: 'hummed it in the car' } });
fireEvent.change(screen.getByLabelText(/Full video URL/), { target: { value: 'https://example.com/v' } });
@@ -47,6 +47,7 @@ describe('PublishKitPanel (#9281)', () => {
expect(screen.getByLabelText(/Song title/)).toBeChecked();
expect(screen.getByLabelText(/Hashtags and YouTube tags/)).not.toBeChecked();
expect(screen.getByLabelText('A sentence or two')).toBeChecked();
+ expect(screen.getByText(/1 timed line$/)).toBeTruthy(); // the untimed cue never reaches the writer
fireEvent.click(screen.getByRole('button', { name: /Draft copy/ }));
const none = { title: true, lyrics: false, chapters: false, spend: false, hashtags: false };
expect(k.draftCopy).toHaveBeenLastCalledWith({ notes: 'hummed it in the car', links: { youtube: 'https://example.com/v' }, include: none, length: 'short' });
@@ -60,9 +61,22 @@ describe('PublishKitPanel (#9281)', () => {
expect(k.draftCopy).toHaveBeenLastCalledWith(expect.objectContaining({ include: { ...none, title: false, lyrics: true, spend: true, hashtags: true }, length: 'full' }));
});
+ it('asks before a draft replaces posts edited by hand', () => {
+ const k = hook();
+ const publishKit = { copy: { x: { hook: 'Mine.' } }, copyDraftedAt: '2026-01-01T00:00:00.000Z', copyEditedAt: '2026-01-02T00:00:00.000Z' };
+ render(<PublishKitPanel project={{ id: 'mv-1', name: 'Example Song', publishKit }} publishKit={k} enabledTargets={['x']} />);
+ fireEvent.click(screen.getByRole('button', { name: /Redraft copy/ }));
+ expect(k.draftCopy).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Keep mine' }));
+ expect(k.draftCopy).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: /Redraft copy/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Replace them' }));
+ expect(k.draftCopy).toHaveBeenCalledWith(expect.objectContaining({ replaceEdited: true }));
+ });
+
it('cannot tick lyrics or spend the project does not have, and lets you write a post without drafting', () => {
const k = hook();
- render(<PublishKitPanel project={{ id: 'mv-1', name: 'Example Song', renderHistoryId: 'rh-1' }} publishKit={k} enabledTargets={['x']} />);
+ render(<PublishKitPanel project={{ id: 'mv-1', name: 'Example Song', renderHistoryId: 'rh-1', lyricCues: [{ text: 'untimed' }] }} publishKit={k} enabledTargets={['x']} />);
expect(screen.getByLabelText(/Lyrics/)).toBeDisabled();
expect(screen.getByLabelText(/Generation spend/)).toBeDisabled();
const hook_ = screen.getByLabelText('Hook post (no links)');
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index f0beaf0619..bde9d3d376 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -687,6 +687,8 @@ export const musicVideoPublishCopyDraftSchema = z.object({
// What the draft may use beyond the notes and links; omitted keys keep their defaults (title on, the rest off).
include: z.object({ title: z.boolean(), lyrics: z.boolean(), spend: z.boolean(), chapters: z.boolean(), hashtags: z.boolean() }).partial().strict().optional(),
length: z.enum(['short', 'full']).optional(),
+ // The director agreed to replace posts written or edited by hand since the last draft.
+ replaceEdited: z.boolean().optional(),
}).strict();
export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().min(1).max(300) }).strict();
diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.js
index 47aa5d7415..e5cd27938e 100644
--- a/server/services/musicVideo/publishKit.js
+++ b/server/services/musicVideo/publishKit.js
@@ -234,6 +234,14 @@ export async function updatePublishKitCopy(projectId, patch) {
});
}
+/** True when a post was written or edited by hand after the last draft (or with no draft yet). */
+export function copyEditedSinceDraft(kit) {
+ const edited = Date.parse(kit?.copyEditedAt || '');
+ if (!Number.isFinite(edited)) return false;
+ const drafted = Date.parse(kit?.copyDraftedAt || '');
+ return !Number.isFinite(drafted) || edited > drafted;
+}
+
/** Generation spend across the project's production runs (what the copy may claim). */
function spentUsd(project) {
const total = (project.productionRuns || []).reduce((sum, run) => sum + (Number.isFinite(Number(run?.usage?.spentUsd)) ? Number(run.usage.spentUsd) : 0), 0);
@@ -243,10 +251,17 @@ function spentUsd(project) {
/**
* Draft the copy for every platform the director posts to, in ONE provider call they asked for.
* `notes` (their making-of story) and what they chose to include (`include`,
- * `length`) are saved with the kit so a redraft reuses them.
+ * `length`) are saved with the kit so a redraft reuses them. A draft replaces
+ * the posts' text, so once a post was written or edited by hand since the last
+ * draft it is refused (409 PUBLISH_COPY_EDITED) unless `replaceEdited` says the
+ * director agreed to replace it. Fields the draft does not return (YouTube tags
+ * with hashtags off) keep what was there.
*/
-export async function draftPublishKitCopy(projectId, { providerId = null, model = null, notes = '', links = {}, include, length } = {}, deps = {}) {
+export async function draftPublishKitCopy(projectId, { providerId = null, model = null, notes = '', links = {}, include, length, replaceEdited = false } = {}, deps = {}) {
const project = await requireProject(projectId);
+ if (!replaceEdited && copyEditedSinceDraft(projectPublishKit(project))) {
+ throw kitError(409, 'PUBLISH_COPY_EDITED', 'The posts were edited by hand since the last draft; confirm replacing them to draft again');
+ }
const { getPublishPlatforms, publishHistory } = await import('./publish/platforms.js');
const enabled = deps.platforms || await getPublishPlatforms();
// Only where the director posts (#9287); Suno's caption reuses the YouTube description.
@@ -264,6 +279,8 @@ export async function draftPublishKitCopy(projectId, { providerId = null, model
if (!copy) throw kitError(502, 'PUBLISH_COPY_UNPARSEABLE', 'The copy draft came back without usable JSON — try again or another model');
return mutateProjectRecord(projectId, (current) => {
const kit = projectPublishKit(current);
- return { project: { ...current, publishKit: { ...kit, copy: { ...(kit.copy || {}), ...copy }, notes, draftOptions: options, links: { ...(kit.links || {}), ...links }, copyDraftedAt: new Date().toISOString() } } };
+ const merged = { ...(kit.copy || {}) };
+ for (const [platform, fields] of Object.entries(copy)) merged[platform] = { ...(merged[platform] || {}), ...fields };
+ return { project: { ...current, publishKit: { ...kit, copy: merged, notes, draftOptions: options, links: { ...(kit.links || {}), ...links }, copyDraftedAt: new Date().toISOString() } } };
});
}
diff --git a/server/services/musicVideo/publishKit.test.js b/server/services/musicVideo/publishKit.test.js
index ee4f8dacb2..f3dff256ec 100644
--- a/server/services/musicVideo/publishKit.test.js
+++ b/server/services/musicVideo/publishKit.test.js
@@ -142,13 +142,26 @@ describe('publishing kit copy (#9281)', () => {
expect(deps.runner.runPromptThroughProvider).toHaveBeenCalledTimes(1);
expect(deps.runner.runPromptThroughProvider.mock.calls[0][0]).toMatchObject({ source: 'music-video-publish-copy' });
// Nothing beyond the title is ticked by default, so the model's tags are dropped and the choice is kept for a redraft.
- expect(project.publishKit).toMatchObject({ notes: 'made it on a Sunday', links: { youtube: 'https://example.com/v' }, copy: { youtube: { title: 'A title', tags: [] }, x: { hook: 'a hook' } } });
+ expect(project.publishKit).toMatchObject({ notes: 'made it on a Sunday', links: { youtube: 'https://example.com/v' }, copy: { youtube: { title: 'A title' }, x: { hook: 'a hook' } } });
+ expect(project.publishKit.copy.youtube).not.toHaveProperty('tags');
expect(project.publishKit.draftOptions).toEqual({ include: { title: true, lyrics: false, spend: false, chapters: false, hashtags: false }, length: 'short' });
const edited = await kit.updatePublishKitCopy(id, { x: { hook: 'my own hook' } });
expect(edited.project.publishKit.copy.x).toEqual({ hook: 'my own hook', story: 'story' });
expect(edited.project.publishKit.copy.youtube.title).toBe('A title');
});
+ it('will not replace posts edited by hand unless the director confirms, and keeps fields the draft leaves out', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ await kit.updatePublishKitCopy(id, { youtube: { title: 'My title', tags: ['my tag'] } });
+ const deps = { platforms: ALL_ON, history: {}, runner: runner(JSON.stringify({ youtube: { title: 'Drafted', description: 'd', tags: ['model tag'] } })) };
+ await expect(kit.draftPublishKitCopy(id, {}, deps)).rejects.toMatchObject({ status: 409, code: 'PUBLISH_COPY_EDITED' });
+ expect(deps.runner.runPromptThroughProvider).not.toHaveBeenCalled();
+ const { project } = await kit.draftPublishKitCopy(id, { replaceEdited: true }, deps);
+ expect(project.publishKit.copy.youtube).toEqual({ title: 'Drafted', description: 'd', tags: ['my tag'] });
+ // Right after a draft nothing was edited, so redrafting needs no confirmation.
+ await expect(kit.draftPublishKitCopy(id, {}, deps)).resolves.toBeTruthy();
+ });
+
it('reports an unusable draft instead of saving it', async () => {
const { id } = await projects.createProject({ name: 'Example Song' });
await expect(kit.draftPublishKitCopy(id, {}, { platforms: ALL_ON, history: {}, runner: runner('sorry, no JSON') })).rejects.toMatchObject({ status: 502, code: 'PUBLISH_COPY_UNPARSEABLE' });
diff --git a/server/services/musicVideo/publishKitText.js b/server/services/musicVideo/publishKitText.js
index 7cc058358e..763cb1062e 100644
--- a/server/services/musicVideo/publishKitText.js
+++ b/server/services/musicVideo/publishKitText.js
@@ -148,15 +148,24 @@ function copySpecs({ include, length }) {
};
}
-// A #word anywhere in the text; markdown headings ("# Heading") have a space and are left alone.
-const HASHTAG = /(^|[^\p{L}\p{N}_&])#[\p{L}\p{N}_]+/gu;
-/** The text with every hashtag removed and the spacing it leaves tidied. */
-export const stripHashtags = (text) => String(text || '')
- .replace(HASHTAG, '$1')
- .replace(/[ \t]+$/gm, '')
- .replace(/[ \t]{2,}/g, ' ')
- .replace(/\n{3,}/g, '\n\n')
- .trim();
+// A run of hashtags: `#` plus a word with at least one letter (so `#1` and
+// `#2` stay), standing at a line start or after a space or opening bracket or
+// quote (so a URL fragment like `/album/#listen` and `&#39;` stay). Markdown
+// headings ("# Heading") have a space after the `#` and never match.
+const TAG = String.raw`#[\p{N}_]*\p{L}[\p{L}\p{N}_]*`;
+const HASHTAG_RUN = new RegExp(String.raw`([ \t]*)(?<=^|[\s(\[{"'“‘])${TAG}(?:[ \t]+${TAG})*([ \t]*)`, 'gmu');
+/**
+ * The text with every hashtag removed. Only the spacing around a removed tag
+ * changes: a run ending its line takes the spaces before it too, and one
+ * mid-line leaves a single space, so indentation and markdown line breaks
+ * elsewhere are untouched.
+ */
+export const stripHashtags = (text) => String(text || '').replace(HASHTAG_RUN, (match, lead, _trail, offset, whole) => {
+ const end = offset + match.length;
+ const lineStart = offset === 0 || whole[offset - 1] === '\n';
+ if (end >= whole.length || whole[end] === '\n' || whole[end] === '\r') return lineStart ? lead : '';
+ return lineStart ? lead : (lead ? ' ' : '');
+});
/**
* The copy prompt. `notes` is the director's own making-of story; the song
@@ -201,17 +210,21 @@ export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, l
/**
* The model's JSON reply as `{ platform: { field: text } }` for `platforms`,
* clipped to each platform's limits; null when unusable. Without
- * `hashtags: true` every hashtag the model slipped in is removed and YouTube
- * tags stay empty, so none reaches a post unasked.
+ * `hashtags: true` every hashtag the model slipped in is removed and no
+ * YouTube tags are returned (the `tags` key is left out, so tags the director
+ * typed survive a redraft), so none reaches a post unasked.
*/
export function parsePublishCopy(text, platforms = PUBLISH_PLATFORMS, { hashtags = true } = {}) {
const { value } = extractJson(text, { blockType: 'object' });
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const clean = (fields) => (hashtags || !fields || typeof fields !== 'object' ? fields
- : Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, k === 'tags' ? [] : (typeof f === 'string' ? stripHashtags(f) : f)])));
+ : Object.fromEntries(Object.entries(fields).filter(([k]) => k !== 'tags').map(([k, f]) => [k, typeof f === 'string' ? stripHashtags(f) : f])));
const v = (k) => (value[k] && typeof value[k] === 'object' ? clean(value[k]) : {});
const all = {
- youtube: () => ({ title: str(v('youtube').title, LIMITS.youtubeTitle), description: str(v('youtube').description, 5000), tags: (Array.isArray(v('youtube').tags) ? v('youtube').tags : []).map((t) => str(t, 60)).filter(Boolean).slice(0, 20) }),
+ youtube: () => ({
+ title: str(v('youtube').title, LIMITS.youtubeTitle), description: str(v('youtube').description, 5000),
+ ...(hashtags ? { tags: (Array.isArray(v('youtube').tags) ? v('youtube').tags : []).map((t) => str(t, 60)).filter(Boolean).slice(0, 20) } : {}),
+ }),
shorts: () => ({ title: str(v('shorts').title, LIMITS.shortsTitle), description: str(v('shorts').description, 5000) }),
x: () => ({ hook: str(v('x').hook, LIMITS.xHook), story: str(v('x').story, 25000) }),
tiktok: () => ({ caption: str(v('tiktok').caption, LIMITS.caption) }),
diff --git a/server/services/musicVideo/publishKitText.test.js b/server/services/musicVideo/publishKitText.test.js
index 7f719e8807..8d2dd6d4cb 100644
--- a/server/services/musicVideo/publishKitText.test.js
+++ b/server/services/musicVideo/publishKitText.test.js
@@ -66,12 +66,15 @@ describe('publish copy prompt + parser (#9281)', () => {
expect(all).toContain('the making-of as a long post');
});
- it('strips hashtags the model added unasked, keeping markdown headings', () => {
- const reply = JSON.stringify({ tiktok: { caption: 'Made this one slowly. #music #aivideo' }, youtube: { title: 'T', description: '# Heading\nA line #tagged here', tags: ['music'] } });
+ it('strips hashtags the model added unasked and leaves everything else as written', () => {
+ const description = '# Heading\nA line #tagged here, my #1 take\n - nested item \nSee https://example.com/album/#listen';
+ const reply = JSON.stringify({ tiktok: { caption: 'Made this one slowly. #music #aivideo' }, youtube: { title: 'T', description, tags: ['music'] } });
const copy = parsePublishCopy(reply, ['tiktok', 'youtube'], { hashtags: false });
expect(copy.tiktok.caption).toBe('Made this one slowly.');
- expect(copy.youtube.description).toBe('# Heading\nA line here');
- expect(copy.youtube.tags).toEqual([]);
+ // Numbers, URL fragments, headings, indentation and markdown hard breaks survive.
+ expect(copy.youtube.description).toBe('# Heading\nA line here, my #1 take\n - nested item \nSee https://example.com/album/#listen');
+ // No tags come back, so a redraft keeps the ones the director typed.
+ expect(copy.youtube).not.toHaveProperty('tags');
expect(parsePublishCopy(reply, ['tiktok']).tiktok.caption).toContain('#music');
});