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
Add Comms → iMessage manager for browse, purge, and blocklist (#2413)
[._.]/ Adam Eivy140388da9cf0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f8512e39ce..423a58d234 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## Features++- **[issue-2413] Comms → iMessage manager for ingested Messages activity.** After Settings → iMessage sync lands events in PortOS, you can browse them under **Comms → iMessage** (`/imessage`): conversation list + short summaries, PortOS-side purge (per event or whole chat), and a handle blocklist that future syncs honor. Deletes never write Apple's `chat.db` (read-only boundary unchanged). Settings → iMessage links to the manager and surfaces when more history remains to drain.+- **A never-run cron task no longer fires an immediate "catch-up" for a scheduled slot that predates when the task was set up.** `shouldRunTask`'s cron catch-up bounded a never-run task only by "the occurrence before the most recent slot" — which is always earlier than that slot, so the guard was vacuous and *every* never-run cron task reported `cron-catch-up` for its most recent past slot. For long periods this was jarring: a weekly `branch-cleanup` scheduled `0 9 * * 0` (Sunday 09:00) that was enabled mid-week immediately showed as **due now (catch-up)** on the Schedule Timeline for *last* Sunday's slot — a slot that elapsed before the task existed and was never actually missed. Tasks now carry a `createdAt` timestamp (stamped when first configured; `loadSchedule` backfills existing installs to "now", which only suppresses catch-up for already-past slots and never affects future cadence), and never-run catch-up only fires for a slot that elapsed *after* `createdAt`. So a weekly task enabled on a Friday now waits for the coming Sunday instead of running immediately, while a task that was genuinely configured before a missed slot (daemon down / check window missed) still catches up as before.## Securitydiff --git a/client/src/App.jsx b/client/src/App.jsxindex d409591eb5..fa96a7b21a 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -30,6 +30,7 @@ const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));const CalendarPage = lazyWithReload(() => import('./pages/Calendar'));const Messages = lazyWithReload(() => import('./pages/Messages'));+const IMessage = lazyWithReload(() => import('./pages/IMessage'));const Tribe = lazyWithReload(() => import('./pages/Tribe'));const Timeline = lazyWithReload(() => import('./pages/Timeline'));const Goals = lazyWithReload(() => import('./pages/Goals'));@@ -282,6 +283,8 @@ export default function App() {<Route path="review" element={<Review />} /><Route path="messages" element={<Navigate to="/messages/inbox" replace />} /><Route path="messages/:tab" element={<Messages />} />+ <Route path="imessage" element={<IMessage />} />+ <Route path="imessage/:chatKey" element={<IMessage />} /><Route path="tribe" element={<Tribe />} /><Route path="timeline" element={<Timeline />} /><Route path="timeline/:date" element={<Timeline />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex dfe9659608..07c9038dc6 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -206,6 +206,7 @@ const navItems = [children: [{ to: '/messages/config', label: 'Config', icon: Settings },{ to: '/messages/drafts', label: 'Drafts', icon: FilePen },+ { to: '/imessage', label: 'iMessage', icon: MessageSquare },{ to: '/messages/inbox', label: 'Inbox', icon: Inbox },{ to: '/messages/sync', label: 'Sync', icon: RefreshCw },],@@ -1167,6 +1168,7 @@ export default function Layout() {location.pathname.startsWith('/meatspace') ||location.pathname.startsWith('/media') ||location.pathname.startsWith('/messages') ||+ location.pathname.startsWith('/imessage') ||location.pathname.startsWith('/local-llm/') ||location.pathname.startsWith('/pipeline/issues/') ||location.pathname.startsWith('/pipeline/series/') ||diff --git a/client/src/components/settings/IMessageTab.jsx b/client/src/components/settings/IMessageTab.jsxindex 64d2430b91..81c101d98f 100644--- a/client/src/components/settings/IMessageTab.jsx+++ b/client/src/components/settings/IMessageTab.jsx@@ -1,5 +1,6 @@import { useEffect, useState } from 'react';-import { Save, Loader2, MessageSquare, ShieldCheck, ShieldAlert, RefreshCw } from 'lucide-react';+import { Link } from 'react-router-dom';+import { Save, Loader2, MessageSquare, ShieldCheck, ShieldAlert, RefreshCw, ExternalLink } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import {@@ -95,6 +96,11 @@ export function IMessageTab() {Reads your local macOS Messages database (<code className="text-gray-300">~/Library/Messages/chat.db</code>) read-onlyand feeds both Tribe touchpoints and the activity timeline. Machine-local — nothing federates to peers.Requires macOS <strong>Full Disk Access</strong> for the process running PortOS.+ Browse, purge spam, and manage ingested events under{' '}+ <Link to="/imessage" className="text-port-accent hover:underline inline-flex items-center gap-1">+ Comms → iMessage <ExternalLink size={12} />+ </Link>+ {' '}— deletes there remove PortOS copies only, never Apple Messages.</p><div className="space-y-3">@@ -177,7 +183,15 @@ export function IMessageTab() {{(lastResult || status?.state?.cursorRowid > 0) && (<div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">- <h3 className="text-sm font-semibold text-white mb-2">Last sync</h3>+ <div className="flex flex-wrap items-center justify-between gap-2 mb-2">+ <h3 className="text-sm font-semibold text-white">Last sync</h3>+ <Link+ to="/imessage"+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"+ >+ Open iMessage manager <ExternalLink size={12} />+ </Link>+ </div><dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm"><div><dt className="text-gray-500 text-xs uppercase">Cursor ROWID</dt><dd className="text-gray-200">{status?.state?.cursorRowid ?? 0}</dd></div><div><dt className="text-gray-500 text-xs uppercase">Events recorded</dt><dd className="text-gray-200">{lastResult?.recorded ?? '—'}</dd></div>@@ -186,6 +200,16 @@ export function IMessageTab() {<div><dt className="text-gray-500 text-xs uppercase">Decode skips</dt><dd className="text-gray-200">{lastResult?.decodeFailures ?? '—'}</dd></div><div><dt className="text-gray-500 text-xs uppercase">Last run</dt><dd className="text-gray-200">{status?.state?.lastRunAt ? new Date(status.state.lastRunAt).toLocaleString() : '—'}</dd></div></dl>+ {lastResult?.hasMore && (+ <p className="mt-3 text-xs text-port-warning">+ More history remains in chat.db — run Sync now again (or open the manager) until the cursor catches up.+ First batches are often older messages; open{' '}+ <Link to="/timeline" className="text-port-accent hover:underline">Timeline</Link>+ {' '}on those dates or use{' '}+ <Link to="/imessage" className="text-port-accent hover:underline">Comms → iMessage</Link>+ {' '}to browse by conversation.+ </p>+ )}</div>)}</div>diff --git a/client/src/pages/IMessage.jsx b/client/src/pages/IMessage.jsxnew file mode 100644index 0000000000..4c49c6bec9--- /dev/null+++ b/client/src/pages/IMessage.jsx@@ -0,0 +1,612 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { Link, useNavigate, useParams } from 'react-router-dom';+import {+ MessageSquare, RefreshCw, Search, Trash2, Ban, ChevronLeft,+ Loader2, ExternalLink, ShieldOff, Settings, CalendarClock, Users,+} from 'lucide-react';+import PageHeader from '../components/PageHeader';+import BrailleSpinner from '../components/BrailleSpinner';+import toast from '../components/ui/Toast';+import * as api from '../services/api';+import { formatClockTime, timeAgo } from '../utils/formatters';++// Comms → iMessage (#2413). Browse / manage PortOS-side activity ingested from+// macOS chat.db. Deletes and blocklists never write Apple's Messages database.++function formatWhen(iso) {+ if (!iso) return '—';+ try {+ return timeAgo(new Date(iso));+ } catch {+ return '—';+ }+}++function ConfirmBar({ message, confirmLabel, onConfirm, onCancel, danger }) {+ return (+ <div className="flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-sm text-gray-200">+ <span className="flex-1 min-w-[12rem]">{message}</span>+ <button+ type="button"+ onClick={onCancel}+ className="rounded border border-port-border bg-port-bg px-3 py-1.5 text-xs hover:border-port-accent"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={onConfirm}+ className={`rounded px-3 py-1.5 text-xs font-medium ${+ danger+ ? 'bg-port-error/20 text-port-error hover:bg-port-error/30'+ : 'bg-port-accent/20 text-port-accent hover:bg-port-accent/30'+ }`}+ >+ {confirmLabel}+ </button>+ </div>+ );+}++function ConversationList({ conversations, selectedKey, onSelect, query, onQueryChange, loading }) {+ return (+ <div className="flex h-full min-h-0 flex-col border border-port-border bg-port-card rounded-lg overflow-hidden">+ <div className="border-b border-port-border p-2">+ <label htmlFor="imessage-search" className="sr-only">Search conversations</label>+ <div className="relative">+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" />+ <input+ id="imessage-search"+ type="search"+ value={query}+ onChange={(e) => onQueryChange(e.target.value)}+ placeholder="Search title, handle, summary…"+ className="w-full rounded border border-port-border bg-port-bg py-2 pl-8 pr-3 text-sm text-white placeholder:text-gray-600 outline-none focus:border-port-accent"+ />+ </div>+ </div>+ <div className="flex-1 overflow-y-auto">+ {loading ? (+ <div className="py-10 text-center text-gray-500 text-sm">Loading…</div>+ ) : conversations.length === 0 ? (+ <div className="px-4 py-10 text-center text-sm text-gray-500">+ No conversations yet.+ <div className="mt-1 text-xs text-gray-600">+ Run a sync from Settings → iMessage, then refresh.+ </div>+ </div>+ ) : (+ <ul className="divide-y divide-port-border">+ {conversations.map((c) => {+ const active = c.chatKey === selectedKey;+ return (+ <li key={c.chatKey || c.chatGuid || c.title}>+ <button+ type="button"+ onClick={() => onSelect(c.chatKey)}+ className={`w-full text-left px-3 py-2.5 transition-colors ${+ active ? 'bg-port-accent/15' : 'hover:bg-port-bg/80'+ }`}+ >+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="truncate font-medium text-sm text-gray-100">{c.title}</span>+ {c.blocked && (+ <span className="shrink-0 rounded bg-port-error/15 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-port-error">+ Blocked+ </span>+ )}+ </div>+ {c.lastSummary && (+ <div className="mt-0.5 truncate text-xs text-gray-500">{c.lastSummary}</div>+ )}+ </div>+ <div className="shrink-0 text-right">+ <div className="text-[10px] text-gray-500">{formatWhen(c.lastAt)}</div>+ <div className="text-[10px] text-gray-600">{c.eventCount}</div>+ </div>+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </div>+ );+}++function ConversationDetail({+ chatKey,+ conversation,+ events,+ loading,+ timezone,+ onBack,+ onPurged,+ onEventDeleted,+ onBlocked,+}) {+ const [confirm, setConfirm] = useState(null); // 'purge' | 'block-purge' | null+ const [busy, setBusy] = useState(false);++ const handle = conversation?.handle;++ const runPurge = async () => {+ setBusy(true);+ const result = await api.purgeImessageConversation(chatKey, { silent: true }).catch(() => null);+ setBusy(false);+ setConfirm(null);+ if (!result) {+ toast.error('Failed to purge conversation');+ return;+ }+ toast.success(`Removed ${result.deleted} event(s) from PortOS`);+ onPurged?.(chatKey);+ };++ const runBlock = async ({ purgeExisting }) => {+ if (!handle) {+ toast.error('No handle to block on this conversation');+ setConfirm(null);+ return;+ }+ setBusy(true);+ const result = await api.addImessageBlocklist(handle, { purgeExisting, silent: true }).catch(() => null);+ setBusy(false);+ setConfirm(null);+ if (!result) {+ toast.error('Failed to update blocklist');+ return;+ }+ const purged = result.purged || 0;+ toast.success(+ purged > 0+ ? `Blocked ${handle} — removed ${purged} PortOS event(s)`+ : `Blocked ${handle} — future syncs will skip it`,+ );+ onBlocked?.(chatKey, { purged });+ };++ const deleteEvent = async (id) => {+ const result = await api.deleteImessageEvent(id, { silent: true }).catch(() => null);+ if (!result) {+ toast.error('Failed to delete event');+ return;+ }+ if (result.deleted > 0) {+ toast.success('Event removed from PortOS');+ onEventDeleted?.(id);+ } else {+ toast.error('Event not found');+ }+ };++ if (!chatKey) {+ return (+ <div className="flex h-full min-h-[16rem] items-center justify-center rounded-lg border border-dashed border-port-border text-sm text-gray-500">+ Select a conversation to inspect summaries and manage PortOS copies.+ </div>+ );+ }++ const lastDay = conversation?.lastAt+ ? new Date(conversation.lastAt).toISOString().slice(0, 10)+ : null;++ return (+ <div className="flex h-full min-h-0 flex-col rounded-lg border border-port-border bg-port-card overflow-hidden">+ <div className="border-b border-port-border p-3 space-y-2">+ <div className="flex items-start gap-2">+ <button+ type="button"+ onClick={onBack}+ className="md:hidden rounded border border-port-border p-1.5 hover:border-port-accent"+ aria-label="Back to conversations"+ >+ <ChevronLeft size={16} />+ </button>+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-base font-semibold text-white">+ {conversation?.title || 'Conversation'}+ </h2>+ <div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-gray-500">+ {handle && <span className="font-mono">{handle}</span>}+ {conversation?.eventCount != null && (+ <span>{conversation.eventCount} event(s)</span>+ )}+ {conversation?.blocked && (+ <span className="rounded bg-port-error/15 px-1.5 py-0.5 text-[10px] uppercase text-port-error">+ Blocked+ </span>+ )}+ </div>+ </div>+ </div>++ <p className="text-[11px] text-gray-600">+ Deletes remove PortOS activity only — Apple Messages is never modified.+ </p>++ {confirm === 'purge' && (+ <ConfirmBar+ message="Purge all PortOS events for this conversation? Messages.app is unchanged."+ confirmLabel={busy ? 'Purging…' : 'Purge from PortOS'}+ danger+ onCancel={() => setConfirm(null)}+ onConfirm={runPurge}+ />+ )}+ {confirm === 'block-purge' && (+ <ConfirmBar+ message={`Block ${handle || 'this handle'} and remove matching PortOS events?`}+ confirmLabel={busy ? 'Working…' : 'Block + purge'}+ danger+ onCancel={() => setConfirm(null)}+ onConfirm={() => runBlock({ purgeExisting: true })}+ />+ )}++ {!confirm && (+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={() => setConfirm('purge')}+ disabled={busy}+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-error hover:text-port-error disabled:opacity-40"+ >+ <Trash2 size={12} />+ Purge from PortOS+ </button>+ {handle && !conversation?.blocked && (+ <>+ <button+ type="button"+ onClick={() => runBlock({ purgeExisting: false })}+ disabled={busy}+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-40"+ >+ <Ban size={12} />+ Block handle+ </button>+ <button+ type="button"+ onClick={() => setConfirm('block-purge')}+ disabled={busy}+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-error hover:text-port-error disabled:opacity-40"+ >+ <Ban size={12} />+ Block + purge+ </button>+ </>+ )}+ {lastDay && (+ <Link+ to={`/timeline/${lastDay}`}+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent"+ >+ <CalendarClock size={12} />+ Timeline day+ <ExternalLink size={10} className="opacity-60" />+ </Link>+ )}+ <Link+ to="/tribe"+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent"+ >+ <Users size={12} />+ Tribe phones+ </Link>+ </div>+ )}+ </div>++ <div className="flex-1 overflow-y-auto p-2 space-y-1.5">+ {loading ? (+ <div className="py-10 text-center text-gray-500 text-sm">Loading events…</div>+ ) : events.length === 0 ? (+ <div className="py-10 text-center text-sm text-gray-500">No events in PortOS for this chat.</div>+ ) : (+ events.map((ev) => (+ <div+ key={ev.id}+ className="flex gap-2 rounded border border-port-border bg-port-bg/50 px-2.5 py-2"+ >+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2 text-[10px] text-gray-500">+ <span className="font-mono">+ {formatClockTime(new Date(ev.happenedAt), timezone ? { timeZone: timezone } : undefined)}+ </span>+ <span className="uppercase tracking-wide">+ {ev.kind === 'message.sent' ? 'Sent' : ev.kind === 'message.received' ? 'Received' : ev.kind}+ </span>+ </div>+ <div className="mt-0.5 text-sm text-gray-200 break-words">+ {ev.summary || <span className="text-gray-600 italic">(no summary)</span>}+ </div>+ </div>+ <button+ type="button"+ onClick={() => deleteEvent(ev.id)}+ className="shrink-0 self-start rounded p-1.5 text-gray-500 hover:bg-port-error/15 hover:text-port-error"+ aria-label="Delete event from PortOS"+ title="Delete from PortOS only"+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))+ )}+ </div>+ </div>+ );+}++export default function IMessage() {+ const { chatKey: chatKeyParam } = useParams();+ const navigate = useNavigate();+ const selectedKey = chatKeyParam || null;++ const [stats, setStats] = useState(null);+ const [conversations, setConversations] = useState([]);+ const [listLoading, setListLoading] = useState(true);+ const [query, setQuery] = useState('');+ const [debouncedQ, setDebouncedQ] = useState('');+ const [events, setEvents] = useState([]);+ const [eventsLoading, setEventsLoading] = useState(false);+ const [syncing, setSyncing] = useState(false);++ useEffect(() => {+ const t = setTimeout(() => setDebouncedQ(query.trim()), 250);+ return () => clearTimeout(t);+ }, [query]);++ const loadList = useCallback(async () => {+ setListLoading(true);+ const [statsRes, convRes] = await Promise.all([+ api.getImessageStats({ silent: true }).catch(() => null),+ api.getImessageConversations({ q: debouncedQ || undefined, silent: true }).catch(() => null),+ ]);+ setStats(statsRes);+ setConversations(convRes?.conversations || []);+ setListLoading(false);+ }, [debouncedQ]);++ useEffect(() => {+ loadList();+ }, [loadList]);++ useEffect(() => {+ if (!selectedKey) {+ setEvents([]);+ return undefined;+ }+ let active = true;+ setEventsLoading(true);+ api.getImessageConversationEvents(selectedKey, { limit: 200, silent: true })+ .then((res) => {+ if (active) setEvents(res?.events || []);+ })+ .catch(() => {+ if (active) {+ setEvents([]);+ toast.error('Failed to load conversation');+ }+ })+ .finally(() => {+ if (active) setEventsLoading(false);+ });+ return () => { active = false; };+ }, [selectedKey]);++ const selectedConversation = useMemo(+ () => conversations.find((c) => c.chatKey === selectedKey) || null,+ [conversations, selectedKey],+ );++ const select = (key) => {+ navigate(key ? `/imessage/${encodeURIComponent(key)}` : '/imessage');+ };++ const handleSync = async () => {+ setSyncing(true);+ const result = await api.syncImessage({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));+ setSyncing(false);+ if (result?.ok) {+ toast.success(+ `Synced: ${result.recorded} event(s)`+ + (result.blockedSkipped ? `, ${result.blockedSkipped} blocked` : '')+ + (result.hasMore ? ' — more history remains' : ''),+ );+ await loadList();+ } else {+ toast.error(result?.fullDiskAccessRequired ? 'Full Disk Access required' : (result?.error || 'Sync failed'));+ }+ };++ const onPurged = (key) => {+ setConversations((prev) => prev.filter((c) => c.chatKey !== key));+ setEvents([]);+ navigate('/imessage');+ loadList();+ };++ const onEventDeleted = (id) => {+ setEvents((prev) => prev.filter((e) => e.id !== id));+ setConversations((prev) => prev.map((c) => (+ c.chatKey === selectedKey+ ? { ...c, eventCount: Math.max(0, (c.eventCount || 1) - 1) }+ : c+ )));+ };++ const onBlocked = (key, { purged }) => {+ if (purged > 0) {+ setConversations((prev) => prev.filter((c) => c.chatKey !== key));+ setEvents([]);+ navigate('/imessage');+ } else {+ setConversations((prev) => prev.map((c) => (+ c.chatKey === key ? { ...c, blocked: true } : c+ )));+ }+ loadList();+ };++ const hasMore = stats?.sync?.state?.lastResult?.hasMore;+ const showDetailMobile = !!selectedKey;++ if (listLoading && conversations.length === 0 && !stats) {+ return (+ <div className="flex h-full items-center justify-center">+ <BrailleSpinner text="Loading iMessage" />+ </div>+ );+ }++ return (+ <div className="flex h-full min-h-0 flex-col gap-3 p-4 md:p-6">+ <PageHeader+ icon={MessageSquare}+ title="iMessage"+ subtitle="Browse and manage PortOS copies of your local Messages activity. Full bodies stay in Apple's chat.db — deletes never write back."+ actions={(+ <div className="flex flex-wrap items-center gap-2">+ <Link+ to="/settings/imessage"+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-300 hover:border-port-accent"+ >+ <Settings size={12} />+ Settings+ </Link>+ <button+ type="button"+ onClick={handleSync}+ disabled={syncing}+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-200 hover:border-port-accent disabled:opacity-40"+ >+ {syncing ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ {hasMore ? 'Sync more history' : 'Sync now'}+ </button>+ </div>+ )}+ />++ <div className="flex flex-wrap gap-2 text-xs text-gray-400">+ <span className="rounded border border-port-border bg-port-card px-2 py-1">+ {stats?.eventCount ?? 0} events+ </span>+ <span className="rounded border border-port-border bg-port-card px-2 py-1">+ {stats?.conversationCount ?? 0} conversations+ </span>+ <span className="rounded border border-port-border bg-port-card px-2 py-1">+ {stats?.blockedCount ?? 0} blocked+ </span>+ {stats?.earliestAt && (+ <span className="rounded border border-port-border bg-port-card px-2 py-1">+ {new Date(stats.earliestAt).toLocaleDateString()} → {stats.latestAt ? new Date(stats.latestAt).toLocaleDateString() : '—'}+ </span>+ )}+ {hasMore && (+ <span className="rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1 text-port-warning">+ More history remains — run Sync more+ </span>+ )}+ </div>++ {stats?.eventCount === 0 && (+ <div className="rounded border border-dashed border-port-border px-4 py-3 text-sm text-gray-500">+ Nothing ingested yet. Grant Full Disk Access if needed, then use{' '}+ <Link to="/settings/imessage" className="text-port-accent hover:underline">Settings → iMessage</Link>+ {' '}or <strong className="text-gray-400">Sync now</strong> above. Data also appears on the{' '}+ <Link to="/timeline" className="text-port-accent hover:underline">Timeline</Link>+ {' '}day view (navigate to the date range of your messages).+ </div>+ )}++ <div className="grid min-h-0 flex-1 gap-3 md:grid-cols-[minmax(16rem,22rem)_1fr]">+ <div className={`min-h-0 ${showDetailMobile ? 'hidden md:block' : 'block'} h-[min(70vh,40rem)] md:h-auto`}>+ <ConversationList+ conversations={conversations}+ selectedKey={selectedKey}+ onSelect={select}+ query={query}+ onQueryChange={setQuery}+ loading={listLoading}+ />+ </div>+ <div className={`min-h-0 ${showDetailMobile ? 'block' : 'hidden md:block'} h-[min(70vh,40rem)] md:h-auto`}>+ <ConversationDetail+ chatKey={selectedKey}+ conversation={selectedConversation}+ events={events}+ loading={eventsLoading}+ timezone={undefined}+ onBack={() => select(null)}+ onPurged={onPurged}+ onEventDeleted={onEventDeleted}+ onBlocked={onBlocked}+ />+ </div>+ </div>++ {(stats?.blockedCount > 0) && (+ <BlocklistPanel onChanged={loadList} />+ )}+ </div>+ );+}++function BlocklistPanel({ onChanged }) {+ const [handles, setHandles] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ api.getImessageBlocklist({ silent: true })+ .then((res) => setHandles(res?.handles || []))+ .catch(() => setHandles([]))+ .finally(() => setLoading(false));+ }, []);++ const unblock = async (handle) => {+ const res = await api.removeImessageBlocklist(handle, { silent: true }).catch(() => null);+ if (!res) {+ toast.error('Failed to unblock');+ return;+ }+ setHandles(res.handles || []);+ toast.success(`Unblocked ${handle}`);+ onChanged?.();+ };++ if (loading || handles.length === 0) return null;++ return (+ <div className="rounded-lg border border-port-border bg-port-card p-3">+ <div className="mb-2 flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-gray-500">+ <ShieldOff size={12} />+ Blocked handles+ </div>+ <ul className="flex flex-wrap gap-2">+ {handles.map((h) => (+ <li key={h} className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2 py-1 text-xs text-gray-300">+ <span className="font-mono">{h}</span>+ <button+ type="button"+ onClick={() => unblock(h)}+ className="text-gray-500 hover:text-port-accent"+ aria-label={`Unblock ${h}`}+ >+ Unblock+ </button>+ </li>+ ))}+ </ul>+ <p className="mt-2 text-[11px] text-gray-600">+ Unblocking does not re-import past messages (the sync cursor only moves forward).+ </p>+ </div>+ );+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 2e24045306..0b246ad922 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -76,7 +76,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiMoodBoard.js` | Mood boards (inspiration canvas + items). || `apiTribe.js` | Tribe people (relationship rings + contacts). || `apiCalendar.js` | Calendar events. |-| `apiMessages.js` | Messages / notifications. |+| `apiMessages.js` | Messages / notifications + iMessage manager (#2413). || `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. || `apiSpotify.js` | Spotify OAuth + listening-history sync. || `apiYoutube.js` | YouTube watch-history scrape sync + setup check. |diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.jsindex b24b02a901..ba39412ad9 100644--- a/client/src/services/apiMessages.js+++ b/client/src/services/apiMessages.js@@ -51,6 +51,38 @@ export const getImessageStatus = (options = {}) => request('/imessage/status', oexport const checkImessageSetup = (options = {}) => request('/imessage/setup-check', options);export const syncImessage = (options = {}) => request('/imessage/sync', { method: 'POST', ...options });+// iMessage manager (#2413) — PortOS-side browse / purge / blocklist (never writes chat.db).+export const getImessageStats = (options = {}) => request('/imessage/stats', options);+export const getImessageConversations = ({ q, limit, silent } = {}) => {+ const params = new URLSearchParams();+ if (q) params.set('q', q);+ if (limit) params.set('limit', String(limit));+ const qs = params.toString();+ return request(`/imessage/conversations${qs ? `?${qs}` : ''}`, { silent });+};+export const getImessageConversationEvents = (chatKey, { limit, before, silent } = {}) => {+ const params = new URLSearchParams();+ if (limit) params.set('limit', String(limit));+ if (before) params.set('before', before);+ const qs = params.toString();+ return request(`/imessage/conversations/${encodeURIComponent(chatKey)}/events${qs ? `?${qs}` : ''}`, { silent });+};+export const purgeImessageConversation = (chatKey, options = {}) =>+ request(`/imessage/conversations/${encodeURIComponent(chatKey)}`, { method: 'DELETE', ...options });+export const deleteImessageEvent = (id, options = {}) =>+ request(`/imessage/events/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });+export const getImessageBlocklist = (options = {}) => request('/imessage/blocklist', options);+export const setImessageBlocklist = (handles, options = {}) =>+ request('/imessage/blocklist', { method: 'PUT', body: JSON.stringify({ handles }), ...options });+export const addImessageBlocklist = (handles, { purgeExisting = false, ...options } = {}) =>+ request('/imessage/blocklist', {+ method: 'POST',+ body: JSON.stringify({ handles, purgeExisting }),+ ...options,+ });+export const removeImessageBlocklist = (handle, options = {}) =>+ request(`/imessage/blocklist/${encodeURIComponent(handle)}`, { method: 'DELETE', ...options });+// Feeds - RSS/Atom Feed Ingestionexport const getFeeds = () => request('/feeds');export const getFeedStats = (options = {}) => request('/feeds/stats', options);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex dd0678f4c8..327c39c929 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -100,6 +100,7 @@ export const NAV_COMMANDS = [{ id: 'nav.messages.drafts', path: '/messages/drafts', label: 'Drafts', section: 'Comms', aliases: ['drafts', 'comms-drafts'], keywords: ['comms'] },{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Comms', aliases: ['messages-config', 'comms-config'], keywords: ['comms'] },{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Comms', aliases: ['messages-sync', 'comms-sync'], keywords: ['comms'] },+ { id: 'nav.imessage', path: '/imessage', label: 'iMessage', section: 'Comms', aliases: ['imessage', 'i-message', 'apple-messages', 'comms-imessage'], keywords: ['comms', 'imessage', 'sms', 'text messages', 'chat.db', 'blocklist', 'spam'] },{ id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Brain', aliases: ['openclaw'] },{ id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily', 'import', 'backfill', 'whatsapp', 'spotify', 'discord', 'youtube'] },{ id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },@@ -182,7 +183,9 @@ export const NAV_COMMANDS = [{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },{ id: 'nav.settings.embeddings', path: '/settings/embeddings', label: 'Embeddings', section: 'Settings', aliases: ['settings-embeddings', 'embeddings', 'embedding'], keywords: ['vector', 'pgvector', 'semantic search', 'nomic', 'ollama', 'lm studio'] },{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },- { id: 'nav.settings.imessage', path: '/settings/imessage', label: 'iMessage', section: 'Settings', aliases: ['settings-imessage', 'imessage', 'imessage-settings'], keywords: ['imessage', 'sync', 'chat.db', 'sms', 'texts', 'tribe', 'timeline', 'full disk access'] },+ // Alias `imessage` lives on Comms → iMessage (the manager page, #2413); settings+ // keeps the explicit settings-* tokens so voice "open iMessage settings" still works.+ { id: 'nav.settings.imessage', path: '/settings/imessage', label: 'iMessage', section: 'Settings', aliases: ['settings-imessage', 'imessage-settings'], keywords: ['imessage', 'sync', 'chat.db', 'sms', 'texts', 'tribe', 'timeline', 'full disk access'] },{ id: 'nav.settings.local-llm', path: '/settings/local-llm', label: 'Local LLMs', section: 'Settings', aliases: ['local-llm', 'local-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend'] },{ id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Local LLM Playground', section: 'Settings', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },diff --git a/server/routes/imessage.js b/server/routes/imessage.jsindex b1de47b728..dd6a91e95e 100644--- a/server/routes/imessage.js+++ b/server/routes/imessage.js@@ -1,7 +1,10 @@import { Router } from 'express';+import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';import * as imessageSync from '../services/imessageSync.js';+import * as imessageManage from '../services/imessageManage.js';const router = Router();@@ -27,4 +30,93 @@ router.post('/sync', asyncHandler(async (req, res) => {res.json(result);}));+// ---------------------------------------------------------------------------+// Manager surface (#2413) — browse / purge / blocklist. PortOS-side only;+// never opens chat.db writable.+// ---------------------------------------------------------------------------++const listConversationsQuerySchema = z.object({+ q: z.string().max(200).optional(),+ limit: z.coerce.number().int().min(1).max(2000).optional(),+});++router.get('/conversations', asyncHandler(async (req, res) => {+ const q = validateRequest(listConversationsQuerySchema, req.query);+ const conversations = await imessageManage.listConversations(q);+ res.json({ conversations });+}));++const eventsQuerySchema = z.object({+ limit: z.coerce.number().int().min(1).max(2000).optional(),+ before: z.string().datetime().optional(),+});++router.get('/conversations/:chatKey/events', asyncHandler(async (req, res) => {+ const chatKey = String(req.params.chatKey || '');+ if (!chatKey) throw new ServerError('chatKey is required', { status: 400, code: 'BAD_REQUEST' });+ const q = validateRequest(eventsQuerySchema, req.query);+ const payload = await imessageManage.listConversationEvents(chatKey, q);+ if (payload.chatGuid == null) {+ throw new ServerError('Invalid chat key', { status: 400, code: 'BAD_REQUEST' });+ }+ res.json(payload);+}));++router.delete('/conversations/:chatKey', asyncHandler(async (req, res) => {+ const chatKey = String(req.params.chatKey || '');+ if (!chatKey) throw new ServerError('chatKey is required', { status: 400, code: 'BAD_REQUEST' });+ const result = await imessageManage.purgeConversation(chatKey);+ if (result.chatGuid == null) {+ throw new ServerError('Invalid chat key', { status: 400, code: 'BAD_REQUEST' });+ }+ res.json(result);+}));++router.delete('/events/:id', asyncHandler(async (req, res) => {+ const id = String(req.params.id || '');+ if (!id) throw new ServerError('id is required', { status: 400, code: 'BAD_REQUEST' });+ const result = await imessageManage.deleteEvent(id);+ res.json(result);+}));++router.get('/blocklist', asyncHandler(async (req, res) => {+ const list = await imessageManage.readBlocklist();+ res.json(list);+}));++const blocklistPutSchema = z.object({+ handles: z.array(z.string().min(1).max(200)).max(5000),+});++router.put('/blocklist', asyncHandler(async (req, res) => {+ const body = validateRequest(blocklistPutSchema, req.body);+ const saved = await imessageManage.setBlocklist(body.handles);+ res.json(saved);+}));++const blocklistAddSchema = z.object({+ handles: z.union([z.string().min(1).max(200), z.array(z.string().min(1).max(200)).min(1).max(100)]),+ purgeExisting: z.boolean().optional().default(false),+});++router.post('/blocklist', asyncHandler(async (req, res) => {+ const body = validateRequest(blocklistAddSchema, req.body);+ const handles = Array.isArray(body.handles) ? body.handles : [body.handles];+ const result = await imessageManage.addToBlocklist(handles, { purgeExisting: body.purgeExisting });+ res.json(result);+}));++router.delete('/blocklist/:handle', asyncHandler(async (req, res) => {+ // Handles are E.164 / emails — may contain `+` which Express already decodes.+ const handle = decodeURIComponent(String(req.params.handle || ''));+ if (!handle) throw new ServerError('handle is required', { status: 400, code: 'BAD_REQUEST' });+ const result = await imessageManage.removeFromBlocklist(handle);+ res.json(result);+}));++router.get('/stats', asyncHandler(async (req, res) => {+ const stats = await imessageManage.getStats();+ res.json(stats);+}));+export default router;diff --git a/server/routes/imessage.test.js b/server/routes/imessage.test.jsnew file mode 100644index 0000000000..f2456e89bb--- /dev/null+++ b/server/routes/imessage.test.js@@ -0,0 +1,94 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/imessageSync.js', () => ({+ checkSetup: vi.fn(async () => ({ ok: true, messageCount: 1 })),+ getStatus: vi.fn(async () => ({ config: { enabled: false }, state: {} })),+ runSync: vi.fn(async () => ({ ok: true, recorded: 0 })),+}));++vi.mock('../services/imessageManage.js', () => ({+ listConversations: vi.fn(async () => [{ chatKey: 'abc', chatGuid: 'g1', title: 'Test', eventCount: 2 }]),+ listConversationEvents: vi.fn(async (key) => (+ key === 'bad'+ ? { chatGuid: null, chatKey: key, events: [] }+ : { chatGuid: 'g1', chatKey: key, events: [{ id: 'e1', summary: 'hi' }] }+ )),+ purgeConversation: vi.fn(async (key) => (+ key === 'bad' ? { deleted: 0, chatGuid: null } : { deleted: 3, chatGuid: 'g1', chatKey: key }+ )),+ deleteEvent: vi.fn(async () => ({ deleted: 1 })),+ readBlocklist: vi.fn(async () => ({ handles: ['+15551234567'], updatedAt: null })),+ setBlocklist: vi.fn(async (handles) => ({ handles, updatedAt: '2026-01-01T00:00:00.000Z' })),+ addToBlocklist: vi.fn(async (handles, opts) => ({+ handles: ['+15551234567'],+ added: Array.isArray(handles) ? handles : [handles],+ purged: opts?.purgeExisting ? 2 : 0,+ updatedAt: '2026-01-01T00:00:00.000Z',+ })),+ removeFromBlocklist: vi.fn(async () => ({ handles: [], updatedAt: null })),+ getStats: vi.fn(async () => ({ source: 'imessage', eventCount: 5, conversationCount: 2, blockedCount: 1 })),+}));++const { default: router } = await import('./imessage.js');++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/imessage', router);+ app.use(errorMiddleware);+ return app;+}++describe('imessage routes (#2413)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('GET /conversations returns the list', async () => {+ const res = await request(makeApp()).get('/api/imessage/conversations');+ expect(res.status).toBe(200);+ expect(res.body.conversations).toHaveLength(1);+ expect(res.body.conversations[0].title).toBe('Test');+ });++ it('GET /conversations/:chatKey/events returns events', async () => {+ const res = await request(makeApp()).get('/api/imessage/conversations/abc/events');+ expect(res.status).toBe(200);+ expect(res.body.events[0].id).toBe('e1');+ });++ it('GET /conversations/:chatKey/events 400s on invalid key', async () => {+ const res = await request(makeApp()).get('/api/imessage/conversations/bad/events');+ expect(res.status).toBe(400);+ });++ it('DELETE /conversations/:chatKey purges', async () => {+ const res = await request(makeApp()).delete('/api/imessage/conversations/abc');+ expect(res.status).toBe(200);+ expect(res.body.deleted).toBe(3);+ });++ it('DELETE /events/:id deletes one event', async () => {+ const res = await request(makeApp()).delete('/api/imessage/events/e1');+ expect(res.status).toBe(200);+ expect(res.body.deleted).toBe(1);+ });++ it('POST /blocklist accepts handles + purgeExisting', async () => {+ const res = await request(makeApp())+ .post('/api/imessage/blocklist')+ .send({ handles: '+15551234567', purgeExisting: true });+ expect(res.status).toBe(200);+ expect(res.body.purged).toBe(2);+ });++ it('GET /stats returns aggregate counts', async () => {+ const res = await request(makeApp()).get('/api/imessage/stats');+ expect(res.status).toBe(200);+ expect(res.body.eventCount).toBe(5);+ expect(res.body.blockedCount).toBe(1);+ });+});diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 14da472c47..8ce42009ac 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -349,8 +349,9 @@ async function insertActivityChunk(rows) {// Query events with optional filters. `from`/`to` are ISO timestamps (inclusive// lower, exclusive upper); `personId` matches a participant via the JSONB-// containment operator. Newest first, capped by `limit` (default 500, max 2000).-export async function listEvents({ from, to, source, kind, personId, limit } = {}) {+// containment operator. `chatGuid` / `handle` match iMessage-style metadata+// pointers. Newest first, capped by `limit` (default 500, max 2000).+export async function listEvents({ from, to, source, kind, personId, chatGuid, handle, limit } = {}) {await ensureReady();const clauses = [];const params = [];@@ -362,6 +363,14 @@ export async function listEvents({ from, to, source, kind, personId, limit } = {params.push(JSON.stringify([{ personId: String(personId) }]));clauses.push(`participants @> $${params.length}::jsonb`);}+ if (chatGuid != null && String(chatGuid).length > 0) {+ params.push(String(chatGuid));+ clauses.push(`metadata->>'chatGuid' = $${params.length}`);+ }+ if (handle != null && String(handle).length > 0) {+ params.push(String(handle));+ clauses.push(`metadata->>'handle' = $${params.length}`);+ }const cap = Math.min(Math.max(Number(limit) || 500, 1), 2000);params.push(cap);const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';@@ -375,6 +384,131 @@ export async function listEvents({ from, to, source, kind, personId, limit } = {return result.rows.map(rowToEvent);}+/**+ * Delete activity events by explicit id list and/or filters. Returns `{ deleted }`.+ *+ * Safety: refuses unbounded wipes. Accepts either:+ * - `ids` (optionally scoped with `source`), or+ * - `source` + (`chatGuid` and/or `handle`)+ *+ * Used by PortOS-side managers (iMessage #2413, later Signal/etc.) — never+ * mutates the external source (chat.db, Gmail, …).+ */+export async function deleteEvents({ ids, source, chatGuid, handle } = {}) {+ await ensureReady();+ const hasIds = Array.isArray(ids) && ids.length > 0;+ const hasChat = chatGuid != null && String(chatGuid).length > 0;+ const hasHandle = handle != null && String(handle).length > 0;+ if (!hasIds && !(source && (hasChat || hasHandle))) return { deleted: 0 };++ const clauses = [];+ const params = [];+ if (hasIds) {+ params.push(ids.map(String));+ clauses.push(`id = ANY($${params.length}::text[])`);+ }+ if (source) {+ params.push(String(source));+ clauses.push(`source = $${params.length}`);+ }+ if (hasChat) {+ params.push(String(chatGuid));+ clauses.push(`metadata->>'chatGuid' = $${params.length}`);+ }+ if (hasHandle) {+ params.push(String(handle));+ clauses.push(`metadata->>'handle' = $${params.length}`);+ }++ const result = await query(+ `DELETE FROM human_activity_events WHERE ${clauses.join(' AND ')}`,+ params,+ );+ const deleted = result.rowCount || 0;+ if (deleted > 0) {+ console.log(`🗓️ Deleted ${deleted} activity event(s)${source ? ` (source=${source})` : ''}`);+ }+ return { deleted };+}++/**+ * Aggregate conversations for a single source (iMessage, Signal, …) grouped by+ * `metadata.chatGuid`. Newest activity first. Optional free-text `q` filters+ * title/handle/summary. Cap defaults to 500 conversations.+ */+export async function listConversations({ source, q, limit } = {}) {+ if (!source) return [];+ await ensureReady();+ const params = [String(source)];+ const clauses = [`source = $1`];+ if (q != null && String(q).trim()) {+ params.push(`%${String(q).trim().toLowerCase()}%`);+ clauses.push(`(+ LOWER(COALESCE(title, '')) LIKE $${params.length}+ OR LOWER(COALESCE(summary, '')) LIKE $${params.length}+ OR LOWER(COALESCE(metadata->>'handle', '')) LIKE $${params.length}+ OR LOWER(COALESCE(metadata->>'chatGuid', '')) LIKE $${params.length}+ )`);+ }+ const cap = Math.min(Math.max(Number(limit) || 500, 1), 2000);+ params.push(cap);+ const result = await query(+ `SELECT+ COALESCE(metadata->>'chatGuid', '') AS chat_guid,+ MAX(title) AS title,+ MAX(NULLIF(metadata->>'handle', '')) AS handle,+ COUNT(*)::int AS event_count,+ MIN(happened_at) AS first_at,+ MAX(happened_at) AS last_at,+ (array_agg(summary ORDER BY happened_at DESC)+ FILTER (WHERE summary IS NOT NULL AND summary <> ''))[1] AS last_summary+ FROM human_activity_events+ WHERE ${clauses.join(' AND ')}+ GROUP BY COALESCE(metadata->>'chatGuid', '')+ ORDER BY MAX(happened_at) DESC+ LIMIT $${params.length}`,+ params,+ );+ return result.rows.map((row) => ({+ chatGuid: row.chat_guid || '',+ title: row.title || row.handle || row.chat_guid || '(unknown)',+ handle: row.handle || null,+ eventCount: Number(row.event_count) || 0,+ firstAt: row.first_at instanceof Date ? row.first_at.toISOString() : row.first_at,+ lastAt: row.last_at instanceof Date ? row.last_at.toISOString() : row.last_at,+ lastSummary: row.last_summary || '',+ }));+}++/**+ * Source-level stats for a manager UI: total events, conversation count, date+ * range. Cheap aggregates over the machine-local activity store.+ */+export async function sourceStats(source) {+ if (!source) {+ return { source: null, eventCount: 0, conversationCount: 0, earliestAt: null, latestAt: null };+ }+ await ensureReady();+ const result = await query(+ `SELECT+ COUNT(*)::int AS event_count,+ COUNT(DISTINCT COALESCE(metadata->>'chatGuid', ''))::int AS conversation_count,+ MIN(happened_at) AS earliest_at,+ MAX(happened_at) AS latest_at+ FROM human_activity_events+ WHERE source = $1`,+ [String(source)],+ );+ const row = result.rows[0] || {};+ return {+ source: String(source),+ eventCount: Number(row.event_count) || 0,+ conversationCount: Number(row.conversation_count) || 0,+ earliestAt: row.earliest_at instanceof Date ? row.earliest_at.toISOString() : (row.earliest_at || null),+ latestAt: row.latest_at instanceof Date ? row.latest_at.toISOString() : (row.latest_at || null),+ };+}+// Day view: all events on a local calendar day plus an hourly histogram and// source/kind tallies. `date` defaults to today in the user's timezone.export async function getDaySummary({ date } = {}) {diff --git a/server/services/imessageManage.js b/server/services/imessageManage.jsnew file mode 100644index 0000000000..184e19b046--- /dev/null+++ b/server/services/imessageManage.js@@ -0,0 +1,275 @@+/**+ * iMessage activity manager (#2413) — PortOS-side browse / purge / blocklist+ * for events ingested from chat.db (#2151).+ *+ * Hard boundary: this module never opens Apple's Messages database. Deletes+ * remove rows from the machine-local `human_activity_events` table only.+ * Blocklisted handles are skipped on future syncs (see imessageSync.runSync).+ */+import { dataPath, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { identityFromHandle, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';+import * as humanActivity from './humanActivity.js';+import { getStatus } from './imessageSync.js';++const SOURCE = 'imessage';+const BLOCKLIST_FILE = 'imessage-blocklist.json';++// ---------------------------------------------------------------------------+// chatKey encode/decode — URL-safe base64 of the raw chatGuid (Apple GUIDs+// contain `:` and `+` which are awkward in path segments).+// ---------------------------------------------------------------------------++// Empty chatGuid (orphan rows with no chat join) maps to a non-empty path+// segment so `/imessage/:chatKey` always has a param.+const EMPTY_CHAT_KEY = '_';++export function encodeChatKey(chatGuid) {+ const raw = chatGuid == null ? '' : String(chatGuid);+ if (!raw) return EMPTY_CHAT_KEY;+ return Buffer.from(raw, 'utf8').toString('base64url');+}++export function decodeChatKey(chatKey) {+ if (chatKey == null || chatKey === '') return null;+ if (String(chatKey) === EMPTY_CHAT_KEY) return '';+ try {+ return Buffer.from(String(chatKey), 'base64url').toString('utf8');+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------------------+// Blocklist — machine-local, not federated (same locality as the sync cursor).+// Handles are stored as normalized match keys so +1 555 / 555-… / +1555… collide.+// ---------------------------------------------------------------------------++function blocklistPath() {+ return dataPath(BLOCKLIST_FILE);+}++/**+ * Stable match key for a raw handle (phone → E.164-ish, email → lowercased).+ * Empty string when the handle can't be classified.+ */+export function blocklistKey(handle) {+ const id = identityFromHandle(handle);+ if (id.phone) return id.phone;+ if (id.email) return id.email;+ // Fallback: trim + lower so free-form keys still dedupe case-insensitively.+ const raw = handle == null ? '' : String(handle).trim().toLowerCase();+ return raw;+}++export async function readBlocklist() {+ const raw = await tryReadFile(blocklistPath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ const handles = Array.isArray(parsed?.handles)+ ? [...new Set(parsed.handles.map((h) => blocklistKey(h)).filter(Boolean))].sort()+ : [];+ return {+ handles,+ updatedAt: parsed?.updatedAt || null,+ };+}++async function writeBlocklist(handles) {+ const cleaned = [...new Set((handles || []).map((h) => blocklistKey(h)).filter(Boolean))].sort();+ const payload = { handles: cleaned, updatedAt: new Date().toISOString() };+ await atomicWrite(blocklistPath(), JSON.stringify(payload, null, 2));+ return payload;+}++export async function setBlocklist(handles) {+ return writeBlocklist(handles);+}++/**+ * Add one or more handles to the blocklist. When `purgeExisting` is true, also+ * deletes PortOS activity events whose metadata.handle matches (normalized).+ * Returns `{ handles, added, purged }`.+ */+export async function addToBlocklist(handles, { purgeExisting = false } = {}) {+ const incoming = (Array.isArray(handles) ? handles : [handles])+ .map((h) => blocklistKey(h))+ .filter(Boolean);+ const current = await readBlocklist();+ const before = new Set(current.handles);+ const next = new Set(current.handles);+ const added = [];+ for (const key of incoming) {+ if (!next.has(key)) {+ next.add(key);+ added.push(key);+ }+ }+ const saved = await writeBlocklist([...next]);+ let purged = 0;+ if (purgeExisting && added.length > 0) {+ // Events store the raw counterpart handle in metadata.handle; match via+ // the same normalization so a stored "+1 555…" still purges.+ for (const key of added.length ? added : incoming) {+ // Direct metadata match for the normalized form, plus common raw variants+ // are unlikely — also scan by listing is too heavy. Instead delete where+ // the stored handle normalizes to the key (SQL can't run JS, so we delete+ // by exact stored handle when it already equals the key, which is what+ // imessageSync writes for phone handles after chat.db).+ const r = await humanActivity.deleteEvents({ source: SOURCE, handle: key });+ purged += r.deleted;+ }+ // Also try un-normalized variants callers may have passed (raw phone).+ for (const raw of Array.isArray(handles) ? handles : [handles]) {+ const rawStr = raw == null ? '' : String(raw).trim();+ if (!rawStr) continue;+ if (blocklistKey(rawStr) && rawStr !== blocklistKey(rawStr)) {+ const r = await humanActivity.deleteEvents({ source: SOURCE, handle: rawStr });+ purged += r.deleted;+ }+ }+ }+ void before; // reserved for diagnostics+ return { ...saved, added, purged };+}++export async function removeFromBlocklist(handle) {+ const key = blocklistKey(handle);+ if (!key) return readBlocklist();+ const current = await readBlocklist();+ if (!current.handles.includes(key)) return current;+ return writeBlocklist(current.handles.filter((h) => h !== key));+}++/**+ * True when a raw message counterpart handle is on the blocklist.+ * Pure given a pre-loaded handle-key set (sync path loads once per pass).+ */+export function isHandleBlocked(handle, blockedKeys) {+ if (!blockedKeys || blockedKeys.size === 0) return false;+ const key = blocklistKey(handle);+ if (key && blockedKeys.has(key)) return true;+ // Also check participant-less from-me messages via empty key — never block empty.+ return false;+}++/**+ * Filter activity/touchpoint candidates whose counterpart handle is blocked.+ * For activity events: metadata.handle (empty for from-me → check participants).+ * For touchpoints: any identity in the candidate.+ */+export function filterBlockedActivityCandidates(candidates = [], blockedKeys) {+ if (!blockedKeys || blockedKeys.size === 0) return { kept: candidates || [], skipped: 0 };+ const kept = [];+ let skipped = 0;+ for (const c of candidates || []) {+ const handle = c?.metadata?.handle || '';+ if (handle && isHandleBlocked(handle, blockedKeys)) {+ skipped += 1;+ continue;+ }+ // Group chats / from-me: skip only when EVERY participant is blocked (rare);+ // if any participant is clean, keep — the user may still want the thread.+ const parts = Array.isArray(c?.participants) ? c.participants : [];+ if (!handle && parts.length > 0) {+ const allBlocked = parts.every((p) => {+ const key = p.phone || p.email || '';+ return key && blockedKeys.has(key);+ });+ if (allBlocked) {+ skipped += 1;+ continue;+ }+ }+ kept.push(c);+ }+ return { kept, skipped };+}++export function filterBlockedTouchpointCandidates(candidates = [], blockedKeys) {+ if (!blockedKeys || blockedKeys.size === 0) return { kept: candidates || [], skipped: 0 };+ const kept = [];+ let skipped = 0;+ for (const c of candidates || []) {+ const identities = Array.isArray(c?.identities) ? c.identities : [];+ if (identities.length === 0) {+ kept.push(c);+ continue;+ }+ // Drop the touchpoint only when every identity is blocked.+ const allBlocked = identities.every((id) => {+ const key = id.phone || id.email || '';+ return key && blockedKeys.has(key);+ });+ if (allBlocked) {+ skipped += 1;+ continue;+ }+ kept.push(c);+ }+ return { kept, skipped };+}++// ---------------------------------------------------------------------------+// Browse / purge wrappers (source-scoped)+// ---------------------------------------------------------------------------++export async function listConversations({ q, limit } = {}) {+ const [rows, blocklist] = await Promise.all([+ humanActivity.listConversations({ source: SOURCE, q, limit }),+ readBlocklist(),+ ]);+ const blocked = new Set(blocklist.handles);+ return rows.map((row) => {+ const handleKey = blocklistKey(row.handle);+ return {+ ...row,+ chatKey: encodeChatKey(row.chatGuid),+ blocked: !!(handleKey && blocked.has(handleKey)),+ };+ });+}++export async function listConversationEvents(chatKey, { limit, before } = {}) {+ const chatGuid = decodeChatKey(chatKey);+ if (chatGuid == null) return { chatGuid: null, chatKey, events: [] };+ const events = await humanActivity.listEvents({+ source: SOURCE,+ chatGuid,+ to: before || undefined,+ limit,+ });+ return {+ chatGuid,+ chatKey: encodeChatKey(chatGuid),+ events,+ };+}++export async function purgeConversation(chatKey) {+ const chatGuid = decodeChatKey(chatKey);+ if (chatGuid == null) return { deleted: 0, chatGuid: null };+ const result = await humanActivity.deleteEvents({ source: SOURCE, chatGuid });+ return { ...result, chatGuid, chatKey: encodeChatKey(chatGuid) };+}++export async function deleteEvent(id) {+ if (!id) return { deleted: 0 };+ // Scope to imessage so a typo'd id from another source can't be wiped via this route.+ return humanActivity.deleteEvents({ ids: [String(id)], source: SOURCE });+}++export async function getStats() {+ const [activity, blocklist, status] = await Promise.all([+ humanActivity.sourceStats(SOURCE),+ readBlocklist(),+ getStatus().catch(() => null),+ ]);+ return {+ ...activity,+ blockedCount: blocklist.handles.length,+ blocklistUpdatedAt: blocklist.updatedAt,+ sync: status,+ };+}++// Re-export normalize helpers for tests / callers that only import this module.+export { normalizeIdentifier, normalizePhone };diff --git a/server/services/imessageManage.test.js b/server/services/imessageManage.test.jsnew file mode 100644index 0000000000..afdd0bc2e7--- /dev/null+++ b/server/services/imessageManage.test.js@@ -0,0 +1,96 @@+import { describe, it, expect } from 'vitest';+import {+ encodeChatKey,+ decodeChatKey,+ blocklistKey,+ isHandleBlocked,+ filterBlockedActivityCandidates,+ filterBlockedTouchpointCandidates,+} from './imessageManage.js';++describe('imessageManage pure helpers', () => {+ describe('encodeChatKey / decodeChatKey', () => {+ it('round-trips an Apple chat GUID', () => {+ const guid = 'iMessage;-;+15551234567';+ const key = encodeChatKey(guid);+ expect(key).toMatch(/^[A-Za-z0-9_-]+$/);+ expect(decodeChatKey(key)).toBe(guid);+ });++ it('round-trips group chat GUIDs with special chars', () => {+ const guid = 'iMessage;+;chat1234567890';+ expect(decodeChatKey(encodeChatKey(guid))).toBe(guid);+ });++ it('maps empty chatGuid to a stable non-empty path key', () => {+ expect(encodeChatKey('')).toBe('_');+ expect(encodeChatKey(null)).toBe('_');+ expect(decodeChatKey('_')).toBe('');+ expect(decodeChatKey('')).toBeNull();+ expect(decodeChatKey(null)).toBeNull();+ });+ });++ describe('blocklistKey', () => {+ it('normalizes phone variants to E.164-ish', () => {+ expect(blocklistKey('+1 555 123 4567')).toBe('+15551234567');+ expect(blocklistKey('5551234567')).toBe('+15551234567');+ expect(blocklistKey('15551234567')).toBe('+15551234567');+ });++ it('lowercases emails', () => {+ expect(blocklistKey('[email protected]')).toBe('[email protected]');+ });++ it('returns empty for blank handles', () => {+ expect(blocklistKey('')).toBe('');+ expect(blocklistKey(null)).toBe('');+ });+ });++ describe('isHandleBlocked / filterBlocked*', () => {+ const blocked = new Set(['+15551234567', '[email protected]']);++ it('matches normalized phone and email', () => {+ expect(isHandleBlocked('+1 (555) 123-4567', blocked)).toBe(true);+ expect(isHandleBlocked('[email protected]', blocked)).toBe(true);+ expect(isHandleBlocked('+19998887777', blocked)).toBe(false);+ });++ it('filters activity candidates by metadata.handle', () => {+ const candidates = [+ { dedupeKey: 'a', metadata: { handle: '+15551234567' }, participants: [] },+ { dedupeKey: 'b', metadata: { handle: '+19998887777' }, participants: [] },+ { dedupeKey: 'c', metadata: { handle: '' }, participants: [{ phone: '+15551234567' }] },+ ];+ const { kept, skipped } = filterBlockedActivityCandidates(candidates, blocked);+ expect(skipped).toBe(2); // a by handle, c all participants blocked+ expect(kept.map((c) => c.dedupeKey)).toEqual(['b']);+ });++ it('keeps from-me / empty when no blocked participants', () => {+ const candidates = [+ { dedupeKey: 'me', metadata: { handle: '' }, participants: [{ phone: '+19998887777' }] },+ ];+ const { kept, skipped } = filterBlockedActivityCandidates(candidates, blocked);+ expect(skipped).toBe(0);+ expect(kept).toHaveLength(1);+ });++ it('filters touchpoints only when every identity is blocked', () => {+ const candidates = [+ { identities: [{ phone: '+15551234567' }], dedupeKey: 't1' },+ { identities: [{ phone: '+15551234567' }, { phone: '+19998887777' }], dedupeKey: 't2' },+ ];+ const { kept, skipped } = filterBlockedTouchpointCandidates(candidates, blocked);+ expect(skipped).toBe(1);+ expect(kept.map((c) => c.dedupeKey)).toEqual(['t2']);+ });++ it('is a no-op with an empty blocklist', () => {+ const candidates = [{ dedupeKey: 'x', metadata: { handle: '+15551234567' } }];+ expect(filterBlockedActivityCandidates(candidates, new Set()).kept).toHaveLength(1);+ expect(filterBlockedActivityCandidates(candidates, null).kept).toHaveLength(1);+ });+ });+});diff --git a/server/services/imessageSync.js b/server/services/imessageSync.jsindex 1a55513c9a..997ea17863 100644--- a/server/services/imessageSync.js+++ b/server/services/imessageSync.js@@ -418,21 +418,31 @@ async function doRunSync() {const timezone = await getUserTimezone();const { recordEvents } = await import('./humanActivity.js');const tribe = await import('./tribe.js');+ // Dynamic import avoids a circular static edge with imessageManage (which+ // pulls getStatus from this module for the manager stats endpoint) (#2413).+ const manage = await import('./imessageManage.js');const activityCandidates = imessageActivityCandidates(batch.messages);const touchpointCandidates = imessageTouchpointCandidates(batch.messages, timezone);+ // PortOS-side blocklist: skip spam handles before they land in the activity+ // store or Tribe touchpoint log. Apple's chat.db is never mutated.+ const blocklist = await manage.readBlocklist().catch(() => ({ handles: [] }));+ const blockedKeys = new Set(blocklist.handles || []);+ const activityFiltered = manage.filterBlockedActivityCandidates(activityCandidates, blockedKeys);+ const touchpointFiltered = manage.filterBlockedTouchpointCandidates(touchpointCandidates, blockedKeys);+// 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) => {+ const activityResult = await recordEvents(activityFiltered.kept).catch((err) => {console.error(`❌ iMessage activity record failed: ${err?.message || err}`);persistFailed = true;- return { recorded: 0, skipped: activityCandidates.length };+ return { recorded: 0, skipped: activityFiltered.kept.length };});- const touchpointResult = await tribe.autoLogTouchpoints(touchpointCandidates).catch((err) => {+ const touchpointResult = await tribe.autoLogTouchpoints(touchpointFiltered.kept).catch((err) => {console.error(`❌ iMessage touchpoint log failed: ${err?.message || err}`);persistFailed = true;return { created: 0, matched: 0 };@@ -444,6 +454,7 @@ async function doRunSync() {...(persistFailed ? { error: 'Persistence failed — cursor held so the batch retries next sync' } : {}),scanned: batch.scanned,recorded: activityResult.recorded,+ blockedSkipped: activityFiltered.skipped,touchpointsCreated: touchpointResult.created,touchpointsMatched: touchpointResult.matched,decodeFailures: batch.decodeFailures,@@ -453,7 +464,7 @@ async function doRunSync() {hasMore: batch.scanned === SCAN_LIMIT,};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' : ''}`);+ console.log(`💬 iMessage sync: scanned ${result.scanned}, recorded ${result.recorded} event(s), blocked ${result.blockedSkipped}, ${result.touchpointsCreated} touchpoint(s), ${result.decodeFailures} decode-skip(s), cursor→${result.cursorRowid}${result.hasMore ? ' (more remaining)' : ''}${persistFailed ? ' — PERSIST FAILED, cursor held' : ''}`);return result;}