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

Fix LinkedIn Fill draft stalling at the media editor

Claudea68997003f51
diff --git a/server/services/musicVideo/publish/linkedin.js b/server/services/musicVideo/publish/linkedin.js
index af37034df8..6e6db950e8 100644
--- a/server/services/musicVideo/publish/linkedin.js
+++ b/server/services/musicVideo/publish/linkedin.js
@@ -12,8 +12,12 @@
* Once the director opens it, findPost records the post's link and, when there
* is a first comment, types it into the post's comment box: the director
* presses Comment.
+ *
+ * LinkedIn draws the share box inside a shadow root, which `document` queries
+ * never reach, so everything here goes through Playwright locators (they pierce
+ * open shadow roots), including the paste.
*/
-import { PUBLISH_STEP_TIMEOUT_MS as T, clickVisibleText, landedOnPost, loginRequired, pasteText, step } from './browser.js';
+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';
const label = 'LinkedIn';
const SHARE_URL = 'https://www.linkedin.com/feed/?shareActive=true';
@@ -23,11 +27,43 @@ const EDITOR = `${DIALOG} .ql-editor[contenteditable=true]`;
const COMMENT_EDITOR = '.comments-comment-box .ql-editor[contenteditable=true], .comments-comment-texteditor .ql-editor[contenteditable=true]';
// Drafts whose first comment was already typed: a reload of the post page must not type it twice.
const commented = new WeakSet();
+const UPLOAD_WAIT_MS = 600_000;
const POST_URL = /^https:\/\/www\.linkedin\.com\/feed\/update\/urn:li:(?:activity|share|ugcPost):\d+/;
/** The post's opening words, as the post page shows them (its first line; LinkedIn folds the rest under "see more"). */
const opening = (text) => String(text || '').split('\n').map((line) => line.trim()).find(Boolean) || '';
+/** The last visible button reading exactly `name` (a dialog stacks its own buttons last). */
+const button = (page, name) => page.locator('button:visible, [role=button]:visible', { hasText: new RegExp(`^\\s*${name}\\s*$`) }).last();
+
+/**
+ * Write `text` into the Quill editor `locator` matches. A synthetic paste keeps
+ * the line breaks; when Quill ignores it, the lines are typed with Enter between.
+ */
+async function pasteInto(page, locator, text) {
+ await locator.click({ timeout: T });
+ await locator.evaluate((el, txt) => {
+ el.focus();
+ const data = new DataTransfer();
+ data.setData('text/plain', txt);
+ el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
+ }, text);
+ await page.waitForTimeout(500);
+ if ((await locator.innerText()).trim()) return;
+ for (const [i, line] of String(text).split('\n').entries()) {
+ if (i > 0) await page.keyboard.press('Enter');
+ if (line) await page.keyboard.insertText(line);
+ }
+}
+
+/** Whether the share box is done uploading: Post enabled, no progress bar or Uploading/Processing note. */
+async function uploadSettled(page) {
+ const post = button(page, 'Post');
+ if (!(await post.count()) || !(await post.isEnabled())) return false;
+ if (await page.locator(`${DIALOG} [role=progressbar], ${DIALOG} progress`).count()) return false;
+ return !(await page.locator(DIALOG).filter({ hasText: /Uploading|Processing/i }).count());
+}
+
async function openComposer(page) {
await step(label, 'open the share box', () => page.goto(SHARE_URL, { waitUntil: 'domcontentloaded', timeout: T }));
await page.waitForTimeout(4000);
@@ -36,7 +72,7 @@ async function openComposer(page) {
const open = await page.locator(EDITOR).first().waitFor({ timeout: 8000 }).then(() => true, () => false);
if (!open) {
await step(label, 'start a post', async () => {
- await clickVisibleText(page, 'Start a post');
+ await button(page, 'Start a post').click({ timeout: T });
await page.locator(EDITOR).first().waitFor({ timeout: T });
});
}
@@ -54,7 +90,7 @@ async function attachVideo(page, video) {
await page.waitForTimeout(1500);
for (const name of ['Next', 'Done']) {
if (await page.locator(EDITOR).first().isVisible().catch(() => false)) break;
- await clickVisibleText(page, name).catch(() => {});
+ await button(page, name).click({ timeout: 5000 }).catch(() => {});
await page.waitForTimeout(1500);
}
await page.locator(EDITOR).first().waitFor({ timeout: T });
@@ -66,29 +102,30 @@ export const linkedinAdapter = {
async prepare(page, payload) {
await openComposer(page);
await attachVideo(page, payload.video);
- await step(label, 'write the post', async () => {
- await page.locator(EDITOR).first().click({ timeout: T });
- await pasteText(page, EDITOR, payload.text);
+ await step(label, 'write the post', () => pasteInto(page, page.locator(EDITOR).first(), payload.text));
+ await step(label, 'wait for the upload', async () => {
+ const deadline = Date.now() + UPLOAD_WAIT_MS;
+ while (!(await uploadSettled(page))) {
+ if (Date.now() > deadline) throw new Error('the upload did not finish');
+ await page.waitForTimeout(2000);
+ }
});
- await step(label, 'wait for the upload', () => page.waitForFunction((dialog) => {
- const box = document.querySelector(dialog);
- const post = [...(box?.querySelectorAll('button') || [])].find((b) => (b.innerText || '').trim() === 'Post');
- const uploading = box?.querySelector('[role=progressbar], progress') || /Uploading|Processing/i.test(box?.innerText || '');
- return post && !post.disabled && post.getAttribute('aria-disabled') !== 'true' && !uploading;
- }, DIALOG, { timeout: 600_000 }));
- const length = await page.evaluate((sel) => document.querySelector(sel)?.innerText.trim().length ?? 0, EDITOR).catch(() => null);
+ const length = await page.locator(EDITOR).first().innerText().then((t) => t.trim().length, () => null);
return {
characters: length,
firstComment: payload.firstComment ? 'Typed into the comment box once you press Post, then View post' : null,
};
},
async findPost(page, payload) {
- const url = await landedOnPost(page, POST_URL, opening(payload.text), ([match]) => `${match}/`);
+ const match = page.url().match(POST_URL);
+ const want = opening(payload.text).slice(0, 40);
+ if (!match || !want) return null;
+ const shown = await page.getByText(want).first().waitFor({ timeout: 15_000 }).then(() => true, () => false);
+ const url = shown ? `${match[0]}/` : null;
if (url && payload.firstComment && !commented.has(payload)) {
commented.add(payload);
// Typed, never sent: the director presses Comment. A miss still records the post.
- await page.locator(COMMENT_EDITOR).first().click({ timeout: 10_000 })
- .then(() => pasteText(page, COMMENT_EDITOR, payload.firstComment))
+ await pasteInto(page, page.locator(COMMENT_EDITOR).first(), payload.firstComment)
.catch((err) => console.warn(`⚠️ ${label}: could not type the first comment (${err?.message?.split('\n')[0]})`));
}
return url;
diff --git a/server/services/musicVideo/publish/linkedin.test.js b/server/services/musicVideo/publish/linkedin.test.js
index 016bd4ec73..0fc4b255b7 100644
--- a/server/services/musicVideo/publish/linkedin.test.js
+++ b/server/services/musicVideo/publish/linkedin.test.js
@@ -1,34 +1,52 @@
/**
- * LinkedIn adapter: the share box gets the video and the post text and is left
- * for the director's Post; once they open the new post, its link is recorded
- * and the first comment is typed (never sent).
+ * LinkedIn adapter: the share box (drawn in a shadow root, so reached only
+ * through locators) gets the video and the post text and is left for the
+ * director's Post; once they open the new post, its link is recorded and the
+ * first comment is typed (never sent).
*/
import { describe, expect, it, vi } from 'vitest';
import { linkedinAdapter } from './linkedin.js';
-function fakePage({ url = 'https://www.linkedin.com/feed/?shareActive=true', shows = '' } = {}) {
+const EDITOR = '[role=dialog] .ql-editor[contenteditable=true]';
+
+// A page whose elements exist only for locators. Like LinkedIn, attaching the
+// video swaps the composer for the media editor until its Next is pressed.
+function fakePage({ url = 'https://www.linkedin.com/feed/?shareActive=true', shows = '', pasteWorks = true } = {}) {
const log = [];
+ let composer = true;
+ const typed = {};
const page = {
log,
goto: async (to) => { log.push(['goto', to]); },
url: () => url,
waitForTimeout: async () => {},
- waitForEvent: async () => ({ setFiles: async (path) => { log.push(['setFiles', path]); } }),
- waitForFunction: async (_fn, arg) => { if (typeof arg === 'string' && arg !== '[role=dialog]' && !shows.includes(arg)) throw new Error('timed out'); },
- locator: (sel) => {
+ waitForEvent: async () => ({ setFiles: async (path) => { log.push(['setFiles', path]); composer = false; } }),
+ keyboard: {
+ press: async (key) => { log.push(['press', key]); },
+ insertText: async (text) => { log.push(['insert', text]); },
+ },
+ getByText: (want) => ({ first: () => ({ waitFor: async () => { if (!shows.includes(want)) throw new Error('timeout'); } }) }),
+ locator: (sel, opts) => {
+ const name = opts?.hasText?.source?.replace(/\^\\s\*|\\s\*\$/g, '');
+ const isEditor = sel === EDITOR || sel.includes('comments-');
const el = {
first: () => el,
- waitFor: async () => {},
- isVisible: async () => true,
- click: async () => { log.push(['click', sel]); },
+ last: () => el,
+ filter: () => ({ count: async () => 0 }),
+ count: async () => (/progressbar/.test(sel) ? 0 : 1),
+ isEnabled: async () => true,
+ waitFor: async () => { if (sel === EDITOR && !composer) throw new Error('timeout'); },
+ isVisible: async () => (sel === EDITOR ? composer : true),
+ click: async () => {
+ if (sel === EDITOR && !composer) throw new Error('not attached');
+ log.push(['click', name || sel]);
+ if (name === 'Next') composer = true;
+ },
+ evaluate: async (_fn, text) => { if (pasteWorks) typed[sel] = text; log.push(['paste', sel, text]); },
+ innerText: async () => (isEditor ? typed[sel] || '' : ''),
};
return el;
},
- // pasteText passes [selector, text]; clickVisibleText passes [selector, label]; the length read passes the selector.
- evaluate: async (_fn, arg) => {
- if (Array.isArray(arg)) { log.push(['paste', arg[0], arg[1]]); return true; }
- return 21;
- },
};
return page;
}
@@ -36,27 +54,37 @@ function fakePage({ url = 'https://www.linkedin.com/feed/?shareActive=true', sho
const payload = { video: { path: '/videos/x.mp4' }, text: 'I made a music video.\n\nMore.', firstComment: 'Full video: https://youtu.be/abc' };
describe('LinkedIn adapter', () => {
- it('uploads the video and pastes the post into the share box, pressing nothing', async () => {
+ it('uploads the video, presses the media editor\'s Next, and pastes the post, never pressing Post', async () => {
const page = fakePage();
const summary = await linkedinAdapter.prepare(page, payload);
expect(page.log[0]).toEqual(['goto', 'https://www.linkedin.com/feed/?shareActive=true']);
expect(page.log).toContainEqual(['setFiles', '/videos/x.mp4']);
- expect(page.log).toContainEqual(['paste', '[role=dialog] .ql-editor[contenteditable=true]', payload.text]);
- expect(page.log.some(([kind, sel]) => kind === 'click' && /Post/.test(sel))).toBe(false);
- expect(summary).toMatchObject({ characters: 21, firstComment: expect.stringMatching(/View post/) });
+ expect(page.log).toContainEqual(['click', 'Next']);
+ expect(page.log).toContainEqual(['paste', EDITOR, payload.text]);
+ expect(page.log.some(([kind, what]) => kind === 'click' && what === 'Post')).toBe(false);
+ expect(summary).toMatchObject({ characters: payload.text.length, firstComment: expect.stringMatching(/View post/) });
+ });
+
+ it('types the lines when Quill ignores the synthetic paste', async () => {
+ const page = fakePage({ pasteWorks: false });
+ await linkedinAdapter.prepare(page, payload);
+ expect(page.log.filter(([kind]) => kind === 'insert' || kind === 'press')).toEqual([
+ ['insert', 'I made a music video.'], ['press', 'Enter'], ['press', 'Enter'], ['insert', 'More.'],
+ ]);
});
it('asks for sign-in when LinkedIn redirects to its login wall', async () => {
await expect(linkedinAdapter.prepare(fakePage({ url: 'https://www.linkedin.com/authwall?trk=x' }), payload)).rejects.toMatchObject({ code: 'PUBLISH_LOGIN_REQUIRED' });
});
- it('records the opened post and types the first comment without sending it', async () => {
+ it('records the opened post and types the first comment once, without sending it', async () => {
const page = fakePage({ url: 'https://www.linkedin.com/feed/update/urn:li:activity:7123456789/?trk=x', shows: 'I made a music video.' });
- await expect(linkedinAdapter.findPost(page, payload)).resolves.toBe('https://www.linkedin.com/feed/update/urn:li:activity:7123456789/');
+ const draft = { ...payload };
+ await expect(linkedinAdapter.findPost(page, draft)).resolves.toBe('https://www.linkedin.com/feed/update/urn:li:activity:7123456789/');
expect(page.log.filter(([kind]) => kind === 'paste').map(([, , text]) => text)).toEqual([payload.firstComment]);
expect(page.log.filter(([kind]) => kind === 'click').every(([, sel]) => /comment/.test(sel))).toBe(true);
// A reload of the post page records it again but never types the comment twice.
- await linkedinAdapter.findPost(page, payload);
+ await linkedinAdapter.findPost(page, draft);
expect(page.log.filter(([kind]) => kind === 'paste')).toHaveLength(1);
});
@@ -69,7 +97,8 @@ describe('LinkedIn adapter', () => {
it('still records the post when the comment box cannot be found', async () => {
const page = fakePage({ url: 'https://www.linkedin.com/feed/update/urn:li:activity:7/', shows: 'I made a music video.' });
- page.locator = () => ({ first() { return this; }, click: async () => { throw new Error('no comment box'); } });
+ const base = page.locator;
+ page.locator = (sel, opts) => (sel.includes('comments-') ? { first() { return this; }, click: async () => { throw new Error('no comment box'); } } : base(sel, opts));
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(linkedinAdapter.findPost(page, { ...payload })).resolves.toBe('https://www.linkedin.com/feed/update/urn:li:activity:7/');
expect(warn).toHaveBeenCalled();