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
fix: harden X Comms review flow
[._.]/ Adam Eivy4cf9df1f53e7
diff --git a/client/src/pages/X.jsx b/client/src/pages/X.jsxindex ed715786f6..2f5e94a658 100644--- a/client/src/pages/X.jsx+++ b/client/src/pages/X.jsx@@ -78,6 +78,11 @@ export default function XPage() {}, [setSearchParams]);const closeAccountForm = useCallback(() => openAccountForm(null), [openAccountForm]);+ const openEditAccount = (account) => {+ setAccountForm({ label: account.label, username: account.username, enabled: account.enabled, notes: account.notes || '' });+ navigate(`/x/${account.id}/accounts?xAccount=edit`);+ };+const loadAccounts = useCallback(async () => {const result = await api.getXAccounts({ silent: true }).catch((err) => ({ error: err.message, accounts: [] }));if (result.error) setError(result.error);@@ -241,10 +246,11 @@ export default function XPage() {const renderDrafts = () => <div className="space-y-4"><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft a post for review</h2><p className="mt-1 text-sm text-gray-400">Drafts stay local until you submit them to Review Hub. PortOS will never publish automatically.</p><form className="mt-3 space-y-3" onSubmit={createDraft}><label htmlFor="x-draft-body" className="sr-only">X draft text</label><textarea id="x-draft-body" className={fieldClass} rows="5" maxLength="4000" placeholder="Write something you actually want to say…" value={draftBody} onChange={(event) => setDraftBody(event.target.value)} /><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-xs text-gray-500">{draftBody.length}/4000</span><button className={buttonClass} disabled={!draftBody.trim() || Boolean(busy)}>Save draft</button></div></form></section><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft queue</h2>{!visibleDrafts.length ? <p className="mt-3 text-sm text-gray-500">No drafts for @{selected.username}.</p> : <div className="mt-3 space-y-2">{visibleDrafts.map((draft) => <article key={draft.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2"><StatusBadge value={draft.state === 'approved' || draft.state === 'opened'}>{stateLabel(draft.state)}</StatusBadge><span className="text-xs text-gray-500">{formatDate(draft.updatedAt)}</span></div><p className="mt-3 whitespace-pre-wrap text-sm text-gray-200">{draft.body}</p><div className="mt-3 flex flex-wrap gap-2">{draft.state === 'draft' && <button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'pending_review')}>Submit for review</button>}{draft.state === 'pending_review' && <><button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'approved')}>Approve</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'rejected')}>Reject</button></>}{draft.state === 'approved' && <button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => openDraft(draft)}><ExternalLink size={15} className="mr-1 inline" />Open compose in X</button>}{draft.reviewNote && <span className="self-center text-xs text-gray-500">{draft.reviewNote}</span>}</div></article>)}</div>}</section></div>;- const renderAccounts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">X accounts</h2><p className="mt-1 text-sm text-gray-400">Browser-only diagnostics and review-gated compose handoffs. No X credentials are stored.</p></div><button type="button" className={buttonClass} onClick={() => { setAccountForm(emptyAccount); openAccountForm('new'); }}><Plus size={15} className="mr-1 inline" />Add account</button></div>{!accounts.length ? <div className="mt-4 rounded border border-port-border p-4 text-sm text-gray-400">Add an X account to begin. Sync is manual, so nothing contacts X at boot.</div> : <div className="mt-4 grid gap-3 md:grid-cols-2">{accounts.map((account) => <article key={account.id} className="rounded border border-port-border p-4"><div className="flex items-start justify-between gap-2"><div><h3 className="font-semibold text-white">{account.label}</h3><p className="text-sm text-gray-400">@{account.username}</p></div><StatusBadge value={account.enabled}>{account.enabled ? 'Enabled' : 'Disabled'}</StatusBadge></div><p className="mt-3 text-xs text-gray-500">{account.lastSyncAt ? `Last diagnostic ${formatDate(account.lastSyncAt)}` : 'No diagnostic yet'}</p><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} onClick={() => { setAccountForm({ label: account.label, username: account.username, enabled: account.enabled, notes: account.notes || '' }); openAccountForm('edit'); }}>Edit</button><button type="button" className={secondaryButton} onClick={() => navigate(accountPath(account.id, 'health'))}>Open</button>{deleteAccountId === account.id ? <><button type="button" className="rounded border border-port-error px-3 py-2 text-sm text-port-error disabled:opacity-50" disabled={Boolean(busy)} onClick={() => removeAccount(account.id)}>Delete</button><button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(null)}>Cancel</button></> : <button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(account.id)}>Remove</button>}</div></article>)}</div>}</section>;+ const renderAccounts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">X accounts</h2><p className="mt-1 text-sm text-gray-400">Browser-only diagnostics and review-gated compose handoffs. No X credentials are stored.</p></div><button type="button" className={buttonClass} onClick={() => { setAccountForm(emptyAccount); openAccountForm('new'); }}><Plus size={15} className="mr-1 inline" />Add account</button></div>{!accounts.length ? <div className="mt-4 rounded border border-port-border p-4 text-sm text-gray-400">Add an X account to begin. Sync is manual, so nothing contacts X at boot.</div> : <div className="mt-4 grid gap-3 md:grid-cols-2">{accounts.map((account) => <article key={account.id} className="rounded border border-port-border p-4"><div className="flex items-start justify-between gap-2"><div><h3 className="font-semibold text-white">{account.label}</h3><p className="text-sm text-gray-400">@{account.username}</p></div><StatusBadge value={account.enabled}>{account.enabled ? 'Enabled' : 'Disabled'}</StatusBadge></div><p className="mt-3 text-xs text-gray-500">{account.lastSyncAt ? `Last diagnostic ${formatDate(account.lastSyncAt)}` : 'No diagnostic yet'}</p><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} onClick={() => openEditAccount(account)}>Edit</button><button type="button" className={secondaryButton} onClick={() => navigate(accountPath(account.id, 'health'))}>Open</button>{deleteAccountId === account.id ? <><button type="button" className="rounded border border-port-error px-3 py-2 text-sm text-port-error disabled:opacity-50" disabled={Boolean(busy)} onClick={() => removeAccount(account.id)}>Delete</button><button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(null)}>Cancel</button></> : <button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(account.id)}>Remove</button>}</div></article>)}</div>}</section>;const accountDrawer = <Drawer open={accountDrawerOpen} onClose={closeAccountForm} title={accountFormMode === 'edit' ? 'Edit X account' : 'Add X account'} subtitle="Read-only diagnostics with human-reviewed drafts" size="md"><form className="space-y-4" onSubmit={saveAccount}><label className="block text-sm text-gray-300" htmlFor="x-account-label">Local label<input id="x-account-label" className={`${fieldClass} mt-1`} required value={accountForm.label} onChange={(event) => updateAccountForm('label', event.target.value)} /></label><label className="block text-sm text-gray-300" htmlFor="x-account-username">X username<input id="x-account-username" className={`${fieldClass} mt-1`} required placeholder="example_user" value={accountForm.username} onChange={(event) => updateAccountForm('username', event.target.value)} /><span className="mt-1 block text-xs text-gray-500">Enter the handle without or with @. PortOS normalizes it.</span></label><label className="block text-sm text-gray-300" htmlFor="x-account-notes">Notes<textarea id="x-account-notes" className={`${fieldClass} mt-1`} rows="4" value={accountForm.notes} onChange={(event) => updateAccountForm('notes', event.target.value)} /></label><label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="x-account-enabled"><input id="x-account-enabled" type="checkbox" checked={accountForm.enabled} onChange={(event) => updateAccountForm('enabled', event.target.checked)} /> Allow diagnostics and compose handoffs</label><div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">The managed browser reads public X pages. PortOS does not store your X password or API token, does not run background posting, and only opens an approved draft for final manual submission.</div>{accountFormError && <p className="text-sm text-port-error">{accountFormError}</p>}<div className="flex justify-end gap-2"><button type="button" className={secondaryButton} onClick={closeAccountForm}>Cancel</button><button className={buttonClass} disabled={Boolean(busy) || accountFormDirty && accountFormMode === 'edit' && !accountForm.label.trim()}>{accountFormMode === 'edit' ? 'Save account' : 'Add account'}</button></div></form></Drawer>;+ const notFound = Boolean(accountId && !selected);if (loading) return <PageSkeleton header="bar" label="Loading X" tabs={TABS.length} cards={3} />;- return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={AtSign} title="X" subtitle="Account health, reach diagnostics, and review-gated drafts" actions={accountSwitcher} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/x')} ariaLabel="X sections" /><main className="flex-1 overflow-auto p-4">{error && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{error}</div>}{notice && <div className="mb-3 rounded border border-port-border p-3 text-sm text-gray-200">{notice}</div>}{!selected && accounts.length > 0 && <div className="mb-3 rounded border border-port-warning/40 bg-port-warning/10 p-3 text-sm text-port-warning">Choose an X account to view diagnostics and drafts.</div>}{activeTab === 'health' && selected && renderHealth()}{activeTab === 'posts' && selected && renderPosts()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'accounts' && renderAccounts()}{accountDrawer}</main></div>;+ return <div className="flex h-full min-h-0 flex-col"><PageHeader icon={AtSign} title="X" subtitle="Account health, reach diagnostics, and review-gated drafts" actions={accountSwitcher} /><TabPills tabs={TABS} activeTab={activeTab} onChange={(nextTab) => selected ? navigate(accountPath(selected.id, nextTab)) : navigate('/x')} ariaLabel="X sections" /><main className="flex-1 overflow-auto p-4">{error && <div className="mb-3 rounded border border-port-error p-3 text-sm text-port-error">{error}</div>}{notice && <div className="mb-3 rounded border border-port-border p-3 text-sm text-gray-200">{notice}</div>}{notFound && <div className="mb-3 rounded border border-port-error p-4 text-sm text-port-error">This X account was not found. <button type="button" className="underline" onClick={() => navigate('/x')}>Return to accounts.</button></div>}{activeTab === 'health' && selected && renderHealth()}{activeTab === 'posts' && selected && renderPosts()}{activeTab === 'drafts' && selected && renderDrafts()}{activeTab === 'accounts' && renderAccounts()}{accountDrawer}</main></div>;}diff --git a/client/src/pages/X.test.jsx b/client/src/pages/X.test.jsxindex ebb9e28366..ca993ae36b 100644--- a/client/src/pages/X.test.jsx+++ b/client/src/pages/X.test.jsx@@ -84,4 +84,19 @@ describe('X page', () => {expect(screen.queryByRole('button', { name: /publish/i })).not.toBeInTheDocument();expect(screen.getByText(/Diagnostic complete/)).toBeInTheDocument();});++ it('opens the account editor from the accounts index with an id-backed URL', async () => {+ const user = userEvent.setup();+ renderPage('/x');+ await screen.findByRole('heading', { name: 'X accounts' });+ await user.click(screen.getByRole('button', { name: 'Edit' }));+ expect(await screen.findByRole('heading', { name: 'Edit X account' })).toBeInTheDocument();+ expect(screen.getByTestId('location')).toHaveTextContent(`/x/${account.id}/accounts?xAccount=edit`);+ });++ it('renders a not-found fallback for stale account URLs', async () => {+ renderPage('/x/00000000-0000-4000-8000-000000000099/health');+ expect(await screen.findByText(/This X account was not found/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Return to accounts.' })).toBeInTheDocument();+ });});diff --git a/server/integrations/x/browserReader.js b/server/integrations/x/browserReader.jsindex 6002eb04bd..0e90b49eda 100644--- a/server/integrations/x/browserReader.js+++ b/server/integrations/x/browserReader.js@@ -9,6 +9,8 @@ const SETTLE_MS = 1_500;const MAX_POSTS = 100;const MAX_BODY_LENGTH = 40_000;const MAX_BIO_LENGTH = 2_000;+const MAX_INTEGER = 2_147_483_647;+const X_STATUS_URL = /^https:\/\/x\.com\/(?:(?:[A-Za-z0-9_]{1,15}|i)\/)?status\/\d+$/;const POST_HELPERS = String.raw`const parseCount = (value) => {@@ -87,14 +89,14 @@ export const PEOPLE_EXPRESSION = `(() => ({}))()`;const boundedString = (value, max) => typeof value === 'string' ? value.replace(/\0/g, '').slice(0, max) : '';-const nullableCount = (value) => Number.isInteger(value) && value >= 0 ? value : null;+const nullableCount = (value) => Number.isInteger(value) && value >= 0 && value <= MAX_INTEGER ? value : null;const normalizedHandle = (value) => boundedString(value, 15).replace(/^@/, '').toLowerCase();const normalizePost = (post) => {const remoteId = boundedString(post?.remoteId, 80);if (!remoteId || !/^\d+$/.test(remoteId)) return null;const sourceUrl = boundedString(post?.sourceUrl, 2_000);- const safeUrl = /^https:\/\/x\.com\/status\/\d+$/.test(sourceUrl) ? sourceUrl : '';+ const safeUrl = X_STATUS_URL.test(sourceUrl) ? sourceUrl : '';const replies = nullableCount(post?.replies) ?? 0;const reposts = nullableCount(post?.reposts) ?? 0;const likes = nullableCount(post?.likes) ?? 0;@@ -107,7 +109,7 @@ const normalizePost = (post) => {authorHandle: normalizedHandle(post?.authorHandle),remoteCreatedAt: typeof post?.remoteCreatedAt === 'string' ? post.remoteCreatedAt.slice(0, 64) : null,impressions: nullableCount(post?.impressions),- engagements: replies + reposts + likes + bookmarks,+ engagements: nullableCount(replies + reposts + likes + bookmarks),replies,reposts,likes,diff --git a/server/integrations/x/browserReader.test.js b/server/integrations/x/browserReader.test.jsindex 376fb128f1..7dd47c2c02 100644--- a/server/integrations/x/browserReader.test.js+++ b/server/integrations/x/browserReader.test.js@@ -26,7 +26,7 @@ describe('X browser read transport', () => {remoteId: '123',authorHandle: 'Example_User',body: 'A public post',- sourceUrl: 'https://x.com/status/123',+ sourceUrl: 'https://x.com/example_user/status/123',impressions: 382,replies: 1,reposts: 2,@@ -49,7 +49,7 @@ describe('X browser read transport', () => {remoteId: '123',kind: 'post',engagements: 10,- sourceUrl: 'https://x.com/status/123',+ sourceUrl: 'https://x.com/example_user/status/123',})],});expect(navigateToUrlPinned).toHaveBeenCalledWith('https://x.com/Example_User', expect.objectContaining({diff --git a/server/services/x.js b/server/services/x.jsindex 55c7bab48a..52a56792c9 100644--- a/server/services/x.js+++ b/server/services/x.js@@ -6,7 +6,10 @@ import { openXHandoff } from './xBrowser.js';const USERNAME_PATTERN = /^[A-Za-z0-9_]{1,15}$/;const DRAFT_STATES = new Set(['draft', 'pending_review', 'approved', 'rejected', 'opened']);const MAX_DRAFT_AGE_MS = 24 * 60 * 60 * 1000;+const MAX_INTEGER = 2_147_483_647;+const X_STATUS_URL = /^https:\/\/x\.com\/(?:(?:[A-Za-z0-9_]{1,15}|i)\/)?status\/\d+$/;const syncLocks = new Map();+const draftOpenLocks = new Map();const normalizeUsername = (value) => {const username = String(value || '').trim().replace(/^@/, '');@@ -126,19 +129,24 @@ export function deriveXDiagnostics({ accountUsername, profile = {}, latest = {},};}-const normalizeRemotePost = (post) => ({- remoteId: boundedText(post?.remoteId, 80),- kind: post?.kind === 'reply' ? 'reply' : 'post',- body: boundedText(post?.body, 40_000),- sourceUrl: boundedText(post?.sourceUrl, 2_000),- remoteCreatedAt: safeDate(post?.remoteCreatedAt),- impressions: Number.isInteger(post?.impressions) ? post.impressions : null,- engagements: Number.isInteger(post?.engagements) ? post.engagements : null,- replies: Number.isInteger(post?.replies) ? post.replies : 0,- reposts: Number.isInteger(post?.reposts) ? post.reposts : 0,- likes: Number.isInteger(post?.likes) ? post.likes : 0,- bookmarks: Number.isInteger(post?.bookmarks) ? post.bookmarks : 0,-});+const safeMetric = (value) => Number.isInteger(value) && value >= 0 && value <= MAX_INTEGER ? value : null;++const normalizeRemotePost = (post) => {+ const sourceUrl = boundedText(post?.sourceUrl, 2_000);+ return {+ remoteId: boundedText(post?.remoteId, 80),+ kind: post?.kind === 'reply' ? 'reply' : 'post',+ body: boundedText(post?.body, 40_000),+ sourceUrl: X_STATUS_URL.test(sourceUrl) ? sourceUrl : '',+ remoteCreatedAt: safeDate(post?.remoteCreatedAt),+ impressions: safeMetric(post?.impressions),+ engagements: safeMetric(post?.engagements),+ replies: safeMetric(post?.replies) ?? 0,+ reposts: safeMetric(post?.reposts) ?? 0,+ likes: safeMetric(post?.likes) ?? 0,+ bookmarks: safeMetric(post?.bookmarks) ?? 0,+ };+};const mergePosts = (...lists) => [...new Map(lists.flat().map(normalizeRemotePost).filter((post) => /^\d+$/.test(post.remoteId)).map((post) => [post.remoteId, post])).values()].slice(0, 100);@@ -208,6 +216,7 @@ export async function listPosts(accountId) {export async function openAccountDestination(accountId, kind) {const account = await getAccountRow(accountId);if (!account) return null;+ if (!account.enabled) throw new Error('Selected X account is disabled');if (!['profile', 'latest', 'people', 'settings'].includes(kind)) throw new Error('Unsupported X handoff destination');const value = kind === 'settings' ? '' : account.username;return openXHandoff({ kind, value });@@ -245,23 +254,19 @@ export async function listPendingReviewActions({ limit = 50 } = {}) {export async function reviewDraft(id, state, reviewNote = '') {if (!DRAFT_STATES.has(state) || !['pending_review', 'approved', 'rejected'].includes(state)) throw new Error('Unsupported X draft review state');- const current = await query('SELECT * FROM x_drafts WHERE id=$1', [id]);- const existing = current.rows[0];- if (!existing) return null;- const allowed = existing.state === 'draft' && state === 'pending_review'- || existing.state === 'pending_review' && ['approved', 'rejected'].includes(state);- if (!allowed) return null;+ const expectedState = state === 'pending_review' ? 'draft' : 'pending_review';const result = await query(`UPDATE x_drafts SET state=$2,review_note=$3,approved_at=CASE WHEN $2='approved' THEN NOW() ELSE approved_at END,updated_at=NOW()- WHERE id=$1 RETURNING *`,- [id, state, boundedText(reviewNote, 2_000)],+ WHERE id=$1 AND state=$4 RETURNING *`,+ [id, state, boundedText(reviewNote, 2_000), expectedState],);const row = result.rows[0];+ if (!row) return null;const account = await getAccountRow(row.account_id);return draftView({ ...row, account_label: account?.label, username: account?.username });}-export async function openApprovedDraft(id) {+async function openApprovedDraftUnlocked(id) {const result = await query(`SELECT d.*, a.label AS account_label, a.username, a.enabledFROM x_drafts d JOIN x_accounts a ON a.id=d.account_id WHERE d.id=$1`,@@ -280,4 +285,11 @@ export async function openApprovedDraft(id) {return opened ? draftView({ ...opened, account_label: draft.account_label, username: draft.username }) : null;}+export async function openApprovedDraft(id) {+ if (draftOpenLocks.has(id)) return draftOpenLocks.get(id);+ const run = openApprovedDraftUnlocked(id).finally(() => draftOpenLocks.delete(id));+ draftOpenLocks.set(id, run);+ return run;+}+export const xDraftStates = [...DRAFT_STATES];