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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(publish): record the post link when you post from a filled tab
Claudec431e98d2ae1
diff --git a/client/src/hooks/useMusicVideoPublishing.js b/client/src/hooks/useMusicVideoPublishing.jsindex bc2f5588f0..7dedef9de5 100644--- a/client/src/hooks/useMusicVideoPublishing.js+++ b/client/src/hooks/useMusicVideoPublishing.js@@ -35,6 +35,9 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}const { drafts, busy, errors } = posting.scope === scope ? posting : EMPTY_POSTING;const [platforms, setPlatforms] = useState(null);const [history, setHistory] = useState({});+ // The socket handler below outlives renders; it reads the latest callback.+ const replaceProjectRef = useRef(replaceProject);+ replaceProjectRef.current = replaceProject;const loadPlatforms = useCallback(() => getMusicVideoPublishPlatforms({ silent: true }).then((res) => { setPlatforms(res?.platforms || {}); setHistory(res?.history || {}); })@@ -54,7 +57,8 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}};// Rehydrate from the server after a reload, and follow its draft events- // (a tab filled elsewhere, closed by hand, or discarded).+ // (a tab filled elsewhere, closed by hand, discarded, or posted from by the+ // director, in which case the server has already recorded the post's link).useEffect(() => {if (!projectId) return undefined;let cancelled = false;@@ -62,7 +66,11 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}getMusicVideoPublishDrafts(projectId, { silent: true }).then((res) => apply(res?.drafts || [])).catch(() => {});const onDraft = (e) => {if (e?.projectId !== projectId) return;- if (e.state === 'discarded') {+ if (e.state === 'posted') {+ if (e.project) replaceProjectRef.current?.(e.project);+ loadPlatforms();+ }+ if (e.state === 'discarded' || e.state === 'posted') {setPosting((prev) => {const current = prev.scope === scope ? prev.drafts[e.target] : null;if (!current || current.draftId !== e.draftId) return prev;@@ -81,7 +89,7 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}socket.on('music-video:publish-draft', onDraft);return () => { cancelled = true; socket.off('music-video:publish-draft', onDraft); };// eslint-disable-next-line react-hooks/exhaustive-deps- }, [projectId, scope]);+ }, [projectId, scope, loadPlatforms]);const prepare = (target, options = {}) => {setFor('busy', target, 'prepare');diff --git a/client/src/hooks/useMusicVideoPublishing.test.jsx b/client/src/hooks/useMusicVideoPublishing.test.jsxindex 65e4fb90be..1ca00d0cd1 100644--- a/client/src/hooks/useMusicVideoPublishing.test.jsx+++ b/client/src/hooks/useMusicVideoPublishing.test.jsx@@ -27,9 +27,9 @@ const deferred = () => {const promise = new Promise((res, rej) => { resolve = res; reject = rej; });return { promise, resolve, reject };};-function Posting({ id }) {+function Posting({ id, replaceProject = vi.fn() }) {const selected = project(id);- const publishing = useMusicVideoPublishing({ project: selected, replaceProject: vi.fn() });+ const publishing = useMusicVideoPublishing({ project: selected, replaceProject });return <PublishPostingPanel project={selected} publishing={publishing} />;}@@ -98,4 +98,17 @@ describe('music-video publishing project boundary', () => {expect(screen.getByText('Tab closed — Fill again')).toBeInTheDocument();expect(screen.queryByText('Example A')).not.toBeInTheDocument();});++ it('applies the post the server detected in a filled tab: the draft goes and its recorded link arrives', async () => {+ api.getMusicVideoPublishDrafts.mockResolvedValueOnce({ drafts: [{ draftId: 'draft-a', target: 'youtube', state: 'open', summary: { title: 'Example A' } }] });+ const replaceProject = vi.fn();+ render(<Posting id="project-a" replaceProject={replaceProject} />);+ expect(await screen.findByText('Example A')).toBeInTheDocument();+ const onDraft = socket.on.mock.calls.find(([event]) => event === 'music-video:publish-draft')[1];+ const posted = { id: 'project-a', publishKit: { posts: { youtube: { url: 'https://www.youtube.com/watch?v=example' } } } };+ await act(async () => { onDraft({ projectId: 'project-a', draftId: 'draft-a', target: 'youtube', state: 'posted', url: posted.publishKit.posts.youtube.url, project: posted }); });+ expect(replaceProject).toHaveBeenCalledWith(posted);+ expect(screen.queryByText('Example A')).not.toBeInTheDocument();+ expect(api.getMusicVideoPublishPlatforms).toHaveBeenCalledTimes(2); // history refreshed+ });});diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdindex ae2a5d8b02..68e5ca4b8e 100644--- a/docs/features/music-video-autonomous.md+++ b/docs/features/music-video-autonomous.md@@ -88,7 +88,7 @@ A proof approval is bound to its exact excerpt ID and filename; `energyCompariso**Automatic planning approvals.** An authenticated start or `POST /api/music-video/:id/autonomous/resume` can grant `autoApprove: ['art', 'storyboard']` (any subset). The run records `brief.autoApprove`, `brief.autoApproveAuthorizedAt`, and `brief.autoApproveAuthorizedBy`; automatic decisions also record the run ID. A resume list replaces the grant; explicit `[]` revokes it and also requires authentication. Omitting the list preserves the existing policy. In **Produce**, the run first waits for Cast & Sets to draft the art guide (`stages.produce.step: 'cast-and-sets'`; its settle event carries the run on, and a failed Cast & Sets fails the run with `CAST_SETS_FAILED`), so the art gate is never judged empty. A `storyboard` grant also makes the run do the lyric-timing chores a director would: after analysis it aligns the vocal to the lyric sheet and times lines alignment skipped, then before the storyboard gate it verifies the timing (reviewer `{ kind: 'autopilot', runId }`), marks an instrumental song as one, and anchors each shot to the lyric lines it overlaps. It verifies only timings it can trust: when alignment failed or the recognizer heard less than half of the words, the timings are mostly guesses, so it leaves them provisional and parks the run with that reason. Automatic planning approval still requires a clean readiness report; a line it cannot time, or any other open problem, still parks the run. Proof is never auto-approved; a legacy brief listing `proof` is ignored for it, since the final render no longer waits on a proof. Start drawer and run panel expose the planning choices without a password field, and the run panel shows existing grants so they can be revoked.-External draft preparation uses the existing authenticated session without password re-entry; agents may prepare drafts. PortOS never submits a final post: review and publish on the destination platform, then record the resulting link. Existing projects and assets remain intact, but an older project's final render now requires the same production review.+External draft preparation uses the existing authenticated session without password re-entry; agents may prepare drafts. PortOS never submits a final post: review and publish on the destination platform. When the filled tab lands on the new post's own page (Stacker News, Reddit, Substack, DistroKid), PortOS records that link itself while the tab's session is attached; otherwise paste the link on the platform's card. Existing projects and assets remain intact, but an older project's final render now requires the same production review.The local browser acceptance test (`server/routes/musicVideoProductionReview.browser.test.js`) exercises the real React controls, approval routes, native code renderer, ffmpeg output and video playback with synthetic data. It requires Chrome, ffmpeg and installed client dependencies; server-only CI skips this cross-workspace check. API and orchestration tests run independently of those visual-test prerequisites.diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 7e9c0807a8..335ee476cd 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -60,7 +60,8 @@ import { EventEmitter } from 'events';// `music-video:dev-artifact`.// 'publish-draft' → { projectId, draftId, target, state } — a publish draft's// tab was filled ('open'), closed by hand ('closed') or discarded; bridged-// to `music-video:publish-draft`.+// to `music-video:publish-draft`. 'posted' adds `url` and `project`: the+// director posted from the filled tab and PortOS recorded the link.// 'cover-art' → { projectId, project } — the release cover art was// composed, or a cover source image was queued, landed or failed; bridged// to `music-video:cover-art`.diff --git a/server/services/musicVideo/publish/browser.js b/server/services/musicVideo/publish/browser.jsindex 643f9ce354..cfe5584457 100644--- a/server/services/musicVideo/publish/browser.js+++ b/server/services/musicVideo/publish/browser.js@@ -120,3 +120,17 @@ export async function ensureToggleBeside(page, labelText) {return null;}, labelText);}++/**+ * Whether the tab now shows the post the director made by hand: its URL is the+ * platform's page for a new post (`pattern`) and the page shows the post's+ * title, so browsing elsewhere in the filled tab never counts. Resolves the+ * post's link (`canonical` of the match) or null. Nothing is pressed.+ */+export async function landedOnPost(page, pattern, title, canonical = (match) => match[0]) {+ const match = page.url().match(pattern);+ const want = String(title || '').trim().slice(0, 40);+ if (!match || !want) return null;+ const shown = await page.waitForFunction((t) => (document.body?.innerText || '').includes(t), want, { timeout: 15_000 }).then(() => true, () => false);+ return shown ? canonical(match) : null;+}diff --git a/server/services/musicVideo/publish/distrokid.js b/server/services/musicVideo/publish/distrokid.jsindex e1e5525cd1..312bab5c1c 100644--- a/server/services/musicVideo/publish/distrokid.js+++ b/server/services/musicVideo/publish/distrokid.js@@ -15,7 +15,7 @@* no longer there is reported in the summary as left for the director rather* than failing the whole draft.*/-import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, landedOnPost, loginRequired, step } from './browser.js';import { discloseDistrokidAi, fillDistrokidFields, setDistrokidArtist, untickDistrokidExtras } from '../../../lib/distrokidForm.js';const label = 'DistroKid';@@ -125,4 +125,6 @@ export const distrokidAdapter = {leftForYou: [...leftForYou, 'which stores (DistroKid picks all by default)', 'the agreement checkboxes', 'Upload'],};},+ // Uploaded, DistroKid opens the release's own dashboard page.+ findPost: (page, payload) => landedOnPost(page, /^https:\/\/distrokid\.com\/dashboard\/album\/\?albumuuid=[0-9a-f-]+/i, payload.title),};diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex f78cd3a2cf..56b01abbce 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -2,8 +2,10 @@* Prepare external platform drafts for manual review and publication.* Draft preparation requires an existing authenticated session, including agents.* PortOS never submits a draft; the operator publishes in the destination- * platform and records its URL. Adapter preparation runs in a serialized,- * dedicated browser tab. Existing drafts can be discarded or replaced.+ * platform. Where a platform lands the filled tab on the new post's own page,+ * PortOS records that link itself; otherwise the operator pastes it. Adapter+ * preparation runs in a serialized, dedicated browser tab. Existing drafts can+ * be discarded or replaced.*/import { randomUUID } from 'crypto';import { existsSync } from 'fs';@@ -85,6 +87,44 @@ async function closeDraft(draft, deps) {emitDraft(draft, 'discarded');}+/**+ * Record the post the director just made by hand in a filled tab, and let the+ * tab go: it now shows their post, so it stays open with no session attached.+ */+async function recordDetectedPost(draft, url) {+ if (!drafts.has(draft.id)) return;+ drafts.delete(draft.id);+ draft.state = 'posted';+ const { project } = await recordPublishPost(draft.projectId, draft.target, { url });+ await detachDraft(draft);+ musicVideoEvents.emit('publish-draft', { projectId: draft.projectId, draftId: draft.id, target: draft.target, state: 'posted', url, project });+ console.log(`🔗 ${draft.target} post recorded for music-video ${draft.projectId.slice(0, 8)}: ${url}`);+}++/**+ * Follow a filled tab while its session is attached: each time it navigates,+ * the adapter's `findPost` says whether it now shows the director's new post+ * (by URL and title). Reads only; PortOS still presses nothing.+ */+function watchForPost(draft, adapter) {+ const { page } = draft;+ if (typeof adapter.findPost !== 'function' || typeof page.on !== 'function') return;+ let checking = false;+ let again = false;+ const check = () => {+ if (draft.page !== page || !drafts.has(draft.id)) return;+ if (checking) { again = true; return; }+ checking = true;+ again = false;+ Promise.resolve()+ .then(() => adapter.findPost(page, draft.payload))+ .then((url) => (url ? recordDetectedPost(draft, url) : null))+ .catch((err) => console.warn(`⚠️ ${adapter.label}: could not read the new post's link (${err?.message})`))+ .finally(() => { checking = false; if (again) check(); });+ };+ page.on('framenavigated', (frame) => { if (frame === page.mainFrame()) check(); });+}+const DIRS = { videos: () => PATHS.videos, videoThumbnails: () => PATHS.videoThumbnails };/** Resolve every `{ dir, name }` file ref in a payload to an existing absolute `path`. */@@ -186,6 +226,7 @@ export async function preparePublishDraft(projectId, target, options = {}, depsdraft.timer.unref?.();page.once?.('close', () => { if (draft.page === page && draft.state === 'open' && drafts.has(id)) { draft.state = 'closed'; emitDraft(draft); } });drafts.set(id, draft);+ watchForPost(draft, adapter);emitDraft(draft);console.log(`📝 ${adapter.label} draft filled for music-video ${projectId.slice(0, 8)} [${id.slice(6, 14)}]`);return draftPresentation(draft);diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.jsindex 6fc5bb4d0a..1f452e0751 100644--- a/server/services/musicVideo/publish/index.test.js+++ b/server/services/musicVideo/publish/index.test.js@@ -16,6 +16,7 @@ const { PATHS } = await import('../../../lib/paths.js');const projects = await import('../projects.js');const { preparePublishDraft, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost } = await import('./index.js');const { musicVideoEvents } = await import('../events.js');+const { stackerNewsAdapter } = await import('./stackerNews.js');const platforms = { stackerNews: { enabled: true, account: null }, youtube: { enabled: true, account: null }, x: { enabled: true, account: 'antic' } };@@ -33,10 +34,18 @@ function fakeBrowser() {pages: () => pages.filter((page) => !page.closed),newPage: async () => {const handlers = [];+ const navigated = [];+ const frame = {};const page = {closed: false, bringToFront: vi.fn(async () => {}), screenshot: vi.fn(async () => Buffer.from('jpg')),- url: () => `https://example.com/post/${pages.indexOf(page)}`,+ href: null, text: '',+ url: () => page.href || `https://example.com/post/${pages.indexOf(page)}`,once: (_event, fn) => handlers.push(fn),+ on: (event, fn) => { if (event === 'framenavigated') navigated.push(fn); },+ mainFrame: () => frame,+ // The director moves the tab on (by posting, or browsing away).+ navigate: async (href, text = '') => { page.href = href; page.text = text; navigated.forEach((fn) => fn(frame)); await new Promise((r) => setTimeout(r, 0)); },+ waitForFunction: vi.fn(async (_fn, want) => { if (!page.text.includes(want)) throw new Error('timed out'); }),isClosed() { return this.closed; },close: vi.fn(async function close() { page.closed = true; handlers.forEach((fn) => fn()); }),};@@ -92,6 +101,32 @@ describe('publish drafts (#9282)', () => {expect(project.publishKit.posts.stackerNews.url).toBe(post.url);});+ it('records the post the director makes by hand in the filled tab, and nothing else they browse to', async () => {+ const id = await readyProject();+ const { connect, pages } = fakeBrowser();+ const events = [];+ const onEvent = (e) => events.push(e);+ musicVideoEvents.on('publish-draft', onEvent);+ try {+ const adapters = { stackerNews: adapter({ findPost: stackerNewsAdapter.findPost }) };+ const draft = await preparePublishDraft(id, 'stackerNews', { territory: 'art' }, { connect, adapters, platforms });+ // Another item's page, or a page without this post's title, is not this post.+ await pages[0].navigate('https://stacker.news/~art', 'Song');+ await pages[0].navigate('https://stacker.news/items/99', 'Someone else\'s post');+ expect((await projects.getProject(id)).publishKit.posts?.stackerNews).toBeUndefined();++ await pages[0].navigate('https://stacker.news/items/123', 'Song \\ stacker news');+ await vi.waitFor(() => expect(events.at(-1)).toMatchObject({ draftId: draft.draftId, state: 'posted', url: 'https://stacker.news/items/123' }));+ expect(events.at(-1).project.publishKit.posts.stackerNews.url).toBe('https://stacker.news/items/123');+ expect((await projects.getProject(id)).publishKit.posts.stackerNews).toMatchObject({ url: 'https://stacker.news/items/123', postedAt: expect.any(String) });+ expect(adapters.stackerNews.submit).not.toHaveBeenCalled();+ expect(pages[0].closed).toBe(false); // the tab now shows their post+ expect(await listPublishDrafts(id, { connect })).toEqual([]);+ } finally {+ musicVideoEvents.off('publish-draft', onEvent);+ }+ });+it('closes the earlier draft when the same target is filled again, and discards on request', async () => {const id = await readyProject();const { connect, pages } = fakeBrowser();diff --git a/server/services/musicVideo/publish/reddit.js b/server/services/musicVideo/publish/reddit.jsindex 57f791ec25..d18398f95c 100644--- a/server/services/musicVideo/publish/reddit.js+++ b/server/services/musicVideo/publish/reddit.js@@ -14,7 +14,7 @@* before posting; submit() posts, then adds the optional first comment.*/import { ServerError } from '../../../lib/errorHandler.js';-import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, landedOnPost, loginRequired, step } from './browser.js';const BASE = 'https://old.reddit.com';const WWW = 'https://www.reddit.com';@@ -107,6 +107,8 @@ export const redditAdapter = {if (!info.user) throw loginRequired(label, `${BASE}/login`);return { account: info.user, subreddit: payload.subreddit, kind: payload.kind, title: payload.title, flairText: payload.flairText, rules: info.rules, flairs: info.flairs };},+ findPost: (page, payload) => landedOnPost(page, /^https:\/\/(?:www|old)\.reddit\.com\/r\/[^/]+\/comments\/[a-z0-9]+(?:\/[^/?#]*)?/i, payload.title,+ ([url]) => url.replace('://old.reddit.com', '://www.reddit.com')),async submit(page, payload) {if (payload.kind === 'video') return submitVideo(page, payload);const result = await step(label, 'post', () => page.evaluate(async (p) => {diff --git a/server/services/musicVideo/publish/stackerNews.js b/server/services/musicVideo/publish/stackerNews.jsindex a3fc286db2..d7520d15ee 100644--- a/server/services/musicVideo/publish/stackerNews.js+++ b/server/services/musicVideo/publish/stackerNews.js@@ -4,7 +4,7 @@* (for example the starter prompt) posted as a reply. The url field is read* back after the body is written, because a stray keystroke once landed in it.*/-import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, landedOnPost, loginRequired, pasteText, step } from './browser.js';const label = 'Stacker News';@@ -32,6 +32,7 @@ export const stackerNewsAdapter = {const cost = await page.evaluate(() => [...document.querySelectorAll('button[type=submit]')].map((b) => b.innerText.trim()).find((t) => /post/i.test(t)) || null);return { territory: payload.territory, title: payload.title, url: payload.url, cost };},+ findPost: (page, payload) => landedOnPost(page, /^https:\/\/stacker\.news\/items\/\d+/, payload.title),async submit(page, payload) {await step(label, 'post', () => page.locator('button[type=submit]').filter({ hasText: 'post' }).first().click({ timeout: T }));const url = await step(label, 'find the new post', async () => {diff --git a/server/services/musicVideo/publish/substack.js b/server/services/musicVideo/publish/substack.jsindex 62194bf6c6..c4f5b4ae88 100644--- a/server/services/musicVideo/publish/substack.js+++ b/server/services/musicVideo/publish/substack.js@@ -8,7 +8,8 @@* into, so a filled draft also appears under the publication's Drafts. PortOS* never presses Continue or Publish: sending to subscribers stays with the director.*/-import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';+import { escapeRegExp } from '../../../lib/textUtils.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, landedOnPost, loginRequired, pasteText, step } from './browser.js';const label = 'Substack';const TITLE = '[data-testid="post-title"], textarea#post-title, textarea.post-title, textarea[placeholder="Title"]';@@ -52,4 +53,6 @@ export const substackAdapter = {saved: 'Substack keeps this under Drafts; each Fill again saves another draft there',};},+ // Published, the post lives at /p/<slug> on the publication.+ findPost: (page, payload) => landedOnPost(page, new RegExp(`^https://${escapeRegExp(payload.publication)}/p/[^/?#]+`), payload.title),};