morethanwords/tweb/master • 5052955 • 1 files, +114/-51
Fix the stories store losing track of its current story
Clicking a story in the sidebar list threw before the viewer could open:
`actions.set` looked the clicked peer up with `indexOf`, and on a miss wrote the
resulting -1 straight into `index`, so `state.peer` read undefined and the
`checkForNearestSkipped` prefetch dereferenced it. That prefetch is an
optimization — it must never be able to break opening a story. It bails on a
missing peer now, `set` falls back to looking the peer up by id, and every
writer of `index` clamps into the list instead of parking it out of bounds
(`deletePeer` used to leave it past the end, `addPeers` could write -1).
What put a peer out of the list in the first place was `addPeers`: it built a
peerId-to-index map once, then spliced the array inside the loop. From the
second peer of a batch on, those positions were stale, so `peers[idx] = peer`
overwrote an unrelated entry — a reordering update over `[p1, p2, p3]` yields
`[1, 1, 2]`, p3 gone and p1 duplicated. The position is looked up per iteration
now.
Two more things that were quietly not working:
`load()` never paginated. `loadPromise` is assigned synchronously, so the
recursive call inside `.then` hit the in-flight guard and got handed the very
promise it was called from — one page, always, and `loaded` stuck at false. It
forces the next page now, only the latest run may clear the guard, and a server
that keeps `has_more` on an unchanged state no longer spins us on one page.
`getNearestStories` fed only the peer index back into `getNearestStory`, which
re-derives the story index from the store — so all three prefetch iterations
returned the same story. It passes the story index it reached along now.
Also: `onStoryNew` sized its index shift against `state.peer` (a different peer
than the one it was inserting into) and `onStoryDeleted` decremented on
`index >= storyIndex`, producing -1 when both were 0. Both go through one
`shiftStoryIndex` helper. Album snapshots take a generation guard so a slow
reply for an abandoned album can't clobber the current one, async callbacks and
the story timer stop at disposal, and `freezedSorting` / `changeTimeout` move
out of the store — a `Set` is not wrappable and a timer id has no business
notifying subscribers.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
#webk
Post #20530
135
- 🫡 4