mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[PR #4719] [MERGED] fix(client): bound the chat-message infinite-query refetch amplifier #6476
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#6476
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/4719
Author: @kolacheee
Created: 8/7/2026
Status: ✅ Merged
Merged: 8/7/2026
Merged by: @kolacheee
Base:
staging← Head:fix/4703-messages-refetch-amplifier📝 Commits (3)
59749cdfix(client): bound the chat-message infinite-query refetch amplifierc336f57Merge branch 'staging' into fix/4703-messages-refetch-amplifier31f731ffix(client): close the unmount race in the coalesced message refresh and resolve react-query via the client workspace in the regression📊 Changes
7 files changed (+494 additions, -14 deletions)
View changed files
📝
package.json(+1 -1)📝
packages/client/src/components/chat/ChatArea.tsx(+7 -0)📝
packages/client/src/components/chat/HomeProfessorMariChat.tsx(+5 -1)📝
packages/client/src/hooks/use-chats.ts(+7 -0)📝
packages/client/src/hooks/use-generate.ts(+61 -12)➕
packages/client/src/lib/message-page-cache.ts(+136 -0)➕
scripts/regressions/message-page-cache.regression.ts(+277 -0)📄 Description
Linked issue
Related to #4703 — deliberately not
Closes: the reporter's specific loop was traced (via their HAR) to a third-party personal extension sweeping every chat's messages continuously; see https://github.com/Pasta-Devs/Marinara-Engine/issues/4703#issuecomment-5219132238. This PR fixes the engine-side refetch-amplification class found while investigating that report — real, reproducible cases where Marinara itself re-downloads message pages far more than needed.Why this change
What changed
packages/client/src/lib/message-page-cache.ts(pure, React-free, regression-testable):trimMessagePagesToNewest/trimInactiveMessagePageCaches— when the user switches chats, chats that no longer have any mounted observer get their message page cache trimmed to the newest 3 pages. Trimming always drops from the old end (this query paginates backward in time —pages[0]is the newest chunk), so the retained window stays a suffix of the chat: absolute message numbering and/gotostay exact, and "Load More" simply re-fetches the dropped history from the oldest retained cursor on demand. The trim preservesdataUpdatedAtso the trimmed cache doesn't masquerade as fresh and suppress the remount refetch.shouldRefetchMessagesOnReconnect— reconnect refetch policy: allowed at ≤1 loaded page (keeps the cheap freshness signal), suppressed for deeper caches (the amplifier). Deep caches still resync via the stale-gatedrefetchOnMount, the post-generation refresh, and the existing explicit invalidations.createLeadingTrailingCoalescer— folds concurrent authoritative refreshes per chat into at most two runs (one in-flight + one trailing), while guaranteeing every caller a refetch that started at or after its own call. Today, overlapping refreshes silently cancel each other (refetchQueriesdefaultscancelRefetch: true), so a burst of completing turns aborts partially-completed page drains and restarts them from page 0.useChatMessages(use-chats.ts):refetchOnReconnectnow uses the function form gated on page depth (React Query evaluates it per reconnect event, still stale-gated first).refreshMessagesAuthoritatively(use-generate.ts): post-generation refreshes are now per-chat coalesced and scoped totype: 'active'. When the chat is not on screen (background/autonomous generation, user navigated away), it spends zero requests now and instead marks the query stale (refetchType: 'none'), so the next mount refetches deterministically — this is what previously re-drained the full page history of a chat nobody was looking at, once per completed turn. The persisted-rows fallback (upsertPersistedMessages) still converges the cache immediately in that case.HomeProfessorMariChat.tsx:invalidateWorkspaceDatano longer passesrefetchType: 'all'to its cache-wideinvalidateQueries. Every query is still marked stale, but only mounted queries refetch immediately; everything else refreshes on its next mount. With'all', every chat opened during the session re-drained its full message page history concurrently on each Mari workspace change — the single largest multiplier in the report.scripts/regressions/message-page-cache.regression.ts(wired intoregression:issues): pins the trim direction (newest page andpageParams[0] === undefinedalways survive; pages/pageParams trimmed in lockstep; idempotent), the reconnect depth gate, the query-key matcher, thedataUpdatedAtpreservation, and the coalescer's concurrency contract (5 concurrent callers → exactly 2 runs; third-wave callers queue instead of orphaning the entry; a rejected leader doesn't wedge the queue; keys are independent).Design notes for reviewers: a plain
maxPageson the infinite query was considered first and rejected — React Query'saddToEndevictspages[0], which for this backward-paginated query is the newest page, and with nogetPreviousPageParamthe evicted page is unrecoverable for the life of the cache entry (a later refetch restarts frompageParams[0], which after eviction is a real cursor rather thanundefined). It would also shift the absolute message numbering thatmessageOffset//gotoderive from a suffix-anchored window. The inactive-chat trim achieves the same bound without either hazard. Likewise, a flatrefetchOnReconnect: falsewas rejected because window-focus refetch is globally disabled in this app — shallow caches keep the reconnect resync so a 1-page chat left open still picks up changes.An adversarial review pass against the installed
@tanstack/query-core@5.100.9source caught three defects in the first cut of this change, all fixed and covered here:setQueryDatadispatches asuccessstate transition even when the updater returns the identical object, which clearsisInvalidated— so the stale-mark the inactive path depends on was being erased by the persisted-row upsert and the edit-overlay pass inside the same function. The mark is now set last, after all cache writes, whenever no refetch ran.QueryClient, not a stub.fetchEvenIfInactive: true, restoring the pre-change fetch for that rare path — bounded by the trim to at most a few pages.Validation
pnpm checkpasses locallyCONTRIBUTING.mdManual verification notes
Verified against the production build (
node packages/server/dist/index.js) with a 130-message chat (7 pages at the default 20/page) and a mock OpenAI-compatible endpoint, using afetch-wrapper request counter:offline/online) on the deep chat: 0 message requests (previously 7 per flap). Same flap on a stale 1-page chat: exactly 1 request — the freshness path is preserved.staleTimewindow stamped by the completion's cache writes → a 3-page remount drain fires (only the re-asserted stale-mark can trigger it at that point) and both the user message and the reply are present. The pre-fix build demonstrably skipped this refetch (empirically probed against the installed query-core during review).recentMessageContentEditsoverlay applies across the new path).Still to verify manually in a real browser (contributor to-do):
Docs and release impact
docs-i18nbranch updated to match, or a[docs-i18n]follow-up issue opened (see CONTRIBUTING.md § Translated documentation)Summary by CodeRabbit
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.