Skip to content

feat(web): per-event write lane for calendar event mutations - #475

Merged
JeanMeijer merged 9 commits into
mainfrom
cursor/per-event-write-lane-dd97
Sep 18, 2026
Merged

JeanMeijer merged 9 commits into
mainfrom
cursor/per-event-write-lane-dd97

Conversation

@JeanMeijer

@JeanMeijer JeanMeijer commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Replaces the single-slot update/create/delete "queues" with a per-event serialized write lane, and makes the event form track the calendar again through a field-level merge.

Today the update machine holds one item; a START arriving while it is in mutate or a prompt state has no transition and is silently dropped, so "rename, then drag" loses whichever edit comes second while its optimistic overlay stays on screen. Optimistic update overlays are also never removed on success, and rapid edits send a stale client etag that both providers reject with 412.

Write lane

  • flows/write-lane.ts: one lane per event id shared by create, update and delete. While a request is in flight, later edits merge into a single pending patch (later field wins; start/end/allDay move as a unit) that is sent once the in-flight request returns. The lane keeps exactly one optimistic overlay per event (keyed by event id), writes the server response through to every events.list cache and Dexie, and only clears the overlay after the awaited refetch lands. It re-keys itself when a provider returns a new id (Microsoft create / copy-and-delete move), keeps an old→new alias map so edits queued behind a prompt under the old id still land, and updates selection, form baseline, caches and Dexie accordingly. On failure it toasts, keeps the server baseline for the failed fields, and still drains later pending writes.
  • Staged edits: edits waiting on a scope/notify prompt, and edits deferred into a dirty form, are staged in the lane per token rather than written into a shared preview overlay. The overlay projects baseline + sent + pending + staged; current(id) (used as the form baseline) projects lane-owned state only, shown(id) includes staged, busy(id) says whether the lane knows more than the stored copy (write in flight, queued, or settling). Dispatch hands the token to enqueue, cancel unstages it, Discard and full rehydration release deferred tokens, and the provider disposes all overlays and tokens on unmount. stage() toasts and returns undefined if the stored event cannot be read, and the action hooks stop there.
  • Race hardening: a create enqueued while a lane already exists for the id merges in as an update instead of creating twice; applyChanges keeps the target's id so a drag queued behind a re-key is sent under the new id; series writes report the edited occurrence back rather than the master; finish() is guarded by a per-lane generation and lane identity, and both enqueue and finish handle their own failures (toast, overlay reset) instead of leaving a permanent overlay; the existing-lane path in enqueue is synchronous so a settle resuming in the same tick cannot tear down a lane a new edit already holds.
  • update-queue.ts / create-queue.ts / delete-queue.ts: machines are now prompt-and-dispatch FIFOs; START is accepted in every state and queued, mutate/rollback states are gone. Create prompts support onCancel like update; cancelling a create prompt puts the draft overlay back. The prompt dialogs use plain Buttons for the choices: a Radix AlertDialogAction closes the dialog itself and its onOpenChange(false) sent CANCEL into the next queued item.
  • use-update-action.tsx: replace-saves compute changedFields(event, previous) against the form snapshot so remote edits are never re-emitted; partial edits pass their changes through untouched, keep the lane's current id, and patch a dirty form from the lane's shown event after staging so two edits arriving together both survive. useUpdateAction reports whether the save was staged; deferred previews are only released when it was.
  • use-event-mutations.ts: bare mutations; the lane owns optimistic state, rollback and the (single, awaited) list invalidation.
  • Providers: Google update uses only the etag from its own GET as If-Match and retries once on 412 (re-GET + reapply the sparse patch). Microsoft retries once on 412 ErrorIrresolvableConflict, re-resolving the recurrence anchor (in case the master moved) and keeping the accept/decline action outside the retry so it is never re-sent. etag is removed from patchEventInputSchema and the payload builders.
  • lib/interfaces.ts: EventChanges is a mapped type written directly over the CalendarEvent union. Partial<CalendarEvent> is not equivalent: Partial is homomorphic over a type parameter and distributes over the union, so a start/allDay/calendar whose arm is not statically known is rejected (this is why two @ts-expect-error directives in the drag code became unnecessary).

Form

  • live-update.tsx follows formAtom.event.id (not the machine state) and takes the lane-owned event (lane.current) only while the lane is busy, else the Dexie row, so the form sees a queued drag/RSVP immediately, stays live after a save, never adopts a staged-only edit as its baseline, and still merges remote changes while an edit is deferred.
  • use-event-form.ts: a pristine form (or a different event) rehydrates with form.reset(values); a dirty form on the same event advances its diff baseline to the incoming event and fills only fields whose TanStack meta is not dirty (setFieldValue(..., { dontUpdateMeta: true })), always taking id/type, so the user's edits win on the next save and a drag made while typing is no longer reverted. The last hydrated event is tracked by ref so a provider re-key (which writes the returned event into the atom first) does not skip hydration. Save success resyncs through LOAD saved instead of CONFIRMED, which also stops server-normalized fields (conference, attendee status) from being re-emitted on every save.
  • Deferred calendar edits (pendingFieldPatchAtom) carry { values, keys } plus their stage tokens (deferredStageTokensAtom) and no longer rewrite the reset baseline; useDiscardAction resets the form, clears the patch, releases the staged edits and marks pristine; cancelling a scope/notify prompt on a form save (create or update) discards the form instead of re-prompting on the next blur.
  • useSaveAction builds the event on top of the snapshot so untouched fields (color, metadata) are not emitted as cleared.
  • Drags/resizes anchor on the displayed item instead of the frozen form snapshot (use-draggable-event-actions.ts, draggable-month-event.tsx); getEventInForm is gone.
  • event-form-state.ts: CONFIRMED removed; the machine stays in loading for the shown event.

Type of Change

  • Bug fix
  • Refactor / Cleanup

Related Areas

  • Calendar UI
  • Data/API

Testing

  • bun run type-check for apps/web, packages/providers, packages/schemas, packages/api; bun run lint 0 errors; oxfmt --check clean on all touched files.
  • Throwaway bun test suites (not committed) against the lane, the machines, a real TanStack FormApi, the real hooks and the real Radix prompt dialog in JSDOM with mocked lane deps, and a stubbed Microsoft client: 34 + 15 + 1 passing. Coverage includes rename + two drags in flight coalescing to 2 requests; failed write keeps the baseline and still sends the pending write; update during an in-flight create waits and follows the new id; writes queued under the old id resolve through the alias; a second save during an in-flight create becomes an update; a drag queued behind a re-key is sent under the new id; a series save reports the occurrence back; older/stale settles cannot tear down a lane a newer write or a re-created lane owns; an enqueue in the tick a settle resolves keeps one lane; cancelling one prompt keeps another queued edit's preview; choosing in the real prompt dialog does not cancel the next queued item; cancelling a create prompt restores the draft overlay; two deferred edits compound, including two arriving before either staged; a deferred drag never advances the form baseline and is emitted on save; a staged-only lane is not busy so remote changes still reach the form; a failing Dexie read toasts instead of rejecting; a save that could not be staged keeps its deferred previews; a re-keyed create still hydrates the form; dirty fields survive a merge while untouched fields follow the incoming event; reset() after a deferred patch returns to the baseline; the Microsoft 412 retry re-resolves the recurrence anchor and runs the RSVP action once. Each race/regression test was also run against the pre-fix code to confirm it fails there.
  • Manual testing performed — requires a signed-in Google/Microsoft account in the browser, which the agent environment does not have.

Notes

Per the confirmed plan: no timer debounce, no new sync/push mechanism, and no per-provider event field split in this pass.

By submitting, I confirm I understand and stand behind this code. If AI was used, I've reviewed and verified everything myself.

Open in Web Open in Cursor 

Summary by cubic

Replaces the single-slot create/update/delete queues with a per-event write lane so rapid edits serialize and coalesce instead of being dropped or rejected with stale etags, and keeps the form live against the event it shows so a drag made while typing is no longer reverted by the next save.

Write lane

  • Edits arriving mid-flight merge into one pending patch; one optimistic overlay per event is written through to the events.list cache and Dexie and cleared only after the awaited refetch.
  • Prompt and deferred edits stage per token, so cancelling one prompt doesn't drop another queued edit's preview; cancelling a create prompt restores the draft overlay so the draft stays visible.
  • The overlay projects baseline + sent + pending + staged while the form baseline only follows lane-owned state; LiveUpdateProvider takes the lane's view only while busy, so staged-only edits never hide remote changes.
  • The lane re-keys on a new provider id and is race-safe: a save during an in-flight create merges in as an update, series writes report the edited occurrence, and an older settle can't clear a lane a newer write owns.
  • The three queue machines are prompt-and-dispatch FIFOs; Google sends only the etag from its own GET as If-Match and retries once on 412, Microsoft drops ifMatch and retries just the sparse PATCH once on 412 — re-resolving the recurrence anchor — so the RSVP action isn't re-sent.

Form

  • A pristine form rehydrates from the stored copy; a dirty form advances its baseline and fills only unedited fields, so a drag made while typing survives the next save.
  • Replace-saves diff against the form snapshot via changedFields so remote edits are never re-emitted; EventChanges is a non-distributing mapped type.

Written for commit 304b7ea. Summary will update on new commits.

Review in cubic

cursoragent and others added 3 commits September 18, 2026 09:35
…ite lane

Replace the single-slot update/create/delete machines with prompt-and-dispatch
FIFOs that hand off to a per-event write lane. The lane merges edits that
arrive while a request is in flight into one pending patch, keeps a single
optimistic overlay per event, writes the server response through to the
query cache and Dexie, and only clears the overlay once the list refetch has
landed. It also re-keys itself when a provider hands back a new event id.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
…lient etags

Google's update already reads the event before the full PUT, so the If-Match
from that read is the only precondition that matters; the client etag rejected
every edit that followed another. Microsoft's PATCH is sparse and therefore a
rebase by construction. Both retry the write once on 412 and the patch schema
drops the etag field.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
… overlay

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
@vercel

vercel Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
analog Ready Ready Preview Sep 18, 2026 3:39pm UTC

Request Review

…live after saves

The form now follows the event it shows from both the lane overlay and the
stored copy. A pristine form rehydrates; a dirty form advances its baseline
and fills only the fields the user has not edited, so a drag made while
typing no longer gets reverted by the next save and server-normalized fields
(conference, attendee status) stop being re-emitted. Saves resync through
LOAD instead of CONFIRMED, deferred edits no longer rewrite the reset
baseline so Discard reverts them, cancelling a prompt on a form save discards
the form, saves build on the snapshot so untouched fields are not cleared,
drags anchor on the displayed item, and the lane resolves re-keyed ids.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 issues found across 27 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/web/src/components/calendar/flows/delete-event/delete-queue.ts">

<violation number="1" location="apps/web/src/components/calendar/flows/delete-event/delete-queue.ts:29">
P2: When `lane.enqueue` fails before `drain` starts, this `void` dispatch contract drops the rejection, so the optimistic delete can remain indefinitely without an error toast. Return and handle the promise, or catch this startup failure and restore the overlay.</violation>
</file>

<file name="apps/web/src/components/event-form/utils/use-event-form.ts">

<violation number="1" location="apps/web/src/components/event-form/utils/use-event-form.ts:160">
P1: When an occurrence is saved with series scope, `saved` is the recurring master, so this LOAD replaces the shown occurrence with the master. Load the lane's displayed occurrence, or skip the master response, instead of treating every provider response as the form event.</violation>
</file>

<file name="apps/web/src/components/event-form/utils/use-update-form-state.ts">

<violation number="1" location="apps/web/src/components/event-form/utils/use-update-form-state.ts:87">
P2: When a lane already has a write in flight, rapid deferred edits can apply stale values to earlier keys and revert the first edit. Preserve previous pending values for keys absent from the newest `changes`, or read the optimistic overlay when accumulating the patch.</violation>
</file>

<file name="apps/web/src/lib/interfaces.ts">

<violation number="1" location="apps/web/src/lib/interfaces.ts:15">
P3: The comment misstates why `EventChanges` is written as an explicit mapped type: it claims `Partial<CalendarEvent>` would "distribute per provider/time arm" and reject a `start`/`calendar` whose arm is unknown statically. `Partial<T>` is itself `{ [K in keyof T]?: T[K] }` and — like the written form — does not distribute over unions; only conditional types distribute. Both forms produce the identical type over `CalendarEvent<EventTime>`, so `Partial<CalendarEvent>` would work exactly the same here. The comment gives future readers a wrong mental model of when to reach for the explicit form; either use `Partial<CalendarEvent>` directly or reword the note so the decision principle is accurate.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

// Resync from the server copy: a pristine form rehydrates, a dirty
// one merges its untouched fields (see the hydration effect).
if (saved) {
actorRef.send({ type: "LOAD", item: saved });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When an occurrence is saved with series scope, saved is the recurring master, so this LOAD replaces the shown occurrence with the master. Load the lane's displayed occurrence, or skip the master response, instead of treating every provider response as the form event.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/event-form/utils/use-event-form.ts, line 160:

<comment>When an occurrence is saved with series scope, `saved` is the recurring master, so this LOAD replaces the shown occurrence with the master. Load the lane's displayed occurrence, or skip the master response, instead of treating every provider response as the form event.</comment>

<file context>
@@ -120,15 +144,24 @@ export function useEventForm() {
+          // Resync from the server copy: a pristine form rehydrates, a dirty
+          // one merges its untouched fields (see the hydration effect).
+          if (saved) {
+            actorRef.send({ type: "LOAD", item: saved });
+          }
+        },
</file context>


export type DeleteEvent = (item: DeleteQueueItem) => Promise<unknown>;
export type RemoveOptimisticAction = (optimisticId: string) => void;
export type Dispatch = (item: DeleteQueueItem) => void;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When lane.enqueue fails before drain starts, this void dispatch contract drops the rejection, so the optimistic delete can remain indefinitely without an error toast. Return and handle the promise, or catch this startup failure and restore the overlay.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/calendar/flows/delete-event/delete-queue.ts, line 29:

<comment>When `lane.enqueue` fails before `drain` starts, this `void` dispatch contract drops the rejection, so the optimistic delete can remain indefinitely without an error toast. Return and handle the promise, or catch this startup failure and restore the overlay.</comment>

<file context>
@@ -27,8 +26,8 @@ export function hasAttendees(event: CalendarEvent) {
 
-export type DeleteEvent = (item: DeleteQueueItem) => Promise<unknown>;
-export type RemoveOptimisticAction = (optimisticId: string) => void;
+export type Dispatch = (item: DeleteQueueItem) => void;
+export type CancelItem = (item: DeleteQueueItem) => void;
 
</file context>

Comment on lines +87 to +89
setPendingFieldPatch((prev) =>
prev ? { values, keys: [...prev.keys, ...keys] } : { values, keys },
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When a lane already has a write in flight, rapid deferred edits can apply stale values to earlier keys and revert the first edit. Preserve previous pending values for keys absent from the newest changes, or read the optimistic overlay when accumulating the patch.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/event-form/utils/use-update-form-state.ts, line 87:

<comment>When a lane already has a write in flight, rapid deferred edits can apply stale values to earlier keys and revert the first edit. Preserve previous pending values for keys absent from the newest `changes`, or read the optimistic overlay when accumulating the patch.</comment>

<file context>
@@ -56,61 +68,26 @@ const patchableFields: FormPatchKey[] = [
+
+      // `event` already carries every earlier deferred change, so its values
+      // are current for the accumulated keys too.
+      setPendingFieldPatch((prev) =>
+        prev ? { values, keys: [...prev.keys, ...keys] } : { values, keys },
+      );
</file context>
Suggested change
setPendingFieldPatch((prev) =>
prev ? { values, keys: [...prev.keys, ...keys] } : { values, keys },
);
setPendingFieldPatch((prev) => {
if (!prev) {
return { values, keys };
}
const preserved = Object.fromEntries(
prev.keys
.filter((key) => !keys.includes(key))
.map((key) => [key, prev.values[key]]),
);
return {
values: { ...values, ...preserved },
keys: [...new Set([...prev.keys, ...keys])],
};
});

// A sparse set of event fields to merge onto an event. Mapped over the union
// directly (not via Partial) so it does not distribute per provider/time arm,
// which would reject a `start` or `calendar` whose arm is unknown statically.
export type EventChanges = { [K in keyof CalendarEvent]?: CalendarEvent[K] };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The comment misstates why EventChanges is written as an explicit mapped type: it claims Partial<CalendarEvent> would "distribute per provider/time arm" and reject a start/calendar whose arm is unknown statically. Partial<T> is itself { [K in keyof T]?: T[K] } and — like the written form — does not distribute over unions; only conditional types distribute. Both forms produce the identical type over CalendarEvent<EventTime>, so Partial<CalendarEvent> would work exactly the same here. The comment gives future readers a wrong mental model of when to reach for the explicit form; either use Partial<CalendarEvent> directly or reword the note so the decision principle is accurate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/lib/interfaces.ts, line 15:

<comment>The comment misstates why `EventChanges` is written as an explicit mapped type: it claims `Partial<CalendarEvent>` would "distribute per provider/time arm" and reject a `start`/`calendar` whose arm is unknown statically. `Partial<T>` is itself `{ [K in keyof T]?: T[K] }` and — like the written form — does not distribute over unions; only conditional types distribute. Both forms produce the identical type over `CalendarEvent<EventTime>`, so `Partial<CalendarEvent>` would work exactly the same here. The comment gives future readers a wrong mental model of when to reach for the explicit form; either use `Partial<CalendarEvent>` directly or reword the note so the decision principle is accurate.</comment>

<file context>
@@ -9,4 +9,9 @@ export type DraftEvent = Partial<CalendarEvent> &
+// A sparse set of event fields to merge onto an event. Mapped over the union
+// directly (not via Partial) so it does not distribute per provider/time arm,
+// which would reject a `start` or `calendar` whose arm is unknown statically.
+export type EventChanges = { [K in keyof CalendarEvent]?: CalendarEvent[K] };
+
 export type { Calendar, Attendee, CalendarEvent };
</file context>

…s, and settle

A save issued while the create is still in flight merges into that lane as
an update instead of creating the event twice. Partial changes can no longer
carry a stale id over a re-keyed baseline. Series writes report the edited
occurrence back to the form rather than the master. finish() is guarded by a
per-lane generation and lane identity so an older settle cannot clear the
overlay or delete a lane that a newer write (or a re-created lane) owns.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 1 file (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

cursoragent and others added 2 commits September 18, 2026 14:19
…ction

The 412 retry wrapped the whole update, so a conflict raised after a
successful PATCH re-ran the PATCH and re-sent the accept/decline action,
which can notify attendees twice. The retry now covers just the sparse
PATCH, which is the only step the rebase rationale applies to.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
…shared preview overlay

Prompting and deferred edits used to overwrite the single overlay slot with
a full event, so cancelling one prompt dropped another queued edit's
preview, two deferred edits reverted each other, and LiveUpdateProvider
could read a deferred drag as the form baseline and silently drop it from
the next save. The lane now holds staged changes per token: the overlay
projects baseline + sent + pending + staged, while the form baseline only
follows lane-owned state. Machine items carry their token; dispatch hands
it to the lane, cancel unstages it, and create prompts get an onCancel.

Also: enqueue and finish handle their own failures instead of leaving a
permanent overlay, the existing-lane path in enqueue is synchronous so a
resumed settle cannot tear down a lane a new edit already holds, the form
tracks the last hydrated event by ref so a re-key does not skip hydration,
and partial edits keep the lane's current id.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 16 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/web/src/components/calendar/flows/write-lane.ts">

<violation number="1" location="apps/web/src/components/calendar/flows/write-lane.ts:292">
P2: When two staging requests for a draft-only event overlap, this fallback can register a second lane and overwrite the first one. The first request's token can then no longer be unstaged or taken, leaving stale preview state; reuse `lanes.get(resolve(eventId))` before registering.</violation>
</file>

<file name="apps/web/src/components/calendar/flows/create-event/create-queue-provider.tsx">

<violation number="1" location="apps/web/src/components/calendar/flows/create-event/create-queue-provider.tsx:35">
P1: When two attendee-bearing creates are queued, accepting the first save can cancel the second. `AlertDialogAction` closes the dialog and its `onOpenChange(false)` sends `CANCEL` after the machine has advanced to the next item, so this callback unstages and discards that next create; distinguish an explicit discard from the action's automatic close before invoking `onCancel`.</violation>
</file>

<file name="apps/web/src/components/calendar/flows/update-event/use-update-action.tsx">

<violation number="1" location="apps/web/src/components/calendar/flows/update-event/use-update-action.tsx:98">
P2: When a partial edit is deferred into a dirty form, its staged token is only ever released by releaseDeferredEdits, which is wired to form save, discard, and full rehydration of that form. If the form is dismissed by any other path (close/navigation) without save or discard, the token stays in deferredStageTokensAtom and the lane keeps the staged edit alive: the calendar keeps showing an edit that represents nothing, and the token accumulates for the event's lifetime. Consider a single release path on form teardown.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

},
cancel: (item) => {
lane.unstage(item.token);
item.onCancel?.();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When two attendee-bearing creates are queued, accepting the first save can cancel the second. AlertDialogAction closes the dialog and its onOpenChange(false) sends CANCEL after the machine has advanced to the next item, so this callback unstages and discards that next create; distinguish an explicit discard from the action's automatic close before invoking onCancel.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/calendar/flows/create-event/create-queue-provider.tsx, line 35:

<comment>When two attendee-bearing creates are queued, accepting the first save can cancel the second. `AlertDialogAction` closes the dialog and its `onOpenChange(false)` sends `CANCEL` after the machine has advanced to the next item, so this callback unstages and discards that next create; distinguish an explicit discard from the action's automatic close before invoking `onCancel`.</comment>

<file context>
@@ -27,10 +27,12 @@ export function CreateQueueProvider({ children }: CreateQueueProviderProps) {
         cancel: (item) => {
-          lane.restoreOverlay(item.event.id);
+          lane.unstage(item.token);
+          item.onCancel?.();
         },
       }),
</file context>

const lane =
lanes.get(resolve(eventId)) ??
(await laneFor(eventId)) ??
register(resolve(eventId), undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When two staging requests for a draft-only event overlap, this fallback can register a second lane and overwrite the first one. The first request's token can then no longer be unstaged or taken, leaving stale preview state; reuse lanes.get(resolve(eventId)) before registering.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/calendar/flows/write-lane.ts, line 292:

<comment>When two staging requests for a draft-only event overlap, this fallback can register a second lane and overwrite the first one. The first request's token can then no longer be unstaged or taken, leaving stale preview state; reuse `lanes.get(resolve(eventId))` before registering.</comment>

<file context>
@@ -236,17 +282,37 @@ export function createWriteLane(initialDeps: WriteLaneDeps): WriteLane {
+    const lane =
+      lanes.get(resolve(eventId)) ??
+      (await laneFor(eventId)) ??
+      register(resolve(eventId), undefined);
+    const token: StageToken = { id: lane.id };
 
</file context>

return;
}

const token = await lane.stage(event.id, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When a partial edit is deferred into a dirty form, its staged token is only ever released by releaseDeferredEdits, which is wired to form save, discard, and full rehydration of that form. If the form is dismissed by any other path (close/navigation) without save or discard, the token stays in deferredStageTokensAtom and the lane keeps the staged edit alive: the calendar keeps showing an edit that represents nothing, and the token accumulates for the event's lifetime. Consider a single release path on form teardown.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/components/calendar/flows/update-event/use-update-action.tsx, line 98:

<comment>When a partial edit is deferred into a dirty form, its staged token is only ever released by releaseDeferredEdits, which is wired to form save, discard, and full rehydration of that form. If the form is dismissed by any other path (close/navigation) without save or discard, the token stays in deferredStageTokensAtom and the lane keeps the staged edit alive: the calendar keeps showing an edit that represents nothing, and the token accumulates for the event's lifetime. Consider a single release path on form teardown.</comment>

<file context>
@@ -91,20 +95,24 @@ export function usePartialUpdateAction() {
       }
 
-      lane.preview(event);
+      const token = await lane.stage(event.id, {
+        kind: "update",
+        changes: req.changes,
</file context>

cursoragent and others added 2 commits September 18, 2026 15:38
…osoft PATCH on 412

If the series master moved under a recurrence-only patch, resending the
same body carried the stale range.startDate. The retry now runs the
resolution again; the RSVP action stays outside it.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
… and unmount

- Prompt choice buttons are plain Buttons: a Radix AlertDialogAction closes
  the dialog itself and its onOpenChange(false) sent CANCEL into the next
  queued item.
- Cancelling a create prompt puts the draft overlay back so the draft stays
  visible while the form still holds it.
- Deferred edits are patched into the form from the lane's shown event
  after staging, so two edits arriving together both survive.
- LiveUpdateProvider only takes the lane's view while it is busy (write in
  flight, queued, or settling); a staged-only lane no longer hides remote
  changes.
- stage() toasts and returns undefined when the stored event cannot be
  read; the action hooks stop instead of rejecting unhandled.
- Deferred previews are released only when the save was actually staged.
- The lane provider disposes overlays and deferred tokens on unmount.

Co-authored-by: Jean P.D. Meijer <JeanMeijer@users.noreply.github.com>
@JeanMeijer
JeanMeijer merged commit 5e2b1bd into main Sep 18, 2026
6 checks passed
@JeanMeijer
JeanMeijer deleted the cursor/per-event-write-lane-dd97 branch September 18, 2026 15:41

This branch was successfully deployed

1 active deployment
Preview — 304b7ea4 Deployed Sep 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants