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
address review (claude): cursor safety, FDA classification, phones UI, sync feedback
Adam Eivyd079201c1f9e
diff --git a/client/src/components/settings/IMessageTab.jsx b/client/src/components/settings/IMessageTab.jsxindex fbb557b85b..64d2430b91 100644--- a/client/src/components/settings/IMessageTab.jsx+++ b/client/src/components/settings/IMessageTab.jsx@@ -72,8 +72,8 @@ export function IMessageTab() {const result = await syncImessage({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));setSyncing(false);if (result?.ok) {- toast.success(`Synced: ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s)`);- setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), lastResult: result, lastRunAt: new Date().toISOString() } }));+ toast.success(`Synced: ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s)${result.hasMore ? ' — more history remains, run again' : ''}`);+ setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), cursorRowid: result.cursorRowid, lastResult: result, lastRunAt: new Date().toISOString() } }));} else {toast.error(result?.fullDiskAccessRequired ? 'Full Disk Access required' : (result?.error || 'Sync failed'));setSetup(result);diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 650c8c055b..2e25c36605 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -54,6 +54,7 @@ const emptyDraft = () => ({energy: 'steady',tags: '',emails: '',+ phones: '',nextMove: '',notes: '',});@@ -313,6 +314,18 @@ function ContactForm({ draft, onChange, onSave, onDelete, onNew, isExisting, savAuto-logs a touchpoint when this person appears in a synced calendar event or message.</span></label>+ <label className="block sm:col-span-2">+ <span className="text-xs text-gray-500">Phone numbers</span>+ <input+ value={draft.phones}+ onChange={(event) => update('phones', event.target.value)}+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"+ placeholder="+1 555 123 4567, 555 987 6543"+ />+ <span className="mt-1 block text-[11px] text-gray-600">+ Matches this person to iMessage conversations (saved in +E.164 form).+ </span>+ </label><label className="block sm:col-span-2"><span className="text-xs text-gray-500">Next Move</span><textarea@@ -762,6 +775,7 @@ export default function Tribe() {...contact,tags: tagsToInput(contact.tags),emails: tagsToInput(contact.emails),+ phones: tagsToInput(contact.phones),cadenceDays: contact.cadenceDays || ringFor(contact.ring).cadenceDays,});@@ -779,6 +793,7 @@ export default function Tribe() {energy: draft.energy,tags: tagsToArray(draft.tags),emails: tagsToArray(draft.emails),+ phones: tagsToArray(draft.phones),nextMove: draft.nextMove.trim(),notes: draft.notes.trim(),};diff --git a/server/services/imessageSync.js b/server/services/imessageSync.jsindex 9ae217b865..ba8e16a56a 100644--- a/server/services/imessageSync.js+++ b/server/services/imessageSync.js@@ -22,6 +22,7 @@* exported and unit-tested with fixtures — no real chat.db required.*/import { DatabaseSync } from 'node:sqlite';+import { statSync } from 'node:fs';import { expandHome, dataPath, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';import { getUserTimezone } from '../lib/timezone.js';@@ -258,15 +259,25 @@ export function chatDbPath() {// Classify a chat.db open failure so the UI can surface an actionable message.// A macOS sandbox / TCC denial surfaces as EPERM/EACCES or SQLite "unable to-// open database file" (SQLITE_CANTOPEN) — all of which mean Full Disk Access is-// missing for the running process.+// open database file" (SQLITE_CANTOPEN) — but SQLITE_CANTOPEN is ALSO what a+// simply-nonexistent chat.db produces (Linux install, a Mac that never used+// Messages), and telling those users to grant Full Disk Access can't help them.+// Disambiguate via stat: a TCC denial surfaces as EPERM/EACCES on stat, while+// ENOENT means the file genuinely doesn't exist.function isFullDiskAccessError(err) {+ if (err?.code === 'EACCES' || err?.code === 'EPERM') return true;const msg = String(err?.message || '').toLowerCase();- return err?.code === 'EACCES'- || err?.code === 'EPERM'- || msg.includes('unable to open')+ const ambiguous = msg.includes('unable to open')|| msg.includes('not authorized')|| msg.includes('operation not permitted');+ if (!ambiguous) return false;+ try {+ statSync(chatDbPath());+ return true; // file exists but SQLite couldn't open it — permission problem+ } catch (statErr) {+ if (statErr?.code === 'ENOENT') return false; // chat.db genuinely absent+ return true; // EPERM/EACCES on stat — the TCC denial itself+ }}const FDA_REMEDIATION = 'Grant Full Disk Access to the process running PortOS (node or the PM2 daemon): System Settings → Privacy & Security → Full Disk Access → enable your terminal / node / pm2, then restart PortOS.';@@ -370,8 +381,20 @@ function readMessages(db, cursorRowid, limit) {* summary. Safe to call repeatedly — dedupe keys make re-ingestion a no-op. This* runs outside the request lifecycle (scheduler / explicit endpoint), so the* chat.db open is try/catch-guarded and returns an error report instead of throwing.+ *+ * Re-entrancy guarded: a manual "Sync now" overlapping a scheduler tick would+ * double-read the same cursor (deduped, but doubled work, and the slower writer+ * could stamp a stale cursor over the fresher one) — so concurrent callers share+ * the in-flight pass instead.*/+let syncInFlight = null;export async function runSync() {+ if (syncInFlight) return syncInFlight;+ syncInFlight = doRunSync().finally(() => { syncInFlight = null; });+ return syncInFlight;+}++async function doRunSync() {const state = await readSyncState();const path = chatDbPath();let db;@@ -399,26 +422,38 @@ export async function runSync() {const activityCandidates = imessageActivityCandidates(batch.messages);const touchpointCandidates = imessageTouchpointCandidates(batch.messages, timezone);+ // Persistence failures must NOT advance the cursor: the dedupe keys make+ // re-processing the batch on the next pass a harmless no-op, but skipping+ // past unpersisted messages loses them permanently (the cursor never revisits+ // a ROWID). Track failure and hold the cursor so the batch gets retried.+ let persistFailed = false;const activityResult = await recordEvents(activityCandidates).catch((err) => {console.error(`❌ iMessage activity record failed: ${err?.message || err}`);+ persistFailed = true;return { recorded: 0, skipped: activityCandidates.length };});const touchpointResult = await tribe.autoLogTouchpoints(touchpointCandidates).catch((err) => {console.error(`❌ iMessage touchpoint log failed: ${err?.message || err}`);+ persistFailed = true;return { created: 0, matched: 0 };});+ const nextCursor = persistFailed ? state.cursorRowid : batch.maxRowid;const result = {- ok: true,+ ok: !persistFailed,+ ...(persistFailed ? { error: 'Persistence failed — cursor held so the batch retries next sync' } : {}),scanned: batch.scanned,recorded: activityResult.recorded,touchpointsCreated: touchpointResult.created,touchpointsMatched: touchpointResult.matched,decodeFailures: batch.decodeFailures,- cursorRowid: batch.maxRowid,+ cursorRowid: nextCursor,+ // A full batch means older history remains beyond this pass — the caller+ // (UI toast / next scheduler tick) should run again to keep draining.+ hasMore: batch.scanned === SCAN_LIMIT,};- await writeSyncState({ cursorRowid: batch.maxRowid, lastRunAt: new Date().toISOString(), lastResult: result });- console.log(`💬 iMessage sync: scanned ${result.scanned}, recorded ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s), ${result.decodeFailures} decode-skip(s), cursor→${result.cursorRowid}`);+ await writeSyncState({ cursorRowid: nextCursor, lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`💬 iMessage sync: scanned ${result.scanned}, recorded ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s), ${result.decodeFailures} decode-skip(s), cursor→${result.cursorRowid}${result.hasMore ? ' (more remaining)' : ''}${persistFailed ? ' — PERSIST FAILED, cursor held' : ''}`);return result;}diff --git a/server/services/imessageSync.runSync.test.js b/server/services/imessageSync.runSync.test.jsnew file mode 100644index 0000000000..f1d6fedd15--- /dev/null+++ b/server/services/imessageSync.runSync.test.js@@ -0,0 +1,164 @@+/**+ * Regression tests for runSync's cursor/persistence contract (#2151 review):+ *+ * - A persistence failure must NOT advance the ROWID cursor — skipping past+ * unpersisted messages loses them permanently (the cursor never revisits a+ * ROWID), while re-processing is a harmless no-op thanks to dedupe keys.+ * - Concurrent callers share one in-flight pass (re-entrancy guard).+ * - checkSetup distinguishes "chat.db doesn't exist" (ENOENT) from a real+ * Full Disk Access denial — the FDA remediation can't help a Linux install.+ *+ * Uses a fixture chat.db built with the real Messages schema — no dependency+ * on ~/Library/Messages or Full Disk Access.+ */+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { join } from 'path';+import { rmSync } from 'fs';+import { DatabaseSync } from 'node:sqlite';++const { recordEventsMock, autoLogTouchpointsMock } = vi.hoisted(() => ({+ recordEventsMock: vi.fn(),+ autoLogTouchpointsMock: vi.fn(),+}));++const dataRoot = vi.hoisted(() => {+ // Inline mkdtemp to avoid importing helpers inside the hoisted block.+ const { mkdtempSync } = require('fs');+ const { tmpdir } = require('os');+ const { join: joinPath } = require('path');+ return mkdtempSync(joinPath(tmpdir(), 'imessage-sync-test-'));+});++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ const { join: joinPath } = await import('path');+ return {+ ...actual,+ // imessageSync persists its cursor via dataPath(STATE_FILE) — redirect it+ // at the export level (proxying PATHS alone wouldn't reach the internal+ // binding dataPath closes over).+ dataPath: (...segments) => joinPath(dataRoot, ...segments),+ };+});++vi.mock('./humanActivity.js', async () => {+ const actual = await vi.importActual('./humanActivity.js');+ return { ...actual, recordEvents: recordEventsMock };+});++vi.mock('./tribe.js', () => ({+ autoLogTouchpoints: autoLogTouchpointsMock,+}));++import { runSync, checkSetup } from './imessageSync.js';++const APPLE_EPOCH_OFFSET_MS = 978307200000;+const FIXTURE_DB = join(dataRoot, 'fixture-chat.db');++function appleNs(utcMs) {+ return String(Math.round((utcMs - APPLE_EPOCH_OFFSET_MS) / 1000) * 1e9);+}++beforeAll(() => {+ const db = new DatabaseSync(FIXTURE_DB);+ db.exec(`+ CREATE TABLE handle (ROWID INTEGER PRIMARY KEY, id TEXT);+ CREATE TABLE chat (ROWID INTEGER PRIMARY KEY, guid TEXT, chat_identifier TEXT, display_name TEXT);+ CREATE TABLE chat_handle_join (chat_id INTEGER, handle_id INTEGER);+ CREATE TABLE message (ROWID INTEGER PRIMARY KEY, guid TEXT, date INTEGER, text TEXT, attributedBody BLOB, is_from_me INTEGER, service TEXT, handle_id INTEGER);+ CREATE TABLE chat_message_join (chat_id INTEGER, message_id INTEGER);+ `);+ db.exec(`INSERT INTO handle VALUES (1,'+15551234567')`);+ db.exec(`INSERT INTO chat VALUES (1,'iMessage;-;+15551234567','+15551234567','Grace')`);+ db.exec(`INSERT INTO chat_handle_join VALUES (1,1)`);+ const insert = db.prepare('INSERT INTO message (ROWID,guid,date,text,is_from_me,service,handle_id) VALUES (?,?,?,?,?,?,?)');+ insert.run(10, 'G-10', appleNs(Date.UTC(2024, 2, 10, 15, 0, 0)), 'hey there', 0, 'iMessage', 1);+ insert.run(11, 'G-11', appleNs(Date.UTC(2024, 2, 10, 15, 1, 0)), 'reply', 1, 'iMessage', 0);+ db.exec('INSERT INTO chat_message_join VALUES (1,10),(1,11)');+ db.close();+ process.env.IMESSAGE_CHAT_DB = FIXTURE_DB;+});++afterAll(() => {+ delete process.env.IMESSAGE_CHAT_DB;+ rmSync(dataRoot, { recursive: true, force: true });+});++beforeEach(() => {+ recordEventsMock.mockReset();+ autoLogTouchpointsMock.mockReset();+ // Fresh cursor per test — remove the persisted state file.+ rmSync(join(dataRoot, 'imessage-sync-state.json'), { force: true });+});++describe('runSync cursor/persistence contract', () => {+ it('holds the cursor when persistence fails, then advances on the successful retry', async () => {+ recordEventsMock.mockRejectedValueOnce(new Error('pg down'));+ autoLogTouchpointsMock.mockResolvedValue({ created: 0, matched: 0 });++ const failed = await runSync();+ expect(failed.ok).toBe(false);+ expect(failed.cursorRowid).toBe(0); // held at the pre-pass cursor, not 11+ expect(failed.scanned).toBe(2);++ // Retry with persistence healthy — the SAME batch is re-read (cursor held)+ // and the cursor now advances to the max ROWID.+ recordEventsMock.mockResolvedValue({ recorded: 2, skipped: 0 });+ const ok = await runSync();+ expect(ok.ok).toBe(true);+ expect(ok.scanned).toBe(2); // re-scanned the held batch — nothing was lost+ expect(ok.cursorRowid).toBe(11);+ expect(ok.hasMore).toBe(false);+ });++ it('advances the cursor and reports counts on a clean pass', async () => {+ recordEventsMock.mockResolvedValue({ recorded: 2, skipped: 0 });+ autoLogTouchpointsMock.mockResolvedValue({ created: 1, matched: 1 });++ const result = await runSync();+ expect(result.ok).toBe(true);+ expect(result.cursorRowid).toBe(11);+ expect(result.recorded).toBe(2);+ expect(result.touchpointsCreated).toBe(1);++ // Incremental: a second pass starts past ROWID 11 and finds nothing.+ const second = await runSync();+ expect(second.scanned).toBe(0);+ expect(second.cursorRowid).toBe(11);+ });++ it('shares one in-flight pass across concurrent callers (re-entrancy guard)', async () => {+ let release;+ recordEventsMock.mockImplementation(() => new Promise((resolve) => {+ release = () => resolve({ recorded: 2, skipped: 0 });+ }));+ autoLogTouchpointsMock.mockResolvedValue({ created: 0, matched: 0 });++ const first = runSync();+ const second = runSync(); // while the first is still awaiting persistence+ // Give the first call time to reach the pending recordEvents await.+ await new Promise((r) => setTimeout(r, 20));+ release();+ const [a, b] = await Promise.all([first, second]);+ expect(a).toBe(b); // same result object — the pass ran once+ expect(recordEventsMock).toHaveBeenCalledTimes(1);+ });+});++describe('checkSetup error classification', () => {+ it('does NOT claim Full Disk Access for a nonexistent chat.db (ENOENT)', async () => {+ const prev = process.env.IMESSAGE_CHAT_DB;+ process.env.IMESSAGE_CHAT_DB = join(dataRoot, 'does-not-exist', 'chat.db');+ const report = await checkSetup();+ process.env.IMESSAGE_CHAT_DB = prev;+ expect(report.ok).toBe(false);+ expect(report.fullDiskAccessRequired).toBe(false);+ expect(report.remediation).not.toContain('Full Disk Access');+ });++ it('reports ok with a message count for a readable chat.db', async () => {+ const report = await checkSetup();+ expect(report.ok).toBe(true);+ expect(report.messageCount).toBe(2);+ });+});