diff --git a/KNOWN-ISSUES.md b/KNOWN-ISSUES.md index e41f5ae..3500667 100644 --- a/KNOWN-ISSUES.md +++ b/KNOWN-ISSUES.md @@ -10,6 +10,8 @@ pending**. Every entry below was exercised against 0.16.19 on the date it names, and the dates still say so: the upgrade was read against the 0.16.19→0.16.20 diff rather than re-run, and nothing in it touches the session capabilities, blob, quota, submission or registry paths these entries describe. +The calendar entries below carrying a 2026-08-31 date are the exception: those +were exercised against the live 0.16.20 directly. What remains here is not a list of unknowns but of things worth knowing — where Stalwart departs from a spec, where a setting has to be turned on for a feature to work, and what ihasmail deliberately does not do. @@ -40,6 +42,10 @@ works the same way — and dropped where 0.15 was the whole subject. Support for - **Self-service credentials** — the registry path is **confirmed live** against Stalwart 0.16.19 (2026-08-25): app passwords created and revoked, password changed, 2FA enabled and disabled, with the browser session surviving the switch to an app password. The 0.15 REST path was confirmed live too, on 0.15.5 (2026-08-24), and has since been removed along with the rest of 0.15 support. The mock enforces the same rules the real server does (current password required, password policy, a TOTP code on every request once 2FA is on, app passwords exempt from it). Password changes are refused by Stalwart for accounts backed by an external directory (LDAP/SQL/OIDC); the server's own message is shown when that happens. - **Scheduled send needs one setting turned on, and says nothing when it is off.** Stalwart advertises the delay in the account's `urn:ietf:params:jmap:submission` capability — `maxDelayedSend: 2592000` (30 days) and `FUTURERELEASE` among its `submissionExtensions`, and note it is the *account* capability, not the session-level one, which is empty. But the MTA only honours a hold when `futureRelease` is set under the session's MTA extensions, and [that setting defaults to `false`](https://stalw.art/docs/ref/object/mta-extensions/). With it off, Stalwart takes the `HOLDUNTIL` parameter, skips the hold and sends the message immediately **without an error** — the capability still says thirty days. So set `futureRelease` (to the longest hold you want to allow) before relying on this; a value shorter than 30 days is fine, and a request past it is refused honestly, with a `forbiddenMailFrom` naming the limit. `npm run dev:mock:no-future-release` reproduces the silent-drop case. ihasmail asks for the delay the way JMAP requires — a `HOLDUNTIL` parameter on the envelope's `mailFrom`, since RFC 8621 makes `sendAt` read-only and server-derived — and files the held message in a **Scheduled** folder, because `onSuccessUpdateEmail` would otherwise drop it in Sent the moment the submission is created. Nothing moves it out when the hold expires, so ihasmail reconciles the folder on the way in: released messages to Sent, cancelled ones back to Drafts. Three fixes this depends on landed in **0.16.17**, below the live instance's 0.16.19: `HOLDUNTIL` taking RFC 3339 date-times again (0.16.16 had it wanting Unix timestamps), `EmailSubmission/query` on `undoStatus` agreeing with `/get` about held submissions, and `EmailSubmission/get` without `ids` iterating the right index. The hold itself is now **confirmed against the live 0.16.19** (2026-08-25), once `futureRelease` was set to `30d` there: a submission carrying a `HOLDUNTIL` ten minutes out came back `pending`, with `sendAt` equal to the time asked for and a `250 2.1.5 Queued` from the MTA, rather than going out at once. Worth repeating that the capability is no evidence either way — it advertised `maxDelayedSend: 2592000` and `FUTURERELEASE` while the setting was still off. Only a submission tells you. The rest of the journey is **confirmed live too (2026-08-26)**: a hold expired and was delivered, and the **Scheduled** folder reconciled on the way in — a released message moved to Sent, a cancelled one back to Drafts. Nothing in Stalwart does that moving, so if ihasmail is never opened again the message still goes out; it is only the folder that waits to be tidied. - **Stalwart 0.16 and RFC 8984 disagree about the calendar vocabulary, and the server only says so half the time.** A participant's address lives in `calendarAddress`, not RFC 8984's `sendTo`/`email`; the organizer is `organizerCalendarAddress`, not `replyTo`; and a recurrence is a single `recurrenceRule`, not a `recurrenceRules` array. Addressed the RFC's way, `CalendarEvent/set` **keeps the event and discards the whole participant map without an error** — guests disappeared on save and no invitation was ever sent, which is what [#26](https://github.com/Coffey-Labs/ihasmail/issues/26) reported. The array form of the rule is refused honestly, with `invalidProperties`, so recurring events could not be created at all and existing ones showed no repeat ([#30](https://github.com/Coffey-Labs/ihasmail/issues/30)). ihasmail now writes Stalwart's names and reads either, and the mock refuses what the real server refuses, since advertising the RFC spelling is precisely how this got as far as a live server. Verified against 0.16.19 on 2026-08-25, end to end: participants, organizer and rule all survive a create, an update and a re-read; an invitation to an external Gmail address arrived as an invite card, and the decline came back and was applied to the event (`needs-action` → `declined`, sequence 1). Cancelling the event notified the guest too. Adding guests to an event that had none, and clearing them again with `null`, both work on the update path, as does RSVP — which patches `participants/{key}/participationStatus` (and `participationComment`) rather than sending the whole map. That patch had to be aimed at the base event: through 0.16.19 `CalendarEvent/set` refused a synthetic id with *"Updating synthetic ids is not yet supported"*, which is why RSVP resolves `baseEventId` first. 0.16.20 accepts one, so that resolution is now a choice rather than the only option — an RSVP aimed at an occurrence would answer for that date alone. It still resolves the base, which is the answer people mean. Adding a *new* participant by patch is refused as well (`Patch operation failed`), so a changed guest list is written as the whole `participants` property. One more thing to know when reading this code: an expanded occurrence carries a `recurrenceId` but *no* rule of its own, and `baseEventId` is set on everything an expanded query returns — a one-off included, whose own id differs from its base — so neither is a test for recurrence. -- **Recurring events: colour, category, edit and delete apply to the whole series.** Every entry point resolves `baseEventId` first, and the delete dialog says *"Delete all occurrences?"* out loud. Until 0.16.20 this was the only thing the server allowed: a synthetic id was refused outright. 0.16.20 added `CalendarEvent/set` support for updating and deleting them, writing a `recurrenceOverrides` entry for the occurrence, so editing a single date is now a thing ihasmail could do and does not yet — [#132](https://github.com/Coffey-Labs/ihasmail/issues/132). Worth knowing while it is unbuilt: the refusal that used to catch a synthetic id reaching `destroy` is gone, so an id resolved wrongly now silently deletes one occurrence and reports success rather than erroring. Nothing does that today; [#133](https://github.com/Coffey-Labs/ihasmail/issues/133) moves the resolution to the store so nothing starts. +- **A synthetic id is only true until the next write, and a stale one is wrong rather than invalid.** Stalwart's expanded-occurrence ids encode a position in the series, and writing a `recurrenceOverrides` entry adds a component that renumbers it. **Confirmed live on 0.16.20 (2026-08-31)**: a five-week series came back as `e i m q u` over 03-01 … 03-29; one override written to 03-08 left the *same five ids* addressing 03-01, 03-15, 03-29, 03-08 and 03-22. Nothing was rejected and nothing reported a change — `i` simply meant a week later than it had a moment earlier. So an id cached across a write silently points at another date, and a delete meant for one occurrence removes a different one. This is the second time the same shape of problem has cost a live debugging session, and it is worth saying plainly why it is dangerous: the failure is not a `notFound` a client would notice, it is a confident answer about the wrong day. ihasmail therefore never mutates an occurrence by an id it is holding. `recurrenceId` is the stable name for a slot in a series — it is the date — so `updateEvent` and `destroyEvent` look the current id up by it immediately before they act, and refuse outright if the date is no longer in the series rather than falling back to the id in hand. The mock renumbers too, by a different permutation to the real server's but with the property that matters, since a mock that kept ids stable would agree with precisely the belief that is wrong. + +- **A per-occurrence patch made only of inherited properties creates an override that loses the title.** The twelve properties 0.16.20 drops from a per-occurrence patch are dropped *after* it has decided to write an override, so a patch consisting only of them still writes one — and that override carries the `start` and `duration` the server fills in and nothing else. **Confirmed live on 0.16.20 (2026-08-31)**: `{"privacy": "private"}` aimed at one occurrence answered `updated`, left `privacy` untouched on the series, and left that date with no title at all. A successful response, a silently discarded change, and real data loss on a third property nobody mentioned. ihasmail narrows a per-occurrence patch before sending it and sends nothing when narrowing empties it, which was written as a point of principle — a request whose response could only be a meaningless "updated" is worse than no request — and turns out to prevent this. Worth remembering as the argument for the principle. + +- **Recurring events can be edited and deleted one date at a time, since 0.16.20.** A write aimed at a synthetic id was refused outright through 0.16.19; 0.16.20 turns it into a `recurrenceOverrides` entry instead, so "this occurrence" and "the whole series" are now two different things ihasmail asks about before acting. **Confirmed live on 0.16.20 (2026-08-31)** end to end against a five-week series: a legal patch landed on the override with `start` and `duration` filled in by the server; `useDefaultAlerts` was refused with *"This property cannot be modified on a single occurrence."*; a destroy removed one date and left the series; and a base event and one of its instances in the same request were refused together, both ids, with *"A base event and its instances cannot be modified in the same request."* The scope is chosen before the editor opens rather than on save, because it decides which event the form is about — one populated from the master shows the *series'* start date, so editing Wednesday would have offered to move Monday. Two entries below are the sharp edges this turned up. - Editable date boxes are always Gregorian and in Latin digits, even for locales whose *display* uses another calendar or numbering system (`fa-IR`, `th-TH`, `ar-EG`) — they keep the locale's field order and separator, but a Buddhist-era year in a text box does not round-trip against the Gregorian calendar grid. Non-Gregorian calendar support is not implemented. - The account locale is read from `x:AccountSettings/get`, whose permission the built-in user role has, falling back to `x:Account/get` (which needs the admin-only `sysAccountGet`). Both are Stalwart 0.16 methods: **on older servers neither is reachable** — they do not implement the registry and reject a request that so much as names the `urn:stalwart:jmap` capability — so there the locale still falls back to the browser's and can be chosen by hand. Confirmed live on 0.16.19 (2026-08-25), once the capability was looked for where Stalwart advertises it; a locale request that is merely refused no longer downgrades the detected generation. diff --git a/server/src/mock/index.ts b/server/src/mock/index.ts index a164e1b..5fda3a7 100644 --- a/server/src/mock/index.ts +++ b/server/src/mock/index.ts @@ -5,7 +5,7 @@ */ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { randomUUID } from "node:crypto"; -import { expandOccurrences, occurrenceAt, occurrenceView, parseSyntheticId, splitOccurrencePatch, syntheticId, type Occurrence } from "./recurrence.js"; +import { expandOccurrences, occurrenceAt, occurrenceView, parseSyntheticId, slotOfOccurrence, splitOccurrencePatch, syntheticId, type Occurrence } from "./recurrence.js"; import { parseOtpauthUrl, verifyTotp } from "../totp.js"; import { holdUntilOf, undoStatusOf } from "./futurerelease.js"; @@ -414,7 +414,7 @@ function resolveEvent(list: Obj[], id: string): { base: Obj; occ?: Occurrence } if (!parsed) return null; const base = list.find((x) => x.id === parsed.baseId); if (!base) return null; - const occ = occurrenceAt(base, parsed.index); + const occ = occurrenceAt(base, parsed.slot); return occ ? { base, occ } : null; } @@ -929,7 +929,7 @@ const handlers: Record = { const from = filter.after ? new Date(filter.after as string) : new Date(-8640000000000); const to = filter.before ? new Date(filter.before as string) : new Date(8640000000000); const ids: string[] = []; - for (const e of matching) for (const occ of expandOccurrences(e, from, to)) ids.push(syntheticId(e.id as string, occ.index)); + for (const e of matching) for (const occ of expandOccurrences(e, from, to)) ids.push(syntheticId(e.id as string, slotOfOccurrence(e, occ))); return { accountId: a.accountId ?? ACCOUNT, queryState: "1", canCalculateChanges: false, position: 0, ids, total: ids.length }; }, "CalendarEvent/get": (a) => { diff --git a/server/src/mock/recurrence.test.ts b/server/src/mock/recurrence.test.ts index b1bfcdf..0023f07 100644 --- a/server/src/mock/recurrence.test.ts +++ b/server/src/mock/recurrence.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { expandOccurrences, occurrenceAt, occurrenceView, parseSyntheticId, splitOccurrencePatch, syntheticId } from "./recurrence.js"; +import { expandOccurrences, occurrenceAt, occurrenceView, parseSyntheticId, slotOfOccurrence, splitOccurrencePatch, syntheticId } from "./recurrence.js"; /** * The mock expands recurrences so that per-occurrence editing can be developed @@ -44,18 +44,17 @@ describe("expandOccurrences", () => { assert.equal(expandOccurrences(ev, a, b).length, 3); }); - it("skips an excluded date but does not renumber the ones after it", () => { - // The whole reason an index rather than a position is the id: deleting - // Tuesday must not turn Wednesday's id into Tuesday's. + it("drops an excluded date from the expansion, keeping the series positions", () => { const ev = { ...series(), recurrenceOverrides: { "2026-09-08T09:00:00": { excluded: true } } }; const [a, b] = week("2026-09-07T00:00:00", "2026-09-14T00:00:00"); const out = expandOccurrences(ev, a, b); assert.deepEqual(out.map((o) => o.start), [ "2026-09-07T09:00:00", "2026-09-09T09:00:00", "2026-09-10T09:00:00", "2026-09-11T09:00:00", ]); - // Wednesday is still index 2, as it was before Tuesday went. + // The position within the series is unchanged — Wednesday is still the + // third date the rule produces, whatever happened to Tuesday. It is the + // *id* built on top of that which moves, and only after a write. assert.equal(out[1]!.index, 2); - assert.equal(occurrenceAt(ev, 2)!.start, "2026-09-09T09:00:00"); }); it("carries an override onto the occurrence it keys", () => { @@ -91,14 +90,17 @@ describe("occurrenceView", () => { it("lets an override win over the series", () => { const base = { ...series(), recurrenceOverrides: { "2026-09-08T09:00:00": { title: "Moved" } } }; - const view = occurrenceView(base, occurrenceAt(base, 1)!); + // Slot 2, not 1: one override has already shifted the numbering. Reaching + // for the id this occurrence had *before* the write is the bug below. + const view = occurrenceView(base, occurrenceAt(base, 2)!); + assert.equal(view.start, "2026-09-08T09:00:00"); assert.equal(view.title, "Moved"); }); }); describe("parseSyntheticId", () => { it("round-trips", () => { - assert.deepEqual(parseSyntheticId(syntheticId("ev1", 12)), { baseId: "ev1", index: 12 }); + assert.deepEqual(parseSyntheticId(syntheticId("ev1", 12)), { baseId: "ev1", slot: 12 }); }); it("does not claim a stored id", () => { assert.equal(parseSyntheticId("ev1"), null); @@ -131,3 +133,36 @@ describe("splitOccurrencePatch", () => { assert.deepEqual(splitOccurrencePatch({ "participants/me/calendarAddress": "mailto:x@y" }).applied, {}); }); }); + + +describe("synthetic ids are only true until the next write", () => { + /* + * Confirmed live on 0.16.20 (2026-08-31): writing one `recurrenceOverrides` + * entry renumbered a five-week series so that the *same* ids addressed + * different dates. Nothing was rejected. The mock reproduces the shape of + * that rather than the exact permutation, because the property that bites is + * not which date an id moves to but that it moves at all, silently. + */ + it("makes a cached id address a different date after an override is written", () => { + const before = series(); + const held = syntheticId("ev1", slotOfOccurrence(before, occurrenceAt(before, 3)!)); + const dateBefore = occurrenceAt(before, parseSyntheticId(held)!.slot)!.start; + + const after = { ...before, recurrenceOverrides: { "2026-09-07T09:00:00": { title: "changed" } } }; + const dateAfter = occurrenceAt(after, parseSyntheticId(held)!.slot)!.start; + + assert.notEqual(dateAfter, dateBefore); + // And crucially it still resolves — a stale id is wrong, not invalid, so a + // client that trusts it gets a confident answer about the wrong day. + assert.ok(dateAfter); + }); + + it("keeps recurrenceId meaning the same date across a write, which is why it is the handle", () => { + const before = series(); + const occ = occurrenceAt(before, 3)!; + const after = { ...before, recurrenceOverrides: { "2026-09-07T09:00:00": { title: "changed" } } }; + const same = expandOccurrences(after, new Date("2026-09-01T00:00:00"), new Date("2026-10-01T00:00:00")) + .find((o) => o.recurrenceId === occ.recurrenceId); + assert.equal(same!.start, occ.start); + }); +}); diff --git a/server/src/mock/recurrence.ts b/server/src/mock/recurrence.ts index 1d5fc57..2ce75c4 100644 --- a/server/src/mock/recurrence.ts +++ b/server/src/mock/recurrence.ts @@ -25,18 +25,41 @@ const MAX_ITERATIONS = 750; const DAYS = ["su", "mo", "tu", "we", "th", "fr", "sa"]; /** - * The id an occurrence is addressed by. + * The id an occurrence is addressed by, which is only true until the next write. * * Stalwart's are opaque; the mock's are parseable because it has to resolve - * them, and nothing in ihasmail may read either. The index counts from the - * start of the series and survives an excluded date, so an id keeps meaning the - * same occurrence after one of its neighbours is deleted. + * them, and nothing in ihasmail may read either. + * + * They are also deliberately **unstable**, because the real ones are. + * **Confirmed live on 0.16.20 (2026-08-31):** a synthetic id encodes a position + * in the expanded series, and writing a `recurrenceOverrides` entry adds a + * component that renumbers it. A five-week series held `e i m q u` over + * 03-01…03-29; after one override was written to 03-08 the same ids addressed + * 03-01, 03-15, 03-29, 03-08, 03-22. Nothing was rejected — they just meant + * different dates. + * + * That is the hazard worth reproducing, and note which way round it goes: a + * stale id is not *invalid*, it is *wrong*. A mock that expired them instead + * would hand back a loud `notFound` and let a client that caches ids look + * careful. So the numbering is shifted by the number of overrides — an + * arbitrary stand-in for Stalwart's renumbering, with the one property that + * matters: hold an id across a write and it silently addresses another date. */ -export const syntheticId = (baseId: string, index: number): string => `${baseId}-o${index}`; +export const syntheticId = (baseId: string, slot: number): string => `${baseId}-o${slot}`; -export function parseSyntheticId(id: string): { baseId: string; index: number } | null { +export function parseSyntheticId(id: string): { baseId: string; slot: number } | null { const m = /^(.+)-o(\d+)$/.exec(id); - return m ? { baseId: m[1]!, index: Number(m[2]) } : null; + return m ? { baseId: m[1]!, slot: Number(m[2]) } : null; +} + +/** How far the id numbering has been rotated away from the series order. */ +function rotation(base: Obj): number { + return Object.keys((base.recurrenceOverrides as Record | undefined) ?? {}).length; +} + +/** The id slot this occurrence currently answers to. */ +export function slotOfOccurrence(base: Obj, occ: Occurrence): number { + return occ.index + rotation(base); } /** `2026-08-31T09:00:00` — the naive local form the mock stores `start` in. */ @@ -81,8 +104,8 @@ export function expandOccurrences(base: Obj, from: Date, to: Date): Occurrence[] const emit = (index: number, at: Date): boolean => { const recurrenceId = localDateTime(at); const override = overrides[recurrenceId]; - // An excluded date still consumes its index: ids have to stay stable when a - // neighbour is deleted, or every occurrence after it silently renumbers. + // An excluded date is simply gone from the expansion. Its slot is not + // reserved -- see `syntheticId` for why nothing here pretends otherwise. if (override?.excluded === true) return true; if (at >= from && at < to) { out.push({ index, recurrenceId, start: recurrenceId, ...(override ? { override } : {}) }); @@ -141,7 +164,7 @@ export function occurrenceView(base: Obj, occ: Occurrence): Obj { const view: Obj = { ...base }; for (const k of SERIES_ONLY) delete view[k]; Object.assign(view, occ.override ?? {}); - view.id = syntheticId(base.id as string, occ.index); + view.id = syntheticId(base.id as string, slotOfOccurrence(base, occ)); view.baseEventId = base.id; view.start = occ.start; // Only a genuine instance of a series carries one. A one-off expanded into @@ -192,8 +215,10 @@ export function splitOccurrencePatch(patch: Obj): { rejected?: string; applied: return { applied }; } -/** One occurrence by its index, wherever in the series it falls. */ -export function occurrenceAt(base: Obj, index: number): Occurrence | null { +/** The occurrence a slot currently addresses — which is not a fixed thing. */ +export function occurrenceAt(base: Obj, slot: number): Occurrence | null { + const index = slot - rotation(base); + if (index < 0) return null; const all = expandOccurrences(base, new Date(-8640000000000), new Date(8640000000000)); return all.find((o) => o.index === index) ?? null; } diff --git a/web/src/store/__tests__/event-scope.test.ts b/web/src/store/__tests__/event-scope.test.ts index 27126f4..e2e0b22 100644 --- a/web/src/store/__tests__/event-scope.test.ts +++ b/web/src/store/__tests__/event-scope.test.ts @@ -38,11 +38,25 @@ const MASTER: CalendarEvent = { ...OCCURRENCE, id: "i", baseEventId: undefined, interface SetCall { update?: Record; destroy?: string[] } -function server() { +/** + * A server that renumbers, the way 0.16.20 does. + * + * `resolvesTo` is the id the occurrence answers to *now* — deliberately not the + * id the cached object carries, because that is exactly the situation a write + * to the series leaves behind. A store that sends the id it was handed rather + * than the one it looked up will send `iaaaaas` and these tests will say so. + */ +function server(opts: { resolvesTo?: string | null } = {}) { const calls: SetCall[] = []; + const resolved = opts.resolvesTo === undefined ? OCCURRENCE.id : opts.resolvesTo; const fetchMock = vi.fn(async (_url: string, init: RequestInit) => { const body = JSON.parse(init.body as string) as { methodCalls: [string, Record, string][] }; const methodResponses = body.methodCalls.map(([name, args, id]) => { + if (name === "CalendarEvent/get" && id === "g") { + // The re-resolution lookup: same recurrenceId, whatever id it wears now. + const list = resolved ? [{ ...OCCURRENCE, id: resolved }] : []; + return [name, { accountId: "a1", state: "1", list, notFound: [] }, id]; + } if (name === "CalendarEvent/set") { calls.push({ update: args.update as Record, destroy: args.destroy as string[] }); return [name, { @@ -115,10 +129,21 @@ describe("destroyEvent", () => { expect(calls[0]!.destroy).not.toContain("iaaaaas"); }); - it("sends the synthetic id for a single occurrence", async () => { - const calls = server(); + it("sends the id the occurrence answers to now, not the one it was handed", async () => { + // The live finding: writing one override renumbers the series, so an id + // cached a moment ago addresses a different date. `recurrenceId` is the + // stable handle, so the store looks the current id up by it. + const calls = server({ resolvesTo: "renumbered7" }); await useCalendar.getState().destroyEvent(OCCURRENCE, false, "occurrence"); - expect(calls[0]!.destroy).toEqual(["iaaaaas"]); + expect(calls[0]!.destroy).toEqual(["renumbered7"]); + expect(calls[0]!.destroy).not.toContain("iaaaaas"); + }); + + it("refuses rather than guessing when the date is no longer in the series", async () => { + const calls = server({ resolvesTo: null }); + await expect(useCalendar.getState().destroyEvent(OCCURRENCE, false, "occurrence")) + .rejects.toThrow(/no longer part of this series/i); + expect(calls).toEqual([]); }); it("drops the occurrence from the cache without evicting the master", async () => { @@ -137,10 +162,10 @@ describe("updateEvent", () => { expect(Object.keys(calls[0]!.update!)).toEqual(["i"]); }); - it("patches the instance for a single occurrence", async () => { - const calls = server(); + it("patches the id the occurrence answers to now", async () => { + const calls = server({ resolvesTo: "renumbered7" }); await useCalendar.getState().updateEvent(OCCURRENCE, { color: "#f00" }, false, "occurrence"); - expect(Object.keys(calls[0]!.update!)).toEqual(["iaaaaas"]); + expect(Object.keys(calls[0]!.update!)).toEqual(["renumbered7"]); }); }); diff --git a/web/src/store/calendar.ts b/web/src/store/calendar.ts index c5ec5c6..bb0a507 100644 --- a/web/src/store/calendar.ts +++ b/web/src/store/calendar.ts @@ -137,6 +137,48 @@ export function isThisAndFutureRefusal(err: unknown): boolean { return err instanceof CalendarSetError && /this-and-future/i.test(err.setError.description ?? ""); } +/** + * A synthetic id is only true until the next write, so an occurrence is + * re-resolved from its `recurrenceId` immediately before it is touched. + * + * **Confirmed live on 0.16.20 (2026-08-31.)** Stalwart's synthetic ids encode a + * position in the expanded series, and writing a `recurrenceOverrides` entry + * adds a component that renumbers it. A five-week series held ids `e i m q u` + * over 03-01…03-29; after one override was written to 03-08 the *same ids* + * addressed 03-01, 03-15, 03-29, 03-08, 03-22. Not one of them was rejected — + * `i` simply meant a week later than it had a moment before. + * + * So an id cached across a write silently points at a different date, and a + * delete aimed at one occurrence removes another. `recurrenceId` is the stable + * name for a slot in a series — it is the date itself — so that is what we hold + * and what we look the current id up by. + */ +async function currentOccurrenceId(accountId: Id, event: CalendarEvent): Promise { + const base = event.baseEventId; + const rid = event.recurrenceId; + // A one-off, or an object with nothing to re-resolve from: its own id is all + // there is, and there is no series for a write to have renumbered. + if (!base || !rid) return event.id; + + const around = new Date(rid); + if (Number.isNaN(around.getTime())) return event.id; + const from = new Date(around.getTime() - DAY_MS); + const to = new Date(around.getTime() + DAY_MS); + + const res = await client.chain([ + ["CalendarEvent/query", { accountId, filter: { after: toLocalDateTime(from), before: toLocalDateTime(to) }, expandRecurrences: true, limit: 200 }, "q"], + ["CalendarEvent/get", { accountId, "#ids": { resultOf: "q", name: "CalendarEvent/query", path: "/ids" }, properties: ["id", "baseEventId", "recurrenceId"] }, "g"], + ]); + const list = (res.get("g")?.[0] as unknown as GetResponse | undefined)?.list ?? []; + const found = list.find((e) => e.baseEventId === base && e.recurrenceId === rid); + if (!found) { + // The date is gone -- already excluded, or the series no longer reaches it. + // Better to say so than to act on an id that means something else now. + throw new Error("That occurrence is no longer part of this series. Reload the calendar and try again."); + } + return found.id; +} + export class OccurrenceScopeError extends Error { constructor(readonly property: string) { super(`"${property}" applies to the whole series and cannot be changed for one occurrence.`); @@ -488,7 +530,7 @@ export const useCalendar = create((set, get) => ({ async updateEvent(event, patch, sendInvites, scope) { const accountId = get().accountId!; - const id = eventIdForScope(event, scope); + const id = scope === "occurrence" ? await currentOccurrenceId(accountId, event) : eventIdForScope(event, scope); // An occurrence takes less than the series does, and says so about only // half of it. Narrow the patch here rather than posting it hopefully. const { patch: body, dropped } = scope === "occurrence" ? occurrencePatch(patch) : { patch, dropped: [] as string[] }; @@ -502,7 +544,7 @@ export const useCalendar = create((set, get) => ({ async destroyEvent(event, sendInvites, scope) { const accountId = get().accountId!; - const id = eventIdForScope(event, scope); + const id = scope === "occurrence" ? await currentOccurrenceId(accountId, event) : eventIdForScope(event, scope); const res = await client.call("CalendarEvent/set", { accountId, destroy: [id], sendSchedulingMessages: sendInvites }); const err = res.notDestroyed?.[id]; if (err) throw new CalendarSetError(err);