@dxv-systems/mail-graph 0.3.1 → 0.3.2

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.
@@ -17,7 +17,7 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
17
17
  ## 1. Install
18
18
 
19
19
  ```bash
20
- npm install --save-exact @dxv-systems/mail-graph@0.3.1 @dxv-systems/helpdesk@0.10.1 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.3.2 @dxv-systems/helpdesk@0.12.2 @vercel/oidc@4.0.1
21
21
  ```
22
22
 
23
23
  Use the published versions (exact, never a range; upgrading is a deliberate change). **Vendored variant** (before publication, e.g. the rehearsal): `npm pack` each package into `vendor/` and install `file:vendor/dxv-systems-mail-graph-<version>.tgz file:vendor/dxv-systems-helpdesk-<version>.tgz` instead; commit the tarballs with `package.json` and the lockfile.
@@ -77,6 +77,7 @@ Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryK
77
77
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
78
78
  import type {
79
79
  DraftRunStatus,
80
+ HistoryState,
80
81
  MessageDirection,
81
82
  MessageLocation,
82
83
  NoiseReason,
@@ -111,6 +112,8 @@ export const helpdeskSettings = pgTable(
111
112
  paused: boolean("paused").notNull().default(false),
112
113
  /** Lease of the sync cron: a run starts only when this is null or past. */
113
114
  syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
115
+ /** Lease of the history cron, apart from the sync's, so neither waits for the other. */
116
+ historyLeaseUntil: timestamp("history_lease_until", { withTimezone: true }),
114
117
  updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }),
115
118
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
116
119
  },
@@ -132,6 +135,13 @@ export const helpdeskSyncStates = pgTable("helpdesk_sync_states", {
132
135
  lastError: text("last_error"),
133
136
  });
134
137
 
138
+ /** History import progress per mailbox (`HistoryState`), apart from the sync state so neither overwrites the other. */
139
+ export const helpdeskHistoryStates = pgTable("helpdesk_history_states", {
140
+ mailbox: varchar("mailbox", { length: 320 }).primaryKey(),
141
+ state: jsonb("state").$type<HistoryState>().notNull(),
142
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
143
+ });
144
+
135
145
  /** Tickets (`Thread`), plus the inbox's assignment (app data). */
136
146
  export const helpdeskThreads = pgTable(
137
147
  "helpdesk_threads",
@@ -276,7 +286,7 @@ export const helpdeskReplyAttachments = pgTable(
276
286
  );
277
287
  ```
278
288
 
279
- Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (eight `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5).
289
+ Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (nine `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5). An app on helpdesk 0.11 upgrades with one generated migration: the table `helpdesk_history_states` and `history_lease_until` on `helpdesk_settings`, nothing dropped (see the helpdesk README, Upgrading from 0.11).
280
290
 
281
291
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
282
292
 
@@ -441,6 +451,7 @@ import { and, asc, desc, eq, gte, inArray, lt } from "drizzle-orm";
441
451
  import type {
442
452
  DraftRun,
443
453
  HelpdeskStore,
454
+ HistoryState,
444
455
  SendIntent,
445
456
  StoredMessage,
446
457
  SyncState,
@@ -450,6 +461,7 @@ import type {
450
461
  import { db, type DbClient } from "@/lib/db";
451
462
  import {
452
463
  helpdeskDraftRuns,
464
+ helpdeskHistoryStates,
453
465
  helpdeskMessages,
454
466
  helpdeskSendIntents,
455
467
  helpdeskSyncStates,
@@ -609,6 +621,22 @@ export const helpdeskStore: HelpdeskStore = {
609
621
  .onConflictDoUpdate({ target: helpdeskSyncStates.mailbox, set: values });
610
622
  },
611
623
 
624
+ async getHistoryState(mailbox): Promise<HistoryState | null> {
625
+ const [row] = await db
626
+ .select({ state: helpdeskHistoryStates.state })
627
+ .from(helpdeskHistoryStates)
628
+ .where(eq(helpdeskHistoryStates.mailbox, mailbox))
629
+ .limit(1);
630
+ return row?.state ?? null;
631
+ },
632
+
633
+ async saveHistoryState(mailbox, state) {
634
+ await db
635
+ .insert(helpdeskHistoryStates)
636
+ .values({ mailbox, state })
637
+ .onConflictDoUpdate({ target: helpdeskHistoryStates.mailbox, set: { state, updatedAt: new Date() } });
638
+ },
639
+
612
640
  async getMessage(mailbox, id) {
613
641
  const [row] = await db
614
642
  .select()
@@ -837,6 +865,7 @@ export const helpdeskStore: HelpdeskStore = {
837
865
  ```ts
838
866
  import "server-only";
839
867
  import { and, asc, desc, eq, ilike, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
868
+ import { UNREAD_WINDOW_DAYS } from "@dxv-systems/helpdesk";
840
869
  import type { HelpdeskInboxQueries, InboxFolder } from "@dxv-systems/helpdesk/server";
841
870
  import { rolesWithPermission } from "@/lib/auth/permissions";
842
871
  import { db } from "@/lib/db";
@@ -898,7 +927,9 @@ const customerIn = (folder: InboxFolder) =>
898
927
  const present = sql`coalesce(${m.location}, '') <> 'gone'`;
899
928
  const ofThread = sql`${m.threadId} = ${helpdeskThreads.id}`;
900
929
  const exists = (condition: SQL) => sql`exists (select 1 from ${m} where ${ofThread} and ${condition})`;
901
- const unreadIn = (folder: InboxFolder) => exists(sql`${customerIn(folder)} and ${m.isRead} = false`);
930
+ // Older unread mail (imported history) does not count as unread.
931
+ const unreadIn = (folder: InboxFolder) =>
932
+ exists(sql`${customerIn(folder)} and ${m.isRead} = false and ${m.receivedAt} >= now() - make_interval(days => ${UNREAD_WINDOW_DAYS})`);
902
933
  const likePattern = (q: string) => `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
903
934
 
904
935
  export const helpdeskInbox: HelpdeskInboxQueries = {
@@ -1096,6 +1127,27 @@ export async function claimSyncLease(ms: number): Promise<boolean> {
1096
1127
  export async function releaseSyncLease(): Promise<void> {
1097
1128
  await db.update(helpdeskSettings).set({ syncLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1098
1129
  }
1130
+
1131
+ /** Claims the history cron's lease, the same way. */
1132
+ export async function claimHistoryLease(ms: number): Promise<boolean> {
1133
+ await db.insert(helpdeskSettings).values({ id: 1 }).onConflictDoNothing();
1134
+ const now = new Date();
1135
+ const claimed = await db
1136
+ .update(helpdeskSettings)
1137
+ .set({ historyLeaseUntil: new Date(now.getTime() + ms) })
1138
+ .where(
1139
+ and(
1140
+ eq(helpdeskSettings.id, 1),
1141
+ or(isNull(helpdeskSettings.historyLeaseUntil), lt(helpdeskSettings.historyLeaseUntil, now)),
1142
+ ),
1143
+ )
1144
+ .returning({ id: helpdeskSettings.id });
1145
+ return claimed.length > 0;
1146
+ }
1147
+
1148
+ export async function releaseHistoryLease(): Promise<void> {
1149
+ await db.update(helpdeskSettings).set({ historyLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1150
+ }
1099
1151
  ```
1100
1152
 
1101
1153
  **No drafter yet.** `HelpdeskDeps.drafter` is optional and left out: every new customer mail opens its ticket in review (`reviewReason: "no_draft"`, label "Zelf antwoorden") with an empty "Jouw antwoord" box. Staff write the reply; saving it creates a staff run (an ordinary draft run with `text: null`, `reason: "staff"`), and "Goedkeuren en versturen" saves and sends it. A blank reply is refused (422 `empty_reply`). When the DXV AI gateway drafter is published, add it as `drafter` in `deps.ts` (its `start` calls the published agent with the idempotency key) and call `completeDraft` when it reports; nothing else changes.
@@ -1281,15 +1333,16 @@ import {
1281
1333
  isPaused,
1282
1334
  isSyncFailing,
1283
1335
  reconcileUnknownSends,
1336
+ runHistory,
1284
1337
  sweepStuckDrafts,
1285
1338
  syncMailbox,
1286
1339
  } from "@dxv-systems/helpdesk";
1287
1340
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
1288
1341
  import { db } from "@/lib/db";
1289
- import { helpdeskSyncStates } from "@/lib/db/schema";
1342
+ import { helpdeskHistoryStates, helpdeskSyncStates } from "@/lib/db/schema";
1290
1343
  import { notifyUsers } from "@/lib/notifications/service";
1291
1344
  import { getHelpdeskDeps } from "./deps";
1292
- import { claimSyncLease, releaseSyncLease } from "./settings";
1345
+ import { claimHistoryLease, claimSyncLease, releaseHistoryLease, releaseSyncLease } from "./settings";
1293
1346
 
1294
1347
  /** Longer than the cron route's maxDuration, so a dead run's lease expires on its own. */
1295
1348
  const SYNC_LEASE_MS = 6 * 60_000;
@@ -1301,9 +1354,10 @@ export async function onHelpdeskConnected(connection: M365Connection): Promise<v
1301
1354
  for (const mailbox of connection.mailboxes) await connectMailbox(deps, mailbox);
1302
1355
  }
1303
1356
 
1304
- /** Setup `onReset`: forget delta positions; tickets stay. Tells the admin who reset. */
1357
+ /** Setup `onReset`: forget delta and history positions; tickets stay. Tells the admin who reset. */
1305
1358
  export async function onHelpdeskReset(adminId: number | null): Promise<void> {
1306
1359
  await db.delete(helpdeskSyncStates);
1360
+ await db.delete(helpdeskHistoryStates);
1307
1361
  if (adminId !== null) {
1308
1362
  await notifyUsers([adminId], {
1309
1363
  type: "helpdesk.disconnected",
@@ -1346,6 +1400,25 @@ export async function runHelpdeskSync(): Promise<HelpdeskSyncOutcome> {
1346
1400
  await releaseSyncLease();
1347
1401
  }
1348
1402
  }
1403
+
1404
+ /** Cron: the history import (off until started per mailbox), one run at a time, apart from the sync. */
1405
+ export async function runHelpdeskHistory(): Promise<HelpdeskSyncOutcome> {
1406
+ const deps = await getHelpdeskDeps();
1407
+ if (!deps) return "not_connected";
1408
+ if (!(await claimHistoryLease(SYNC_LEASE_MS))) return "busy";
1409
+ try {
1410
+ for (const mailbox of deps.config.connectedMailboxes) {
1411
+ const result = await runHistory(deps, mailbox);
1412
+ if (isPaused(result)) return "paused";
1413
+ if (result.status === "throttled") {
1414
+ console.warn("helpdesk history: Microsoft asked to wait", { mailbox, retryAfter: result.retryAfter, error: result.error });
1415
+ }
1416
+ }
1417
+ return "done";
1418
+ } finally {
1419
+ await releaseHistoryLease();
1420
+ }
1421
+ }
1349
1422
  ```
1350
1423
 
1351
1424
  `src/lib/helpdesk/queries.ts` (guarded reads for the pages)
@@ -1495,6 +1568,21 @@ export async function GET(request: Request): Promise<Response> {
1495
1568
  }
1496
1569
  ```
1497
1570
 
1571
+ `src/app/api/cron/helpdesk-history/route.ts`
1572
+
1573
+ ```ts
1574
+ import { runHelpdeskHistory } from "@/lib/helpdesk/service";
1575
+ import { isCronRequest } from "@/lib/m365/cron";
1576
+
1577
+ export const maxDuration = 300;
1578
+
1579
+ /** History import of the mailboxes where it was started; idle otherwise. */
1580
+ export async function GET(request: Request): Promise<Response> {
1581
+ if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
1582
+ return Response.json({ outcome: await runHelpdeskHistory() });
1583
+ }
1584
+ ```
1585
+
1498
1586
  `vercel.json`:
1499
1587
 
1500
1588
  ```json
@@ -1502,6 +1590,7 @@ export async function GET(request: Request): Promise<Response> {
1502
1590
  "framework": "nextjs",
1503
1591
  "crons": [
1504
1592
  { "path": "/api/cron/helpdesk-sync", "schedule": "*/5 * * * *" },
1593
+ { "path": "/api/cron/helpdesk-history", "schedule": "2-59/5 * * * *" },
1505
1594
  { "path": "/api/cron/m365-access", "schedule": "*/10 * * * *" }
1506
1595
  ]
1507
1596
  }
@@ -1957,6 +2046,23 @@ describe("helpdesk store on Postgres", () => {
1957
2046
  expect(await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "failed")).toEqual([]);
1958
2047
  });
1959
2048
 
2049
+ it("keeps the history state apart from the sync state", async () => {
2050
+ const sync = (await helpdeskStore.getSyncState(MAILBOX))!;
2051
+ const folder = { link: null, oldest: null, imported: 0, doneAt: null };
2052
+ const history = {
2053
+ since: "2026-05-01T00:00:00.000Z",
2054
+ startedAt: "2026-11-01T00:00:00.000Z",
2055
+ pausedAt: null,
2056
+ retryAfter: null,
2057
+ lastError: null,
2058
+ lastRunAt: null,
2059
+ folders: { inbox: folder, sentitems: folder },
2060
+ };
2061
+ await helpdeskStore.saveHistoryState!(MAILBOX, history);
2062
+ expect(await helpdeskStore.getHistoryState!(MAILBOX)).toEqual(history);
2063
+ expect(await helpdeskStore.getSyncState(MAILBOX)).toEqual(sync);
2064
+ });
2065
+
1960
2066
  it("lists conversations by folder with unread, preview and search, and counts unread", async () => {
1961
2067
  mailbox.deliver({ id: "m9", from: "trap@example.test", fromName: "Trap & Co", subject: "Leuning 50%", conversationId: "c9", receivedDateTime: soon(9_000), bodyText: "Graag een offerte" });
1962
2068
  await syncMailbox(deps, MAILBOX);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
5
5
  "keywords": [
6
6
  "dxv",