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: stop offering unread-only Teams sync while read state is unavailable (#9968)
Adam Eivybbb5c143a20b
diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsxindex 0bb761766f..c6ab46225c 100644--- a/client/src/components/messages/InboxTab.jsx+++ b/client/src/components/messages/InboxTab.jsx@@ -8,6 +8,7 @@ import socket from '../../services/socket';import { timeAgo, formatDateNumeric } from '../../utils/formatters';import MessageDetail from './MessageDetail';import AddToThreadButton from '../threads/AddToThreadButton';+import { messageReadState, partitionAccountsBySyncMode } from '../../lib/messageSyncModes';const ACTION_CONFIG = {reply: { icon: Reply, color: 'text-port-accent', bg: 'bg-port-accent/10', hoverBg: 'hover:bg-port-accent/20', label: 'Reply' },@@ -36,6 +37,9 @@ const TRIAGE_TABS = [{ key: 'untriaged', label: 'Untriaged', icon: Mail, filter: m => !m.evaluation },];+const READ_STATE_FROM_CLASS = { unread: 'text-white font-medium', unknown: 'text-gray-300', read: 'text-gray-400' };+const READ_STATE_SUBJECT_CLASS = { unread: 'text-gray-300', unknown: 'text-gray-400', read: 'text-gray-500' };+const EMPTY_ACTION_CLASS = 'inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm transition-colors disabled:opacity-50';/**@@ -73,8 +77,10 @@ export function latestSyncAt(accounts) {* from `[]` ("loaded, and there are genuinely no accounts"); likewise a null* `lastSyncAt` means "never synced", not "synced and found nothing".*/-export function InboxEmptyState({ accounts, lastSyncAt, hasFilters, syncing, onSync, onClearFilters }) {+export function InboxEmptyState({ accounts, lastSyncAt, hasFilters, syncing, onSync, onClearFilters, syncMode = 'unread' }) {const navigate = useNavigate();+ // The label names the mode `onSync` will actually run — a Teams-only view has no unread sync.+ const syncLabel = syncMode === 'full' ? 'Full Sync' : 'Sync Unread';const body = (() => {if (!Array.isArray(accounts)) return {@@ -118,7 +124,7 @@ export function InboxEmptyState({ accounts, lastSyncAt, hasFilters, syncing, onSclassName={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}><RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />- {syncing ? 'Syncing...' : 'Sync Unread'}+ {syncing ? 'Syncing...' : syncLabel}</button>)};@@ -149,7 +155,7 @@ export function InboxEmptyState({ accounts, lastSyncAt, hasFilters, syncing, onSclassName={`${EMPTY_ACTION_CLASS} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}><RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />- {syncing ? 'Syncing...' : 'Sync Unread'}+ {syncing ? 'Syncing...' : syncLabel}</button>)};@@ -291,10 +297,12 @@ export default function InboxTab({ accounts }) {}, []);const handleSync = async (mode) => {- const targets = selectedAccount- ? accountList.filter(a => a.id === selectedAccount && a.enabled)- : accountList.filter(a => a.enabled);- if (targets.length === 0) return toast.error('No enabled accounts to sync');+ if (syncTargets.length === 0) return toast.error('No enabled accounts to sync');+ // Aggregate unread sync only runs on accounts that can measure read state; say+ // which were left out so a skipped account never looks like a synced one.+ const { supported: targets, excluded } = partitionAccountsBySyncMode(syncTargets, mode);+ if (targets.length === 0) return toast.error(`Unread sync isn't available for ${excluded.map(a => a.name).join(', ')} — use Full Sync`);+ if (excluded.length > 0) toast.warning(`Skipping ${excluded.map(a => a.name).join(', ')} — unread sync isn't available for ${excluded.length === 1 ? 'it' : 'them'}; use Full Sync`);setSyncing(true);let totalNew = 0;let totalPruned = 0;@@ -406,6 +414,11 @@ export default function InboxTab({ accounts }) {// show — with an account filter on, another account's sync says nothing about// this one. A sync that landed in this session wins over the (not-yet-refetched)// account timestamps; absent both, these accounts have genuinely never synced.+ // Enabled accounts a sync action in the current view would run on, and which+ // sync actions that scope still offers (no unread action for a Teams-only view).+ const syncTargets = useMemo(() => accountList.filter(a => a.enabled && (!selectedAccount || a.id === selectedAccount)), [accountList, selectedAccount]);+ const unreadSyncExcluded = useMemo(() => partitionAccountsBySyncMode(syncTargets, 'unread').excluded, [syncTargets]);+ const offerUnreadSync = syncTargets.length === 0 || unreadSyncExcluded.length < syncTargets.length;const lastSyncAt = useMemo(() => {const scoped = selectedAccount? accountList.filter(a => a.id === selectedAccount)@@ -477,15 +490,19 @@ export default function InboxTab({ accounts }) {<Sparkles size={14} className={evaluating ? 'animate-pulse' : ''} />{evaluating ? 'Evaluating...' : 'Triage'}</button>- <button- onClick={() => handleSync('unread')}- disabled={syncing}- className={`${toolbarBtn} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}- title="Sync unread messages from all enabled accounts"- >- <RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />- {syncing ? 'Syncing...' : 'Sync Unread'}- </button>+ {offerUnreadSync && (+ <button+ onClick={() => handleSync('unread')}+ disabled={syncing}+ className={`${toolbarBtn} bg-port-accent/10 text-port-accent hover:bg-port-accent/20`}+ title={unreadSyncExcluded.length > 0+ ? `Sync unread messages — skips ${unreadSyncExcluded.map(a => a.name).join(', ')} (read state unavailable; use Full Sync)`+ : 'Sync unread messages from all enabled accounts'}+ >+ <RefreshCw size={14} className={syncing ? 'animate-spin' : ''} />+ {syncing ? 'Syncing...' : 'Sync Unread'}+ </button>+ )}<buttononClick={() => handleSync('full')}disabled={syncing}@@ -551,7 +568,8 @@ export default function InboxTab({ accounts }) {lastSyncAt={lastSyncAt}hasFilters={hasFilters}syncing={syncing}- onSync={() => handleSync('unread')}+ syncMode={offerUnreadSync ? 'unread' : 'full'}+ onSync={() => handleSync(offerUnreadSync ? 'unread' : 'full')}onClearFilters={clearFilters}/>)}@@ -559,11 +577,13 @@ export default function InboxTab({ accounts }) {<div className="space-y-1">{visibleMessages.map((msg) => {const ev = msg.evaluation;+ // 'unknown' (provider can't measure read state) renders neutrally, never as read or unread.+ const readState = messageReadState(msg);return (<divkey={msg.id}className={`flex flex-col gap-2 p-3 rounded-lg transition-colors hover:bg-port-card group min-w-0 sm:flex-row sm:items-center sm:gap-3 ${- msg.isRead && !msg.isUnread ? 'opacity-70' : ''+ readState === 'read' ? 'opacity-70' : ''}`}><div className="flex items-start gap-2 min-w-0 sm:items-center sm:gap-3 sm:flex-1">@@ -580,14 +600,14 @@ export default function InboxTab({ accounts }) {className="flex-1 min-w-0 text-left"><div className="flex items-center gap-2 min-w-0">- <span className={`text-sm truncate min-w-0 ${msg.isUnread || !msg.isRead ? 'text-white font-medium' : 'text-gray-400'}`}>+ <span className={`text-sm truncate min-w-0 ${READ_STATE_FROM_CLASS[readState]}`}>{msg.from?.name || msg.from?.email || 'Unknown'}</span><span className="text-xs text-gray-600 shrink-0">{formatDateNumeric(msg.date)}</span></div>- <div className={`text-sm truncate ${msg.isUnread || !msg.isRead ? 'text-gray-300' : 'text-gray-500'}`}>+ <div className={`text-sm truncate ${READ_STATE_SUBJECT_CLASS[readState]}`}>{msg.subject || '(no subject)'}</div><div className="text-xs text-gray-600 truncate">diff --git a/client/src/components/messages/InboxTab.test.jsx b/client/src/components/messages/InboxTab.test.jsxindex 53174d018a..b17b428c37 100644--- a/client/src/components/messages/InboxTab.test.jsx+++ b/client/src/components/messages/InboxTab.test.jsx@@ -16,6 +16,7 @@ const api = vi.hoisted(() => ({const toast = vi.hoisted(() => Object.assign(vi.fn(), {error: vi.fn(),success: vi.fn(),+ warning: vi.fn(),}));const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));@@ -190,6 +191,84 @@ describe('InboxTab empty state', () => {});});+describe('InboxTab sync capability (#9968)', () => {+ const gmail = { ...syncedAccount, syncModes: ['unread', 'full'], hasReadState: true };+ const teams = {+ ...syncedAccount, id: '33333333-3333-3333-3333-333333333333', name: 'Chat', type: 'teams',+ syncModes: ['full'], hasReadState: false,+ };++ it('skips Teams in an aggregate unread sync and says so', async () => {+ renderInbox([gmail, teams]);+ await screen.findByText('Your inbox is empty');++ fireEvent.click(screen.getAllByRole('button', { name: /sync unread/i })[0]);++ await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledTimes(1));+ expect(api.syncMessageAccount).toHaveBeenCalledWith(gmail.id, 'unread', { silent: true });+ expect(toast.warning).toHaveBeenCalledWith(expect.stringContaining('Skipping Chat'));+ });++ it('runs Full Sync on every account, Teams included', async () => {+ renderInbox([gmail, teams]);+ await screen.findByText('Your inbox is empty');++ fireEvent.click(screen.getByRole('button', { name: 'Full Sync' }));++ await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledTimes(2));+ expect(api.syncMessageAccount).toHaveBeenCalledWith(gmail.id, 'full', { silent: true });+ expect(api.syncMessageAccount).toHaveBeenCalledWith(teams.id, 'full', { silent: true });+ expect(toast.warning).not.toHaveBeenCalled();+ });++ it('offers only Full Sync, in the toolbar and the empty state, when only Teams is in scope', async () => {+ renderInbox([{ ...teams, lastSyncAt: null }]);++ expect(await screen.findByText('Nothing synced yet')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /sync unread/i })).not.toBeInTheDocument();+ const fullSyncButtons = screen.getAllByRole('button', { name: 'Full Sync' });+ expect(fullSyncButtons).toHaveLength(2); // toolbar + empty-state action++ fireEvent.click(fullSyncButtons.at(-1));+ await waitFor(() => expect(api.syncMessageAccount).toHaveBeenCalledWith(teams.id, 'full', { silent: true }));+ });++ it('restores the unread action when the account filter narrows to a capable account', async () => {+ renderInbox([gmail, teams]);+ await screen.findByText('Your inbox is empty');++ fireEvent.change(screen.getByRole('combobox'), { target: { value: teams.id } });+ await act(async () => {});+ expect(screen.queryByRole('button', { name: /sync unread/i })).not.toBeInTheDocument();++ fireEvent.change(screen.getByRole('combobox'), { target: { value: gmail.id } });+ await act(async () => {});+ expect(screen.getAllByRole('button', { name: /sync unread/i }).length).toBeGreaterThan(0);+ });++ it('renders unknown read state neutrally, distinct from read and unread rows', async () => {+ const row = (id, flags) => ({+ id, accountId: gmail.id, threadId: null, subject: `Subject ${id}`, bodyText: 'preview',+ from: { name: `Sender ${id}`, email: `${id}@example.com` }, date: HOUR_AGO, ...flags,+ });+ api.getMessageInbox.mockResolvedValue({ total: 3, messages: [+ row('unread', { isRead: false, isUnread: true }),+ row('read', { isRead: true, isUnread: false }),+ row('unknown', { isRead: null, isUnread: null }),+ ] });+ renderInbox([gmail]);++ const sender = async (id) => (await screen.findByText(`Sender ${id}`));+ expect((await sender('unread')).className).toContain('font-medium');+ expect((await sender('read')).className).toContain('text-gray-400');+ const unknown = await sender('unknown');+ expect(unknown.className).not.toContain('font-medium');+ expect(unknown.className).not.toContain('text-gray-400');+ expect(unknown.closest('div.group').className).not.toContain('opacity-70');+ expect((await sender('read')).closest('div.group').className).toContain('opacity-70');+ });+});+describe('InboxTab message selection URL', () => {const message = {id: 'message-1',diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsxindex 2f75bf2bee..3b4bb7ea56 100644--- a/client/src/components/messages/SyncTab.jsx+++ b/client/src/components/messages/SyncTab.jsx@@ -7,6 +7,7 @@ import { formatDateTime } from '../../utils/formatters';import { buildSelectorTestFailureTask } from '../../lib/selectorTestFailureTask';import * as api from '../../services/api';import { useAccountSyncStatus } from '../../hooks/useAccountSyncStatus';+import { accountSupportsSyncMode } from '../../lib/messageSyncModes';// Human-facing summary per `testSelectors()` status — kept out of JSX so the// failure-task builder and the toast can share the same wording.@@ -58,7 +59,7 @@ export default function SyncTab({ accounts, onRefresh }) {if (result?.success) toast.success('Browser tab opened — log in if needed, then sync');};- const handleSync = (accountId, mode = 'unread') =>+ const handleSync = (accountId, mode) =>sync(accountId, () => api.syncMessageAccount(accountId, mode, { silent: true }));const handleSaveSelectors = async (provider) => {@@ -103,6 +104,11 @@ export default function SyncTab({ accounts, onRefresh }) {: 'Never synced'}{account.lastSyncStatus && ` (${account.lastSyncStatus})`}</div>+ {!accountSupportsSyncMode(account, 'unread') && (+ <div className="text-xs text-gray-500">+ Unread-only sync isn't available — read state can't be read from this provider yet+ </div>+ )}</div><div className="flex items-center gap-2">{syncing[account.id] === 'auth-required' && (@@ -123,14 +129,16 @@ export default function SyncTab({ accounts, onRefresh }) {<RefreshCw size={16} className="text-port-accent animate-spin" />) : (<>- <button- onClick={() => handleSync(account.id, 'unread')}- disabled={!account.enabled}- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"- title="Sync unread messages only"- >- <MailOpen size={14} /> Sync Unread- </button>+ {accountSupportsSyncMode(account, 'unread') && (+ <button+ onClick={() => handleSync(account.id, 'unread')}+ disabled={!account.enabled}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"+ title="Sync unread messages only"+ >+ <MailOpen size={14} /> Sync Unread+ </button>+ )}<buttononClick={() => handleSync(account.id, 'full')}disabled={!account.enabled}diff --git a/client/src/components/messages/SyncTab.test.jsx b/client/src/components/messages/SyncTab.test.jsxindex d28231dfeb..69a8d18aa8 100644--- a/client/src/components/messages/SyncTab.test.jsx+++ b/client/src/components/messages/SyncTab.test.jsx@@ -135,3 +135,30 @@ describe('Messages sync lifecycle', () => {expect(toast.error).toHaveBeenCalledExactlyOnceWith('Sync failed: Connection lost');});});++describe('Messages sync actions by provider capability (#9968)', () => {+ const gmail = { id: 'gmail-1', name: 'Gmail', enabled: true, provider: 'api', syncModes: ['unread', 'full'] };+ const teams = { id: 'teams-1', name: 'Chat', enabled: true, provider: 'playwright', syncModes: ['full'] };+ const legacy = { id: 'legacy-1', name: 'Legacy', enabled: true, provider: 'api' }; // older server: no syncModes++ it('offers no unread-only sync for Teams but keeps Full Sync working', async () => {+ api.syncMessageAccount.mockResolvedValue({ status: 'success', newMessages: 0 });+ render(<SyncTab accounts={[teams]} onRefresh={vi.fn()} />);++ expect(screen.queryByRole('button', { name: 'Sync Unread' })).toBeNull();+ expect(screen.getByText(/unread-only sync isn.t available/i)).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: 'Full Sync' }));+ expect(api.syncMessageAccount).toHaveBeenCalledWith(teams.id, 'full', { silent: true });+ await waitFor(() => expect(toast.success).toHaveBeenCalled());+ });++ it('keeps Sync Unread for accounts that support it, including payloads without syncModes', async () => {+ render(<SyncTab accounts={[gmail, teams, legacy]} onRefresh={vi.fn()} />);+ await waitFor(() => expect(api.getMessageSelectors).toHaveBeenCalled());+ await act(async () => {});++ expect(screen.getAllByRole('button', { name: 'Sync Unread' })).toHaveLength(2);+ expect(screen.getAllByRole('button', { name: 'Full Sync' })).toHaveLength(3);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 90a6396e76..db6636747c 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -230,6 +230,7 @@ grep -i "what you want to do" client/src/lib/README.md| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the `resumeAudioContext()` call with the teardown-race guard, the optional `audioSession` claim held for exactly as long as the transport sounds, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. || `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `managedAppSources.js` | Readers for the managed-app repository-source payload (`GET /api/apps/:id/repository-sources`). `primaryRepositorySource` picks the application checkout out of the source list; `repositoryForkDiverged` / `repositoryForkPushable` / `repositoryForkNeedsSync` answer whether a managed update may ask the server to fast-forward the origin fork (a diverged fork never can, nor can a fork PortOS lacks push access to — a correctness rule, not a label), with `describeForkUnsyncable` explaining why when it may not; `describeRepositorySourcesBehind` renders one clause per checkout an update can actually pull forward, over the shared `countText` pluralizer both surfaces phrase counts with. Shared by the app Git tab's Repository sources panel and the Eidoverse page's out-of-date advisory. |+| `messageSyncModes.js` | Message-account sync capability + read-state helpers (#9968): `accountSupportsSyncMode(account, mode)` (reads the server-derived `syncModes`; a missing field means every mode), `partitionAccountsBySyncMode(accounts, mode)` → `{ supported, excluded }` for aggregate sync actions, and `messageReadState(message)` → `'unread'`/`'read'`/`'unknown'` (unknown only when the provider recorded `null` read flags, e.g. Teams). || `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`, and `normalizeBeatsPerBar` — the ONE reading of a time-signature numerator (garbled/zero/negative → 4), shared by the scheduler and the visual `<BeatPulse>` so the dots can't disagree with the clicks. || `mindThinkingPresets.js` | Presentation helpers for the Persistent Mind's temporary thinking sessions (#6285). `classifyMindRouteBilling(provider)` answers the question the composer must settle without contacting anything: does borrowing this route run on THIS machine (`local`), stand behind a credential/subscription (`account`), or can PortOS not tell (`unknown`)? Unknown is treated as billable — guessing "free" is the one direction that costs money. Plus `formatMindRoute` (the one "provider / model · effort" phrasing), `sameMindRoute` (client mirror of the server's route-only equality, so a label rename does not read as a changed route), `findMindThinkingPreset` / `mintMindPresetId` (a server-legal id minted from a label), and the receipt readers `formatMindCallUsage` / `formatMindCallOutcome` / `formatMindElapsed` / `mindTurnOutcome` / `mindTurnElapsedMs` / `temporaryMindTurns` — all of which keep "the provider reported nothing" rendering as unknown rather than as a free, instant, successful call. Pure; no fetches, so previewing a preset can never start an inference. || `mindTurnProgress.js` | Live progress derivation for a Persistent Mind turn (#7409). `describeMindTurnProgress({ state, runtime, events })` folds the public state and the `/mind/runtime` snapshot into one `{ phase: 'thinking'|'stalled'|'blocked'|'idle', busy, stage, retryAt, reason, detail }` reading, so the Mind page can tell healthy-but-slow local inference from a wedged turn from a quota autopause instead of showing one indefinite three-dot indicator for all three. Freshness comes from the runtime snapshot ONLY when its `turnId` matches the claimed turn (a stale snapshot would date a fresh turn as stalled), and an unreported measurement renders nothing rather than zero. `retryAt` reads `runtime.usageLimitRetryAt` before `state.nextEligibleWakeAt`, because a usage-limit autopause clears the backoff gate and its schedule lives only in the readiness probe. `mindTurnHeadline(progress, formatRetry)` is the one phrasing of a stalled/blocked turn, shared by the header pill and the chat indicator; `mindTurnStage` reads the newest trajectory event for the turn by `sequence`; `mindTurnRuntimeSnapshot` is the one turn-match rule. Status enums and durations only — no provider reasoning crosses the hidden chain-of-thought boundary. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 5f6589d88d..4e511d2645 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -185,6 +185,7 @@ export * from './estimationTolerance.js';export * from './lookaheadTransport.js';export * from './lossSparkline.js';export * from './managedAppSources.js';+export * from './messageSyncModes.js';export * from './metronome.js';export * from './mindThinkingPresets.js';export * from './mindTurnProgress.js';diff --git a/client/src/lib/messageSyncModes.js b/client/src/lib/messageSyncModes.jsnew file mode 100644index 0000000000..c7c287f3f7--- /dev/null+++ b/client/src/lib/messageSyncModes.js@@ -0,0 +1,30 @@+// Which sync actions a message account offers, and how a cached message's read+// state is classified. Mirrors the server's transport table (`syncModes` on the+// account response); an account payload without the field (older server) is+// treated as supporting every mode, so nothing is hidden by a missing field.++const ALL_MODES = ['unread', 'full'];++export const accountSupportsSyncMode = (account, mode) =>+ (Array.isArray(account?.syncModes) ? account.syncModes : ALL_MODES).includes(mode);++/**+ * Split accounts for a requested mode into those that can run it and those+ * excluded because the provider cannot honor it.+ */+export function partitionAccountsBySyncMode(accounts, mode) {+ const supported = [];+ const excluded = [];+ for (const account of accounts) (accountSupportsSyncMode(account, mode) ? supported : excluded).push(account);+ return { supported, excluded };+}++/**+ * 'unknown' only when the provider explicitly recorded no measurement+ * (`null` on both flags). A record lacking the flags entirely keeps the legacy+ * unread-styling, and legacy `isRead: true` records stay read.+ */+export function messageReadState(message) {+ if (message?.isUnread === null && message?.isRead === null) return 'unknown';+ return message?.isUnread || !message?.isRead ? 'unread' : 'read';+}diff --git a/server/lib/messageTransport.js b/server/lib/messageTransport.jsindex 4280df8502..fab6a98314 100644--- a/server/lib/messageTransport.js+++ b/server/lib/messageTransport.js@@ -4,12 +4,34 @@//// `email` marks accounts that can deliver to an arbitrary email address. A Teams// chat reaches a person, not a mailbox, so it is sendable but never an email lane.+//+// `syncModes` lists the sync modes the provider can honor, first entry = the mode an+// omitted request selects. `readState` says whether sync can measure read/unread:+// without it an `unread` sync is indistinguishable from a full one, so it is not+// offered (Teams' extraction cannot see read state yet — #9968).export const MESSAGE_ACCOUNT_TRANSPORT = Object.freeze({- gmail: Object.freeze({ sendVia: 'api', email: true }),- outlook: Object.freeze({ sendVia: 'playwright', email: true }),- teams: Object.freeze({ sendVia: 'playwright', email: false })+ gmail: Object.freeze({ sendVia: 'api', email: true, syncModes: Object.freeze(['unread', 'full']), readState: true }),+ outlook: Object.freeze({ sendVia: 'playwright', email: true, syncModes: Object.freeze(['unread', 'full']), readState: true }),+ teams: Object.freeze({ sendVia: 'playwright', email: false, syncModes: Object.freeze(['full']), readState: false })});+const ALL_SYNC_MODES = Object.freeze(['unread', 'full']);++/** Sync modes an account type can honor; an unknown type keeps every mode (the provider dispatch rejects it). */+export function syncModesForAccountType(type) {+ return MESSAGE_ACCOUNT_TRANSPORT[type]?.syncModes ?? ALL_SYNC_MODES;+}++/** The mode an omitted request selects for this account type. */+export function defaultSyncModeForAccountType(type) {+ return syncModesForAccountType(type)[0];+}++/** Whether sync can measure read/unread for this account type; `false` means state is unknown, not "read". */+export function accountTypeHasReadState(type) {+ return MESSAGE_ACCOUNT_TRANSPORT[type]?.readState ?? true;+}+export function sendViaForAccountType(type) {return MESSAGE_ACCOUNT_TRANSPORT[type]?.sendVia ?? null;}diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 09e0a1e777..ccd3633fa1 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -138,7 +138,9 @@ router.post('/sync/:accountId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {throw new ServerError('Invalid account ID format', { status: 400 });}- const mode = ['unread', 'full'].includes(req.body?.mode) ? req.body.mode : 'unread';+ // An omitted/unrecognized mode stays undefined so syncAccount selects the account's+ // supported default; an explicit one is validated against the account there.+ const mode = ['unread', 'full'].includes(req.body?.mode) ? req.body.mode : undefined;const io = req.app.get('io');const result = await messageSync.syncAccount(req.params.accountId, io, { mode });if (result.error) throw new ServerError(result.error, { status: result.status || 404 });diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsindex 4e18c2d645..43d4fc15cd 100644--- a/server/routes/messages.test.js+++ b/server/routes/messages.test.js@@ -265,7 +265,18 @@ describe('Messages Routes', () => {expect(response.status).toBe(200);expect(response.body.newMessages).toBe(5);+ // An omitted mode is left for syncAccount to resolve against the account's supported default.+ expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined, { mode: undefined });+ });++ it('forwards an explicit mode and surfaces an unsupported-mode rejection as 400', async () => {+ messageSync.syncAccount.mockResolvedValue({ error: 'teams accounts do not support unread sync', status: 400 });++ const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`).send({ mode: 'unread' });+expect(messageSync.syncAccount).toHaveBeenCalledWith(VALID_UUID, undefined, { mode: 'unread' });+ expect(response.status).toBe(400);+ expect(response.body.error).toContain('unread');});it('should return 400 for invalid UUID', async () => {diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex a35af0a76b..e3cd54015f 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -4,7 +4,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isPlainObject } from '../lib/objects.js';-import { accountTypeCanSend, sendViaForAccountType } from '../lib/messageTransport.js';+import { accountTypeCanSend, accountTypeHasReadState, sendViaForAccountType, syncModesForAccountType } from '../lib/messageTransport.js';const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');// All account IDs share this file, including sync metadata writes.@@ -23,9 +23,15 @@ async function saveAccounts(accounts) {noteReadinessChanged();}-// `canSend` is derived from the transport table, never stored: it flips with the-// code that implements a provider's send, not with data an install carries.-const withDerivedCapabilities = account => ({ ...account, canSend: accountTypeCanSend(account.type) });+// `canSend`, `syncModes` and `hasReadState` are derived from the transport table, never+// stored: they flip with the code that implements a provider, not with data an install+// carries. `syncModes` tells the UI which sync actions to offer (#9968).+const withDerivedCapabilities = account => ({+ ...account,+ canSend: accountTypeCanSend(account.type),+ syncModes: [...syncModesForAccountType(account.type)],+ hasReadState: accountTypeHasReadState(account.type)+});export async function listAccounts() {const accounts = await loadAccounts();diff --git a/server/services/messageAccounts.test.js b/server/services/messageAccounts.test.jsindex 73c8a6fbe0..39dbdda86e 100644--- a/server/services/messageAccounts.test.js+++ b/server/services/messageAccounts.test.js@@ -51,6 +51,19 @@ describe('messageAccounts', () => {expect(await messageAccounts.getAccount('teams-id')).toMatchObject({ type: 'teams', canSend: true, provider: 'playwright' });});+ it('derives the offered sync modes and read-state capability per provider (#9968)', async () => {+ await messageAccounts.createAccount({ name: 'Gmail', type: 'gmail' });+ uuid.mockReturnValueOnce('outlook-id');+ await messageAccounts.createAccount({ name: 'Outlook', type: 'outlook' });+ uuid.mockReturnValueOnce('teams-id');+ await messageAccounts.createAccount({ name: 'Teams', type: 'teams' });+ expect((await messageAccounts.listAccounts()).map(({ type, syncModes, hasReadState }) => ({ type, syncModes, hasReadState }))).toEqual([+ { type: 'gmail', syncModes: ['unread', 'full'], hasReadState: true },+ { type: 'outlook', syncModes: ['unread', 'full'], hasReadState: true },+ { type: 'teams', syncModes: ['full'], hasReadState: false }+ ]);+ });+beforeEach(() => {atomicWrite.mockReset().mockImplementation(persist);uuid.mockReset().mockReturnValue('msg-uuid-5678');diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.jsindex 863eec3b3f..a6672dcd6b 100644--- a/server/services/messageEvaluator.js+++ b/server/services/messageEvaluator.js@@ -23,7 +23,8 @@ const messageEvidence = (message) => ({from: message.from?.name || message.from?.email || 'Unknown',subject: message.subject || '',bodyText: message.bodyText || '',- isUnread: message.isUnread ?? !message.isRead,+ // null = provider cannot measure read state; do not present that as unread.+ isUnread: message.isUnread ?? (message.isRead === null ? null : !message.isRead),isFlagged: message.isFlagged ?? false,hasMeetingInvite: message.hasMeetingInvite ?? false,});diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 27e064013c..183966defc 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -119,8 +119,10 @@ export async function syncPlaywright(account, cache, io, options = {}) {bodyText: msg.preview || '',bodyFull: false,date: msg.date || new Date().toISOString(),- isRead: !(msg.isUnread ?? false),- isUnread: msg.isUnread ?? false,+ // `isUnread: null` = the provider cannot measure read state (Teams): record it as+ // unknown rather than manufacturing a read message.+ isRead: msg.isUnread === null ? null : !(msg.isUnread ?? false),+ isUnread: msg.isUnread === null ? null : (msg.isUnread ?? false),isPinned: msg.isPinned ?? false,isFlagged: msg.isFlagged ?? false,isReplied: msg.isReplied ?? false,@@ -413,7 +415,9 @@ function buildExtractionScript(type, sels, mode = 'unread') {subject: '',preview: lines[1] || '',date: lines[2] || '',- isUnread: false,+ // The Teams list view exposes no read-state marker we can trust, so the+ // state is unknown — never "read" (#9968). null survives normalization.+ isUnread: null,isPinned: false,isFlagged: false,isReplied: false,diff --git a/server/services/messagePlaywrightSync.test.js b/server/services/messagePlaywrightSync.test.jsindex 1be8bc8dbc..9862e93ccf 100644--- a/server/services/messagePlaywrightSync.test.js+++ b/server/services/messagePlaywrightSync.test.js@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import vm from 'node:vm';const findOrOpenPage = vi.fn();const isAuthPage = vi.fn();@@ -105,6 +106,29 @@ it('retains the ingested provider row ID when detail is unavailable', async () =expect(result.messages).toEqual([expect.objectContaining({ providerRowId: 'stable-row', subject: 'Example subject' })]);});+// Teams' list view exposes no trusted read-state marker, so a Teams sync must record+// read state as unknown (null) — not manufacture read messages (#9968). Runs the real+// generated extraction script against a synthetic DOM, independent of the requested mode.+it('records Teams read state as unknown for both sync modes', async () => {+ findOrOpenPage.mockResolvedValue({ url: 'https://teams.microsoft.com/', webSocketDebuggerUrl: 'ws://x' });+ isAuthPage.mockReturnValue(false);+ tryReadFile.mockResolvedValue('{}');+ const document = { querySelectorAll: () => [+ { innerText: 'Alice Example\nHello there\n10:00' },+ { innerText: 'Bob Example\n3 unread messages\n09:00' }+ ] };+ const scripts = [];+ evaluateOnPage.mockReset();+ evaluateOnPage.mockImplementation(async (_page, script) => { scripts.push(script); return vm.runInNewContext(script, { document }); });++ for (const mode of ['unread', 'full']) {+ const result = await syncPlaywright({ id: 'example-account', type: 'teams' }, { messages: [] }, null, { mode });+ expect(result.messages).toHaveLength(2);+ for (const message of result.messages) expect(message).toMatchObject({ isRead: null, isUnread: null });+ }+ expect(scripts[0]).toBe(scripts[1]);+});+// Browser-delivered drafts. evaluateOnPage is scripted per compose phase, so the// whole success / failure / ambiguity matrix runs with no mailbox and no recipient.describe('sendPlaywright', () => {diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex aebb32ac10..e80fbbb9a1 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -4,6 +4,7 @@ import { createHash } from 'crypto';import { join } from 'path';import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, safeDate, safeJSONParse, UUID_RE, tryReadFile } from '../lib/fileUtils.js';import { getAccount, updateSyncStatus, markSentIngested, updateSendAsAliases } from './messageAccounts.js';+import { defaultSyncModeForAccountType, syncModesForAccountType } from '../lib/messageTransport.js';import { getLocalParts } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { v4 as uuidv4 } from '../lib/uuid.js';@@ -169,8 +170,14 @@ export async function syncAccount(accountId, io, options = {}) {if (!account) return { error: 'Account not found' };if (!account.enabled) return { error: 'Account is disabled', status: 400 };+ // Reject an explicit mode the provider cannot honor BEFORE taking the lock, emitting+ // events, or touching the browser/cache. An omitted mode takes the account's default.+ const mode = options.mode || defaultSyncModeForAccountType(account.type);+ if (!syncModesForAccountType(account.type).includes(mode)) {+ return { error: `${account.type} accounts do not support ${mode} sync`, status: 400 };+ }+syncLocks.set(accountId, true);- const mode = options.mode || 'unread';io?.emit('messages:sync:started', { accountId, mode });console.log(`📧 Starting ${mode} sync for account ${account.id} (${account.type})`);@@ -409,8 +416,9 @@ function mergeRefreshedMessage(cache, existingByExternalId, accountId, source, mbodyText: threadMsg.body || '',bodyFull: true,date: threadMsg.date || message.date || new Date().toISOString(),- isRead: message.isRead ?? true,- isUnread: message.isUnread ?? false,+ // null = read state unknown (Teams cannot measure it) — keep it null, not "read"+ isRead: message.isRead === undefined ? true : message.isRead,+ isUnread: message.isUnread === undefined ? false : message.isUnread,isPinned: message.isPinned ?? false,isFlagged: message.isFlagged ?? false,isReplied: message.isReplied ?? false,diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex e23b023ec0..2e3647a02b 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -520,7 +520,7 @@ describe('syncAccount', () => {expect(result.newMessages).toBe(0);});- it('should call syncPlaywright for teams accounts', async () => {+ it('selects the supported full mode for a Teams sync that omits the mode', async () => {getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Teams', type: 'teams', enabled: true });readFile.mockResolvedValue(JSON.stringify({ syncCursor: null, messages: [] }));syncPlaywright.mockResolvedValue([]);@@ -528,7 +528,44 @@ describe('syncAccount', () => {await syncAccount(VALID_UUID, mockIo);- expect(syncPlaywright).toHaveBeenCalled();+ expect(syncPlaywright).toHaveBeenCalledWith(expect.objectContaining({ type: 'teams' }), expect.any(Object), mockIo, { mode: 'full' });+ expect(mockIo.emit).toHaveBeenCalledWith('messages:sync:started', { accountId: VALID_UUID, mode: 'full' });+ });++ it('rejects an explicit Teams unread sync before any browser dispatch or cache write', async () => {+ getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Teams', type: 'teams', enabled: true });+ syncPlaywright.mockClear();+ atomicWrite.mockClear();+ readFile.mockClear();++ const result = await syncAccount(VALID_UUID, mockIo, { mode: 'unread' });++ expect(result).toMatchObject({ status: 400, error: expect.stringContaining('unread') });+ expect(syncPlaywright).not.toHaveBeenCalled();+ expect(readFile).not.toHaveBeenCalled();+ expect(atomicWrite).not.toHaveBeenCalled();+ expect(mockIo.emit).not.toHaveBeenCalled();+ // The lock was never taken, so a following supported sync is not blocked.+ syncPlaywright.mockResolvedValue([]);+ readFile.mockResolvedValue(JSON.stringify({ syncCursor: null, messages: [] }));+ updateSyncStatus.mockResolvedValue();+ expect(await syncAccount(VALID_UUID, mockIo, { mode: 'full' })).toMatchObject({ status: 'success' });+ });++ it('overwrites a legacy fabricated-read Teams record with unknown read state', async () => {+ getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Teams', type: 'teams', enabled: true });+ readFile.mockResolvedValue(JSON.stringify({ syncCursor: null, messages: [+ { id: 'legacy', externalId: 'teams-ext', date: '2026-01-01', isRead: true, isUnread: false }+ ] }));+ syncPlaywright.mockResolvedValue([{ id: 'new', externalId: 'teams-ext', date: '2026-01-01', isRead: null, isUnread: null }]);+ updateSyncStatus.mockResolvedValue();+ atomicWrite.mockClear();++ await syncAccount(VALID_UUID, mockIo);++ expect(atomicWrite.mock.calls[0][1].messages).toEqual([+ expect.objectContaining({ id: 'legacy', isRead: null, isUnread: null })+ ]);});it('removes only the confirmed action target from the current cache', async () => {