Files
DeepTutor/web/lib/optimistic-id.ts
Bingxi Zhao (Frank) 2faaef9ee8 fix(chat): mint unique optimistic message ids (#698)
An optimistic row's id was `-Date.now()`, and ADD_USER_MSG / STREAM_START
are dispatched back-to-back — so the user row and the assistant placeholder
routinely landed in the same millisecond and shared one id.

`reconcileTurnIds` keys its optimistic->persisted remap by id, so the two
rows collapsed onto a single persisted id when the turn's `done` arrived.
The next turn then pinned `parent_message_id` to the previous USER message
(an orphan branch server-side) and `buildVisiblePath` dropped the assistant
reply until a session reload put the DB's ids back.

Invisible until v1.5.4: the post-turn full-session refetch that 308a0606
replaced with in-place reconciliation used to overwrite the collision.

Mint ids from one seam that never repeats itself instead — same negative,
time-ordered shape the sibling ranking relies on.
2026-07-26 20:46:36 +08:00

28 lines
1.2 KiB
TypeScript

/**
* Client-minted ids for optimistic (not-yet-persisted) chat rows.
*
* Optimistic rows carry a NEGATIVE id until the turn's ``done`` event reports
* the persisted ones; ``lib/message-branches`` relies on that sign (a more
* negative id ranks as the newer sibling) and ``lib/turn-reconcile`` keys its
* optimistic→persisted remap by it.
*
* Keying by id is why plain ``-Date.now()`` was not enough: the user row and
* the assistant placeholder are dispatched back-to-back (``ADD_USER_MSG``
* then ``STREAM_START``), so they routinely landed in the same millisecond
* and shared one id. The remap then collapsed both rows onto a single
* persisted id, which pinned the next turn's ``parent_message_id`` to the
* previous USER message and dropped the assistant reply out of the visible
* path until a session reload (issue #698).
*
* So: keep the timestamp shape, but never return the same value twice —
* every call is strictly smaller than the last.
*/
let lastOptimisticId = 0;
export function nextOptimisticId(): number {
const stamp = -Date.now();
lastOptimisticId = stamp < lastOptimisticId ? stamp : lastOptimisticId - 1;
return lastOptimisticId;
}