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: X sync no longer stores other authors' reposts as the account's own posts (#12973)
[._.]/ Adam Eivycca2727b5782
diff --git a/server/lib/db/schema/x.js b/server/lib/db/schema/x.jsindex 36d28bd3c1..c70e4ff2fb 100644--- a/server/lib/db/schema/x.js+++ b/server/lib/db/schema/x.js@@ -36,6 +36,7 @@ export const xDdl = [updated_at TIMESTAMPTZ DEFAULT NOW(),UNIQUE (account_id, remote_id))`,+ `ALTER TABLE x_posts ADD COLUMN IF NOT EXISTS author_handle TEXT`,`CREATE INDEX IF NOT EXISTS idx_x_posts_account_received ON x_posts (account_id, received_at DESC)`,`CREATE TABLE IF NOT EXISTS x_drafts (id UUID PRIMARY KEY,diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex bec6951c19..451158a2ff 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1927,6 +1927,7 @@ CREATE TABLE IF NOT EXISTS x_posts (updated_at TIMESTAMPTZ DEFAULT NOW(),UNIQUE (account_id, remote_id));+ALTER TABLE x_posts ADD COLUMN IF NOT EXISTS author_handle TEXT;CREATE INDEX IF NOT EXISTS idx_x_posts_account_received ON x_posts (account_id, received_at DESC);CREATE TABLE IF NOT EXISTS x_drafts (id UUID PRIMARY KEY,diff --git a/server/services/x.js b/server/services/x.jsindex 9fe7080737..535cabea1b 100644--- a/server/services/x.js+++ b/server/services/x.js@@ -166,6 +166,7 @@ const normalizeRemotePost = (post) => {kind: post?.kind === 'reply' ? 'reply' : 'post',body: boundedText(post?.body, 40_000),sourceUrl: X_STATUS_URL.test(sourceUrl) ? sourceUrl : '',+ authorHandle: safeUsername(post?.authorHandle),remoteCreatedAt: safeDate(post?.remoteCreatedAt),impressions: safeMetric(post?.impressions),engagements: safeMetric(post?.engagements),@@ -176,7 +177,18 @@ const normalizeRemotePost = (post) => {};};-const mergePosts = (...lists) => [...new Map(lists.flat().map(normalizeRemotePost).filter((post) => /^\d+$/.test(post.remoteId)).map((post) => [post.remoteId, post])).values()].slice(0, 100);+// A profile timeline also lists reposts of other authors. An unreadable handle is unknown, not a mismatch.+const isForeignPost = (post, username) => Boolean(post.authorHandle) && post.authorHandle !== username;++// Splits normalized posts into the account's own and the foreign ids, before the 100 cap so reposts can't crowd real posts out.+const mergePosts = (username, ...lists) => {+ const byId = new Map(lists.flat().map(normalizeRemotePost).filter((post) => /^\d+$/.test(post.remoteId)).map((post) => [post.remoteId, post]));+ const all = [...byId.values()];+ return {+ posts: all.filter((post) => !isForeignPost(post, username)).slice(0, 100),+ foreignIds: all.filter((post) => isForeignPost(post, username)).map((post) => post.remoteId),+ };+};async function syncAccountUnlocked(accountId) {const account = await getAccountRow(accountId);@@ -198,23 +210,25 @@ async function syncAccountUnlocked(accountId) {peopleSearch: { exactMatch: people.exactMatch === true },latestSearch: { postCount: diagnostics.latestSearchPostCount },};- const posts = mergePosts(profileResult.posts || [], latestPosts);+ const { posts, foreignIds } = mergePosts(safeUsername(account.username), profileResult.posts || [], latestPosts);const readError = buildXReadError(diagnostics);if (readError) console.warn(`⚠️ X read for @${account.username} came back empty — reporting affected visibility checks as unknown`);await withTransaction(async (client) => {+ // Rows an older sync stored for someone else's repost; only ids seen in this read are purged.+ if (foreignIds.length) await client.query('DELETE FROM x_posts WHERE account_id=$1 AND remote_id = ANY($2)', [accountId, foreignIds]);for (const post of posts) {await client.query(`INSERT INTO x_posts- (id,account_id,remote_id,kind,body,source_url,remote_created_at,impressions,engagements,replies,reposts,likes,bookmarks,content_hash)- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)+ (id,account_id,remote_id,kind,body,source_url,remote_created_at,impressions,engagements,replies,reposts,likes,bookmarks,content_hash,author_handle)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)ON CONFLICT (account_id,remote_id) DO UPDATE SET kind=EXCLUDED.kind,body=EXCLUDED.body,source_url=EXCLUDED.source_url,remote_created_at=EXCLUDED.remote_created_at,impressions=EXCLUDED.impressions,engagements=EXCLUDED.engagements,replies=EXCLUDED.replies,reposts=EXCLUDED.reposts,likes=EXCLUDED.likes,bookmarks=EXCLUDED.bookmarks,- content_hash=EXCLUDED.content_hash,received_at=NOW(),updated_at=NOW()`,+ content_hash=EXCLUDED.content_hash,author_handle=EXCLUDED.author_handle,received_at=NOW(),updated_at=NOW()`,[randomUUID(), accountId, post.remoteId, post.kind, post.body, post.sourceUrl, post.remoteCreatedAt,- post.impressions, post.engagements, post.replies, post.reposts, post.likes, post.bookmarks, stableHash(post.body)],+ post.impressions, post.engagements, post.replies, post.reposts, post.likes, post.bookmarks, stableHash(post.body), post.authorHandle || null],);}await client.query(diff --git a/server/services/x.test.js b/server/services/x.test.jsindex 81e734fa74..70d645b555 100644--- a/server/services/x.test.js+++ b/server/services/x.test.js@@ -196,6 +196,48 @@ describe('syncAccount error reporting', () => {expect(result.ingested).toBe(2);});+ it('stores only the account\'s own posts, purges stored reposts, and keeps posts with no readable handle', async () => {+ executeXBrowserRead.mockImplementation(async (name) => {+ if (name === 'people') return { handles: [], exactMatch: false };+ if (name === 'profile') {+ return {+ profile: { username: 'example_user' },+ posts: [+ { authorHandle: '@Example_User', remoteId: '1750000000000000001' },+ { authorHandle: 'other_user', remoteId: '1750000000000000002' },+ { authorHandle: '', remoteId: '1750000000000000003' },+ ],+ };+ }+ return { posts: [] };+ });+ const client = { query: vi.fn().mockResolvedValue({ rows: [] }) };+ withTransaction.mockImplementation(async (callback) => callback(client));++ const result = await syncAccount('acct-1');++ const inserted = client.query.mock.calls.filter(([sql]) => /INSERT INTO x_posts/.test(sql)).map(([, params]) => params[2]);+ expect(inserted).toEqual(['1750000000000000001', '1750000000000000003']);+ const purge = client.query.mock.calls.find(([sql]) => /DELETE FROM x_posts/.test(sql));+ expect(purge[1]).toEqual(['acct-1', ['1750000000000000002']]);+ expect(result.ingested).toBe(2);+ });++ it('applies the 100-post cap after dropping reposts', async () => {+ const reposts = Array.from({ length: 100 }, (_, i) => ({ authorHandle: 'other_user', remoteId: String(1760000000000000000n + BigInt(i)) }));+ const own = { authorHandle: 'example_user', remoteId: '1750000000000000001' };+ executeXBrowserRead.mockImplementation(async (name) => (name === 'profile'+ ? { profile: { username: 'example_user' }, posts: [...reposts, own] }+ : { posts: [], handles: [] }));+ const client = { query: vi.fn().mockResolvedValue({ rows: [] }) };+ withTransaction.mockImplementation(async (callback) => callback(client));++ await syncAccount('acct-1');++ const inserted = client.query.mock.calls.filter(([sql]) => /INSERT INTO x_posts/.test(sql)).map(([, params]) => params[2]);+ expect(inserted).toEqual([own.remoteId]);+ });+// Re-entrancy guard, not a concurrency defense (see the Security Model): the// UI can fire the same sync twice — from a button and a socket refresh — and// the second must join the in-flight read instead of opening a second browser