ofw-mcp 2.27.3 → 2.27.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -1
- package/dist/bundle.js +951 -760
- package/dist/sync.js +210 -39
- package/dist/tools/_shared.js +59 -10
- package/dist/tools/draft-freshness.js +11 -5
- package/dist/tools/lifecycle.js +4 -1
- package/dist/tools/messages.js +81 -30
- package/dist/tools/project.js +40 -0
- package/dist/tools/reply-source.js +28 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/skills/ofw/SKILL.md +16 -1
- package/skills/ofw-fpx/references/requests.md +7 -3
package/dist/sync.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { ApiRecipientSchema, hasRealView, mapRecipients,
|
|
3
|
+
import { ApiRecipientSchema, draftReplyTarget, hasRealView, mapRecipients, scrapeSaysRead } from './tools/_shared.js';
|
|
4
|
+
import { setReplyToSource } from './tools/reply-source.js';
|
|
5
|
+
import { senderOf } from './tools/project.js';
|
|
4
6
|
import { parseLenient } from '@chrischall/mcp-utils';
|
|
5
|
-
import { nowNaiveWallClock } from './timestamps.js';
|
|
7
|
+
import { displayTimeZone, nowNaiveWallClock, parseTimestampValue } from './timestamps.js';
|
|
6
8
|
import { readingBlockedToday } from './read-days.js';
|
|
7
9
|
// Each OFW message detail returns `files: [fileId, ...]`. We fetch the metadata
|
|
8
10
|
// for each file id (cheap JSON call) so the model can see filenames/mime types
|
|
@@ -104,14 +106,18 @@ export async function resolveFolderIds(client, store) {
|
|
|
104
106
|
return ids;
|
|
105
107
|
}
|
|
106
108
|
// Required fields are the ones the sync loop reads unguarded (id keys the
|
|
107
|
-
// cache; showNeverViewed
|
|
108
|
-
//
|
|
109
|
+
// cache; showNeverViewed is the SENT folder's read signal, so its
|
|
110
|
+
// disappearance must warn loudly). `read` is the INBOX list's own read flag —
|
|
111
|
+
// the only inbox read evidence (see scrapeSaysRead). It stays optional because
|
|
112
|
+
// sent items need not carry it, and a missing inbox `read` already fails
|
|
113
|
+
// closed to "unread", which is the safe answer.
|
|
109
114
|
const ListItemSchema = z.looseObject({
|
|
110
115
|
id: z.number(),
|
|
111
116
|
subject: z.string(),
|
|
112
117
|
date: z.looseObject({ dateTime: z.string() }),
|
|
113
118
|
from: z.looseObject({ name: z.string().optional() }).optional(),
|
|
114
119
|
showNeverViewed: z.boolean(),
|
|
120
|
+
read: z.boolean().optional(),
|
|
115
121
|
recipients: z.array(ApiRecipientSchema).optional(),
|
|
116
122
|
});
|
|
117
123
|
const ListResponseSchema = z.looseObject({ data: z.array(ListItemSchema).optional() });
|
|
@@ -122,6 +128,32 @@ const DetailResponseSchema = z.looseObject({
|
|
|
122
128
|
// endpoint only has an epoch placeholder) — used by the view-status refresh.
|
|
123
129
|
recipients: z.array(ApiRecipientSchema).optional(),
|
|
124
130
|
});
|
|
131
|
+
/**
|
|
132
|
+
* How far BEFORE the request start a detail's view time may fall and still
|
|
133
|
+
* count as stamped by that request. OFW reports view times to the second
|
|
134
|
+
* (truncation costs up to 1 s) and its clock is not ours; 2 s absorbs both
|
|
135
|
+
* without blaming us for a view that genuinely happened earlier.
|
|
136
|
+
*/
|
|
137
|
+
export const STAMP_TOLERANCE_MS = 2000;
|
|
138
|
+
/**
|
|
139
|
+
* True when `viewedAt` (OFW's naive wall clock, read in DISPLAY_TZ like every
|
|
140
|
+
* other OFW time) is at or after `startedAtMs` less STAMP_TOLERANCE_MS — i.e.
|
|
141
|
+
* the fetch that began at `startedAtMs` is what stamped it. A missing or
|
|
142
|
+
* unparseable time is not evidence. If DISPLAY_TZ does not match the
|
|
143
|
+
* account's zone the comparison is off by the offset; this check is a
|
|
144
|
+
* backstop for the read-state rule, never a substitute for it.
|
|
145
|
+
*/
|
|
146
|
+
export function stampedByFetch(viewedAt, startedAtMs) {
|
|
147
|
+
if (viewedAt === null)
|
|
148
|
+
return false;
|
|
149
|
+
const at = parseTimestampValue('viewedAt', viewedAt, displayTimeZone());
|
|
150
|
+
return at !== null && at.getTime() >= startedAtMs - STAMP_TOLERANCE_MS;
|
|
151
|
+
}
|
|
152
|
+
/** The latest real (non-placeholder) view time on a detail's recipients. */
|
|
153
|
+
export function latestViewedAt(recipients) {
|
|
154
|
+
const times = mapRecipients(recipients).map((r) => r.viewedAt).filter((t) => t !== null);
|
|
155
|
+
return times.length === 0 ? null : times.sort().at(-1);
|
|
156
|
+
}
|
|
125
157
|
const maxId = (a, b) => a === null ? b : b === null ? a : Math.max(a, b);
|
|
126
158
|
/**
|
|
127
159
|
* Walk one folder's list pages from `startPage` toward older messages, caching
|
|
@@ -135,17 +167,41 @@ async function walkPages(client, folder, folderId, opts, store) {
|
|
|
135
167
|
let synced = 0;
|
|
136
168
|
let pagesFetched = 0;
|
|
137
169
|
const unread = [];
|
|
170
|
+
const newMessages = [];
|
|
171
|
+
const markedRead = [];
|
|
172
|
+
const totals = () => ({ synced, unread, newMessages, markedRead, newestId, pagesFetched });
|
|
173
|
+
/**
|
|
174
|
+
* GET one message's detail. For an INBOX message, compare the view time OFW
|
|
175
|
+
* now reports with when the request began: a view at/after it means this
|
|
176
|
+
* fetch stamped "First Viewed", and that is reported, never silent.
|
|
177
|
+
* `deliberate` = the caller asked for unread bodies, so it is reported
|
|
178
|
+
* whatever the echo says.
|
|
179
|
+
*/
|
|
180
|
+
const fetchDetail = async (item, row, context, deliberate) => {
|
|
181
|
+
const startedAt = Date.now();
|
|
182
|
+
const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context });
|
|
183
|
+
if (folder === 'inbox') {
|
|
184
|
+
const viewedAt = latestViewedAt(detail.recipients);
|
|
185
|
+
if (deliberate || stampedByFetch(viewedAt, startedAt)) {
|
|
186
|
+
markedRead.push({
|
|
187
|
+
id: item.id, subject: row.subject, from: row.from, sentAt: row.sentAt, viewedAt,
|
|
188
|
+
reason: deliberate ? 'fetchUnreadBodies' : 'unexpected',
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return detail;
|
|
193
|
+
};
|
|
138
194
|
while (true) {
|
|
139
195
|
// One unit per list-page fetch. Out of budget → pause and resume at `page`.
|
|
140
196
|
if (!budget.take()) {
|
|
141
|
-
return {
|
|
197
|
+
return { ...totals(), done: false, nextPage: page };
|
|
142
198
|
}
|
|
143
199
|
const path = `/pub/v3/messages?folders=${encodeURIComponent(folderId)}&page=${page}&size=50&sort=date&sortDirection=desc`;
|
|
144
200
|
const list = parseLenient(ListResponseSchema, await client.request('GET', path), { label: 'ofw-mcp', context: `GET /pub/v3/messages?folders={${folder}}` });
|
|
145
201
|
pagesFetched++;
|
|
146
202
|
const items = list.data ?? [];
|
|
147
203
|
if (items.length === 0) {
|
|
148
|
-
return {
|
|
204
|
+
return { ...totals(), done: true, nextPage: null };
|
|
149
205
|
}
|
|
150
206
|
// One batch read of this page's ids (S1) instead of a per-item getMessage.
|
|
151
207
|
const existingById = new Map((await store.getMessages(items.map((it) => it.id))).map((row) => [row.id, row]));
|
|
@@ -157,18 +213,24 @@ async function walkPages(client, folder, folderId, opts, store) {
|
|
|
157
213
|
if (newestId === null || item.id > newestId)
|
|
158
214
|
newestId = item.id;
|
|
159
215
|
const existing = existingById.get(item.id);
|
|
160
|
-
|
|
216
|
+
// Read per the LIST, before we touch anything. For inbox that is the
|
|
217
|
+
// list's own `read === true` and nothing else: `showNeverViewed` on the
|
|
218
|
+
// inbox list is the sender-side badge and reads false on a message we
|
|
219
|
+
// never opened, so trusting it fetched — and stamped — unread bodies.
|
|
220
|
+
// Missing/non-boolean `read` fails closed to unread (scrapeSaysRead).
|
|
221
|
+
const listRead = scrapeSaysRead(folder, item);
|
|
222
|
+
const isInboxUnread = folder === 'inbox' && !listRead;
|
|
161
223
|
if (existing) {
|
|
162
224
|
// Heal a row cached without its body — typically one listed on a
|
|
163
225
|
// no-read day — once fetching it can stamp nothing: a sent message, or
|
|
164
|
-
// an inbox message OFW
|
|
226
|
+
// an inbox message OFW's list reports as read. An unread inbox body
|
|
165
227
|
// stays the caller's explicit choice (ofw_get_message), as before.
|
|
166
228
|
if (opts.fetchBodies && existing.body === null && !isInboxUnread) {
|
|
167
229
|
if (!budget.take()) {
|
|
168
230
|
pageBudgetHit = true;
|
|
169
231
|
break;
|
|
170
232
|
}
|
|
171
|
-
const detail =
|
|
233
|
+
const detail = await fetchDetail(item, { subject: existing.subject, sentAt: existing.sentAt, from: senderOf(existing) }, 'GET /pub/v3/messages/{id} (body backfill)', false);
|
|
172
234
|
toUpsert.push({
|
|
173
235
|
...existing,
|
|
174
236
|
body: detail.body ?? '',
|
|
@@ -215,12 +277,29 @@ async function walkPages(client, folder, folderId, opts, store) {
|
|
|
215
277
|
// already read by the time we first saw it — reporting "never viewed" for
|
|
216
278
|
// a message OFW shows as read, until a later sync's refresh healed it.
|
|
217
279
|
let detailRecipients;
|
|
280
|
+
// The row as the list describes it; the detail (if fetched) fills in
|
|
281
|
+
// body and real view times below.
|
|
282
|
+
const row = {
|
|
283
|
+
id: item.id,
|
|
284
|
+
folder,
|
|
285
|
+
subject: item.subject ?? '(no subject)',
|
|
286
|
+
fromUser: item.from?.name ?? '',
|
|
287
|
+
sentAt: item.date?.dateTime ?? nowNaiveWallClock(),
|
|
288
|
+
recipients: mapRecipients(item.recipients),
|
|
289
|
+
body: null,
|
|
290
|
+
fetchedBodyAt: null,
|
|
291
|
+
replyToId: null,
|
|
292
|
+
chainRootId: null,
|
|
293
|
+
listData: item,
|
|
294
|
+
};
|
|
295
|
+
const from = senderOf(row);
|
|
218
296
|
if (shouldFetchBody) {
|
|
219
297
|
if (!budget.take()) {
|
|
220
298
|
pageBudgetHit = true;
|
|
221
299
|
break;
|
|
222
300
|
}
|
|
223
|
-
|
|
301
|
+
// Reached for an unread inbox message only under fetchUnreadBodies.
|
|
302
|
+
const detail = await fetchDetail(item, { subject: row.subject, sentAt: row.sentAt, from }, 'GET /pub/v3/messages/{id} (sync)', isInboxUnread);
|
|
224
303
|
body = detail.body ?? '';
|
|
225
304
|
fetchedBodyAt = new Date().toISOString();
|
|
226
305
|
detailRecipients = detail.recipients;
|
|
@@ -228,27 +307,24 @@ async function walkPages(client, folder, folderId, opts, store) {
|
|
|
228
307
|
detailFileIds = detail.files;
|
|
229
308
|
}
|
|
230
309
|
}
|
|
231
|
-
|
|
310
|
+
if (isInboxUnread) {
|
|
311
|
+
// Pre-sync state: listed even when fetchUnreadBodies then opened it.
|
|
232
312
|
unread.push({
|
|
233
313
|
id: item.id,
|
|
234
314
|
subject: item.subject,
|
|
235
|
-
from:
|
|
315
|
+
from: from ?? '',
|
|
236
316
|
sentAt: item.date.dateTime,
|
|
317
|
+
bodyFetched: shouldFetchBody,
|
|
237
318
|
});
|
|
238
319
|
}
|
|
239
|
-
|
|
240
|
-
id: item.id,
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
fetchedBodyAt,
|
|
248
|
-
replyToId: null,
|
|
249
|
-
chainRootId: null,
|
|
250
|
-
listData: item,
|
|
251
|
-
};
|
|
320
|
+
newMessages.push({
|
|
321
|
+
id: item.id, folder, from, subject: row.subject, sentAt: row.sentAt,
|
|
322
|
+
read: listRead, bodyFetched: shouldFetchBody,
|
|
323
|
+
});
|
|
324
|
+
row.body = body;
|
|
325
|
+
row.fetchedBodyAt = fetchedBodyAt;
|
|
326
|
+
if (detailRecipients)
|
|
327
|
+
row.recipients = mapRecipients(detailRecipients);
|
|
252
328
|
toUpsert.push(row);
|
|
253
329
|
synced++;
|
|
254
330
|
if (detailFileIds.length > 0) {
|
|
@@ -265,14 +341,14 @@ async function walkPages(client, folder, folderId, opts, store) {
|
|
|
265
341
|
if (pageBudgetHit) {
|
|
266
342
|
// Paused mid-page. Resume at THIS page: the partial rows are cached, so
|
|
267
343
|
// getMessages skips them next time and upserts are idempotent.
|
|
268
|
-
return {
|
|
344
|
+
return { ...totals(), done: false, nextPage: page };
|
|
269
345
|
}
|
|
270
346
|
// Reached cached history (see `stopAtCachedPage`). Report THIS page as the
|
|
271
347
|
// resume point rather than the next one: it costs one redundant (cheap,
|
|
272
348
|
// all-cached) fetch if a backfill later starts here, and it cannot skip a
|
|
273
349
|
// message the way an off-by-one `page + 1` could.
|
|
274
350
|
if (opts.stopAtCachedPage && !pageHadNewItem) {
|
|
275
|
-
return {
|
|
351
|
+
return { ...totals(), done: true, nextPage: page };
|
|
276
352
|
}
|
|
277
353
|
page++;
|
|
278
354
|
}
|
|
@@ -309,6 +385,8 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
|
|
|
309
385
|
}, store);
|
|
310
386
|
let synced = fwd.synced;
|
|
311
387
|
const unread = [...fwd.unread];
|
|
388
|
+
const newMessages = [...fwd.newMessages];
|
|
389
|
+
const markedRead = [...fwd.markedRead];
|
|
312
390
|
// Never regress the folder's newest id: a pass that only walked cached pages
|
|
313
391
|
// still saw page 1, but a paused one may not have.
|
|
314
392
|
let newestId = maxId(saved?.newestId ?? null, fwd.newestId);
|
|
@@ -360,6 +438,8 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
|
|
|
360
438
|
}, store);
|
|
361
439
|
synced += bf.synced;
|
|
362
440
|
unread.push(...bf.unread);
|
|
441
|
+
newMessages.push(...bf.newMessages);
|
|
442
|
+
markedRead.push(...bf.markedRead);
|
|
363
443
|
newestId = maxId(newestId, bf.newestId);
|
|
364
444
|
done = bf.done;
|
|
365
445
|
resumePage = bf.done ? null : bf.nextPage;
|
|
@@ -373,7 +453,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
|
|
|
373
453
|
// sync (buildFreshness downgrades when lastSyncAt runs ahead of verifiedAt).
|
|
374
454
|
if (fwd.done)
|
|
375
455
|
await markFolderVerified(store, folder, now);
|
|
376
|
-
return { synced, unread, done, verified: fwd.done };
|
|
456
|
+
return { synced, unread, newMessages, markedRead, done, verified: fwd.done };
|
|
377
457
|
}
|
|
378
458
|
const DraftListItemSchema = z.looseObject({
|
|
379
459
|
id: z.number(),
|
|
@@ -391,6 +471,14 @@ const DraftListResponseSchema = z.looseObject({ data: z.array(DraftListItemSchem
|
|
|
391
471
|
const DraftDetailSchema = z.looseObject({
|
|
392
472
|
body: z.string().optional(),
|
|
393
473
|
subject: z.string().optional(),
|
|
474
|
+
// The reply linkage and recipients are read from the DETAIL, not the list
|
|
475
|
+
// item: the drafts list carries no replyToId/inReplyTo/showContext key at all
|
|
476
|
+
// (verified live 2026-11-08), so a row built from it hashed to a different
|
|
477
|
+
// revision than the save echo and lost the reply target.
|
|
478
|
+
replyToId: z.number().nullable().optional(),
|
|
479
|
+
inReplyTo: z.number().nullable().optional(),
|
|
480
|
+
showContext: z.boolean().optional(),
|
|
481
|
+
recipients: z.array(ApiRecipientSchema).optional(),
|
|
394
482
|
});
|
|
395
483
|
/**
|
|
396
484
|
* Meta key holding whether the drafts cache has been compared against OFW.
|
|
@@ -515,26 +603,36 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
|
|
|
515
603
|
// Fetch every draft's detail up front, still buffered. OFW's list
|
|
516
604
|
// `date.dateTime` is NOT a reliable modification timestamp for drafts —
|
|
517
605
|
// direct UI edits don't bump it — so we can't skip the detail fetch.
|
|
606
|
+
//
|
|
607
|
+
// Pre-sync state (S1 batch read) — for the synced-count comparison below,
|
|
608
|
+
// and as the reply-target fallback when a payload does not echo the linkage.
|
|
609
|
+
const ids = items.map((it) => it.id);
|
|
610
|
+
const existingById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
|
|
518
611
|
const rows = [];
|
|
612
|
+
const replySources = [];
|
|
519
613
|
for (const item of items) {
|
|
520
614
|
if (!b.take())
|
|
521
615
|
return defer();
|
|
522
616
|
const detail = parseLenient(DraftDetailSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (drafts sync)' });
|
|
617
|
+
// The same rule ofw_save_draft and the freshness snapshot apply
|
|
618
|
+
// (draftReplyTarget), so the revision a read reports matches the one the
|
|
619
|
+
// save returned for the same server state.
|
|
620
|
+
const reply = draftReplyTarget([detail, item], existingById.get(item.id)?.replyToId ?? null);
|
|
523
621
|
rows.push({
|
|
524
622
|
id: item.id,
|
|
525
623
|
subject: detail.subject ?? item.subject ?? '(no subject)',
|
|
526
624
|
body: detail.body ?? '',
|
|
527
|
-
recipients: mapRecipients(item.recipients),
|
|
528
|
-
replyToId:
|
|
625
|
+
recipients: mapRecipients(detail.recipients ?? item.recipients),
|
|
626
|
+
replyToId: reply.replyToId,
|
|
529
627
|
modifiedAt: item.date?.dateTime ?? nowNaiveWallClock(),
|
|
530
628
|
listData: item,
|
|
531
629
|
});
|
|
630
|
+
replySources.push(reply.replyToSource);
|
|
532
631
|
}
|
|
533
|
-
// Budget funded the whole walk — apply atomically.
|
|
534
|
-
// pre-upsert state for the synced-count comparison and stale-row eviction.
|
|
535
|
-
const ids = items.map((it) => it.id);
|
|
536
|
-
const existingById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
|
|
632
|
+
// Budget funded the whole walk — apply atomically.
|
|
537
633
|
await store.upsertDrafts(rows);
|
|
634
|
+
for (const [i, row] of rows.entries())
|
|
635
|
+
await setReplyToSource(store, row.id, replySources[i]);
|
|
538
636
|
// If a stale `messages` row exists for a draft id (cached by a prior
|
|
539
637
|
// ofw_get_message call before the drafts table knew about this id), evict it.
|
|
540
638
|
// The drafts table is the source of truth for drafts.
|
|
@@ -566,6 +664,21 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
|
|
|
566
664
|
await markFolderVerified(store, 'drafts', now);
|
|
567
665
|
return { synced, done: true };
|
|
568
666
|
}
|
|
667
|
+
/**
|
|
668
|
+
* The most new messages one sync response lists. A first sync of a large
|
|
669
|
+
* account caches thousands of rows; echoing them all would make the response
|
|
670
|
+
* the problem (see "Response shape" in CLAUDE.md). The newest are the ones a
|
|
671
|
+
* caller acts on, `newMessagesTotal` keeps the real count, and
|
|
672
|
+
* `newMessagesTruncated` says the array is a slice — ofw_list_messages pages
|
|
673
|
+
* through the rest.
|
|
674
|
+
*/
|
|
675
|
+
export const NEW_MESSAGES_CAP = 50;
|
|
676
|
+
/** Newest first: by sentAt (OFW's uniform naive format sorts as text), then id. */
|
|
677
|
+
function newestFirst(a, b) {
|
|
678
|
+
if (a.sentAt !== b.sentAt)
|
|
679
|
+
return a.sentAt < b.sentAt ? 1 : -1;
|
|
680
|
+
return b.id - a.id;
|
|
681
|
+
}
|
|
569
682
|
/**
|
|
570
683
|
* The sync note for unread inbox messages cached without bodies. Exported so
|
|
571
684
|
* ofw_sync_messages can rewrite it after a confirmed open of some of them —
|
|
@@ -575,6 +688,49 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
|
|
|
575
688
|
export function unreadInboxNote(count) {
|
|
576
689
|
return `${count} unread inbox messages cached without bodies. Call ofw_get_message(id) to read them — this will mark them as read on OFW.`;
|
|
577
690
|
}
|
|
691
|
+
const MARKED_READ_LEAD = 'MARKED READ on OurFamilyWizard by this sync:';
|
|
692
|
+
/**
|
|
693
|
+
* The note line for messages this sync marked read. Exported, like
|
|
694
|
+
* unreadInboxNote, so ofw_sync_messages can rewrite it after a confirmed open.
|
|
695
|
+
*/
|
|
696
|
+
export function markedReadNote(markedRead) {
|
|
697
|
+
const unexpected = markedRead.filter((m) => m.reason === 'unexpected').length;
|
|
698
|
+
return `${MARKED_READ_LEAD} ${markedRead.length} inbox message${markedRead.length === 1 ? '' : 's'} (ids ${markedRead.map((m) => m.id).join(', ')}). Each now carries a "First Viewed" time your co-parent can see; it cannot be undone.${unexpected > 0 ? ` ${unexpected} of them ${unexpected === 1 ? 'was' : 'were'} NOT requested (reason "unexpected").` : ''}`;
|
|
699
|
+
}
|
|
700
|
+
/** The top-level `warning` for messages this sync marked read. */
|
|
701
|
+
export function markedReadWarning(markedRead) {
|
|
702
|
+
const unexpected = markedRead.filter((m) => m.reason === 'unexpected').length;
|
|
703
|
+
return `WARNING: this sync marked ${markedRead.length} inbox message${markedRead.length === 1 ? '' : 's'} READ on OurFamilyWizard (see markedRead). Your co-parent can see the "First Viewed" time, and it cannot be undone.${unexpected > 0 ? ` ${unexpected} of them ${unexpected === 1 ? 'was' : 'were'} NOT requested: the list reported ${unexpected === 1 ? 'it' : 'them'} as already read, but the fetch stamped ${unexpected === 1 ? 'it' : 'them'}. Tell the user, and report this as a bug.` : ''}`;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Recompute everything in a sync result DERIVED from `markedRead` and
|
|
707
|
+
* `unreadInbox` — `warning`, `markedReadCount`, and their two note lines —
|
|
708
|
+
* from the arrays as they now stand. syncAll calls it once; ofw_sync_messages
|
|
709
|
+
* calls it again after a confirmed open adds to them, so one payload never
|
|
710
|
+
* carries two counts for the same thing. Other note lines keep their order.
|
|
711
|
+
*/
|
|
712
|
+
export function refreshReadReporting(result) {
|
|
713
|
+
const markedRead = result.markedRead ?? [];
|
|
714
|
+
const notes = (result.note === undefined ? [] : result.note.split('\n\n'))
|
|
715
|
+
.filter((n) => !n.startsWith(MARKED_READ_LEAD) && !/^\d+ unread inbox messages cached without bodies\./.test(n));
|
|
716
|
+
const bodiless = result.unreadInbox.filter((h) => !h.bodyFetched).length;
|
|
717
|
+
if (bodiless > 0)
|
|
718
|
+
notes.push(unreadInboxNote(bodiless));
|
|
719
|
+
if (markedRead.length > 0)
|
|
720
|
+
notes.unshift(markedReadNote(markedRead));
|
|
721
|
+
result.note = notes.length > 0 ? notes.join('\n\n') : undefined;
|
|
722
|
+
if (result.note === undefined)
|
|
723
|
+
delete result.note;
|
|
724
|
+
result.markedReadCount = markedRead.length;
|
|
725
|
+
if (markedRead.length > 0) {
|
|
726
|
+
result.warning = markedReadWarning(markedRead);
|
|
727
|
+
result.markedRead = markedRead;
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
delete result.warning;
|
|
731
|
+
delete result.markedRead;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
578
734
|
export async function syncAll(client, opts, store) {
|
|
579
735
|
const requested = opts.folders ?? ['inbox', 'sent', 'drafts'];
|
|
580
736
|
// Drafts go FIRST. They are the only folder a destructive tool
|
|
@@ -601,6 +757,8 @@ export async function syncAll(client, opts, store) {
|
|
|
601
757
|
const ids = await resolveFolderIds(client, store);
|
|
602
758
|
const synced = {};
|
|
603
759
|
let unreadInbox = [];
|
|
760
|
+
const newMessages = [];
|
|
761
|
+
const markedRead = [];
|
|
604
762
|
let done = true;
|
|
605
763
|
let draftsUnverified = false;
|
|
606
764
|
const refreshed = [];
|
|
@@ -628,6 +786,8 @@ export async function syncAll(client, opts, store) {
|
|
|
628
786
|
}, store);
|
|
629
787
|
record('inbox', r.verified, r.synced);
|
|
630
788
|
unreadInbox = r.unread;
|
|
789
|
+
newMessages.push(...r.newMessages);
|
|
790
|
+
markedRead.push(...r.markedRead);
|
|
631
791
|
if (!r.done)
|
|
632
792
|
done = false;
|
|
633
793
|
}
|
|
@@ -639,6 +799,8 @@ export async function syncAll(client, opts, store) {
|
|
|
639
799
|
budget,
|
|
640
800
|
}, store);
|
|
641
801
|
record('sent', r.verified, r.synced);
|
|
802
|
+
// A sent detail never stamps OUR read state, so it adds no markedRead.
|
|
803
|
+
newMessages.push(...r.newMessages);
|
|
642
804
|
if (!r.done)
|
|
643
805
|
done = false;
|
|
644
806
|
}
|
|
@@ -662,9 +824,6 @@ export async function syncAll(client, opts, store) {
|
|
|
662
824
|
if (draftsUnverified) {
|
|
663
825
|
notes.push('The drafts folder was NOT checked against OurFamilyWizard on this call (the request budget ran out first), so no drafts count is reported and the cached drafts are marked "unverified". Cached draft bodies may be behind the server. Call ofw_sync_messages again — or ofw_sync_messages with folders:["drafts"] — before editing or deleting a draft.');
|
|
664
826
|
}
|
|
665
|
-
if (unreadInbox.length > 0) {
|
|
666
|
-
notes.push(unreadInboxNote(unreadInbox.length));
|
|
667
|
-
}
|
|
668
827
|
if (notRefreshed.length > 0) {
|
|
669
828
|
notes.push(`NOT checked against OurFamilyWizard on this call: ${notRefreshed.join(', ')}. No count is reported for ${notRefreshed.length > 1 ? 'those folders' : 'that folder'} — absence of a count means "not looked at", not "no changes". Cached contents may be behind the server; call ofw_sync_messages again to finish, or ofw_check_freshness for a cheap live confirmation.`);
|
|
670
829
|
}
|
|
@@ -672,14 +831,26 @@ export async function syncAll(client, opts, store) {
|
|
|
672
831
|
notes.push('Paused after the request budget to stay within the hosting limit; more pages remain — call ofw_sync_messages again with the same arguments to resume where it left off and continue the backfill.');
|
|
673
832
|
}
|
|
674
833
|
const note = notes.length > 0 ? notes.join('\n\n') : undefined;
|
|
675
|
-
|
|
834
|
+
newMessages.sort(newestFirst);
|
|
835
|
+
// Key order is the emitted order: the warning first (a truncated read must
|
|
836
|
+
// hit it), counts before arrays, newMessages last. `warning` is declared
|
|
837
|
+
// here as a placeholder so refreshReadReporting fills it IN PLACE.
|
|
838
|
+
const result = {
|
|
839
|
+
warning: undefined,
|
|
676
840
|
synced,
|
|
841
|
+
markedReadCount: 0,
|
|
842
|
+
newMessagesTotal: newMessages.length,
|
|
843
|
+
newMessagesTruncated: newMessages.length > NEW_MESSAGES_CAP,
|
|
677
844
|
unreadInbox,
|
|
678
845
|
done,
|
|
679
846
|
syncComplete: done,
|
|
680
847
|
refreshed,
|
|
681
848
|
notRefreshed,
|
|
682
849
|
...(readingBlocked ? { bodiesWithheld: true } : {}),
|
|
683
|
-
|
|
850
|
+
note,
|
|
851
|
+
markedRead,
|
|
852
|
+
newMessages: newMessages.slice(0, NEW_MESSAGES_CAP),
|
|
684
853
|
};
|
|
854
|
+
refreshReadReporting(result);
|
|
855
|
+
return result;
|
|
685
856
|
}
|
package/dist/tools/_shared.js
CHANGED
|
@@ -78,7 +78,8 @@ export const ApiRecipientSchema = z.looseObject({
|
|
|
78
78
|
// viewed. Only the DETAIL endpoint (/pub/v3/messages/{id}) carries a real
|
|
79
79
|
// timestamp; the LIST endpoint returns an epoch-zero PLACEHOLDER
|
|
80
80
|
// ("1970-01-01T00:00:00") in the SAME field even for read messages (on the
|
|
81
|
-
// list, read status lives in
|
|
81
|
+
// list, read status lives in the flags — `read` for inbox, `showNeverViewed`
|
|
82
|
+
// for sent; see scrapeSaysRead — not the timestamp). So treat
|
|
82
83
|
// the epoch placeholder as "no real view time" — otherwise a list-sourced row
|
|
83
84
|
// reports a bogus 1970 read time. A detail re-fetch is what fills in the truth.
|
|
84
85
|
export function mapRecipients(items) {
|
|
@@ -101,6 +102,35 @@ export function hasRealView(recipients) {
|
|
|
101
102
|
export function threadedReplyTo(detail) {
|
|
102
103
|
return detail.replyToId ?? detail.inReplyTo ?? null;
|
|
103
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The ONE rule for a draft's reply target, used by every path that builds a
|
|
107
|
+
* draft's content (save echo, drafts sync, the freshness snapshot, the
|
|
108
|
+
* destructive-draft guard), so the revision hashed from it cannot depend on
|
|
109
|
+
* which path produced it.
|
|
110
|
+
*
|
|
111
|
+
* The first echo that names a target wins (`server`). When none does, the
|
|
112
|
+
* `fallback` (the cached row's target, or the one just posted) is kept as
|
|
113
|
+
* `cache` — unless an echo POSITIVELY reports the draft unthreaded
|
|
114
|
+
* ({@link reportsUnthreaded}), in which case OFW's answer stands and nothing
|
|
115
|
+
* is resurrected.
|
|
116
|
+
*
|
|
117
|
+
* Why the fallback exists: the drafts LIST payload carries no `replyToId`,
|
|
118
|
+
* `inReplyTo` or `showContext` key at all (verified live 2026-11-08), so a
|
|
119
|
+
* cached row built from it read `replyToId: null` for a draft whose detail said
|
|
120
|
+
* `inReplyTo: 574607114` — and its revision disagreed with the one the save
|
|
121
|
+
* returned. Silence about the linkage is not evidence it is gone.
|
|
122
|
+
*/
|
|
123
|
+
export function draftReplyTarget(echoes, fallback) {
|
|
124
|
+
for (const echo of echoes) {
|
|
125
|
+
const target = threadedReplyTo(echo);
|
|
126
|
+
if (target !== null)
|
|
127
|
+
return { replyToId: target, replyToSource: 'server' };
|
|
128
|
+
}
|
|
129
|
+
if (fallback !== null && !echoes.some(reportsUnthreaded)) {
|
|
130
|
+
return { replyToId: fallback, replyToSource: 'cache' };
|
|
131
|
+
}
|
|
132
|
+
return { replyToId: null, replyToSource: null };
|
|
133
|
+
}
|
|
104
134
|
/** True when the payload positively reports the message as threaded. */
|
|
105
135
|
export function reportsThreaded(detail) {
|
|
106
136
|
return threadedReplyTo(detail) !== null || detail.showContext === true;
|
|
@@ -122,15 +152,31 @@ export function reportsUnthreaded(detail) {
|
|
|
122
152
|
return false;
|
|
123
153
|
return detail.inReplyTo !== undefined || detail.showContext !== undefined;
|
|
124
154
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
155
|
+
/**
|
|
156
|
+
* True when the once-scraped LIST flags themselves say the message is read.
|
|
157
|
+
* Both are only ever captured at first sight, so they can go stale — they
|
|
158
|
+
* raise `read` but never lower it (see deriveRead).
|
|
159
|
+
*
|
|
160
|
+
* - INBOX: only the inbox list's own `read === true` counts. Anything else —
|
|
161
|
+
* `read: false`, a missing `read`, a non-boolean — is UNREAD. On the inbox
|
|
162
|
+
* list `showNeverViewed` is NOT our read state: it is the sender-side
|
|
163
|
+
* "recipient never viewed" badge flag, and it comes back `false` on a
|
|
164
|
+
* brand-new message we have never opened. Treating it as read evidence
|
|
165
|
+
* once let a routine sync fetch an unread body, which stamped a
|
|
166
|
+
* co-parent-visible "First Viewed" time. Unknown must fail closed: a false
|
|
167
|
+
* "unread" costs a confirmation, a false "read" stamps the record.
|
|
168
|
+
* - SENT: `showNeverViewed === false` is the reliable "a recipient has viewed
|
|
169
|
+
* it" signal (or `read === true`) — unchanged.
|
|
170
|
+
*
|
|
171
|
+
* Exported for sync.ts, which applies the same rule to a list item before
|
|
172
|
+
* deciding whether a body fetch could stamp it.
|
|
173
|
+
*/
|
|
174
|
+
export function scrapeSaysRead(folder, listData) {
|
|
131
175
|
if (typeof listData !== 'object' || listData === null)
|
|
132
176
|
return false;
|
|
133
177
|
const ld = listData;
|
|
178
|
+
if (folder === 'inbox')
|
|
179
|
+
return ld.read === true;
|
|
134
180
|
return ld.read === true || ld.showNeverViewed === false;
|
|
135
181
|
}
|
|
136
182
|
/**
|
|
@@ -150,7 +196,10 @@ function scrapeSaysRead(listData) {
|
|
|
150
196
|
* counts. OFW co-parent threads are 1:1 — the sole inbox recipient is us —
|
|
151
197
|
* so this is exact, not an approximation. Fetching the body marks the message
|
|
152
198
|
* read on OFW, so a non-null `fetchedBodyAt` is also read=true. The stale
|
|
153
|
-
* scrape flag is only a last-resort fallback
|
|
199
|
+
* scrape flag is only a last-resort fallback, and for inbox it is the list's
|
|
200
|
+
* `read === true` ONLY — never `showNeverViewed`, which on the inbox list is
|
|
201
|
+
* the sender-side badge and reads `false` on a message we never opened
|
|
202
|
+
* (see scrapeSaysRead).
|
|
154
203
|
* - SENT: "read" means a *recipient* has opened it — tracked via their
|
|
155
204
|
* `viewedAt` (the detail endpoint's real timestamp) — never our own body
|
|
156
205
|
* fetch, which is always set for sent messages.
|
|
@@ -172,9 +221,9 @@ function scrapeSaysRead(listData) {
|
|
|
172
221
|
export function deriveRead(row) {
|
|
173
222
|
const viewedByAnyone = row.recipients.some((r) => r.viewedAt !== null);
|
|
174
223
|
if (row.folder === 'inbox') {
|
|
175
|
-
return viewedByAnyone || row.fetchedBodyAt !== null || scrapeSaysRead(row.listData);
|
|
224
|
+
return viewedByAnyone || row.fetchedBodyAt !== null || scrapeSaysRead('inbox', row.listData);
|
|
176
225
|
}
|
|
177
|
-
return viewedByAnyone || scrapeSaysRead(row.listData);
|
|
226
|
+
return viewedByAnyone || scrapeSaysRead(row.folder, row.listData);
|
|
178
227
|
}
|
|
179
228
|
/**
|
|
180
229
|
* Return the row augmented with an authoritative top-level `read` boolean and a
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { parseLenient } from '@chrischall/mcp-utils';
|
|
3
|
-
import { ApiRecipientSchema,
|
|
3
|
+
import { ApiRecipientSchema, draftReplyTarget, mapRecipients } from './_shared.js';
|
|
4
4
|
/** Thrown when the freshness check itself could not be completed. */
|
|
5
5
|
export class DraftFreshnessError extends Error {
|
|
6
6
|
}
|
|
@@ -52,6 +52,7 @@ const ServerDraftSchema = z.looseObject({
|
|
|
52
52
|
// that disagreed about the same draft.
|
|
53
53
|
replyToId: z.number().nullable().optional(),
|
|
54
54
|
inReplyTo: z.number().nullable().optional(),
|
|
55
|
+
showContext: z.boolean().optional(),
|
|
55
56
|
recipients: z.array(ApiRecipientSchema).optional(),
|
|
56
57
|
// Attachment fileIds — read so send-by-draft carries the draft's
|
|
57
58
|
// attachments onto the sent message (see DraftContent.files).
|
|
@@ -89,7 +90,7 @@ function isNotFound(e) {
|
|
|
89
90
|
* the narrower type (the catch blocks read only `.message`, which every Error
|
|
90
91
|
* carries).
|
|
91
92
|
*/
|
|
92
|
-
export async function fetchMessageSnapshot(client, id) {
|
|
93
|
+
export async function fetchMessageSnapshot(client, id, fallbackReplyTo = null) {
|
|
93
94
|
let raw;
|
|
94
95
|
try {
|
|
95
96
|
raw = await client.request('GET', `/pub/v3/messages/${id}`);
|
|
@@ -109,17 +110,22 @@ export async function fetchMessageSnapshot(client, id) {
|
|
|
109
110
|
context: 'GET /pub/v3/messages/{id} (draft freshness check)',
|
|
110
111
|
mode: 'strict',
|
|
111
112
|
});
|
|
113
|
+
// The same reply-target rule as the save echo and the drafts sync
|
|
114
|
+
// (draftReplyTarget), with the cached target as the fallback, so a detail
|
|
115
|
+
// that does not echo the linkage hashes exactly like the cached row.
|
|
116
|
+
const reply = draftReplyTarget([detail], fallbackReplyTo);
|
|
112
117
|
return {
|
|
113
118
|
content: {
|
|
114
119
|
subject: detail.subject ?? '',
|
|
115
120
|
body: detail.body ?? '',
|
|
116
|
-
replyToId:
|
|
121
|
+
replyToId: reply.replyToId,
|
|
117
122
|
recipients: mapRecipients(detail.recipients),
|
|
118
123
|
...(detail.files !== undefined ? { files: detail.files } : {}),
|
|
119
124
|
},
|
|
120
125
|
folderId: detail.folder?.id === undefined ? null : String(detail.folder.id),
|
|
121
126
|
folderName: detail.folder?.name ?? null,
|
|
122
127
|
dateTime: detail.date?.dateTime ?? null,
|
|
128
|
+
replyToSource: reply.replyToSource,
|
|
123
129
|
};
|
|
124
130
|
}
|
|
125
131
|
/**
|
|
@@ -130,8 +136,8 @@ export async function fetchMessageSnapshot(client, id) {
|
|
|
130
136
|
* the callers in messages.ts abort on ALL of them: a freshness check that could
|
|
131
137
|
* not run must never wave the write through.
|
|
132
138
|
*/
|
|
133
|
-
export async function fetchServerDraft(client, id) {
|
|
134
|
-
return (await fetchMessageSnapshot(client, id))?.content ?? null;
|
|
139
|
+
export async function fetchServerDraft(client, id, fallbackReplyTo = null) {
|
|
140
|
+
return (await fetchMessageSnapshot(client, id, fallbackReplyTo))?.content ?? null;
|
|
135
141
|
}
|
|
136
142
|
/**
|
|
137
143
|
* The fields whose divergence constitutes a REAL conflict — the actual message
|
package/dist/tools/lifecycle.js
CHANGED
|
@@ -210,7 +210,10 @@ async function probeOne(client, prepared, map, draftKey, heldFiles) {
|
|
|
210
210
|
const { id, cachedDraft } = prepared;
|
|
211
211
|
let snapshot;
|
|
212
212
|
try {
|
|
213
|
-
|
|
213
|
+
// The cached target is the fallback for a detail that does not echo the
|
|
214
|
+
// linkage, the same rule the drafts sync applies, so an unchanged draft
|
|
215
|
+
// reports cacheRevision === serverRevision.
|
|
216
|
+
snapshot = await fetchMessageSnapshot(client, id, cachedDraft?.replyToId ?? null);
|
|
214
217
|
}
|
|
215
218
|
catch (e) {
|
|
216
219
|
return {
|