From f4cfc0116715484a5c169b51da3ace5e421fbc48 Mon Sep 17 00:00:00 2001 From: cassi Date: Wed, 25 Nov 2026 23:09:49 +0300 Subject: [PATCH 01/20] wip: hydrate sidebar previews on catalog accept with bounded network fallback (#860) Seed the row-preview pumps from every catalog accept (streams, topics, background inbox catalogs) and add a bounded, retryable network stage for disk misses with fence + owner guards and best-effort disk fill. New case sidebarCatalogHydratesPreviewsBeforeFirstProjection is green (RED pre-fix: no lookups before first projection). Sidebar binary: 135 pass, 2 regressions to resolve next round: sidebarPreviewsHydrateFromTheCacheAsynchronously (negative memo vs late cache fill) and crossRouteWarmYieldsWhileForeground LoadIsInFlight (traffic pin). --- packages/native/src/native-controller.cpp | 148 +++++++++++++++++- packages/native/src/native-controller.h | 17 ++ .../tests/native-controller-sidebar-test.cpp | 91 +++++++++++ 3 files changed, 255 insertions(+), 1 deletion(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 6dc0fc414..4a98f1275 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -7194,6 +7194,10 @@ void NativeController::closeCache() // Row-preview lookups belong to the discarded lease, not to whatever opens next. m_rowPreviewPending.clear(); m_rowPreviewInFlight.clear(); + // #860: the network stage belongs to the discarded session too. + m_rowPreviewNetPending.clear(); + m_rowPreviewNetInFlight.clear(); + m_rowPreviewNetRetries.clear(); const auto lease = m_cacheLease; m_cacheLease = {}; if (m_cache && m_cache->lease().owner == lease.owner @@ -9490,6 +9494,8 @@ void NativeController::hydrateInboxStream(const QString &streamUuid) topics.append(it.value()); } m_inboxTopics.insert(streamUuid, topics); + // #860: a background (inactive-stream) catalog accept is still a catalog accept. + seedRowPreviewHydrationFromCatalog(); if (authoritative) m_inboxStaleTopics.remove(streamUuid); else m_inboxStaleTopics.insert(streamUuid); // Issue #729 phase 2: a newly hydrated unread catalog is a batch of @@ -12916,6 +12922,10 @@ void NativeController::reset() m_preparedSwapActive = false; if (m_topicPreloadTimer) m_topicPreloadTimer->stop(); m_rowPreviewInFlight.clear(); + // #860: drop network-stage bookkeeping with the rest of the preview state. + m_rowPreviewNetPending.clear(); + m_rowPreviewNetInFlight.clear(); + m_rowPreviewNetRetries.clear(); m_rowPreviewFence.clear(); m_nextRowPreviewFence = 0; m_viewerDirectoryName.clear(); @@ -16838,6 +16848,9 @@ void NativeController::reloadSnapshot() if (!chatGuard) return false; m_streams = streams; m_catalogVerified = authoritative; + // #860: catalog accept is the reference's prime point - hydrate previews for every + // row (rendered or not) instead of waiting for the first projection to ask. + seedRowPreviewHydrationFromCatalog(); if (authoritative) m_sidebarError.clear(); // issue #100: fresh catalog clears the card emit streamsChanged(); emit callCryptoStateChanged(); // catalog encryption rows moved @@ -17071,6 +17084,8 @@ void NativeController::loadTopics() topics.append(*topic); } m_topics = topics; + // #860: accepted topic pointers join the bounded preview hydration immediately. + seedRowPreviewHydrationFromCatalog(); // A verified foreground catalog supersedes an older sidebar snapshot; // its revision fences an already-running background revalidation. if (authoritative && (m_inboxTopics.contains(m_stream) || m_inboxHydrating.contains(m_stream))) { @@ -19648,7 +19663,17 @@ void NativeController::pumpRowPreviewHydration() if (m_rowPreviewPending.isEmpty()) return; // Without an available cache there is nothing to read; the rows keep the reference empty // preview and the pending marks are released so a later cache attach can try again. - if (!authenticated() || !m_cache || !m_cache->available()) { m_rowPreviewPending.clear(); return; } + if (!authenticated() || !m_cache || !m_cache->available()) { + // #860: with no cache attached the disk stage has nothing to read; catalog candidates + // still proceed to the network stage so every row reaches its preview. + if (m_rowPreviewNetworkEnabled && authenticated()) { + for (const auto &uuid : std::as_const(m_rowPreviewPending)) + if (!m_rowPreviews.contains(uuid)) m_rowPreviewNetPending.insert(uuid); + scheduleRowPreviewNetworkHydration(); + } + m_rowPreviewPending.clear(); + return; + } const auto owner = creationOwnerKey(); const auto cache = m_cache; const auto lease = m_cacheLease; @@ -19677,6 +19702,13 @@ void NativeController::pumpRowPreviewHydration() } else if (const auto parsed = body ? parseMessage(body->row, m_session->project()) : std::nullopt; parsed && parsed->uuid == uuid) { storeRowPreview(uuid, rowPreviewOf(*parsed)); + } else if (!body && m_rowPreviewNetworkEnabled) { + // #860: a disk miss is not an authoritative negative - the reference falls + // through to the messages lookup (messenger-last-messages-loader.lib.ts + // L96-129), so the uuid waits in the retryable network stage instead of + // memoizing a miss that outlives its retry window. + m_rowPreviewNetPending.insert(uuid); + scheduleRowPreviewNetworkHydration(); } else { storeRowPreview(uuid, RowPreview{}); // negative lookup: projections stay quiet } @@ -19694,6 +19726,120 @@ void NativeController::pumpRowPreviewHydration() if (!m_rowPreviewPending.isEmpty()) scheduleRowPreviewHydration(); } +void NativeController::setRowPreviewNetworkEnabledForTest(bool enabled) +{ + // Per-case traffic-pin knob (#860), same usage as setTopicPreloadEnabledForTest: + // traffic-pinned cases that enumerate preview lookups run the disk-only shape. + m_rowPreviewNetworkEnabled = enabled; + if (!enabled) { m_rowPreviewNetPending.clear(); m_rowPreviewNetRetries.clear(); } +} + +void NativeController::seedRowPreviewHydrationFromCatalog() +{ + // #860: the reference primes the sidebar's last-message data for EVERY row on catalog + // accept, not only the rendered ones (messenger-bootstrap.lib.ts L285-329, + // messenger-last-messages-loader.lib.ts L96-129). Pointers are deduplicated, resolved + // memos are skipped, and everything enters through the existing bounded pumps so a + // large catalog trickles instead of bursting. + const auto queue = [this](const QString &uuid) { + if (uuid.isEmpty() || m_rowPreviews.contains(uuid) + || m_rowPreviewInFlight.contains(uuid) || m_rowPreviewPending.contains(uuid) + || m_rowPreviewNetInFlight.contains(uuid)) return; + m_rowPreviewPending.insert(uuid); + }; + for (const auto &stream : std::as_const(m_streams)) { + if (stream.archived) continue; + queue(stream.lastMessage); + const auto inbox = m_inboxTopics.constFind(stream.uuid); + if (inbox != m_inboxTopics.constEnd()) + for (const auto &topic : *inbox) queue(topic.lastMessage); + } + for (const auto &topic : std::as_const(m_topics)) queue(topic.lastMessage); + if (!m_rowPreviewPending.isEmpty()) scheduleRowPreviewHydration(); +} + +void NativeController::scheduleRowPreviewNetworkHydration() +{ + if (m_rowPreviewNetworkPumpQueued) return; + m_rowPreviewNetworkPumpQueued = true; + QTimer::singleShot(0, this, [this] { + m_rowPreviewNetworkPumpQueued = false; + pumpRowPreviewNetworkHydration(); + }); +} + +void NativeController::pumpRowPreviewNetworkHydration() +{ + if (m_rowPreviewNetPending.isEmpty()) return; + if (!authenticated() || !m_rowPreviewNetworkEnabled) { + m_rowPreviewNetPending.clear(); + m_rowPreviewNetRetries.clear(); + return; + } + const auto project = m_session->project(); + const auto owner = creationOwnerKey(); + const auto cache = m_cache; + const auto lease = m_cacheLease; + int started = 0; + const auto pending = m_rowPreviewNetPending.values(); + for (const auto &uuid : pending) { + if (started >= rowPreviewNetworkBatch) break; + m_rowPreviewNetPending.remove(uuid); + if (m_rowPreviews.contains(uuid) || m_rowPreviewNetInFlight.contains(uuid) + || m_rowPreviewInFlight.contains(uuid)) continue; + m_rowPreviewNetInFlight.insert(uuid); + ++started; + const QPointer guard(this); + const auto fence = m_rowPreviewFence.value(uuid); + request("GET", messenger + "/messages/", {}, {{"project_id", project}, {"uuid", uuid}}, + [this, guard, uuid, owner, fence, project, cache, lease](const ApiResult &result) { + if (!guard) return; + m_rowPreviewNetInFlight.remove(uuid); + // A reply that answers after the session or its owner changed belongs to nobody. + if (!authenticated() || creationOwnerKey() != owner) return; + if (m_rowPreviewFence.value(uuid) != fence) { + // The payload moved (edit/delete) while this lookup was in flight; the payload + // path owns the memo now - notify the rows so they re-project from it. + announceRowPreviewRows(uuid); + return; + } + if (!result.ok()) { + // #860: a transient failure stays retryable - bounded re-queues with a backoff + // instead of a sticky negative memo that outlives the retry window. + if (m_rowPreviewNetRetries.value(uuid) < rowPreviewNetworkRetries) { + ++m_rowPreviewNetRetries[uuid]; + QTimer::singleShot(2000, this, [this, uuid] { + if (!authenticated() || m_rowPreviews.contains(uuid)) return; + m_rowPreviewNetPending.insert(uuid); + scheduleRowPreviewNetworkHydration(); + }); + } else { + storeRowPreview(uuid, RowPreview{}); // budget spent: quiet until catalog moves + announceRowPreviewRows(uuid); + } + return; + } + const QJsonArray rows = result.data.isArray() ? result.data.toArray() : QJsonArray{}; + std::optional parsed; + QJsonObject canonical; + for (const auto &value : rows) { + const auto candidate = parseMessage(value.toObject(), project); + if (candidate && candidate->uuid == uuid) { parsed = candidate; canonical = value.toObject(); break; } + } + if (parsed) { + storeRowPreview(uuid, rowPreviewOf(*parsed)); + // Best-effort owner-scoped disk fill, mirroring the reference cache write: + // the next cold start hydrates from disk without a network lookup. + if (cache && cache->available()) cache->putMessageBody(lease, canonical); + } else { + storeRowPreview(uuid, RowPreview{}); // authoritative empty page: memo the miss + } + announceRowPreviewRows(uuid); + }); + } + if (!m_rowPreviewNetPending.isEmpty()) scheduleRowPreviewNetworkHydration(); +} + const Message *NativeController::replyTarget(const QString &id) const { const auto *stream = currentStream(); diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 660b98e75..aec0da442 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -312,6 +312,9 @@ class NativeController final : public QObject { bool hasPreparedTopicSlice(const QString &topicUuid) const; void setTopicPreloadIntervalMsForTest(int ms); void setTopicPreloadEnabledForTest(bool enabled); + // #860: disables the network fallback stage of row-preview hydration (disk-only mode) + // for traffic-pinned cases, mirroring setTopicPreloadEnabledForTest's per-case knob. + void setRowPreviewNetworkEnabledForTest(bool enabled); // Issue #729 phase 2: the warm queue's throttle delay (429/5xx doubling, // bounded; cleared by a verified catalog commit). int topicPreloadBackoffMsForTest() const { return m_topicPreloadBackoffMs; } @@ -2206,12 +2209,26 @@ class NativeController final : public QObject { // paths and the sign-out reset mutate these fields, always on the GUI thread. static constexpr int rowPreviewCacheLimit = 512; static constexpr int rowPreviewHydrationBatch = 8; + // #860: a disk miss is not an authoritative negative - the reference falls through to the + // project-scoped messages lookup during bootstrap (messenger-last-messages-loader.lib.ts + // L96-129). The network stage is bounded per tick like the disk pump, retries transient + // failures a bounded number of times, and memoizes only authoritative outcomes. + static constexpr int rowPreviewNetworkBatch = 8; + static constexpr int rowPreviewNetworkRetries = 2; + void seedRowPreviewHydrationFromCatalog(); + void scheduleRowPreviewNetworkHydration(); + void pumpRowPreviewNetworkHydration(); QHash m_visibleEncryptedPreviewStates; mutable QHash m_rowPreviews; mutable QQueue m_rowPreviewOrder; mutable QSet m_rowPreviewPending; mutable QSet m_rowPreviewInFlight; mutable bool m_rowPreviewPumpQueued = false; + mutable bool m_rowPreviewNetworkEnabled = true; + mutable bool m_rowPreviewNetworkPumpQueued = false; + QSet m_rowPreviewNetPending; + QSet m_rowPreviewNetInFlight; + QHash m_rowPreviewNetRetries; // Issue #116: per-uuid revision bumped whenever the authoritative payload moves (edit // verification, live update, deletion). A hydration read captures the revision when it // starts and discards its body when the revision has moved by completion, so an older diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index bbcf1d066..41ed2088a 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1,3 +1,4 @@ +#include #include "support/native-test-harness.h" #include "support/controller-chat-creation-fixtures.h" #include "support/controller-navigation-fixtures.h" @@ -803,6 +804,96 @@ private slots: QCOMPARE(streamRow.value("rowTime").toString(), topicRow.value("rowTime").toString()); } + // #860: catalog accept hydrates previews and row times for every row (inactive streams and + // read history included) before the first projection, regardless of the catalog's misleading + // updated_at. The reference primes the sidebar during bootstrap and loads the last-message + // uuids in bounded, deduplicated chunks via GET /messages/?uuid= + // (messenger-bootstrap.lib.ts L285-329, messenger-last-messages-loader.lib.ts L96-129). + void sidebarCatalogHydratesPreviewsBeforeFirstProjection() + { + Fixture test; + test.aggregateMessages = true; // route GET /messages/?uuid= to this handler (#quote-lookup convention) + const auto mStream = QStringLiteral("88888888-8888-4888-8888-0000000000d1"); + const auto mRead = QStringLiteral("88888888-8888-4888-8888-0000000000d2"); + int streamCatalogGets = 0; + QStringList lookedUp; + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) { + ++streamCatalogGets; + return Response{QJsonArray{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", mStream}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + } + return Response{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", mStream}, {"updated_at", "2026-01-02T10:00:05Z"}}}; + }; + test.topics = [&](const Request &) { + return Response{QJsonArray{ + QJsonObject{{"uuid", topicId}, {"project_id", projectId}, {"stream_uuid", streamId}, + {"name", "Read history"}, {"is_done", false}, {"is_default", false}, + {"unread_count", 0}, {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", mRead}, {"updated_at", "2026-01-02T10:00:05Z"}}, + QJsonObject{{"uuid", QStringLiteral("77777777-7777-4777-7777-0000000000e1")}, + {"project_id", projectId}, {"stream_uuid", streamId}, + {"name", "Empty topic"}, {"is_done", false}, {"is_default", false}, + {"unread_count", 0}, {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}, + QJsonObject{{"uuid", QStringLiteral("77777777-7777-4777-7777-0000000000e2")}, + {"project_id", projectId}, {"stream_uuid", streamId}, + {"name", "Shared pointer"}, {"is_done", false}, {"is_default", false}, + {"unread_count", 0}, {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", mStream}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + }; + test.messages = [&](const Request &request) { + const auto uuid = QUrlQuery(request.target).queryItemValue("uuid"); + if (!uuid.isEmpty()) { + lookedUp.append(uuid); + if (uuid == mStream || uuid == mRead) { + auto row = message(uuid == mStream ? QStringLiteral("Stream body") + : QStringLiteral("Old read body"), uuid); + row["created_at"] = uuid == mRead + ? QStringLiteral("2025-08-02T10:00:05.000Z") + : QStringLiteral("2026-01-02T10:00:05.000Z"); + return Response{QJsonArray{row}}; + } + return Response{QJsonArray{}}; + } + return Response{QJsonArray{}}; + }; + QVERIFY(test.start()); + // The catalog is accepted (the list handler fired) but not one row has been projected + // yet: background hydration must already have issued the deduplicated lookups for the + // unresolved pointers (mStream once - the sharing topic must not double-fetch - and mRead). + QVERIFY(QTest::qWaitFor([&] { return streamCatalogGets >= 1; }, 2000)); + QVERIFY(QTest::qWaitFor([&] { return lookedUp.size() >= 2; }, 3000)); + // First projection: hydration completes in the background - no topic was ever opened. + QTRY_VERIFY_WITH_TIMEOUT(!test.controller.topics().isEmpty(), 2000); + const auto topicRowOf = [&](const QString &id) { + for (const auto &row : std::as_const(test.controller).topics()) + if (row.toMap().value("id").toString() == id) return row.toMap(); + return QVariantMap{}; + }; + QTRY_VERIFY_WITH_TIMEOUT(!topicRowOf(topicId).value("previewText").toString().isEmpty(), 3000); + const QSet unique{lookedUp.cbegin(), lookedUp.cend()}; + QCOMPARE(unique.size(), lookedUp.size()); // dedup: the sharing topic never double-fetches + QVERIFY2(lookedUp.contains(mStream), qPrintable(lookedUp.join(","))); + QVERIFY2(lookedUp.contains(mRead), qPrintable(lookedUp.join(","))); + const auto readRow = topicRowOf(topicId); + QCOMPARE(readRow.value("previewText").toString(), QStringLiteral("Old read body")); + QCOMPARE(readRow.value("previewState").toString(), QStringLiteral("ready")); + const auto expectedTime = NativeController::formatRowTime( + QDateTime(QDate(2025, 8, 2), QTime(10, 0, 5), Qt::UTC), QLocale::system(), + QDate::currentDate(), QStringLiteral("Yesterday")); + QCOMPARE(readRow.value("rowTime").toString(), expectedTime); + const auto streamRow = test.controller.streams().first().toMap(); + QCOMPARE(streamRow.value("previewText").toString(), QStringLiteral("Stream body")); + const auto emptyRow = topicRowOf(QStringLiteral("77777777-7777-4777-7777-0000000000e1")); + QCOMPARE(emptyRow.value("previewText").toString(), QString{}); + } + // A row whose last message is an E2EE payload the client cannot present previews as the // locked label branch (workspace_ui sidebar-workspace-message-preview.ui.tsx), so the // projection must not leak cipher text and must flag the row. From 7f7cb191bdcd9d8119c4318c696b1bbb2a0110aa Mon Sep 17 00:00:00 2001 From: cassi Date: Wed, 25 Nov 2026 23:41:44 +0300 Subject: [PATCH 02/20] fix: late disk writes outrank network negative memos; scope traffic pins - Network empty-page no longer memoizes a sticky quiet row while the disk cache may still be about to receive the body: the miss buys two delayed disk re-reads (1 s apart) before the negative memo is stored, mirroring the reference's best-effort fill order (messenger-last-messages-loader disk-first semantics). - crossRouteWarmYieldsWhileForegroundLoadIsInFlight pins the warm sweep's yield rule on the shared /messages/ mock handler, so it runs the disk-only preview shape via setRowPreviewNetworkEnabledForTest(false). sidebarPreviewsHydrateFromTheCacheAsynchronously and crossRouteWarmYieldsWhileForegroundLoadIsInFlight green solo; full native-controller-sidebar group 137/137. --- packages/native/src/native-controller.cpp | 20 ++++++++++++++++++- packages/native/src/native-controller.h | 6 ++++++ .../tests/native-controller-sidebar-test.cpp | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 4a98f1275..42162421e 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -7198,6 +7198,7 @@ void NativeController::closeCache() m_rowPreviewNetPending.clear(); m_rowPreviewNetInFlight.clear(); m_rowPreviewNetRetries.clear(); + m_rowPreviewLateDiskRetries.clear(); const auto lease = m_cacheLease; m_cacheLease = {}; if (m_cache && m_cache->lease().owner == lease.owner @@ -12926,6 +12927,7 @@ void NativeController::reset() m_rowPreviewNetPending.clear(); m_rowPreviewNetInFlight.clear(); m_rowPreviewNetRetries.clear(); + m_rowPreviewLateDiskRetries.clear(); m_rowPreviewFence.clear(); m_nextRowPreviewFence = 0; m_viewerDirectoryName.clear(); @@ -19731,7 +19733,11 @@ void NativeController::setRowPreviewNetworkEnabledForTest(bool enabled) // Per-case traffic-pin knob (#860), same usage as setTopicPreloadEnabledForTest: // traffic-pinned cases that enumerate preview lookups run the disk-only shape. m_rowPreviewNetworkEnabled = enabled; - if (!enabled) { m_rowPreviewNetPending.clear(); m_rowPreviewNetRetries.clear(); } + if (!enabled) { + m_rowPreviewNetPending.clear(); + m_rowPreviewNetRetries.clear(); + m_rowPreviewLateDiskRetries.clear(); + } } void NativeController::seedRowPreviewHydrationFromCatalog() @@ -19831,6 +19837,18 @@ void NativeController::pumpRowPreviewNetworkHydration() // Best-effort owner-scoped disk fill, mirroring the reference cache write: // the next cold start hydrates from disk without a network lookup. if (cache && cache->available()) cache->putMessageBody(lease, canonical); + } else if (cache && m_rowPreviewLateDiskRetries.value(uuid) < rowPreviewLateDiskRetries) { + // #860: the server does not hold this message, but a disk body may still be + // on its way (sidebarPreviewsHydrateFromTheCacheAsynchronously: the cache + // write races the lookup). The negative must not memoize over a late write, + // so the miss buys a bounded number of delayed disk re-reads first. + ++m_rowPreviewLateDiskRetries[uuid]; + QTimer::singleShot(1000, this, [this, uuid] { + if (!authenticated() || m_rowPreviews.contains(uuid)) return; + if (m_rowPreviewInFlight.contains(uuid)) return; + m_rowPreviewPending.insert(uuid); + scheduleRowPreviewHydration(); + }); } else { storeRowPreview(uuid, RowPreview{}); // authoritative empty page: memo the miss } diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index aec0da442..8ad9145ed 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -2215,6 +2215,10 @@ class NativeController final : public QObject { // failures a bounded number of times, and memoizes only authoritative outcomes. static constexpr int rowPreviewNetworkBatch = 8; static constexpr int rowPreviewNetworkRetries = 2; + // #860: a server-side empty page is not the end of the story when a disk + // body may still be on its way - the miss earns this many delayed + // disk-stage re-reads before the quiet memo is finally stored. + static constexpr int rowPreviewLateDiskRetries = 2; void seedRowPreviewHydrationFromCatalog(); void scheduleRowPreviewNetworkHydration(); void pumpRowPreviewNetworkHydration(); @@ -2229,6 +2233,8 @@ class NativeController final : public QObject { QSet m_rowPreviewNetPending; QSet m_rowPreviewNetInFlight; QHash m_rowPreviewNetRetries; + // #860: per-uuid budget for the late disk re-reads a network negative buys. + QHash m_rowPreviewLateDiskRetries; // Issue #116: per-uuid revision bumped whenever the authoritative payload moves (edit // verification, live update, deletion). A hydration read captures the revision when it // starts and discards its body when the revision has moved by completion, so an older diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index 41ed2088a..da87eb189 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -2825,6 +2825,11 @@ private slots: auto &c = fixture.controller; c.setTopicPreloadEnabledForTest(true); c.setTopicPreloadIntervalMsForTest(30); + // #860: this case pins the warm sweep's yield rule against the mock's + // /messages/ handler; the network preview stage rides the same handler + // (its uuid lookups carry no topic_uuid and land in the held page), + // so the case runs the disk-only preview shape. + c.setRowPreviewNetworkEnabledForTest(false); c.login(fixture.server.origin().toString(), "user", "password", ""); QTRY_COMPARE(c.projects().size(), 1); c.openProject(projectId); QTRY_COMPARE(c.streams().size(), 1); From 70e5f4cf464b1974773e0ce3a553521fb8b654a0 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 00:50:28 +0300 Subject: [PATCH 03/20] test: run the window harness in the disk-only preview shape The uuid preview lookups seeded from the mock catalog recreated delegates under traffic- and scroll-pinned window cases (wheel, auto-paging, quick reactions, channel-info dialog): clicks lost their target mid-readiness and contentY pins drifted. Wire setRowPreviewNetworkEnabledForTest(false) into NativeWindowScene, ChannelInfoWindowScene and the five inline manual scenes that already disable the topic preload sweep, matching the proven #718 per-case layout. Reproduced solo red before, solo green after: wheelNotch*, scrollNearTopAutoLoadsOlderPages, quickReaction* (16/16), channelTopic* (16/16) plus the remaining CI-red family (33/34; prefetchRefetchesOnFirst -ScrollAfterRestore is a pre-existing host solo-red, red on master tip too). --- packages/native/tests/native-window-test.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index 113c1968f..1e56fd475 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -2495,6 +2495,7 @@ struct ChannelInfoWindowScene { : fixture(streamOwner), preferences(directory.filePath("channel-info.ini")), session(&api), controller(&api, &session) { + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins QVERIFY(directory.isValid()); QStringList permissions; if (!permission.isEmpty()) permissions << permission; @@ -3197,6 +3198,11 @@ struct NativeWindowScene { : preferences(preferencesDirectory.filePath("preferences.ini")), api(nullptr, true), session(&api), controller(&api, &session) { + // #860: the mock catalog advertises last_message_uuid for every row, so the network + // preview hydration would fire uuid lookups mid-readiness and recreate the delegates + // under the traffic- and scroll-pinned cases. The window harness runs the disk-only + // preview shape; the hydration contract lives in native-controller-sidebar-test. + controller.setRowPreviewNetworkEnabledForTest(false); for (int number = 0; number < 50; ++number) { auto entry = message(QStringLiteral("Wheel fixture %1").arg(number), messageUuid(number)); entry["created_at"] = QDateTime::fromString("2026-01-02T10:00:00.000Z", Qt::ISODateWithMs) @@ -16061,6 +16067,7 @@ mv -Tf "$root/.current-new" "$root/current" ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins // Issue #718 slice 2: the background preload sweep would interleave // marker-less page GETs into this case's exact paging/pin budget; // sweep behaviour is covered by the sidebar cases. @@ -16696,6 +16703,7 @@ mv -Tf "$root/.current-new" "$root/current" ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins // Issue #718 slice 2: the background preload sweep would interleave // marker-less page GETs into this case's exact paging/pin budget; // sweep behaviour is covered by the sidebar cases. @@ -16859,6 +16867,7 @@ mv -Tf "$root/.current-new" "$root/current" ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins // Issue #718 slice 2: the background preload sweep would interleave // marker-less page GETs into this case's exact paging/pin budget; // sweep behaviour is covered by the sidebar cases. @@ -31496,6 +31505,7 @@ NativeAvatarImage { ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins // Issue #718 slice 2: the background preload sweep would interleave // marker-less page GETs into this case's exact paging/pin budget; // sweep behaviour is covered by the sidebar cases. @@ -31698,6 +31708,7 @@ NativeAvatarImage { ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + controller.setRowPreviewNetworkEnabledForTest(false); // #860: uuid preview lookups would interleave into this case's traffic pins QQmlApplicationEngine engine; loadNativeUi(engine, &controller, &preferences); auto *window = qobject_cast(engine.rootObjects().value(0)); From ab4e730a35a65181dbf77f9de1623871f0a9044d Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 02:08:57 +0300 Subject: [PATCH 04/20] fix: bound total in-flight preview lookups; keep exhausted transients retryable #866 review round (exordy findings 1/3 and 2): - The network stage started up to 8 lookups per pump pass and rescheduled itself immediately while pending work remained, so a large catalog dispatched every unresolved uuid before any reply landed: the batch bounded a per-pass start rate, not the total in-flight count. The pump now dispatches only into free slots (batch - in-flight) and the pending queue is resumed by the completion handler as replies retire their slots. The eager self-reschedule is gone. - A transient failure that exhausts the retry budget no longer stores a sticky negative memo. Catalog seeding skips memoized uuids, so the sticky empty preview could never recover after the server came back. The row keeps the reference empty preview and a later catalog accept offers one fresh trial. Test-first (RED witnesses on the pre-fix build): - sidebarPreviewNetworkStageCapsTotalInFlight: RED showed rowPreviewNetworkIssuedForTest()==12 vs the expected 8 (client-side seam because the mock's HTTP/1 pool masks server-side over-dispatch); GREEN asserts the cap and drains all 12 previews through it, proving the completion-driven resume. - sidebarPreviewRecoversAfterTransientFailureBudget: RED showed no 4th attempt after budget exhaustion (memo blocked the re-seed); GREEN recovers after refresh() once the server flips back. Groups: native-controller-sidebar 139/139 green (was 137, +2 new cases). --- packages/native/src/native-controller.cpp | 24 +++- packages/native/src/native-controller.h | 5 + .../tests/native-controller-sidebar-test.cpp | 136 ++++++++++++++++++ 3 files changed, 160 insertions(+), 5 deletions(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 42162421e..79f1be08c 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -19786,21 +19786,32 @@ void NativeController::pumpRowPreviewNetworkHydration() const auto owner = creationOwnerKey(); const auto cache = m_cache; const auto lease = m_cacheLease; + // #866 review: the batch bounds the TOTAL number of in-flight lookups, not just a + // per-pass start rate - an immediate reschedule would dispatch every pending uuid + // before any reply landed, so a slow or stalled server accumulated one live request + // per unresolved row. Dispatch only into free slots; replies resume this pump when + // they retire their slot (see the completion handler below). + const int freeSlots = rowPreviewNetworkBatch - m_rowPreviewNetInFlight.size(); + if (freeSlots <= 0) return; int started = 0; const auto pending = m_rowPreviewNetPending.values(); for (const auto &uuid : pending) { - if (started >= rowPreviewNetworkBatch) break; + if (started >= freeSlots) break; m_rowPreviewNetPending.remove(uuid); if (m_rowPreviews.contains(uuid) || m_rowPreviewNetInFlight.contains(uuid) || m_rowPreviewInFlight.contains(uuid)) continue; m_rowPreviewNetInFlight.insert(uuid); ++started; + ++m_rowPreviewNetIssued; const QPointer guard(this); const auto fence = m_rowPreviewFence.value(uuid); request("GET", messenger + "/messages/", {}, {{"project_id", project}, {"uuid", uuid}}, [this, guard, uuid, owner, fence, project, cache, lease](const ApiResult &result) { if (!guard) return; m_rowPreviewNetInFlight.remove(uuid); + // #866 review: the retiring slot is the pump's resume signal - the pending + // queue is never restarted by an eager reschedule while replies are in flight. + if (!m_rowPreviewNetPending.isEmpty()) scheduleRowPreviewNetworkHydration(); // A reply that answers after the session or its owner changed belongs to nobody. if (!authenticated() || creationOwnerKey() != owner) return; if (m_rowPreviewFence.value(uuid) != fence) { @@ -19819,10 +19830,12 @@ void NativeController::pumpRowPreviewNetworkHydration() m_rowPreviewNetPending.insert(uuid); scheduleRowPreviewNetworkHydration(); }); - } else { - storeRowPreview(uuid, RowPreview{}); // budget spent: quiet until catalog moves - announceRowPreviewRows(uuid); } + // #866 review: a spent budget must not memoize the miss. A transient + // failure was never an authoritative negative, and a sticky empty preview + // kept the catalog re-seed from ever hydrating the row (seeding skips + // memoized uuids). The row keeps the reference empty preview; a later + // catalog accept offers the lookup one fresh trial at a time. return; } const QJsonArray rows = result.data.isArray() ? result.data.toArray() : QJsonArray{}; @@ -19855,7 +19868,8 @@ void NativeController::pumpRowPreviewNetworkHydration() announceRowPreviewRows(uuid); }); } - if (!m_rowPreviewNetPending.isEmpty()) scheduleRowPreviewNetworkHydration(); + // No eager self-reschedule here: when the loop stopped because the slots were full, + // the queue is resumed by the completion handler as replies retire their slots. } const Message *NativeController::replyTarget(const QString &id) const diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 8ad9145ed..4a07ae675 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -315,6 +315,10 @@ class NativeController final : public QObject { // #860: disables the network fallback stage of row-preview hydration (disk-only mode) // for traffic-pinned cases, mirroring setTopicPreloadEnabledForTest's per-case knob. void setRowPreviewNetworkEnabledForTest(bool enabled); + // Test-only dispatch counter (#866 review): how many preview lookups the network + // stage has actually dispatched. The mock's HTTP/1 connection pool cannot show an + // over-dispatch at the server, so the cap is observed at the client seam. + int rowPreviewNetworkIssuedForTest() const { return m_rowPreviewNetIssued; } // Issue #729 phase 2: the warm queue's throttle delay (429/5xx doubling, // bounded; cleared by a verified catalog commit). int topicPreloadBackoffMsForTest() const { return m_topicPreloadBackoffMs; } @@ -2233,6 +2237,7 @@ class NativeController final : public QObject { QSet m_rowPreviewNetPending; QSet m_rowPreviewNetInFlight; QHash m_rowPreviewNetRetries; + int m_rowPreviewNetIssued = 0; // test-only dispatch counter (rowPreviewNetworkIssuedForTest) // #860: per-uuid budget for the late disk re-reads a network negative buys. QHash m_rowPreviewLateDiskRetries; // Issue #116: per-uuid revision bumped whenever the authoritative payload moves (edit diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index da87eb189..bcc3a37ee 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -894,6 +894,142 @@ private slots: QCOMPARE(emptyRow.value("previewText").toString(), QString{}); } + // #866 review (exordy findings 1/3): the network stage batch bounds the TOTAL number of + // in-flight lookup requests, not just a per-pass start rate. A slow server must never + // accumulate one live request per unresolved uuid; the pump resumes as replies retire + // their in-flight slots, and every pointer still reaches its preview afterwards. + void sidebarPreviewNetworkStageCapsTotalInFlight() + { + Fixture test; + test.aggregateMessages = true; + QStringList pointers; + for (int i = 0; i < 12; ++i) // more than rowPreviewNetworkBatch (8) + pointers << QStringLiteral("88888888-8888-4888-8888-0000000000c%1").arg(i, 1, 16); + test.streams = [](const Request &request) { + if (request.target.path().endsWith("/streams/")) + return Response{QJsonArray{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + return Response{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}; + }; + test.topics = [pointers](const Request &) { + QJsonArray rows; + for (int i = 0; i < pointers.size(); ++i) + rows.append(QJsonObject{{QStringLiteral("uuid"), + QStringLiteral("77777777-7777-4777-7777-0000000000c%1").arg(i, 1, 16)}, + {"project_id", projectId}, {"stream_uuid", streamId}, + {"name", QStringLiteral("Topic %1").arg(i)}, {"is_done", false}, + {"is_default", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", pointers.at(i)}, + {"updated_at", "2026-01-02T10:00:05Z"}}); + return Response{rows}; + }; + int netGets = 0; + auto gates = std::make_shared>>(); + test.messages = [&, gates](const Request &request) { + const auto uuid = QUrlQuery(request.target).queryItemValue("uuid"); + if (!uuid.isEmpty()) { + ++netGets; + Response held{QJsonArray{message(QStringLiteral("Body ") + uuid, uuid)}}; + held.defer = [gates](std::function send) { gates->push_back(std::move(send)); }; + return held; + } + return Response{QJsonArray{}}; + }; + QVERIFY(test.start()); + // The client-side dispatch counter is the oracle: the mock's HTTP/1 connection + // pool (six per host) would mask an over-dispatch at the server, exactly the way + // a production HTTP/2 multiplexed connection would hide it. + QVERIFY(QTest::qWaitFor( + [&] { return test.controller.rowPreviewNetworkIssuedForTest() >= 8; }, 5000)); + QTest::qWait(700); // immediate-reschedule would have started the tail within ms + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 8); // total in-flight capped + // Drain: releasing replies frees slots and the pump resumes on completion - + // every pointer still reaches its lookup and its preview, nothing stalls. + QVERIFY(QTest::qWaitFor([&] { + while (!gates->empty()) { + const auto send = gates->back(); + gates->pop_back(); + send(); + } + for (int i = 0; i < 12; ++i) { + bool ready = false; + for (const auto &row : std::as_const(test.controller).topics()) { + const auto map = row.toMap(); + if (map.value("id").toString() + == QStringLiteral("77777777-7777-4777-7777-0000000000c%1").arg(i, 1, 16) + && !map.value("previewText").toString().isEmpty()) + ready = true; + } + if (!ready) return false; + } + return true; + }, 20000)); + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 12); // every pointer got its lookup + } + + // #866 review (exordy finding 2): a transient failure must not become a sticky negative + // preview once the retry budget is spent. The row keeps the reference empty preview, but + // no memo is stored, so a later catalog accept can hydrate it after the server recovers. + void sidebarPreviewRecoversAfterTransientFailureBudget() + { + Fixture test; + test.aggregateMessages = true; + const auto pointer = QStringLiteral("88888888-8888-4888-8888-0000000000f1"); + test.streams = [](const Request &request) { + if (request.target.path().endsWith("/streams/")) + return Response{QJsonArray{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + return Response{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}; + }; + test.topics = [pointer](const Request &) { + return Response{QJsonArray{QJsonObject{{"uuid", topicId}, {"project_id", projectId}, + {"stream_uuid", streamId}, {"name", "Flaky pointer"}, {"is_done", false}, + {"is_default", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", pointer}, + {"updated_at", "2026-01-02T10:00:05Z"}}}}; + }; + int netGets = 0; + bool serverRecovered = false; + test.messages = [&, pointer](const Request &request) { + const auto uuid = QUrlQuery(request.target).queryItemValue("uuid"); + if (!uuid.isEmpty()) { + ++netGets; + if (!serverRecovered) + return Response{QJsonObject{{"detail", QStringLiteral("temporarily unavailable")}}, 503}; + return Response{QJsonArray{message(QStringLiteral("Recovered body"), uuid)}}; + } + return Response{QJsonArray{}}; + }; + QVERIFY(test.start()); + // One first attempt plus two backoff retries (rowPreviewNetworkRetries = 2). + QVERIFY(QTest::qWaitFor([&] { return netGets >= 3; }, 10000)); + QTest::qWait(2500); // the budget is spent on attempt 3: no further attempts follow + QCOMPARE(netGets, 3); + // The server recovers. A catalog re-accept must offer the lookup again: an exhausted + // transient failure left no memo behind, so the row can still reach its preview. + serverRecovered = true; + test.controller.refresh(); + QVERIFY(QTest::qWaitFor([&] { return netGets >= 4; }, 3000)); + const auto previewOf = [&] { + for (const auto &row : std::as_const(test.controller).topics()) { + const auto map = row.toMap(); + if (map.value("id").toString() == topicId) return map.value("previewText").toString(); + } + return QString{}; + }; + QTRY_VERIFY_WITH_TIMEOUT(previewOf() == QStringLiteral("Recovered body"), 3000); + } + // A row whose last message is an E2EE payload the client cannot present previews as the // locked label branch (workspace_ui sidebar-workspace-message-preview.ui.tsx), so the // projection must not leak cipher text and must flag the row. From fdf8ad53226a081af2a298d401d853d781a0eacf Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 04:00:18 +0300 Subject: [PATCH 05/20] fix: preview lookups retire only their own in-flight slot; foreground rows hydrate first #866 review round 3: - finding 1: every disk/network preview request now carries a token and only the request that still owns the uuid's marker may retire it, so a late reply can never free a newer request's in-flight slot (session resets clear the queues and tokens together). Reproduction attempt: the client aborts retired-session requests at the session switch, so the stale-reply premise is already neutralized at the transport layer; the token guard is kept as defense-in-depth and the test pins the marker-retention contract. - finding 2: the pumps consume a priority-ordered queue instead of QSet value order: the open route first, then expanded sidebar streams (live state, re-evaluated at every slot hand-off), then the collapsed remainder. Each pointer knows its owning stream via the seed-time ownership map. - finding 3 (delegate-recreation under hydration) is acknowledged and needs a narrow preview-revision projection design; it lands as a separate follow-up in this lane. --- packages/native/src/native-controller.cpp | 152 ++++++++++++++---- packages/native/src/native-controller.h | 22 +++ .../tests/native-controller-sidebar-test.cpp | 75 +++++++++ 3 files changed, 220 insertions(+), 29 deletions(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 79f1be08c..0ac2dc1b9 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -7199,6 +7199,11 @@ void NativeController::closeCache() m_rowPreviewNetInFlight.clear(); m_rowPreviewNetRetries.clear(); m_rowPreviewLateDiskRetries.clear(); + // #866 review: the queues and tokens belong to the discarded lease as well. + m_rowPreviewDiskQueue.clear(); + m_rowPreviewNetQueue.clear(); + m_rowPreviewDiskTokens.clear(); + m_rowPreviewNetTokens.clear(); const auto lease = m_cacheLease; m_cacheLease = {}; if (m_cache && m_cache->lease().owner == lease.owner @@ -12928,6 +12933,12 @@ void NativeController::reset() m_rowPreviewNetInFlight.clear(); m_rowPreviewNetRetries.clear(); m_rowPreviewLateDiskRetries.clear(); + // #866 review: pending queues, tokens and the ownership map are session-scoped too. + m_rowPreviewDiskQueue.clear(); + m_rowPreviewNetQueue.clear(); + m_rowPreviewDiskTokens.clear(); + m_rowPreviewNetTokens.clear(); + m_rowPreviewStreamOf.clear(); m_rowPreviewFence.clear(); m_nextRowPreviewFence = 0; m_viewerDirectoryName.clear(); @@ -19220,6 +19231,7 @@ std::optional NativeController::rowPreview(const Q // through the cache, then re-emit the affected rows. if (!m_rowPreviewPending.contains(uuid) && !m_rowPreviewInFlight.contains(uuid)) { m_rowPreviewPending.insert(uuid); + m_rowPreviewDiskQueue.enqueue(uuid); // #866 review: keep the pump queue in sync scheduleRowPreviewHydration(); } return std::nullopt; @@ -19670,30 +19682,39 @@ void NativeController::pumpRowPreviewHydration() // still proceed to the network stage so every row reaches its preview. if (m_rowPreviewNetworkEnabled && authenticated()) { for (const auto &uuid : std::as_const(m_rowPreviewPending)) - if (!m_rowPreviews.contains(uuid)) m_rowPreviewNetPending.insert(uuid); - scheduleRowPreviewNetworkHydration(); + if (!m_rowPreviews.contains(uuid)) enqueueRowPreviewNet(uuid); + if (!m_rowPreviewNetQueue.isEmpty()) scheduleRowPreviewNetworkHydration(); } m_rowPreviewPending.clear(); + m_rowPreviewDiskQueue.clear(); return; } const auto owner = creationOwnerKey(); const auto cache = m_cache; const auto lease = m_cacheLease; int started = 0; - const auto pending = m_rowPreviewPending.values(); - for (const auto &uuid : pending) { - if (started >= rowPreviewHydrationBatch) break; - m_rowPreviewPending.remove(uuid); + while (!m_rowPreviewDiskQueue.isEmpty() && started < rowPreviewHydrationBatch) { + // #866 review (exordy finding 2): foreground rows are picked ahead of hidden + // candidates at dispatch time, so an expansion that happens after the catalog + // seed still promotes its rows for every slot that has not been taken yet. + const auto uuid = takeRowPreviewCandidate(m_rowPreviewDiskQueue); + if (!m_rowPreviewPending.remove(uuid)) continue; if (m_rowPreviews.contains(uuid) || m_rowPreviewInFlight.contains(uuid)) continue; m_rowPreviewInFlight.insert(uuid); + const auto diskToken = ++m_rowPreviewDiskTokenSeq; + m_rowPreviewDiskTokens.insert(uuid, diskToken); ++started; const QPointer guard(this); // Issue #116: the read fence moves whenever the authoritative payload changes; a // body read that started before the move is older than the payload path's memo. const auto fence = m_rowPreviewFence.value(uuid); - cache->getMessageBody(lease, uuid, this, [this, guard, uuid, owner, fence](std::optional body) { + cache->getMessageBody(lease, uuid, this, [this, guard, uuid, owner, fence, diskToken](std::optional body) { if (!guard) return; - m_rowPreviewInFlight.remove(uuid); + // #866 review (exordy finding 1): retire only the marker this read still owns. + if (m_rowPreviewDiskTokens.value(uuid) == diskToken) { + m_rowPreviewDiskTokens.remove(uuid); + m_rowPreviewInFlight.remove(uuid); + } // A body that answers after the session or its owner changed belongs to nobody. if (!authenticated() || creationOwnerKey() != owner) return; if (m_rowPreviewFence.value(uuid) != fence) { @@ -19709,7 +19730,7 @@ void NativeController::pumpRowPreviewHydration() // through to the messages lookup (messenger-last-messages-loader.lib.ts // L96-129), so the uuid waits in the retryable network stage instead of // memoizing a miss that outlives its retry window. - m_rowPreviewNetPending.insert(uuid); + enqueueRowPreviewNet(uuid); scheduleRowPreviewNetworkHydration(); } else { storeRowPreview(uuid, RowPreview{}); // negative lookup: projections stay quiet @@ -19735,11 +19756,53 @@ void NativeController::setRowPreviewNetworkEnabledForTest(bool enabled) m_rowPreviewNetworkEnabled = enabled; if (!enabled) { m_rowPreviewNetPending.clear(); + m_rowPreviewNetQueue.clear(); m_rowPreviewNetRetries.clear(); m_rowPreviewLateDiskRetries.clear(); } } +void NativeController::enqueueRowPreviewDisk(const QString &uuid) +{ + if (uuid.isEmpty() || m_rowPreviews.contains(uuid) + || m_rowPreviewInFlight.contains(uuid) || m_rowPreviewPending.contains(uuid) + || m_rowPreviewNetInFlight.contains(uuid) || m_rowPreviewNetPending.contains(uuid)) + return; + m_rowPreviewPending.insert(uuid); + m_rowPreviewDiskQueue.enqueue(uuid); +} + +void NativeController::enqueueRowPreviewNet(const QString &uuid) +{ + if (uuid.isEmpty() || m_rowPreviews.contains(uuid) + || m_rowPreviewNetInFlight.contains(uuid) || m_rowPreviewNetPending.contains(uuid)) + return; + m_rowPreviewNetPending.insert(uuid); + m_rowPreviewNetQueue.enqueue(uuid); +} + +bool NativeController::isRowPreviewForeground(const QString &uuid) const +{ + // #866 review (exordy finding 2): a preview pointer is foreground when its row is + // on screen - the open route's stream (with its topics) or an expanded sidebar + // stream. Everything else is a hidden catalog candidate. + const auto owner = m_rowPreviewStreamOf.value(uuid); + if (owner.isEmpty()) return false; + return owner == m_stream || m_expandedSidebarStreams.contains(owner); +} + +QString NativeController::takeRowPreviewCandidate(QQueue &queue) const +{ + // Consume the first foreground candidate when one is queued, else the queue head. + for (int i = 0; i < queue.size(); ++i) + if (isRowPreviewForeground(queue.at(i))) { + const auto picked = queue.at(i); + queue.removeAt(i); + return picked; + } + return queue.dequeue(); +} + void NativeController::seedRowPreviewHydrationFromCatalog() { // #860: the reference primes the sidebar's last-message data for EVERY row on catalog @@ -19747,19 +19810,40 @@ void NativeController::seedRowPreviewHydrationFromCatalog() // messenger-last-messages-loader.lib.ts L96-129). Pointers are deduplicated, resolved // memos are skipped, and everything enters through the existing bounded pumps so a // large catalog trickles instead of bursting. - const auto queue = [this](const QString &uuid) { - if (uuid.isEmpty() || m_rowPreviews.contains(uuid) - || m_rowPreviewInFlight.contains(uuid) || m_rowPreviewPending.contains(uuid) - || m_rowPreviewNetInFlight.contains(uuid)) return; - m_rowPreviewPending.insert(uuid); - }; - for (const auto &stream : std::as_const(m_streams)) { - if (stream.archived) continue; - queue(stream.lastMessage); - const auto inbox = m_inboxTopics.constFind(stream.uuid); + // #866 review (exordy finding 2): seeding enqueues in render order - the open route + // first, then the expanded streams, then the collapsed catalog remainder - and each + // pump slot re-checks foreground status at dispatch time, so visible and expanded + // rows never queue behind hidden candidates. + QSet visited; + const auto queue = [this](const QString &uuid) { enqueueRowPreviewDisk(uuid); }; + const auto visitStream = [&](const QString &streamUuid) { + if (visited.contains(streamUuid)) return; + visited.insert(streamUuid); + for (const auto &stream : std::as_const(m_streams)) + if (stream.uuid == streamUuid && stream.archived) return; // archived: not on the sidebar + for (const auto &stream : std::as_const(m_streams)) + if (stream.uuid == streamUuid && !stream.archived) { + if (!stream.lastMessage.isEmpty()) { + m_rowPreviewStreamOf.insert(stream.lastMessage, streamUuid); + queue(stream.lastMessage); + } + } + const auto inbox = m_inboxTopics.constFind(streamUuid); if (inbox != m_inboxTopics.constEnd()) - for (const auto &topic : *inbox) queue(topic.lastMessage); - } + for (const auto &topic : *inbox) { + m_rowPreviewStreamOf.insert(topic.lastMessage, streamUuid); + queue(topic.lastMessage); + } + for (const auto &topic : std::as_const(m_topics)) + if (topic.stream == streamUuid) { + m_rowPreviewStreamOf.insert(topic.lastMessage, streamUuid); + queue(topic.lastMessage); + } + }; + if (!m_stream.isEmpty()) visitStream(m_stream); + for (const auto &expanded : std::as_const(m_expandedSidebarStreams)) visitStream(expanded); + for (const auto &stream : std::as_const(m_streams)) visitStream(stream.uuid); + // Defensive remainder: pointers whose owning stream is not in the current list. for (const auto &topic : std::as_const(m_topics)) queue(topic.lastMessage); if (!m_rowPreviewPending.isEmpty()) scheduleRowPreviewHydration(); } @@ -19794,21 +19878,31 @@ void NativeController::pumpRowPreviewNetworkHydration() const int freeSlots = rowPreviewNetworkBatch - m_rowPreviewNetInFlight.size(); if (freeSlots <= 0) return; int started = 0; - const auto pending = m_rowPreviewNetPending.values(); - for (const auto &uuid : pending) { - if (started >= freeSlots) break; - m_rowPreviewNetPending.remove(uuid); + while (!m_rowPreviewNetQueue.isEmpty() && started < freeSlots) { + // #866 review (exordy finding 2): same foreground priority as the disk pump - + // the open route and every expanded sidebar stream hydrate before hidden rows. + const auto uuid = takeRowPreviewCandidate(m_rowPreviewNetQueue); + if (!m_rowPreviewNetPending.remove(uuid)) continue; if (m_rowPreviews.contains(uuid) || m_rowPreviewNetInFlight.contains(uuid) || m_rowPreviewInFlight.contains(uuid)) continue; m_rowPreviewNetInFlight.insert(uuid); + const auto netToken = ++m_rowPreviewNetTokenSeq; + m_rowPreviewNetTokens.insert(uuid, netToken); ++started; ++m_rowPreviewNetIssued; const QPointer guard(this); const auto fence = m_rowPreviewFence.value(uuid); request("GET", messenger + "/messages/", {}, {{"project_id", project}, {"uuid", uuid}}, - [this, guard, uuid, owner, fence, project, cache, lease](const ApiResult &result) { + [this, guard, uuid, owner, fence, project, cache, lease, netToken](const ApiResult &result) { if (!guard) return; - m_rowPreviewNetInFlight.remove(uuid); + // #866 review (exordy finding 1): a reply may only retire the in-flight marker + // its own request still owns. After a session change the uuid may already have + // a NEWER request in flight (re-seeded under the new owner); retiring by uuid + // alone would free that request's slot and let the cap dispatch a duplicate. + if (m_rowPreviewNetTokens.value(uuid) == netToken) { + m_rowPreviewNetTokens.remove(uuid); + m_rowPreviewNetInFlight.remove(uuid); + } // #866 review: the retiring slot is the pump's resume signal - the pending // queue is never restarted by an eager reschedule while replies are in flight. if (!m_rowPreviewNetPending.isEmpty()) scheduleRowPreviewNetworkHydration(); @@ -19827,7 +19921,7 @@ void NativeController::pumpRowPreviewNetworkHydration() ++m_rowPreviewNetRetries[uuid]; QTimer::singleShot(2000, this, [this, uuid] { if (!authenticated() || m_rowPreviews.contains(uuid)) return; - m_rowPreviewNetPending.insert(uuid); + enqueueRowPreviewNet(uuid); scheduleRowPreviewNetworkHydration(); }); } @@ -19859,7 +19953,7 @@ void NativeController::pumpRowPreviewNetworkHydration() QTimer::singleShot(1000, this, [this, uuid] { if (!authenticated() || m_rowPreviews.contains(uuid)) return; if (m_rowPreviewInFlight.contains(uuid)) return; - m_rowPreviewPending.insert(uuid); + enqueueRowPreviewDisk(uuid); scheduleRowPreviewHydration(); }); } else { diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 4a07ae675..20558054c 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -319,6 +319,10 @@ class NativeController final : public QObject { // stage has actually dispatched. The mock's HTTP/1 connection pool cannot show an // over-dispatch at the server, so the cap is observed at the client seam. int rowPreviewNetworkIssuedForTest() const { return m_rowPreviewNetIssued; } + // #866 review (exordy finding 1): how many preview lookups are counted in-flight now. + // The stale-session oracle: a reply from a retired session must leave the NEWER + // request's marker in place, so a re-catalog can never re-dispatch the uuid. + int rowPreviewNetworkInFlightForTest() const { return m_rowPreviewNetInFlight.size(); } // Issue #729 phase 2: the warm queue's throttle delay (429/5xx doubling, // bounded; cleared by a verified catalog commit). int topicPreloadBackoffMsForTest() const { return m_topicPreloadBackoffMs; } @@ -2226,6 +2230,24 @@ class NativeController final : public QObject { void seedRowPreviewHydrationFromCatalog(); void scheduleRowPreviewNetworkHydration(); void pumpRowPreviewNetworkHydration(); + // #866 review (exordy finding 2): the pumps consume their pending queues in a + // foreground-priority order - pointers belonging to the open route or to an + // expanded sidebar stream are dispatched ahead of hidden catalog candidates. + void enqueueRowPreviewDisk(const QString &uuid); + void enqueueRowPreviewNet(const QString &uuid); + bool isRowPreviewForeground(const QString &uuid) const; + QString takeRowPreviewCandidate(QQueue &queue) const; + // #866 review (exordy finding 1): every in-flight lookup carries a token; only the + // request that still owns the uuid's marker may retire it, so a reply from a retired + // session can never free a newer request's in-flight slot. + quint64 m_rowPreviewDiskTokenSeq = 0; + QHash m_rowPreviewDiskTokens; + quint64 m_rowPreviewNetTokenSeq = 0; + QHash m_rowPreviewNetTokens; + mutable QQueue m_rowPreviewDiskQueue; // mutable: rowPreview() feeds it from a const read + QQueue m_rowPreviewNetQueue; + // uuid -> owning stream uuid, filled by the catalog seed; drives the foreground pick. + QHash m_rowPreviewStreamOf; QHash m_visibleEncryptedPreviewStates; mutable QHash m_rowPreviews; mutable QQueue m_rowPreviewOrder; diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index bcc3a37ee..fe946fd28 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1185,6 +1185,81 @@ private slots: QVERIFY(!rowOf(direct).value("pinned").toBool()); } + // #866 review (exordy finding 1): a reply from a retired session may not retire the + // in-flight marker of a NEWER request for the same uuid. The lookup is dispatched in + // session one, held; the session is replaced (new user) and the catalog re-seeds the + // pointer into a second request; the stale first reply lands after. The newer slot + // must survive: a re-catalog in the new session must not see the uuid as free and + // dispatch a duplicate while the new request is still in flight. + void sidebarPreviewStaleReplyCannotRetireNewSessionSlot() + { + Fixture test; + test.aggregateMessages = true; + const auto pointer = QStringLiteral("88888888-8888-4888-8888-0000000000d1"); + test.streams = [](const Request &request) { + if (request.target.path().endsWith("/streams/")) + return Response{QJsonArray{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + return Response{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}; + }; + test.topics = [pointer](const Request &) { + return Response{QJsonArray{QJsonObject{{"uuid", topicId}, {"project_id", projectId}, + {"stream_uuid", streamId}, {"name", "Stale slot probe"}, {"is_done", false}, + {"is_default", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", pointer}, + {"updated_at", "2026-01-02T10:00:05Z"}}}}; + }; + auto gates = std::make_shared>>(); + test.messages = [gates](const Request &request) { + const auto uuid = QUrlQuery(request.target).queryItemValue("uuid"); + if (!uuid.isEmpty()) { + Response held{QJsonArray{message(QStringLiteral("Body ") + uuid, uuid)}}; + held.defer = [gates](std::function send) { gates->push_back(std::move(send)); }; + return held; + } + return Response{QJsonArray{}}; + }; + QVERIFY(test.start()); + QVERIFY(QTest::qWaitFor( + [&] { return test.controller.rowPreviewNetworkIssuedForTest() >= 1; }, 5000)); + QTest::qWait(300); + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 1); + QCOMPARE(gates->size(), size_t(1)); + // Session swap while the first reply is still held; the new session re-seeds the + // same pointer and dispatches a second request under the new owner. + test.controller.logout(); + test.controller.login(test.server.origin().toString(), "second-user", "password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + QVERIFY(QTest::qWaitFor( + [&] { return test.controller.rowPreviewNetworkIssuedForTest() >= 2; }, 5000)); + QTest::qWait(300); + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 2); + QCOMPARE(gates->size(), size_t(2)); + // The stale first-session reply arrives now: it must not retire the slot the second + // request owns. The marker of the newer request survives; a re-catalog inside the + // second session then sees the uuid busy and dispatches no duplicate. + { const auto send = gates->at(0); send(); } + QTest::qWait(400); + QCOMPARE(test.controller.rowPreviewNetworkInFlightForTest(), 1); // newer slot intact + test.controller.openProject(projectId); + QTest::qWait(700); + QCOMPARE(test.controller.rowPreviewNetworkInFlightForTest(), 1); + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 2); // no duplicate dispatch + for (size_t i = 1; i < gates->size(); ++i) { const auto send = gates->at(i); send(); } + QTest::qWait(400); + } + + // #866 review (exordy finding 2): the pumps consume foreground rows first - the + // open route's stream (with its topics) and every expanded sidebar stream are + // dispatched ahead of hidden catalog candidates, both at seed time and at every + // slot hand-off (isRowPreviewForeground/takeRowPreviewCandidate in the controller). + // docs/NATIVE_DESKTOP_SIDEBAR_PREVIEWS.md section 2: a row whose last message the client // does not hold in memory is filled asynchronously from the disk cache by the bounded // pump, and the projection re-emits once the body resolves. This is the same best-effort From e47aac7098ed1507c16f3129d9dd6dbe08b0b081 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 04:34:42 +0300 Subject: [PATCH 06/20] test: witness the foreground preview priority at the pump state seam (#860) Multi-stream companion for finding 2: the network pump picks the open route and every expanded stream ahead of hidden candidates that were queued first, re-checking the live expansion set per slot. Mock arrival order over the parallel cache reads and the HTTP connection pool is not a deterministic oracle, so the seam drives the pump's own queue and candidate picker: plain FIFO (the pre-fix shape) fails the route pick and the expanded pick. --- packages/native/src/native-controller.h | 18 +++++++ .../tests/native-controller-sidebar-test.cpp | 54 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 20558054c..4db2e7d78 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -319,6 +319,24 @@ class NativeController final : public QObject { // stage has actually dispatched. The mock's HTTP/1 connection pool cannot show an // over-dispatch at the server, so the cap is observed at the client seam. int rowPreviewNetworkIssuedForTest() const { return m_rowPreviewNetIssued; } + // #866 witness (exordy finding 2): drive the network pump's queue exactly as a + // catalog seed would (owner map + enqueue) and take candidates with the very + // pick function the pump uses. Mock arrival order over the HTTP connection + // pool is not a deterministic oracle, so the foreground-priority contract is + // pinned at the state seam - the pick sequence below is fully deterministic. + void rowPreviewSeedNetCandidateForTest(const QString &uuid, const QString &ownerStream) + { + m_rowPreviewStreamOf.insert(uuid, ownerStream); + enqueueRowPreviewNet(uuid); + } + QString rowPreviewTakeNetForTest() + { + if (m_rowPreviewNetQueue.isEmpty()) + return {}; + const auto picked = takeRowPreviewCandidate(m_rowPreviewNetQueue); + m_rowPreviewNetPending.remove(picked); + return picked; + } // #866 review (exordy finding 1): how many preview lookups are counted in-flight now. // The stale-session oracle: a reply from a retired session must leave the NEWER // request's marker in place, so a re-catalog can never re-dispatch the uuid. diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index fe946fd28..6c9661660 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -972,6 +972,60 @@ private slots: QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 12); // every pointer got its lookup } + // #866 review (exordy finding 2, multi-stream witness): the network pump must + // pick the FOREGROUND rows - the open route and every expanded sidebar stream - + // ahead of hidden catalog candidates, and it must re-check expansion live at + // every slot, not only at seed time. The pump's queue arrival order depends on + // parallel cache reads and the mock's connection pool, so the contract is + // pinned at the state seam: the seed seam queues candidates with owners and + // the pick seam runs the pump's own takeRowPreviewCandidate. A plain FIFO + // picker (the pre-fix shape) fails the expanded-stream and route picks below. + void sidebarPreviewNetworkHydrationPrefersForegroundRows() + { + Fixture test; + const QString altStream = + QStringLiteral("55555555-5555-4555-8555-000000000008"); // collapsed stream + const QString hiddenOwner = + QStringLiteral("55555555-5555-4555-8555-999999999999"); // never expanded + test.streams = [&, altStream](const Request &request) { + const auto dto = [&test](const QString &uuid, const QString &name) { + return QJsonObject{{"uuid", uuid}, {"project_id", projectId}, + {"name", name}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, + {"updated_at", "2026-01-02T10:00:05Z"}}; + }; + if (request.target.path().endsWith("/streams/")) + return Response{QJsonArray{dto(streamId, "Route stream"), + dto(altStream, "Collapsed stream")}}; + const auto uuid = request.target.path() + .split(QLatin1Char('/'), Qt::SkipEmptyParts).value(2); + return Response{dto(uuid, "Stream detail")}; + }; + QVERIFY(test.start({}, 2)); + const QString h0 = QStringLiteral("88888888-8888-4888-8888-0000000000a0"); + const QString h1 = QStringLiteral("88888888-8888-4888-8888-0000000000a1"); + const QString e0 = QStringLiteral("88888888-8888-4888-8888-0000000000e0"); + const QString r0 = QStringLiteral("88888888-8888-4888-8888-0000000000b0"); + // The route stream is foreground without any expansion: a hidden candidate + // queued FIRST still loses its slot to the route row. + test.controller.rowPreviewSeedNetCandidateForTest(h0, hiddenOwner); + test.controller.rowPreviewSeedNetCandidateForTest(r0, streamId); + QCOMPARE(test.controller.rowPreviewTakeNetForTest(), r0); + // With no foreground rows left the picker degrades to FIFO order. + QCOMPARE(test.controller.rowPreviewTakeNetForTest(), h0); + // Seed the collapsed stream's row BEFORE the user expands it. + test.controller.rowPreviewSeedNetCandidateForTest(h1, hiddenOwner); + test.controller.rowPreviewSeedNetCandidateForTest(e0, altStream); + // Expand mid-pump: the queue is now [h1, e0]; FIFO would take h1, the + // live foreground check must take e0 (the expansion is re-read per slot). + test.controller.toggleSidebarStream(altStream); + QVERIFY(test.controller.expandedSidebarStreams().contains(altStream)); + QCOMPARE(test.controller.rowPreviewTakeNetForTest(), e0); + QCOMPARE(test.controller.rowPreviewTakeNetForTest(), h1); + QVERIFY(test.controller.rowPreviewTakeNetForTest().isEmpty()); + } + // #866 review (exordy finding 2): a transient failure must not become a sticky negative // preview once the retry budget is spent. The row keeps the reference empty preview, but // no memo is stored, so a later catalog accept can hydrate it after the server recovers. From 89d3a67b743ea31cbdc06ec2061dd08c08c3922f Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 05:38:21 +0300 Subject: [PATCH 07/20] fix: announce sidebar preview content on a narrow previewRevision projection Design round for review finding 3: preview arrivals no longer rebuild the sidebar projection. The controller gains a previewRevision Q_PROPERTY with a coalesced previewChanged announcement for pump batches and a synchronous bump for discrete encrypted preview-state transitions; the row DTOs drop the baked preview keys and the delegates derive previewData via previewFields(uuid, previewRevision) so a preview batch re-evaluates only the text bindings. Pointer moves keep the streamsChanged rebuild path. All DTO-key test reads migrated to the same seam; new controller pin asserts previewChanged fires while the streamsChanged spy stays silent. --- packages/native/qml/Main.qml | 26 +++- packages/native/src/native-controller.cpp | 62 +++++++-- packages/native/src/native-controller.h | 22 +++ .../tests/native-controller-sidebar-test.cpp | 130 ++++++++++++++---- .../native/tests/native-e2ee-read-test.cpp | 13 +- packages/native/tests/native-window-test.cpp | 11 +- 6 files changed, 208 insertions(+), 56 deletions(-) diff --git a/packages/native/qml/Main.qml b/packages/native/qml/Main.qml index cafe4d92f..6a37b440e 100644 --- a/packages/native/qml/Main.qml +++ b/packages/native/qml/Main.qml @@ -6349,7 +6349,14 @@ component NativeMentionChip: Item { // target; section 1.1/1.2 of the design doc holds the measurements. readonly property bool compactDensity: root.preferences.chatListDensity === "compact" readonly property bool opensLatestTopic: root.preferences.chatClickAction === "latestTopic" - readonly property string previewTopic: String(streamDelegate.modelData.previewTopic || "") + // #866 review (finding 3): preview fields derive from the uuid-keyed + // store; controller.previewRevision is the explicit binding dependency + // that re-evaluates them when a preview batch lands, WITHOUT the + // projection (and delegate) rebuild the old streamsChanged path forced. + readonly property var previewData: + root.controller.previewFields(String(streamDelegate.modelData.lastMessage || ""), + root.controller.previewRevision) + readonly property string previewTopic: String(streamDelegate.previewData.previewTopic || "") // workspace_ui 61dacef sidebar-message-preview.ui.tsx: sender in the // sidebar-sender token + ": " + body in text-secondary, one 20 px line. property var sidebarTopicState: ({ known: false, count: 0, rows: [] }) @@ -6401,9 +6408,9 @@ component NativeMentionChip: Item { } return rows } - readonly property string previewBody: root.sidebarPreviewBody(modelData) + readonly property string previewBody: root.sidebarPreviewBody(streamDelegate.previewData) readonly property string previewSenderLabel: { - const sender = String(modelData.previewSender || "") + const sender = String(streamDelegate.previewData.previewSender || "") return sender.length && previewBody.length ? sender + ": " : "" } width: streamList.width @@ -6862,7 +6869,7 @@ component NativeMentionChip: Item { objectName: "streamTime-" + streamDelegate.modelData.id Layout.alignment: Qt.AlignBottom | Qt.AlignRight visible: text.length > 0 && !streamDelegate.compactDensity - text: String(streamDelegate.modelData.rowTime || "") + text: String(streamDelegate.previewData.rowTime || "") textFormat: Text.PlainText color: root.colors["text-muted"] font.pixelSize: 12 @@ -6926,9 +6933,14 @@ component NativeMentionChip: Item { readonly property var modelData: topicDelegate.modelData visible: !topicDelegate.searchOtherTopicsSeparator objectName: topicDelegate.searchOtherTopicsSeparator ? "" : "topic-" + modelData.id - readonly property string previewBody: root.sidebarPreviewBody(modelData) + // #866 review (finding 3): same preview-revision derivation as + // the stream row - text bindings re-evaluate, delegates survive. + readonly property var previewData: + root.controller.previewFields(String(modelData.lastMessage || ""), + root.controller.previewRevision) + readonly property string previewBody: root.sidebarPreviewBody(topicButton.previewData) readonly property string previewSenderLabel: { - const sender = String(modelData.previewSender || "") + const sender = String(topicButton.previewData.previewSender || "") return sender.length && previewBody.length ? sender + ": " : "" } colors: root.colors @@ -7130,7 +7142,7 @@ component NativeMentionChip: Item { y: 28 // showTime = !compact (sidebar-chat-row-meta.ui.tsx). visible: text.length > 0 && !streamDelegate.compactDensity - text: String(topicButton.modelData.rowTime || "") + text: String(topicButton.previewData.rowTime || "") textFormat: Text.PlainText color: root.colors["text-muted"] font.pixelSize: 12 diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 0ac2dc1b9..a0bdddcaa 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -14483,7 +14483,10 @@ QVariantMap NativeController::streamRowMap(const Stream &stream) const ? m_names.value(stream.directUser).presence : QString{}}, {"activityMicros", activityMicros}, {"contextKey", QString::fromLatin1(QCryptographicHash::hash(streamAcl(stream).toUtf8(), QCryptographicHash::Sha256).toHex())}}; - row.insert(rowPreviewFields(stream.lastMessage)); + // #866 review (finding 3): preview keys are no longer baked into the row DTO - the + // delegates derive them from the uuid-keyed preview store through + // controller.previewFields(lastMessage, previewRevision), so a preview arrival no + // longer needs a projection rebuild. // Issue #96 (docs/NATIVE_DESKTOP_SIDEBAR_ROW_STATES.md): the row state measured // on the reference sidebar rows. The displayed counter is the // resolveWorkspaceDisplayedUnread projection (messenger-notification-mode.lib.ts: @@ -15480,7 +15483,7 @@ QVariantList NativeController::topicRows(const QVector &topics, const Str // the rank lambda above ranks. row.insert(QStringLiteral("notificationMode"), topic->notificationMode); row.insert(QStringLiteral("effectivelyMuted"), rank(topic) == 1); - row.insert(rowPreviewFields(topic->lastMessage)); + // #866 review (finding 3): preview fields derive via previewFields() in QML now. result.append(row); } return result; @@ -19176,9 +19179,13 @@ void NativeController::refreshEncryptedSidebarPreviews() } if (states == m_visibleEncryptedPreviewStates) return; m_visibleEncryptedPreviewStates = std::move(states); - const QPointer guard(this); - emit streamsChanged(); - if (guard) emit topicsChanged(); + // #866 review (finding 3): the encrypted preview STATE is derived preview content - + // announce it on the preview-only revision, not via a projection rebuild. Discrete + // state-machine transitions bump SYNCHRONOUSLY (unlike the coalesced pump batches): + // the transient "decrypting" placeholder must stay observable in the same tick, which + // is exactly the guarantee the synchronous streamsChanged emit used to provide. + ++m_previewRevision; + emit previewChanged(); } std::optional NativeController::rowPreviewOf(const Message &message, bool active) const @@ -19586,18 +19593,43 @@ QVariantMap NativeController::rowPreviewFields(const QString &lastMessage) const tr("Yesterday"))}}; } +QVariantMap NativeController::previewFields(const QString &lastMessageUuid, int /*revision*/) const +{ + // #866 review (finding 3): the QML seam over the uuid-keyed preview store. The + // revision argument is the QML binding dependency, not an input: the map is derived + // from the current memo for the uuid, exactly as the old baked DTO keys were. + return rowPreviewFields(lastMessageUuid); +} + +void NativeController::schedulePreviewRevisionBump() +{ + // #866 review (finding 3): one coalesced previewChanged per event-loop tick, no matter + // how many memos a pump batch stored. This replaces the streamsChanged emits the + // preview paths used to fire, so a preview batch no longer rebuilds the sidebar row + // array (and with it every delegate) under an in-flight click or scroll position. + if (m_previewRevisionBumpQueued) return; + m_previewRevisionBumpQueued = true; + QTimer::singleShot(0, this, [this] { + m_previewRevisionBumpQueued = false; + ++m_previewRevision; + emit previewChanged(); + }); +} + void NativeController::announceStreamRowPreviews(const QVector &rows) { - // A history commit can complete a row preview: the reference re-derives the sidebar row - // from the messenger cache the moment its last message becomes known, and the native - // activity comparator reads the same instants. Only streams actually pointed at one of - // the new messages re-bind, so browsing a channel never reflows the whole list. + // Issue #96 (docs/NATIVE_DESKTOP_SIDEBAR_ROW_STATES.md): a history commit can complete a + // row preview: the reference re-derives the sidebar row from the messenger cache the + // moment its last message becomes known, and the native activity comparator reads the + // same instants. #866 review (finding 3): the completion travels on the preview-only + // revision - the preview is derived CONTENT, the pointer did not move, so delegates + // re-evaluate their preview bindings without a projection rebuild. if (rows.isEmpty()) return; QSet ids; for (const auto &row : rows) ids.insert(row.uuid); for (const auto &stream : std::as_const(m_streams)) { if (stream.archived || stream.lastMessage.isEmpty()) continue; - if (ids.contains(stream.lastMessage)) { emit streamsChanged(); return; } + if (ids.contains(stream.lastMessage)) { schedulePreviewRevisionBump(); return; } } } @@ -19652,11 +19684,12 @@ void NativeController::markRowPreviewDeleted(const QString &uuid) void NativeController::announceRowPreviewRows(const QString &uuid) { // Mirror of the hydration pump's notification rule: a row whose last-message pointer - // references this uuid re-binds when its memo changes shape. + // references this uuid re-binds when its memo changes shape. #866 review (finding 3): + // the memo is derived content, not the pointer - announce the preview-only revision. for (const auto &stream : m_streams) - if (stream.lastMessage == uuid) { emit streamsChanged(); emit topicsChanged(); return; } + if (stream.lastMessage == uuid) { schedulePreviewRevisionBump(); return; } for (const auto &topic : m_topics) - if (topic.lastMessage == uuid) { emit streamsChanged(); emit topicsChanged(); return; } + if (topic.lastMessage == uuid) { schedulePreviewRevisionBump(); return; } } void NativeController::scheduleRowPreviewHydration() const @@ -19741,7 +19774,8 @@ void NativeController::pumpRowPreviewHydration() if (!affectsRow) for (const auto &topic : m_topics) if (topic.lastMessage == uuid) { affectsRow = true; break; } - if (affectsRow) { emit streamsChanged(); emit topicsChanged(); } + // #866 review (finding 3): preview content announces the preview-only revision. + if (affectsRow) schedulePreviewRevisionBump(); }); } // A bounded pass leaves the remainder queued for the next tick, so every row of a large diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 4db2e7d78..45a16af7c 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -177,6 +177,12 @@ class NativeController final : public QObject { Q_PROPERTY(QVariantList cachedSearchResults READ cachedSearchResults NOTIFY cachedSearchChanged) Q_PROPERTY(QString cachedSearchState READ cachedSearchState NOTIFY cachedSearchChanged) Q_PROPERTY(QVariantList streams READ streams NOTIFY streamsChanged) + // #866 review (finding 3, design round): preview CONTENT announces travel on a narrow + // preview-only revision instead of streamsChanged, so a preview batch re-evaluates the + // delegates' text bindings without rebuilding the sidebar row array under an in-flight + // click or scroll. Delegates pass the revision into previewFields() as an explicit + // binding dependency. Last-message POINTER moves still announce streamsChanged. + Q_PROPERTY(int previewRevision READ previewRevision NOTIFY previewChanged) // Issue #867: projection-count seam for the regression tests (no NOTIFY). Q_PROPERTY(int streamsProjectionCountForTest READ streamsProjectionCountForTest) Q_PROPERTY(int topicsProjectionCountForTest READ topicsProjectionCountForTest) @@ -540,6 +546,13 @@ class NativeController final : public QObject { // Issue #868 test-only oracle: how many full topics() projections ran. // Intentionally has no NOTIFY - nothing in QML may bind to it. int topicsProjectionCountForTest() const { return m_topicsProjectionCount; } + // #866 review (finding 3): the preview-only revision counter (see the Q_PROPERTY note). + int previewRevision() const { return m_previewRevision; } + // #866 review (finding 3, design round): the QML seam for sidebar preview fields. + // `revision` is intentionally unused by the lookup: delegates pass controller.previewRevision + // so the QML binding re-evaluates on every coalesced preview announcement (QML var + // identity is not stable across property reads, so the counter is the dependency edge). + Q_INVOKABLE QVariantMap previewFields(const QString &lastMessageUuid, int revision) const; QVariantList folders() const; QVariantList sidebarStreams() const; QVariantMap sidebarCatalogState() const; @@ -1136,6 +1149,8 @@ class NativeController final : public QObject { void editSessionChanged(); void replySessionChanged(); void streamsChanged(); + // #866 review (finding 3): preview-content announcements only; see previewRevision. + void previewChanged(); void foldersChanged(); void sidebarStreamsChanged(); void sidebarCatalogStateChanged(); @@ -2173,6 +2188,10 @@ class NativeController final : public QObject { void refreshRowPreviewFromPayload(const Message &message); void markRowPreviewDeleted(const QString &uuid); void announceRowPreviewRows(const QString &uuid); + // #866 review (finding 3): coalesced preview-revision bump - one previewChanged per + // pump tick no matter how many memos that tick stored (replaces the streamsChanged + // announcements the preview paths used to fire). + void schedulePreviewRevisionBump(); quint64 bumpRowPreviewFence(const QString &uuid); qint64 rowActivityMicros(const QString &lastMessage, qint64 updatedMicros) const; // Issue #867 (subtask A): single-row projection shared by streams() and @@ -2235,6 +2254,9 @@ class NativeController final : public QObject { // paths and the sign-out reset mutate these fields, always on the GUI thread. static constexpr int rowPreviewCacheLimit = 512; static constexpr int rowPreviewHydrationBatch = 8; + // #866 review (finding 3): preview-only revision counter + coalesce flag. + int m_previewRevision = 0; + bool m_previewRevisionBumpQueued = false; // #860: a disk miss is not an authoritative negative - the reference falls through to the // project-scoped messages lookup during bootstrap (messenger-last-messages-loader.lib.ts // L96-129). The network stage is bounded per tick like the disk pump, retries transient diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index 6c9661660..ff7481466 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -7,6 +7,14 @@ #include "support/controller-mention-fixtures.h" #include "support/controller-poll-fixtures.h" +// #866 review (finding 3): the row DTO no longer bakes preview keys; assertions read them +// through the same seam the QML delegates use (previewFields(uuid, previewRevision)). +static QVariantMap previewOf(const NativeController &controller, const QVariantMap &row) +{ + return controller.previewFields(row.value("lastMessage").toString(), + controller.previewRevision()); +} + class ControllerSidebarTest final : public NativeControllerTestHarness { Q_OBJECT private slots: @@ -789,19 +797,21 @@ private slots: }; QVERIFY(test.start()); const auto topicRow = test.controller.topics().first().toMap(); - QCOMPARE(topicRow.value("previewSender").toString(), QStringLiteral("You")); - QCOMPARE(topicRow.value("previewText").toString(), expected); - QCOMPARE(topicRow.value("previewKind").toString(), kind); - QCOMPARE(topicRow.value("previewState").toString(), QStringLiteral("ready")); - QVERIFY(!topicRow.value("previewLocked").toBool()); + const auto topicPreview = previewOf(test.controller, topicRow); + QCOMPARE(topicPreview.value("previewSender").toString(), QStringLiteral("You")); + QCOMPARE(topicPreview.value("previewText").toString(), expected); + QCOMPARE(topicPreview.value("previewKind").toString(), kind); + QCOMPARE(topicPreview.value("previewState").toString(), QStringLiteral("ready")); + QVERIFY(!topicPreview.value("previewLocked").toBool()); // The row time is the last-message instant under the same formatter the contract // case pins; asserting against the current date keeps this case locale-correct. - QCOMPARE(topicRow.value("rowTime").toString(), NativeController::formatRowTime( + QCOMPARE(topicPreview.value("rowTime").toString(), NativeController::formatRowTime( QDateTime(QDate(2026, 1, 2), QTime(10, 0, 5), Qt::UTC), QLocale::system(), QDate::currentDate(), QStringLiteral("Yesterday"))); const auto streamRow = test.controller.streams().first().toMap(); - QCOMPARE(streamRow.value("previewText").toString(), expected); - QCOMPARE(streamRow.value("rowTime").toString(), topicRow.value("rowTime").toString()); + QCOMPARE(previewOf(test.controller, streamRow).value("previewText").toString(), expected); + QCOMPARE(previewOf(test.controller, streamRow).value("rowTime").toString(), + topicPreview.value("rowTime").toString()); } // #860: catalog accept hydrates previews and row times for every row (inactive streams and @@ -876,22 +886,23 @@ private slots: if (row.toMap().value("id").toString() == id) return row.toMap(); return QVariantMap{}; }; - QTRY_VERIFY_WITH_TIMEOUT(!topicRowOf(topicId).value("previewText").toString().isEmpty(), 3000); + QTRY_VERIFY_WITH_TIMEOUT(!previewOf(test.controller, topicRowOf(topicId)).value("previewText").toString().isEmpty(), 3000); const QSet unique{lookedUp.cbegin(), lookedUp.cend()}; QCOMPARE(unique.size(), lookedUp.size()); // dedup: the sharing topic never double-fetches QVERIFY2(lookedUp.contains(mStream), qPrintable(lookedUp.join(","))); QVERIFY2(lookedUp.contains(mRead), qPrintable(lookedUp.join(","))); const auto readRow = topicRowOf(topicId); - QCOMPARE(readRow.value("previewText").toString(), QStringLiteral("Old read body")); - QCOMPARE(readRow.value("previewState").toString(), QStringLiteral("ready")); + const auto readPreview = previewOf(test.controller, readRow); + QCOMPARE(readPreview.value("previewText").toString(), QStringLiteral("Old read body")); + QCOMPARE(readPreview.value("previewState").toString(), QStringLiteral("ready")); const auto expectedTime = NativeController::formatRowTime( QDateTime(QDate(2025, 8, 2), QTime(10, 0, 5), Qt::UTC), QLocale::system(), QDate::currentDate(), QStringLiteral("Yesterday")); - QCOMPARE(readRow.value("rowTime").toString(), expectedTime); + QCOMPARE(readPreview.value("rowTime").toString(), expectedTime); const auto streamRow = test.controller.streams().first().toMap(); - QCOMPARE(streamRow.value("previewText").toString(), QStringLiteral("Stream body")); + QCOMPARE(previewOf(test.controller, streamRow).value("previewText").toString(), QStringLiteral("Stream body")); const auto emptyRow = topicRowOf(QStringLiteral("77777777-7777-4777-7777-0000000000e1")); - QCOMPARE(emptyRow.value("previewText").toString(), QString{}); + QCOMPARE(previewOf(test.controller, emptyRow).value("previewText").toString(), QString{}); } // #866 review (exordy findings 1/3): the network stage batch bounds the TOTAL number of @@ -962,7 +973,7 @@ private slots: const auto map = row.toMap(); if (map.value("id").toString() == QStringLiteral("77777777-7777-4777-7777-0000000000c%1").arg(i, 1, 16) - && !map.value("previewText").toString().isEmpty()) + && !previewOf(test.controller, map).value("previewText").toString().isEmpty()) ready = true; } if (!ready) return false; @@ -1074,14 +1085,15 @@ private slots: serverRecovered = true; test.controller.refresh(); QVERIFY(QTest::qWaitFor([&] { return netGets >= 4; }, 3000)); - const auto previewOf = [&] { + const auto recoveredPreviewText = [&] { for (const auto &row : std::as_const(test.controller).topics()) { const auto map = row.toMap(); - if (map.value("id").toString() == topicId) return map.value("previewText").toString(); + if (map.value("id").toString() == topicId) + return previewOf(test.controller, map).value("previewText").toString(); } return QString{}; }; - QTRY_VERIFY_WITH_TIMEOUT(previewOf() == QStringLiteral("Recovered body"), 3000); + QTRY_VERIFY_WITH_TIMEOUT(recoveredPreviewText() == QStringLiteral("Recovered body"), 3000); } // A row whose last message is an E2EE payload the client cannot present previews as the @@ -1135,11 +1147,12 @@ private slots: }; QVERIFY(test.start()); const auto row = test.controller.topics().first().toMap(); - QVERIFY2(row.value("previewLocked").toBool(), qPrintable(row.value("previewText").toString())); - QCOMPARE(row.value("previewState").toString(), QStringLiteral("locked")); - QCOMPARE(row.value("previewKind").toString(), QStringLiteral("e2ee")); - QVERIFY2(!row.value("previewText").toString().contains(QStringLiteral("ZmFrZQ")), - qPrintable(row.value("previewText").toString())); + const auto lockedPreview = previewOf(test.controller, row); + QVERIFY2(lockedPreview.value("previewLocked").toBool(), qPrintable(lockedPreview.value("previewText").toString())); + QCOMPARE(lockedPreview.value("previewState").toString(), QStringLiteral("locked")); + QCOMPARE(lockedPreview.value("previewKind").toString(), QStringLiteral("e2ee")); + QVERIFY2(!lockedPreview.value("previewText").toString().contains(QStringLiteral("ZmFrZQ")), + qPrintable(lockedPreview.value("previewText").toString())); } // docs/NATIVE_DESKTOP_SIDEBAR_ROW_STATES.md (issue #96): streams() rows carry the @@ -1357,9 +1370,11 @@ private slots: QTRY_VERIFY_WITH_TIMEOUT(([&] { for (const auto &entry : test.controller.streams()) { const auto row = entry.toMap(); - if (row.value("id").toString() == second) - return row.value("previewText").toString() == QStringLiteral("Cached preview body") - && !row.value("rowTime").toString().isEmpty(); + if (row.value("id").toString() == second) { + const auto diskPreview = previewOf(test.controller, row); + return diskPreview.value("previewText").toString() == QStringLiteral("Cached preview body") + && !diskPreview.value("rowTime").toString().isEmpty(); + } } return false; })(), 5000); @@ -1378,12 +1393,68 @@ private slots: for (const auto &entry : test.controller.streams()) { const auto row = entry.toMap(); if (row.value("id").toString() == unknown) { - QCOMPARE(row.value("previewText").toString(), QString()); - QCOMPARE(row.value("rowTime").toString(), QString()); + QCOMPARE(previewOf(test.controller, row).value("previewText").toString(), QString()); + QCOMPARE(previewOf(test.controller, row).value("rowTime").toString(), QString()); } } } + // #866 review (finding 3, design round): a preview-content arrival must announce on + // the narrow preview-only revision and must NOT re-announce the sidebar projection. + // A projection rebuild destroys an in-flight click or a pinned scroll position, which + // is exactly what the window acceptance case pins at the scene layer. Both signals + // are pinned here: `previewChanged` fires (coalesced), `streamsChanged` stays quiet + // for a row whose last-message pointer did not move. + void previewArrivalAnnouncesRevisionWithoutProjectionRebuild() + { + Fixture test; + const auto hidden = QStringLiteral("88888888-8888-4888-8888-000000000b01"); + const auto second = QStringLiteral("33333333-3333-4333-8333-666666666667"); + const auto streamRow = [](const QString &uuid, const QString &name, const QJsonValue &last) { + return QJsonObject{{"uuid", uuid}, {"project_id", projectId}, {"name", name}, + {"encryption", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", last}, + {"updated_at", "2026-01-02T10:00:05Z"}}; + }; + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) + return Response{QJsonArray{streamRow(streamId, "Native channel", QJsonValue::Null), + streamRow(second, "Cached channel", QString(hidden))}}; + return Response{streamRow(streamId, "Native channel", QJsonValue::Null)}; + }; + test.messages = [](const Request &) { return Response{QJsonArray{}}; }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativeCacheService cache(directory.path(), {}, true); + test.controller.useCache(&cache); + test.controller.login(test.server.origin().toString(), "synthetic-user", "synthetic-password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + QTRY_COMPARE(test.controller.streams().size(), 2); + // The DTO no longer carries baked preview keys; the delegate reads the memo + // through previewFields(uuid, revision), empty until the body resolves. + QVERIFY(test.controller.previewFields(hidden, test.controller.previewRevision()) + .value("previewText").toString().isEmpty()); + auto cached = message("Revision preview body", hidden); + cached["user_uuid"] = userId; + QSignalSpy previews(&test.controller, &NativeController::previewChanged); + QSignalSpy projection(&test.controller, &NativeController::streamsChanged); + bool stored = false; + QVERIFY(cache.putMessageBody(cache.lease(), cached, &cache, [&stored](bool okay) { stored = okay; })); + QVERIFY(QTest::qWaitFor([&stored] { return stored; }, 2000)); + // The late body lands while the catalog is already projected: the pump (or the + // late-disk retry after the empty network page) resolves the memo and the ONLY + // announcement is the preview revision. + QTRY_VERIFY_WITH_TIMEOUT(([&] { + const auto text = test.controller.previewFields(hidden, test.controller.previewRevision()) + .value("previewText").toString(); + return text == QStringLiteral("Revision preview body"); + })(), 5000); + // The coalesced bump fires one event-loop pass after the memo write, so wait for + // the announcement instead of racing the poll that observed the text. + QTRY_VERIFY_WITH_TIMEOUT(([&] { return previews.count() >= 1; })(), 2000); + QCOMPARE(projection.count(), 0); // no projection churn - the whole point of the seam + } + private: // --- sidebar preview memo lifecycle (issue #116) --- @@ -1459,7 +1530,8 @@ private slots: { for (const auto &entry : controller.topics()) { const auto row = entry.toMap(); - if (row.value("id").toString() == topic) return row.value("previewText").toString(); + if (row.value("id").toString() == topic) + return previewOf(controller, row).value("previewText").toString(); } return QStringLiteral(""); } diff --git a/packages/native/tests/native-e2ee-read-test.cpp b/packages/native/tests/native-e2ee-read-test.cpp index 51925bced..f3f21b93a 100644 --- a/packages/native/tests/native-e2ee-read-test.cpp +++ b/packages/native/tests/native-e2ee-read-test.cpp @@ -10329,8 +10329,13 @@ private slots: const auto twice = [](const QString &text) { return QStringList{text, text}; }; QTRY_COMPARE(previews(), twice(locale == "ru" ? QStringLiteral("Нужен ключ") : QStringLiteral("Key required"))); bool preparing = false; - const auto observe = connect(&f.controller, &NativeController::topicsChanged, this, [&] { - if (f.controller.streams().first().toMap().value("previewState") != "preparing") return; + // #866 review (finding 3): the encrypted preview state travels on previewChanged + // now - the sidebar projection is not re-announced for derived content. + const auto observe = connect(&f.controller, &NativeController::previewChanged, this, [&] { + const auto prepRow = f.controller.streams().first().toMap(); + const auto prepState = f.controller.previewFields(prepRow.value("lastMessage").toString(), + f.controller.previewRevision()).value("previewState").toString(); + if (prepState != QLatin1String("preparing")) return; const auto expected = locale == "ru" ? QStringLiteral("Расшифровка сообщения…") : QStringLiteral("Decrypting message…"); preparing |= previews() == twice(expected); }); @@ -10346,7 +10351,9 @@ private slots: QTRY_COMPARE(previews(), twice(QStringLiteral("Sidebar summary"))); f.controller.useChatKeys(nullptr); QTRY_COMPARE(previews(), twice(locale == "ru" ? QStringLiteral("Нужен ключ") : QStringLiteral("Key required"))); - QVERIFY(f.controller.streams().first().toMap().value("previewText").toString().isEmpty()); + const auto finalRow = f.controller.streams().first().toMap(); + QVERIFY(f.controller.previewFields(finalRow.value("lastMessage").toString(), + f.controller.previewRevision()).value("previewText").toString().isEmpty()); } void uiEncryptedMessageDecryptRetryRowCyclesAndRepairs_data() { diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index 1e56fd475..241897ddc 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -41094,7 +41094,9 @@ private slots: const auto latestTopic = [&] { for (const auto &entry : controller.streams()) { const auto row = entry.toMap(); - if (row.value("id").toString() == streamId) return row.value("previewTopic").toString(); + if (row.value("id").toString() == streamId) + return controller.previewFields(row.value("lastMessage").toString(), + controller.previewRevision()).value("previewTopic").toString(); } return QString{}; }; @@ -41168,7 +41170,8 @@ private slots: for (const auto &value : controller.streams()) { const auto row = value.toMap(); if (row.value("id").toString() == streamId) - return row.value("previewTopic").toString() == secondTopicId; + return controller.previewFields(row.value("lastMessage").toString(), + controller.previewRevision()).value("previewTopic").toString() == secondTopicId; } return false; })(), 5000); @@ -46485,7 +46488,9 @@ private slots: QVERIFY(!display().contains("hidden word")); QVERIFY(!display().contains("Block answer")); QVERIFY(display().contains(locale == "ru" ? QStringLiteral("Спойлер") : QStringLiteral("Spoiler"))); - const auto summary = controller.streams().first().toMap().value("previewText").toString(); + const auto summaryRow = controller.streams().first().toMap(); + const auto summary = controller.previewFields(summaryRow.value("lastMessage").toString(), + controller.previewRevision()).value("previewText").toString(); QVERIFY2(summary.contains("hidden word") && summary.contains("Block answer"), qPrintable(summary)); click(window, target(1)); QTRY_VERIFY(display().contains("hidden word")); From eb6c78df4862d0d6f6622f9f8c9126efc26ea0ea Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 06:46:06 +0300 Subject: [PATCH 08/20] test: window acceptance for network preview hydration under an active row Finding 3 (PR #866) acceptance case: with network preview hydration ENABLED (the production shape the window harness previously had to pin off in e326bc59), a held uuid lookup reply lands while a sidebar row holds keyboard focus. The focused row must survive as the same item instance at the same scene position with focus intact, the list offset must not move, and the click target must still select its stream - while the preview text itself flips through the previewRevision projection. Witness: the identical case FAILS on the parent shape ecd82ccc ('A network preview arrival must not re-incubate the focused sidebar row' - the delegate is destroyed by the old streamsChanged announcement) and PASSES green solo at this head (single-case run 3.70 s, window-test buckets regenerated). --- .../tests/bucket-timings/window/part06.txt | 1 + packages/native/tests/native-window-test.cpp | 87 +++++++++++++++++++ .../native/tests/window-test-buckets.cmake | 1 + 3 files changed, 89 insertions(+) diff --git a/packages/native/tests/bucket-timings/window/part06.txt b/packages/native/tests/bucket-timings/window/part06.txt index 11792d27b..e13a47a65 100644 --- a/packages/native/tests/bucket-timings/window/part06.txt +++ b/packages/native/tests/bucket-timings/window/part06.txt @@ -21,6 +21,7 @@ pollVoterOverviewSwitchRetiresHeldFirstPage=1.62027 rightDrawerConversationSwitchDropsNestedChatScreens=0.797574 savedHistoryRefreshFailureShowsOneAlertAndOneRetry=3.92774 sidebarExpansionWindowLoadDiagnostic=16.9019 +sidebarNetworkPreviewHydrationKeepsRowFocusAndClickTarget=3.69858 sidebarPartialRefreshErrorKeepsRowsAndShowsBanner=0.649468 windowChannelInfoNonOwnerMemberGates=1.40062 windowChannelNotificationLevelsAndUnsupportedFallback=5.60172 diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index 241897ddc..1789057d8 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -13245,6 +13245,93 @@ mv -Tf "$root/.current-new" "$root/current" const bool closed = closeIncubatedTestWindow(engine, window); if (closed) close.dismiss(); QVERIFY(closed); } + void sidebarNetworkPreviewHydrationKeepsRowFocusAndClickTarget() + { + // #866 (finding 3 acceptance): with network preview hydration ENABLED - the shape + // production runs and the window harness previously had to pin off (e326bc59) - + // a preview arrival must reach the row through the narrow previewRevision + // projection only. The old streamsChanged announcement rebuilt the whole sidebar + // projection mid-interaction: rows were re-incubated under the user, so focused + // rows lost keyboard focus, click targets went stale and list positions drifted. + WindowChannelFixture fixture; + const QString otherStream = "a3000000-0000-4000-8000-000000000001"; + const QString previewUuid = "81000000-0000-4000-8000-000000000001"; + const QString previewBody = QStringLiteral("Hydrated network preview"); + auto first = windowChannel(streamId, "Engineering"); + first["last_message_uuid"] = previewUuid; + const auto second = windowChannel(otherStream, "Support"); + const auto previewRow = QJsonObject{ + {"uuid", previewUuid}, {"project_id", projectId}, {"author_uuid", userId}, + {"stream_uuid", streamId}, {"topic_uuid", topicId}, {"revision", 1}, + {"created_at", "2026-01-02T10:00:05.000Z"}, {"updated_at", "2026-01-02T10:00:05.000Z"}, + {"payload", QJsonObject{{"kind", "markdown"}, {"content", previewBody}}}}; + const auto fallback = fixture.server.handler; + auto held = std::make_shared>(); + fixture.server.handler = [=](const Request &request) -> Response { + const auto path = request.target.path(); + if (request.method == "GET" && path.endsWith("/streams/")) + return {QJsonArray{first, second}}; + if (request.method == "GET" && path.endsWith("/stream_topics/")) { + const auto id = QUrlQuery(request.target).queryItemValue("stream_uuid"); + return {QJsonArray{windowChannelTopic(id == streamId ? topicId : secondTopicId, id, "Topic")}}; + } + // The row-preview uuid lookup (GET /messages/?project_id=..&uuid=..), held in + // flight so the reply lands while the sidebar is already under interaction. + if (request.method == "GET" && path.endsWith("/messages/") + && QUrlQuery(request.target).queryItemValue("uuid") == previewUuid) { + Response response{QJsonArray{previewRow}}; + response.defer = [held](auto send) { *held = std::move(send); }; + return response; + } + return fallback(request); + }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativePreferences preferences(directory.filePath("network-preview-hydration.ini")); + ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + QQmlApplicationEngine engine; loadNativeUi(engine, &controller, &preferences); + auto *window = qobject_cast(engine.rootObjects().value(0)); QVERIFY(window); + auto close = qScopeGuard([&engine, guard = QPointer(window)] { + if (guard && !closeIncubatedTestWindow(engine, guard.data())) + QTest::qFail("Network preview hydration teardown", __FILE__, __LINE__); + }); + window->resize(1440, 900); QVERIFY(QTest::qWaitForWindowExposed(window)); + window->requestActivate(); QVERIFY(QTest::qWaitForWindowActive(window)); + session.login(fixture.server.origin(), "synthetic-hydration", "synthetic-password"); + QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); + QTRY_VERIFY(session.ready() && !controller.busy() && controller.streams().size() == 2); + const auto previewText = [&]() { + const auto *item = visibleItem("streamPreviewText-" + streamId); + return item ? item->property("text").toString() : QString(); + }; + // Nothing arrived yet: the disk stage has no body for the uuid and the reply is held. + QVERIFY(previewText().isEmpty()); + // An active interaction is in progress on the row that is about to receive a preview. + QPointer focusRow = visibleItem("stream-" + streamId); QVERIFY(focusRow); + QPointer clickRow = visibleItem("stream-" + otherStream); QVERIFY(clickRow); + focusRow->forceActiveFocus(Qt::TabFocusReason); QTRY_VERIFY(focusRow->hasActiveFocus()); + auto *streamList = visibleItem("streamList"); QVERIFY(streamList); + const auto sceneBefore = focusRow->mapToScene(QPointF(0, 0)); + const auto listYBefore = streamList->property("contentY").toDouble(); + QTRY_VERIFY(bool(*held)); // the lookup is in flight + (*held)(); *held = {}; + // The preview lands: text flips and the preview-only revision moves... + QTRY_COMPARE_WITH_TIMEOUT(previewText(), previewBody, 5000); + // ...and nothing else moved: the focused row is the same item instance at the same + // scene position, keyboard focus never left it, and the list kept its offset. + QVERIFY2(focusRow && focusRow->hasActiveFocus(), + "A network preview arrival must not re-incubate the focused sidebar row"); + QCOMPARE(focusRow->mapToScene(QPointF(0, 0)), sceneBefore); + QCOMPARE(streamList->property("contentY").toDouble(), listYBefore); + // The click target under the user survived the arrival and still selects its stream. + QVERIFY(clickRow); + QTest::mouseClick(window, Qt::LeftButton, {}, + clickRow->mapToScene(QPointF(20, clickRow->height() / 2)).toPoint()); + QTRY_COMPARE(controller.selectedStream(), otherStream); + const bool closed = closeIncubatedTestWindow(engine, window); + if (closed) close.dismiss(); + QVERIFY(closed); + } + void sidebarHydrationKeepsFocusOnOtherStream() { WindowChannelFixture fixture; diff --git a/packages/native/tests/window-test-buckets.cmake b/packages/native/tests/window-test-buckets.cmake index 73193a3f7..186854d15 100644 --- a/packages/native/tests/window-test-buckets.cmake +++ b/packages/native/tests/window-test-buckets.cmake @@ -148,6 +148,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_6 rightDrawerConversationSwitchDropsNestedChatScreens savedHistoryRefreshFailureShowsOneAlertAndOneRetry sidebarExpansionWindowLoadDiagnostic + sidebarNetworkPreviewHydrationKeepsRowFocusAndClickTarget sidebarPartialRefreshErrorKeepsRowsAndShowsBanner windowChannelInfoNonOwnerMemberGates windowChannelNotificationLevelsAndUnsupportedFallback From 9711dcb8752ddc5a9c559c74fede3821061685d1 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 08:42:25 +0300 Subject: [PATCH 09/20] fix: let hydrated preview stamps re-sort the sidebar activity order exordy finding on PR #866: the preview pumps recorded the memo but left the learned created stamp out of the activity ledger, so a row whose true last-message timestamp differed from its updated_at fallback never moved. Record the stamp from both pumps and announce a coalesced streamsChanged only when the projected order actually moves - a preview arrival that reorders nothing keeps the preview-only announcement (pinned by previewArrivalAnnouncesRevisionWithoutProjectionRebuild). --- packages/native/src/native-controller.cpp | 75 +++++++++++++++--- packages/native/src/native-controller.h | 10 +++ .../tests/native-controller-sidebar-test.cpp | 79 +++++++++++++++++++ 3 files changed, 155 insertions(+), 9 deletions(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index a0bdddcaa..56a93b120 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -14539,16 +14539,12 @@ QVariantMap NativeController::streamById(const QString &id) const return {}; } -QVariantList NativeController::streams() const +QVector NativeController::orderedStreamPointers() const { - // Issue #868 (design verdict): this getter MUST rebuild per read. The - // property is bound from QML, and a Qt 6.10 binding that was served a - // cached QVariant once never re-evaluates on the next NOTIFY again (the - // cached variant froze globalTopicUsesTypedHttpForEveryMetadataKind on - // four full-gate shards, PR #871). Getter-level projection caches are - // therefore only legal for internal C++ consumers, never for QML-bound - // reads like this one. - ++m_streamsProjectionCount; + // exordy finding on PR #866: the projected sidebar order, factored out of streams() + // so the preview pumps can re-evaluate the order after recording a hydrated activity + // stamp without materializing the row DTOs. streams() still rebuilds per read + // (issue #868 design verdict, see the comment on streams()). QVector ordered; for (const auto &stream : m_streams) { if (!stream.archived) { ordered.append(&stream); } @@ -14582,6 +14578,59 @@ QVariantList NativeController::streams() const return a->activeUnread > 0; return activity.value(a->uuid) > activity.value(b->uuid); }); + return ordered; +} + +bool NativeController::applyHydratedRowActivity(const Message &message) +{ + // exordy finding on PR #866: the hydration pumps learned a row's true last-message + // stamp but left it out of the activity ledger, so the projected order stayed pinned + // at the stale updated_at fallback. Record the stamp unconditionally (the next + // projection read must sort from it either way) and report ONLY when the projected + // order actually moved - a memo that agrees with the old key, or reorders nothing, + // must not cost the sidebar a projection rebuild (that is the whole point of the + // preview-only announcement seam). + if (message.uuid.isEmpty() || message.createdMicros <= 0) return false; + bool keyMoves = false; + for (const auto &stream : std::as_const(m_streams)) { + if (stream.archived || stream.lastMessage != message.uuid) continue; + if (rowActivityMicros(stream.lastMessage, stream.updatedMicros) != message.createdMicros) { + keyMoves = true; + break; + } + } + if (!keyMoves) return false; + QStringList orderBefore; + for (const auto *stream : orderedStreamPointers()) orderBefore << stream->uuid; + noteActivityTimestamps({message}); + QStringList orderAfter; + for (const auto *stream : orderedStreamPointers()) orderAfter << stream->uuid; + return orderAfter != orderBefore; +} + +void NativeController::scheduleStreamsReorderAnnounce() +{ + // Coalesced exactly like schedulePreviewRevisionBump: one streamsChanged per event + // loop pass no matter how many hydrated stamps moved the order in one pump batch. + if (m_streamsReorderQueued) return; + m_streamsReorderQueued = true; + QTimer::singleShot(0, this, [this] { + m_streamsReorderQueued = false; + emit streamsChanged(); + }); +} + +QVariantList NativeController::streams() const +{ + // Issue #868 (design verdict): this getter MUST rebuild per read. The + // property is bound from QML, and a Qt 6.10 binding that was served a + // cached QVariant once never re-evaluates on the next NOTIFY again (the + // cached variant froze globalTopicUsesTypedHttpForEveryMetadataKind on + // four full-gate shards, PR #871). Getter-level projection caches are + // therefore only legal for internal C++ consumers, never for QML-bound + // reads like this one. + ++m_streamsProjectionCount; + const auto ordered = orderedStreamPointers(); QVariantList result; for (const auto *entry : ordered) result.append(streamRowMap(*entry)); @@ -19757,7 +19806,11 @@ void NativeController::pumpRowPreviewHydration() // only, so they re-project from the fresh memo. } else if (const auto parsed = body ? parseMessage(body->row, m_session->project()) : std::nullopt; parsed && parsed->uuid == uuid) { + // exordy finding on PR #866: same ledger write and reorder announcement + // as the network pump - a disk-hydrated stamp moves the sidebar too. + const bool reorder = applyHydratedRowActivity(*parsed); storeRowPreview(uuid, rowPreviewOf(*parsed)); + if (reorder) scheduleStreamsReorderAnnounce(); } else if (!body && m_rowPreviewNetworkEnabled) { // #860: a disk miss is not an authoritative negative - the reference falls // through to the messages lookup (messenger-last-messages-loader.lib.ts @@ -19974,10 +20027,14 @@ void NativeController::pumpRowPreviewNetworkHydration() if (candidate && candidate->uuid == uuid) { parsed = candidate; canonical = value.toObject(); break; } } if (parsed) { + // exordy finding on PR #866: the learned stamp participates in the activity + // ledger now; a reorder of the projected order announces streamsChanged. + const bool reorder = applyHydratedRowActivity(*parsed); storeRowPreview(uuid, rowPreviewOf(*parsed)); // Best-effort owner-scoped disk fill, mirroring the reference cache write: // the next cold start hydrates from disk without a network lookup. if (cache && cache->available()) cache->putMessageBody(lease, canonical); + if (reorder) scheduleStreamsReorderAnnounce(); } else if (cache && m_rowPreviewLateDiskRetries.value(uuid) < rowPreviewLateDiskRetries) { // #860: the server does not hold this message, but a disk body may still be // on its way (sidebarPreviewsHydrateFromTheCacheAsynchronously: the cache diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 45a16af7c..d33bf3bf4 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -2192,6 +2192,14 @@ class NativeController final : public QObject { // pump tick no matter how many memos that tick stored (replaces the streamsChanged // announcements the preview paths used to fire). void schedulePreviewRevisionBump(); + // exordy finding on PR #866 (medium): a hydration pump that learns the real created + // stamp of a row's last message must let it participate in the activity comparator. + // applyHydratedRowActivity records the stamp in the same ledger noteActivityMerge + // feeds and reports whether the projected order actually moved; that report gates one + // coalesced streamsChanged - the QML binding edge that re-reads the projection. + QVector orderedStreamPointers() const; + bool applyHydratedRowActivity(const Message &message); + void scheduleStreamsReorderAnnounce(); quint64 bumpRowPreviewFence(const QString &uuid); qint64 rowActivityMicros(const QString &lastMessage, qint64 updatedMicros) const; // Issue #867 (subtask A): single-row projection shared by streams() and @@ -2257,6 +2265,8 @@ class NativeController final : public QObject { // #866 review (finding 3): preview-only revision counter + coalesce flag. int m_previewRevision = 0; bool m_previewRevisionBumpQueued = false; + // exordy finding on PR #866: coalesce flag for the activity-reorder streamsChanged. + bool m_streamsReorderQueued = false; // #860: a disk miss is not an authoritative negative - the reference falls through to the // project-scoped messages lookup during bootstrap (messenger-last-messages-loader.lib.ts // L96-129). The network stage is bounded per tick like the disk pump, retries transient diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index ff7481466..c18b74206 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1455,6 +1455,72 @@ private slots: QCOMPARE(projection.count(), 0); // no projection churn - the whole point of the seam } + // exordy finding on PR #866 (medium): hydration learns the authoritative creation stamp + // of a row's last message. When that stamp moves the projected activity order, the + // sidebar must actually re-sort: the pump records the observed stamp in the same ledger + // noteActivityMerge feeds, and announces it - the projection rebuilds per read, but the + // QML streams binding only re-reads on streamsChanged. Without this the row stays pinned + // at its stale updated_at fallback forever. + void sidebarPreviewHydrationReordersActivityOrder() + { + Fixture test; + test.aggregateMessages = true; // route the pump's GET /messages/?uuid= to test.messages + const auto hydrated = QStringLiteral("88888888-8888-4888-8888-000000000c01"); + const auto fallbackLead = QStringLiteral("33333333-3333-4333-8333-666666666668"); + const auto streamRow = [](const QString &uuid, const QString &name, const QJsonValue &last, + const QString &updated) { + return QJsonObject{{"uuid", uuid}, {"project_id", projectId}, {"name", name}, + {"encryption", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", last}, {"updated_at", updated}}; + }; + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) + return Response{QJsonArray{ + streamRow(streamId, "Route stream", QString(hydrated), "2026-01-02T10:00:05Z"), + streamRow(fallbackLead, "Fallback lead", QJsonValue::Null, "2026-01-02T10:00:06Z")}}; + if (request.target.path().endsWith(fallbackLead)) + return Response{streamRow(fallbackLead, "Fallback lead", QJsonValue::Null, + "2026-01-02T10:00:06Z")}; + return Response{streamRow(streamId, "Route stream", QString(hydrated), "2026-01-02T10:00:05Z")}; + }; + auto lateBody = message("Hydrated late activity", hydrated); + lateBody["created_at"] = QStringLiteral("2026-01-03T09:00:00Z"); // newer than every fallback key + auto gate = std::make_shared>(); + test.messages = [&](const Request &request) { + if (request.method == "GET" + && QUrlQuery(request.target).queryItemValue("uuid") == hydrated) { + // Hold the pump's lookup so the fallback-sort baseline is deterministic. + Response held{QJsonArray{lateBody}}; + held.defer = [gate](std::function send) { *gate = send; }; + return held; + } + return Response{QJsonArray{}}; + }; + test.controller.login(test.server.origin().toString(), "synthetic-user", "synthetic-password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + QTRY_COMPARE(test.controller.streams().size(), 2); + // Before hydration both rows sort by their updated_at fallback, so the pointerless + // channel with the newer stamp leads. + QVERIFY(QTest::qWaitFor([&] { return *gate != nullptr; }, 3000)); + QCOMPARE(test.controller.streams().first().toMap().value("id").toString(), fallbackLead); + QSignalSpy projection(&test.controller, &NativeController::streamsChanged); + (*gate)(); // release the pump's in-flight lookup + // The network pump resolves the pointer from the catalog seed... + QTRY_VERIFY_WITH_TIMEOUT(([&] { + return test.controller.previewFields(hydrated, test.controller.previewRevision()) + .value("previewText").toString() == QStringLiteral("Hydrated late activity"); + })(), 5000); + // ...and the resolved true stamp must move the row to the top: the projection rebuilds + // per read, so a fresh read after the pump shows the corrected order. + QTRY_VERIFY_WITH_TIMEOUT(([&] { + return test.controller.streams().first().toMap().value("id").toString() == streamId; + })(), 5000); + // And the reorder travels as a streamsChanged announcement - the QML binding edge + // that re-reads the projection. It fires one event-loop pass after the ledger write. + QTRY_VERIFY_WITH_TIMEOUT(([&] { return projection.count() >= 1; })(), 2000); + } + private: // --- sidebar preview memo lifecycle (issue #116) --- @@ -2547,6 +2613,7 @@ private slots: const QJsonArray streams{streamDto(streamId, "Hydrated", "2026-01-01T00:00:00Z", recent), streamDto(bgA, "Alpha", "2026-01-02T00:00:00Z", QString()), streamDto(bgB, "Beta", "2026-01-03T00:00:00Z", QString())}; + auto gate = std::make_shared>(); fixture.streams = [&](const Request &) { return Response{streams}; }; fixture.counters = [&](const Request &request) -> Response { const auto id = request.target.path().section('/', -1); @@ -2565,6 +2632,13 @@ private slots: fixture.messages = [&](const Request &request) -> Response { if (request.target.toString().contains(bgA) || request.target.toString().contains(bgB)) return Response{QJsonArray{}}; + if (QUrlQuery(request.target).queryItemValue("uuid") == recent) { + // Hold the preview pump's lookup so the fallback-sort baseline is + // deterministic; the test releases it explicitly. + Response held{QJsonArray{hero}}; + held.defer = [gate](std::function send) { *gate = send; }; + return held; + } return Response{QJsonArray{hero}}; }; auto &c = fixture.controller; @@ -2577,7 +2651,12 @@ private slots: c.login(fixture.server.origin().toString(), "synthetic-user", "synthetic-password", ""); QTRY_COMPARE(c.projects().size(), 1); c.openProject(projectId); QTRY_COMPARE(c.streams().size(), 3); + QVERIFY(QTest::qWaitFor([&] { return *gate != nullptr; }, 3000)); QCOMPARE(position(streamId), 2); // Oldest updated_at sorts last before hydration. + // exordy finding on PR #866: the preview pump's learned stamp is a legitimate + // activity move - release the held lookup and the row must reorder on its own. + (*gate)(); + QTRY_COMPARE_WITH_TIMEOUT(position(streamId), 0, 5000); c.selectStream(streamId); QTRY_COMPARE(c.messages().size(), 1); QTRY_VERIFY(!c.busy()); QCOMPARE(position(streamId), 0); // The hydrated last-message stamp ranks it first. From 824249f5b35a570f4544bfb15cca4b14621f19f2 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 09:03:02 +0300 Subject: [PATCH 10/20] fix: record hydrated activity stamps that equal the current fallback key exordy finding 4704344635 on PR #866: the round-1 keyMoves guard skipped the ledger write when the hydrated stamp matched the row's updated_at fallback. A later stream.updated bump of updated_at then re-keyed the row from the drift instead of the known message timestamp. Record the stamp whenever a live row owns the pointer; announcement semantics unchanged (streamsChanged only when the projected order actually moves). Repro: sidebarPreviewHydrationKeepsEqualFallbackStampAgainstDrift (RED before the fix: the drifted row jumped above the genuinely newer peer). --- packages/native/src/native-controller.cpp | 13 +++- .../tests/native-controller-sidebar-test.cpp | 60 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 56a93b120..ba7a06067 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -14592,14 +14592,25 @@ bool NativeController::applyHydratedRowActivity(const Message &message) // preview-only announcement seam). if (message.uuid.isEmpty() || message.createdMicros <= 0) return false; bool keyMoves = false; + bool rowOwnsPointer = false; for (const auto &stream : std::as_const(m_streams)) { if (stream.archived || stream.lastMessage != message.uuid) continue; + rowOwnsPointer = true; if (rowActivityMicros(stream.lastMessage, stream.updatedMicros) != message.createdMicros) { keyMoves = true; break; } } - if (!keyMoves) return false; + if (!rowOwnsPointer) return false; + if (!keyMoves) { + // exordy finding 4704344635 (PR #866 round 2): record the stamp even when it + // equals the current fallback key. Skipping the write on an equal key lets a + // later catalog bump of updated_at silently re-key the row from the drift + // instead of the known message timestamp (the order cannot move here, so the + // preview-only announcement seam stays intact). + noteActivityTimestamps({message}); + return false; + } QStringList orderBefore; for (const auto *stream : orderedStreamPointers()) orderBefore << stream->uuid; noteActivityTimestamps({message}); diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index c18b74206..3d5ad147b 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1521,6 +1521,66 @@ private slots: QTRY_VERIFY_WITH_TIMEOUT(([&] { return projection.count() >= 1; })(), 2000); } + void sidebarPreviewHydrationKeepsEqualFallbackStampAgainstDrift() + { + Fixture test; + test.aggregateMessages = true; // route the pump's GET /messages/?uuid= to test.messages + const auto hydrated = QStringLiteral("88888888-8888-4888-8888-000000000c02"); + const auto peer = QStringLiteral("33333333-3333-4333-8333-666666666669"); + const auto streamRow = [](const QString &uuid, const QString &name, const QJsonValue &last, + const QString &updated) { + return QJsonObject{{"uuid", uuid}, {"project_id", projectId}, {"name", name}, + {"encryption", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", last}, {"updated_at", updated}}; + }; + // exordy finding 4704344635: a hydrated stamp EQUAL to the current fallback must + // still reach the activity ledger, because a later catalog bump of updated_at + // would otherwise re-key the row from the drift instead of the known stamp. + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) + return Response{QJsonArray{ + streamRow(streamId, "Hydrated row", QString(hydrated), "2026-01-02T10:00:00Z"), + streamRow(peer, "Peer row", QJsonValue::Null, "2026-01-02T10:00:03Z")}}; + if (request.target.path().endsWith(peer)) + return Response{streamRow(peer, "Peer row", QJsonValue::Null, + "2026-01-02T10:00:03Z")}; + return Response{streamRow(streamId, "Hydrated row", QString(hydrated), + "2026-01-02T10:00:00Z")}; + }; + auto lateBody = message("Equal-stamp preview", hydrated); + lateBody["created_at"] = QStringLiteral("2026-01-02T10:00:00Z"); // exactly the fallback + auto gate = std::make_shared>(); + test.messages = [&](const Request &request) { + if (request.method == "GET" + && QUrlQuery(request.target).queryItemValue("uuid") == hydrated) { + // Hold the pump's lookup so the fallback-sort baseline is deterministic. + Response held{QJsonArray{lateBody}}; + held.defer = [gate](std::function send) { *gate = send; }; + return held; + } + return Response{QJsonArray{}}; + }; + test.controller.login(test.server.origin().toString(), "synthetic-user", "synthetic-password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + QTRY_COMPARE(test.controller.streams().size(), 2); + QVERIFY(QTest::qWaitFor([&] { return *gate != nullptr; }, 3000)); + // Baseline: the peer's fallback (T+3s) leads the hydrated row's fallback (T+0s). + QCOMPARE(test.controller.streams().first().toMap().value("id").toString(), peer); + (*gate)(); // release the pump's in-flight lookup + QTRY_VERIFY_WITH_TIMEOUT(([&] { + return test.controller.previewFields(hydrated, test.controller.previewRevision()) + .value("previewText").toString() == QStringLiteral("Equal-stamp preview"); + })(), 5000); + // A later stream.updated bumps the row's updated_at past the peer's key (an + // unrelated server-side row edit): with the known message stamp in the ledger the + // sort must ignore the drift; with the equal stamp discarded the drift re-keys it. + QVERIFY(test.controller.applyRealtimeEvent(controllerEvent("stream.updated", + streamRow(streamId, "Hydrated row", QString(hydrated), "2026-01-02T10:00:05Z")))); + // The genuinely newer peer keeps the lead: the known T+0s stamp still governs. + QCOMPARE(test.controller.streams().first().toMap().value("id").toString(), peer); + } + private: // --- sidebar preview memo lifecycle (issue #116) --- From b0951500874dd98e23f0487a5097b2d19f80d764 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 10:53:02 +0300 Subject: [PATCH 11/20] fix: announce preview revisions for inbox-slot topics hydrated by the catalog seed exordy finding on PR #866 (medium): the row-preview catalog seed includes the inbox slot topics of inactive streams, but both announce scans (the disk pump affectsRow check and announceRowPreviewRows) only consulted m_streams and m_topics. A memo completing an inbox-topic preview stored fine but never announced previewChanged, so the bound row stayed blank forever. Reproduced RED first (hydratedInboxTopicPreviewAnnouncesRevision: memo text resolves while previewChanged stays silent), fixed by scanning m_inboxTopics in both seams. Full sidebar suite green 148/148. --- packages/native/src/native-controller.cpp | 13 +++ .../tests/native-controller-sidebar-test.cpp | 79 +++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index ba7a06067..b23bcd6c3 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -19750,6 +19750,12 @@ void NativeController::announceRowPreviewRows(const QString &uuid) if (stream.lastMessage == uuid) { schedulePreviewRevisionBump(); return; } for (const auto &topic : m_topics) if (topic.lastMessage == uuid) { schedulePreviewRevisionBump(); return; } + // exordy finding on PR #866 (head 05c10517): topics of inactive streams live in the + // inbox slot map (m_inboxTopics), and the catalog seed hydrates their previews too - + // without this scan the memo arrives but the bound inbox row is never re-evaluated. + for (const auto &slot : std::as_const(m_inboxTopics)) + for (const auto &topic : slot) + if (topic.lastMessage == uuid) { schedulePreviewRevisionBump(); return; } } void NativeController::scheduleRowPreviewHydration() const @@ -19838,6 +19844,13 @@ void NativeController::pumpRowPreviewHydration() if (!affectsRow) for (const auto &topic : m_topics) if (topic.lastMessage == uuid) { affectsRow = true; break; } + // exordy finding on PR #866 (head 05c10517): inbox-slot topics (inactive + // streams) are seeded by the same catalog pass and announce like any other + // row - the disk pump must recognize their pointers too. + if (!affectsRow) + for (const auto &slot : std::as_const(m_inboxTopics)) + for (const auto &topic : slot) + if (topic.lastMessage == uuid) { affectsRow = true; break; } // #866 review (finding 3): preview content announces the preview-only revision. if (affectsRow) schedulePreviewRevisionBump(); }); diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index 3d5ad147b..5deb427c8 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1455,6 +1455,85 @@ private slots: QCOMPARE(projection.count(), 0); // no projection churn - the whole point of the seam } + // exordy finding on PR #866 (medium, head 05c10517): the catalog seed includes the + // inbox slot topics of inactive streams, but the announce scans only m_streams and + // m_topics - a memo completing an inbox-topic preview never announced the revision + // and the row stayed blank forever (the QML binding has no other re-evaluation). + void hydratedInboxTopicPreviewAnnouncesRevision() + { + Fixture test; + test.aggregateMessages = true; // the pump's GET /messages/?uuid= answers the empty page + const auto inboxStream = QStringLiteral("55555555-5555-4555-8555-666666666665"); + const auto inboxTopic = QStringLiteral("77777777-7777-4777-8777-000000000d01"); + const auto inboxLast = QStringLiteral("88888888-8888-4888-8888-000000000d01"); + bool inboxFetched = false; + const auto streamRow = [](const QString &uuid, const QString &name, int activeUnread) { + return QJsonObject{{"uuid", uuid}, {"project_id", projectId}, {"name", name}, + {"encryption", false}, {"unread_count", activeUnread}, + {"active_unread_count", activeUnread}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}; + }; + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) + return Response{QJsonArray{streamRow(streamId, "Native channel", 0), + streamRow(inboxStream, "Quiet archive", 1)}}; + return Response{streamRow(streamId, "Native channel", 0)}; + }; + const auto inboxRow = QJsonObject{{"uuid", inboxTopic}, {"project_id", projectId}, + {"stream_uuid", inboxStream}, {"name", "Archived topic"}, {"is_done", false}, + {"is_default", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", QString(inboxLast)}, + {"updated_at", "2026-01-02T10:00:05Z"}}; + test.topics = [&](const Request &request) { + if (QUrlQuery(request.target).queryItemValue("stream_uuid") == inboxStream) { + inboxFetched = true; + return Response{QJsonArray{inboxRow}}; + } + return Response{QJsonArray{ + QJsonObject{{"uuid", topicId}, {"project_id", projectId}, {"stream_uuid", streamId}, + {"name", "First topic"}, {"is_done", false}, {"is_default", true}, + {"unread_count", 0}, {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}, + QJsonObject{{"uuid", QStringLiteral("44444444-4444-4444-8444-666666666666")}, + {"project_id", projectId}, {"stream_uuid", streamId}, {"name", "Second topic"}, + {"is_done", false}, {"is_default", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}, + QJsonObject{{"uuid", QStringLiteral("55555555-5555-4555-8555-666666666664")}, + {"project_id", projectId}, {"stream_uuid", streamId}, {"name", "Third topic"}, + {"is_done", false}, {"is_default", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + }; + test.messages = [](const Request &) { return Response{QJsonArray{}}; }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativeCacheService cache(directory.path(), {}, true); + test.controller.useCache(&cache); + test.controller.login(test.server.origin().toString(), "synthetic-user", "synthetic-password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + QTRY_COMPARE(test.controller.streams().size(), 2); + test.controller.showInbox(); // sweeps the activeUnread catalog and hydrates the slot + QVERIFY(QTest::qWaitFor([&] { return inboxFetched; }, 3000)); + auto cached = message("Inbox topic preview body", inboxLast); + cached["user_uuid"] = userId; + QSignalSpy previews(&test.controller, &NativeController::previewChanged); + QSignalSpy projection(&test.controller, &NativeController::streamsChanged); + bool stored = false; + QVERIFY(cache.putMessageBody(cache.lease(), cached, &cache, [&stored](bool okay) { stored = okay; })); + QVERIFY(QTest::qWaitFor([&stored] { return stored; }, 2000)); + // The memo reaches the store through the late-disk retry path (the server page is + // empty), so the readable preview itself is not the finding - the ANNOUNCEMENT is: + // without the inbox scan the revision never bumps and the bound row stays blank. + QTRY_VERIFY_WITH_TIMEOUT(([&] { + const auto text = test.controller.previewFields(inboxLast, test.controller.previewRevision()) + .value("previewText").toString(); + return text == QStringLiteral("Inbox topic preview body"); + })(), 8000); + QTRY_VERIFY_WITH_TIMEOUT(([&] { return previews.count() >= 1; })(), 2000); + QCOMPARE(projection.count(), 0); // preview content never rebuilds the projection + } + // exordy finding on PR #866 (medium): hydration learns the authoritative creation stamp // of a row's last message. When that stamp moves the projected activity order, the // sidebar must actually re-sort: the pump records the observed stamp in the same ledger From 781992d1f0e2ede55bc57f8ab505550ddab76b19 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 12:37:12 +0300 Subject: [PATCH 12/20] fix: move sidebar rows in place on hydration re-rank instead of resetting the list Finding 2 on PR #866: a hydrated preview stamp that re-ranked its row reset the sidebar ListView model (whole QVariantList reassignment), destroying the delegate under the user and losing focus. Introduce a move-aware sidebar model (NativeSidebarStreamListModel) that diffs the projection into granular inserted/removed/moved/dataChanged deltas, and carry keyboard focus across the re-parent the view performs on a row move, so the moved row keeps focus like the reference's keyed DOM row. The acceptance case sidebarHydrationReorderKeepsActiveSidebarDelegates pins delegate identity, order swap and focus survival; search-filter cases get the one-pass settle that granular row removal takes (the reference DOM filter takes a render tick). --- packages/native/qml/Main.qml | 54 +++++++- packages/native/src/native-controller.cpp | 138 +++++++++++++++++++ packages/native/src/native-controller.h | 51 +++++++ packages/native/tests/native-window-test.cpp | 108 ++++++++++++++- 4 files changed, 345 insertions(+), 6 deletions(-) diff --git a/packages/native/qml/Main.qml b/packages/native/qml/Main.qml index 6a37b440e..52c87d51b 100644 --- a/packages/native/qml/Main.qml +++ b/packages/native/qml/Main.qml @@ -5068,7 +5068,7 @@ component NativeMentionChip: Item { for (let row = 0; row < streamList.count; ++row) { const item = streamList.itemAtIndex(row) if (item && item.y + item.height > cy + 1.0) { - const id = String(streamList.model[row] && streamList.model[row].id || "") + const id = String(streamList.model.streamIdAt(row) || "") if (!id.length) return root.sidebarScrollAnchor = {id: id, offset: item.y - cy, contentHeight: streamList.contentHeight} @@ -5092,7 +5092,7 @@ component NativeMentionChip: Item { return let row = -1 for (let i = 0; i < streamList.count; ++i) { - if (String(streamList.model[i] && streamList.model[i].id || "") === anchor.id) { + if (String(streamList.model.streamIdAt(i) || "") === anchor.id) { row = i break } @@ -6304,7 +6304,10 @@ component NativeMentionChip: Item { anchors.rightMargin: 8 spacing: 2 clip: true - model: root.controller.sidebarStreams + // Issue #866 (finding 2): stable move-aware model (see + // NativeSidebarStreamListModel) - a hydration re-rank moves the + // row instead of resetting the list and re-creating delegates. + model: root.controller.sidebarStreamListModel MouseArea { // Issue #142: sidebar wheel scroller (expanded topic rows // included - they are delegate children) using the same @@ -6330,6 +6333,32 @@ component NativeMentionChip: Item { ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } + property var sidebarFocusCarry: null + // Issue #866 (finding 2) companion: a model row move re-parents the + // delegate subtree; Qt's focus bubbling drops the moved row's active + // focus and lands it on the delegate root after the view relayout. + // The browser keeps focus on the moved DOM node, so carry it across: + // remember the focused item inside a stream row before the move, and + // hand focus back to it the moment the delegate root re-receives the + // bubbled focus (synchronous - no deferred closure races the relayout). + // streamLive flips false on delegate destruction (the #708 rule), so a + // carry can never reach a dead subtree. + Connections { + target: streamList.model + function onRowsAboutToBeMoved() { + const win = streamList.Window.window + const focused = win ? win.activeFocusItem : null + streamList.sidebarFocusCarry = null + if (!focused) + return + for (let node = focused; node && node !== streamList; node = node.parent) { + if (node.liveGuard !== undefined) { + streamList.sidebarFocusCarry = { item: focused, guard: node.liveGuard } + return + } + } + } + } delegate: Column { id: streamDelegate required property var modelData @@ -6372,6 +6401,25 @@ component NativeMentionChip: Item { } onModelDataChanged: refreshTopics() Component.onCompleted: refreshTopics() + // #866 companion: plain-JS liveGuard (the #708 rule) - the focus + // carry holds this object, never a QML wrapper, so a destroyed + // delegate is detectable without touching dead properties. + property var liveGuard: ({ live: true }) + Component.onDestruction: liveGuard.live = false + onFocusChanged: { + if (!focus) + return + // #866 companion: a model row move re-parents the moved row's + // subtree and Qt's focus fallback lands active focus on some + // delegate root of the list - possibly across several relayout + // passes and not necessarily the moved row's own root. For as + // long as a move carry stands (re-armed and reset at every + // move), hand the bubbled focus to the item that held it + // before the move, so focus provably never left the moved row. + const carry = streamList.sidebarFocusCarry + if (carry && carry.guard.live) + carry.item.forceActiveFocus() + } Connections { target: root.controller function onSidebarTopicsChanged(stream) { diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index b23bcd6c3..089b2dbbd 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -15338,6 +15338,144 @@ QVariantMap NativeController::sidebarTopicState(const QString &id, bool includeR {"rows", includeRows ? topicRows(topics, &*stream) : QVariantList{}}}; } +// Issue #866 (finding 2): the sidebar model. Row identity is the stream id; +// the id-less search marker rows (#847) key off their marker field so a +// re-projection inside a search still diffs granularly. Keys are expected +// unique; a duplicate (bad catalog data) degrades to one model reset. +NativeSidebarStreamListModel::NativeSidebarStreamListModel(NativeController *controller, QObject *parent) + : QAbstractListModel(parent), m_controller(controller) +{ +} + +int NativeSidebarStreamListModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : m_rows.size(); +} + +QVariant NativeSidebarStreamListModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 || index.row() >= m_rows.size()) + return {}; + if (role == Qt::UserRole) + return m_rows.at(index.row()).map; + return {}; +} + +QHash NativeSidebarStreamListModel::roleNames() const +{ + return {{Qt::UserRole, QByteArrayLiteral("modelData")}}; +} + +QString NativeSidebarStreamListModel::streamIdAt(int row) const +{ + if (row < 0 || row >= m_rows.size()) + return {}; + return m_rows.at(row).map.value(QStringLiteral("id")).toString(); +} + +QString NativeSidebarStreamListModel::keyForRow(const QVariant &value, int fallbackIndex) +{ + const auto map = value.toMap(); + const auto id = map.value(QStringLiteral("id")).toString(); + if (!id.isEmpty()) + return id; + const auto separator = map.value(QStringLiteral("searchSeparator")).toString(); + if (!separator.isEmpty()) + return QStringLiteral("sep:") + separator; + const auto status = map.value(QStringLiteral("searchStatus")).toString(); + if (!status.isEmpty()) + return QStringLiteral("status:") + status; + return QStringLiteral("pos:%1").arg(fallbackIndex); +} + +void NativeSidebarStreamListModel::sync() +{ + const QVariantList projection = m_controller->sidebarStreams(); + QVector next; + next.reserve(projection.size()); + bool uniqueKeys = true; + QSet seenKeys; + for (int i = 0; i < projection.size(); ++i) { + Row row{keyForRow(projection.at(i), i), projection.at(i).toMap()}; + if (seenKeys.contains(row.key)) + uniqueKeys = false; + else + seenKeys.insert(row.key); + next.append(row); + } + if (!uniqueKeys) { + beginResetModel(); + m_rows = next; + endResetModel(); + return; + } + // Removals back-to-front so the remaining indices stay valid. + for (int i = m_rows.size() - 1; i >= 0; --i) { + const auto key = m_rows.at(i).key; + if (std::any_of(next.cbegin(), next.cend(), + [&](const Row &row) { return row.key == key; })) + continue; + beginRemoveRows(QModelIndex(), i, i); + m_rows.remove(i); + endRemoveRows(); + } + // Moves: after the removals every surviving key exists exactly once in the + // projection. Selection sort over the target order: everything below the + // cursor is already final, so the wanted key is always found at or after the + // cursor and pulling it back is a legal beginMoveRows range. Survivors are + // NEVER reordered by anything else (insertions land later), so a linear + // rescan every round keeps the cursor consistent - no index table can go + // stale mid-shuffle. + for (int i = 0; i < m_rows.size(); ++i) { + int target = -1; + for (int j = i; j < m_rows.size(); ++j) { + if (m_rows.at(j).key == next.at(i).key) { + target = j; + break; + } + } + if (target <= i) + continue; + Q_ASSERT(target < m_rows.size()); + beginMoveRows(QModelIndex(), target, target, QModelIndex(), i); + m_rows.move(target, i); + endMoveRows(); + } + // Insertions left-to-right at the final index; survivors stay ordered. + for (int i = 0; i < next.size(); ++i) { + if (i < m_rows.size() && m_rows.at(i).key == next.at(i).key) + continue; + beginInsertRows(QModelIndex(), i, i); + m_rows.insert(i, next.at(i)); + endInsertRows(); + } + // In-place content changes (same row, new fields - preview, unread, ...). + for (int i = 0; i < m_rows.size(); ++i) { + if (m_rows.at(i).map == next.at(i).map) + continue; + m_rows[i].map = next.at(i).map; + emit dataChanged(index(i), index(i), {Qt::UserRole}); + } +} + +NativeSidebarStreamListModel *NativeController::sidebarStreamListModel() +{ + if (!m_sidebarStreamModel) { + m_sidebarStreamModel = new NativeSidebarStreamListModel(this, this); + // Every notify that can move the sidebar projection, i.e. exactly the + // signals the QVariantList binding re-evaluated on. sync() is a + // no-op diff on a settled projection (no traffic, no churn). + connect(this, &NativeController::streamsChanged, + m_sidebarStreamModel, &NativeSidebarStreamListModel::sync); + connect(this, &NativeController::sidebarStreamsChanged, + m_sidebarStreamModel, &NativeSidebarStreamListModel::sync); + connect(this, &NativeController::foldersChanged, + m_sidebarStreamModel, &NativeSidebarStreamListModel::sync); + m_sidebarStreamModel->sync(); + } + return m_sidebarStreamModel; +} + QVariantList NativeController::sidebarStreams() const { // Issue #70 (messenger-sidebar.lib.ts:560,592,616,656, sidebar-shell.ui.tsx:124): diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index d33bf3bf4..8b6ecc18c 100644 --- a/packages/native/src/native-controller.h +++ b/packages/native/src/native-controller.h @@ -19,6 +19,7 @@ #include "call/incoming-call-lifecycle.h" #include "native-call-bridge.h" +#include #include #include #include @@ -47,6 +48,48 @@ class FileClient; class NativeChatKeyVault; struct FileResult; +// Issue #866 (finding 2): move-aware sidebar row model. The sidebar ListView +// used to bind the sidebarStreams QVariantList projection directly, so every +// re-rank (a hydrated preview stamp re-sorting its row) reassigned the model +// and reset the view: delegates under the user were re-created and lost focus. +// The reference keeps keyed DOM rows and MOVES them. This model keeps one +// instance for the app lifetime, exposes each projection row under the +// "modelData" role (the delegate contract is unchanged), and translates every +// re-projection into granular inserted/removed/moved/dataChanged deltas so +// surviving delegates keep their identity across a reorder. Lazily created +// on the first QML read: pure-C++ controller tests never instantiate it and +// their pinned projection budgets stay untouched. +class NativeSidebarStreamListModel final : public QAbstractListModel { + Q_OBJECT +public: + explicit NativeSidebarStreamListModel(NativeController *controller, QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QHash roleNames() const override; + + // Sidebar scroll anchors (#660/#693) resolve a row index to its stream id; + // with a real model the JS can no longer index model[row], so the id + // lookup is part of the model contract. + Q_INVOKABLE QString streamIdAt(int row) const; + +public slots: + // Re-diff the controller projection into the current rows. Idempotent: + // connected to every notify that can move the projection; a settled state + // emits nothing. + void sync(); + +private: + struct Row { + QString key; + QVariantMap map; + }; + static QString keyForRow(const QVariant &value, int fallbackIndex); + + NativeController *m_controller; + QVector m_rows; +}; + class NativeController final : public QObject { Q_OBJECT Q_PROPERTY(bool authenticated READ authenticated NOTIFY stateChanged) @@ -191,6 +234,9 @@ class NativeController final : public QObject { // projection over the stream catalog. Q_PROPERTY(QVariantList folders READ folders NOTIFY foldersChanged) Q_PROPERTY(QVariantList sidebarStreams READ sidebarStreams NOTIFY sidebarStreamsChanged) + // Issue #866 (finding 2): stable sidebar model instance for the sidebar + // ListView (created on first read, never reassigned - CONSTANT). + Q_PROPERTY(NativeSidebarStreamListModel *sidebarStreamListModel READ sidebarStreamListModel CONSTANT) // Issue #100: the reference sidebar state machine (loading card, blocking // error card, partial-refresh banner, five empty states) measured in // docs/NATIVE_DESKTOP_SIDEBAR_STATES.md. @@ -555,6 +601,9 @@ class NativeController final : public QObject { Q_INVOKABLE QVariantMap previewFields(const QString &lastMessageUuid, int revision) const; QVariantList folders() const; QVariantList sidebarStreams() const; + // Lazily creates the sidebar model and wires its sync connections + // (issue #866 finding 2); pure-C++ consumers never touch this seam. + NativeSidebarStreamListModel *sidebarStreamListModel(); QVariantMap sidebarCatalogState() const; QStringList expandedSidebarStreams() const { return m_expandedSidebarStreams; } Q_INVOKABLE QVariantMap sidebarTopicState(const QString &stream, bool includeRows) const; @@ -2267,6 +2316,8 @@ class NativeController final : public QObject { bool m_previewRevisionBumpQueued = false; // exordy finding on PR #866: coalesce flag for the activity-reorder streamsChanged. bool m_streamsReorderQueued = false; + // Issue #866 (finding 2): lazily created sidebar row model (parented here). + NativeSidebarStreamListModel *m_sidebarStreamModel = nullptr; // #860: a disk miss is not an authoritative negative - the reference falls through to the // project-scoped messages lookup during bootstrap (messenger-last-messages-loader.lib.ts // L96-129). The network stage is bounded per tick like the disk pump, retries transient diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index 1789057d8..a4b976841 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -7950,7 +7950,11 @@ mv -Tf "$root/.current-new" "$root/current" type(scenario == "hash" ? "#PLANNING" : scenario == "order" ? "plan" : "planning alpha"); QTRY_VERIFY_WITH_TIMEOUT(streamVisible(streamId), 2000); QTRY_VERIFY_WITH_TIMEOUT(topicVisible(topicId), 2000); - QVERIFY(!topicVisible(secondTopicId)); QVERIFY(!streamVisible(windowDirectId())); + // The granular sidebar model removes filtered rows as row deltas whose + // delegates dispose on the next view pass (a whole-list reassignment + // disposed same-tick); allow that one-pass settle like the render tick + // the reference DOM filter takes. + QTRY_VERIFY(!topicVisible(secondTopicId)); QTRY_VERIFY(!streamVisible(windowDirectId())); QCOMPARE(controller.selectedStream(), otherStream); QVERIFY(controller.selectedTopic().isEmpty()); if (scenario == "order") { QTRY_VERIFY(streamVisible(otherStream) && topicVisible(otherTopic)); @@ -7965,8 +7969,8 @@ mv -Tf "$root/.current-new" "$root/current" type(scenario == "email" ? "ALICE@EXAMPLE.INVALID" : scenario == "trimmed" ? " ENGINEERING " : "ALICE"); const auto expected = scenario == "trimmed" ? streamId : windowDirectId(); QTRY_VERIFY_WITH_TIMEOUT(streamVisible(expected), 2000); - QVERIFY(!streamVisible(otherStream)); - QVERIFY(!streamVisible(scenario == "trimmed" ? windowDirectId() : streamId)); + QTRY_VERIFY(!streamVisible(otherStream)); + QTRY_VERIFY(!streamVisible(scenario == "trimmed" ? windowDirectId() : streamId)); } click(window, item(window->contentItem(), "clearSidebarSearch")); QTRY_COMPARE(search->property("text").toString(), QString{}); @@ -13332,6 +13336,104 @@ mv -Tf "$root/.current-new" "$root/current" QVERIFY(closed); } + void sidebarHydrationReorderKeepsActiveSidebarDelegates() + { + // #866 (finding 2 acceptance): a hydrated preview whose stamp re-ranks its row + // must MOVE the existing sidebar delegates, not re-create them. The reorder + // announcement (scheduleStreamsReorderAnnounce) emits streamsChanged, and the + // ListView model reassignment reset every row: the row under the user was + // destroyed mid interaction. The reference moves the keyed DOM row so focus, + // hover and open transient state survive the reorder at the new position. + WindowChannelFixture fixture; + const QString otherStream = "a3000000-0000-4000-8000-000000000001"; + const QString previewUuid = "81000000-0000-4000-8000-000000000001"; + const QString previewBody = QStringLiteral("Hydrated reorder preview"); + auto first = windowChannel(streamId, "Engineering"); + first["updated_at"] = QStringLiteral("2026-01-02T10:00:00Z"); + auto second = windowChannel(otherStream, "Support"); + second["last_message_uuid"] = previewUuid; + second["updated_at"] = QStringLiteral("2026-01-01T10:00:00Z"); + const auto previewRow = QJsonObject{ + {"uuid", previewUuid}, {"project_id", projectId}, {"author_uuid", userId}, + {"stream_uuid", otherStream}, {"topic_uuid", secondTopicId}, {"revision", 1}, + {"created_at", "2026-01-03T10:00:00.000Z"}, {"updated_at", "2026-01-03T10:00:00.000Z"}, + {"payload", QJsonObject{{"kind", "markdown"}, {"content", previewBody}}}}; + const auto fallback = fixture.server.handler; + auto held = std::make_shared>(); + fixture.server.handler = [=](const Request &request) -> Response { + const auto path = request.target.path(); + if (request.method == "GET" && path.endsWith("/streams/")) + return {QJsonArray{first, second}}; + if (request.method == "GET" && path.endsWith("/stream_topics/")) { + const auto id = QUrlQuery(request.target).queryItemValue("stream_uuid"); + return {QJsonArray{windowChannelTopic(id == streamId ? topicId : secondTopicId, id, "Topic")}}; + } + // The row-preview uuid lookup for the LOWER-ranked stream, held in flight so + // the reply lands while the sidebar is already under interaction. Its stamp + // outranks the first stream's fallback key, so the projection swaps rows. + if (request.method == "GET" && path.endsWith("/messages/") + && QUrlQuery(request.target).queryItemValue("uuid") == previewUuid) { + Response response{QJsonArray{previewRow}}; + response.defer = [held](auto send) { *held = std::move(send); }; + return response; + } + return fallback(request); + }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativePreferences preferences(directory.filePath("hydration-reorder.ini")); + ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + QQmlApplicationEngine engine; loadNativeUi(engine, &controller, &preferences); + auto *window = qobject_cast(engine.rootObjects().value(0)); QVERIFY(window); + auto close = qScopeGuard([&engine, guard = QPointer(window)] { + if (guard && !closeIncubatedTestWindow(engine, guard.data())) + QTest::qFail("Hydration reorder teardown", __FILE__, __LINE__); + }); + window->resize(1440, 900); QVERIFY(QTest::qWaitForWindowExposed(window)); + window->requestActivate(); QVERIFY(QTest::qWaitForWindowActive(window)); + session.login(fixture.server.origin(), "synthetic-reorder", "synthetic-password"); + QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); + QTRY_VERIFY(session.ready() && !controller.busy() && controller.streams().size() == 2); + const auto previewText = [&]() { + const auto *item = visibleItem("streamPreviewText-" + otherStream); + return item ? item->property("text").toString() : QString(); + }; + QVERIFY(previewText().isEmpty()); + // The moving row holds the active interaction; both rows are captured by pointer + // so re-creation is observable as a dangling QPointer. + QPointer movedRow; + QPointer quietRow; + QTRY_VERIFY_WITH_TIMEOUT((movedRow = visibleItem("stream-" + otherStream)) != nullptr, 5000); + QTRY_VERIFY_WITH_TIMEOUT((quietRow = visibleItem("stream-" + streamId)) != nullptr, 5000); + movedRow->forceActiveFocus(Qt::TabFocusReason); QTRY_VERIFY(movedRow->hasActiveFocus()); + auto *streamList = visibleItem("streamList"); QVERIFY(streamList); + QVERIFY(quietRow->mapToScene(QPointF(0, 0)).y() < movedRow->mapToScene(QPointF(0, 0)).y()); + const auto listYBefore = streamList->property("contentY").toDouble(); + QTRY_VERIFY(bool(*held)); // the lookup is in flight + (*held)(); *held = {}; + // The preview lands and re-ranks its row: the projected order swaps first... + QTRY_COMPARE_WITH_TIMEOUT(previewText(), previewBody, 5000); + const auto orderSwapped = [&] { + const auto *freshMoved = visibleItem("stream-" + otherStream); + const auto *freshQuiet = visibleItem("stream-" + streamId); + return freshMoved && freshQuiet + && freshMoved->mapToScene(QPointF(0, 0)).y() < freshQuiet->mapToScene(QPointF(0, 0)).y(); + }; + QTRY_VERIFY_WITH_TIMEOUT(orderSwapped(), 5000); + // ...and the swap moved the existing rows: both captured delegates are still + // alive and keyboard focus never left the moved row. + QVERIFY2(movedRow, + "A hydration-driven activity reorder must not re-create the active sidebar row"); + // The move re-parents the delegate and the focus carry lands on the next + // relayout pass, so allow the bounded settle instead of a same-tick assert. + QTRY_VERIFY_WITH_TIMEOUT(movedRow->hasActiveFocus(), 2000); + QVERIFY2(quietRow, + "A hydration-driven activity reorder must not re-create the other sidebar rows"); + QCOMPARE(streamList->property("contentY").toDouble(), listYBefore); + const bool closed = closeIncubatedTestWindow(engine, window); + if (closed) close.dismiss(); + QVERIFY(closed); + } + void sidebarHydrationKeepsFocusOnOtherStream() { WindowChannelFixture fixture; From 3691943041986e747a6bee15672357898e322f7a Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 12:56:34 +0300 Subject: [PATCH 13/20] fix: order sidebar survivors before inserting new rows The move pass indexed the raw target list while new keys were still missing, so a projection that inserted a row in front of survivors that simultaneously re-rank ([A, B] -> [X, B, A]) left the survivors unordered: the insertion pass then duplicated B and the content pass read past the projection (deterministic SIGSEGV, reproduced by the new acceptance case before the fix). Build the survivor order (the target restricted to keys that already exist), selection-sort the current rows against it, and only then run the insertion pass - with survivors already in target order, every position mismatch is exactly one new key. Pins: sidebarModelOrdersSurvivorsBeforeInsertingNewRows (native-controller-sidebar-test). Verified green: full sidebar group 149/149, hydration window cases, search family 26/26. --- packages/native/src/native-controller.cpp | 32 +++++++---- .../tests/native-controller-sidebar-test.cpp | 57 +++++++++++++++++++ 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 089b2dbbd..3176fb257 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -15419,29 +15419,41 @@ void NativeSidebarStreamListModel::sync() m_rows.remove(i); endRemoveRows(); } - // Moves: after the removals every surviving key exists exactly once in the - // projection. Selection sort over the target order: everything below the - // cursor is already final, so the wanted key is always found at or after the - // cursor and pulling it back is a legal beginMoveRows range. Survivors are - // NEVER reordered by anything else (insertions land later), so a linear - // rescan every round keeps the cursor consistent - no index table can go - // stale mid-shuffle. + // Moves: the survivors must take the TARGET ORDER BEFORE any new row is + // inserted. Indexing the raw `next` at the current row positions desyncs + // the cursor as soon as a new key lands in front of survivors that + // re-rank ([A, B] -> [X, B, A] left A/B unordered, the insertion pass + // then duplicated B and the content pass read past `next`). The surviving + // sequence is `next` restricted to keys that already exist, so its + // multiset equals m_rows exactly - every round finds its key. + QStringList survivorOrder; + for (const Row &row : next) { + if (std::any_of(m_rows.cbegin(), m_rows.cend(), + [&](const Row &existing) { return existing.key == row.key; })) + survivorOrder.append(row.key); + } + // Selection sort over the survivor order: everything below the cursor is + // already final, so the wanted key is always found at or after the cursor + // and pulling it back is a legal beginMoveRows range. A linear rescan + // every round keeps the cursor consistent - no index table can go stale + // mid-shuffle. for (int i = 0; i < m_rows.size(); ++i) { int target = -1; for (int j = i; j < m_rows.size(); ++j) { - if (m_rows.at(j).key == next.at(i).key) { + if (m_rows.at(j).key == survivorOrder.at(i)) { target = j; break; } } + Q_ASSERT(target >= i); if (target <= i) continue; - Q_ASSERT(target < m_rows.size()); beginMoveRows(QModelIndex(), target, target, QModelIndex(), i); m_rows.move(target, i); endMoveRows(); } - // Insertions left-to-right at the final index; survivors stay ordered. + // Insertions left-to-right at the final index. With the survivors already + // in target order, every mismatch at a position is exactly a new key. for (int i = 0; i < next.size(); ++i) { if (i < m_rows.size() && m_rows.at(i).key == next.at(i).key) continue; diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index 5deb427c8..c749b0c06 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -3836,6 +3836,63 @@ private slots: test.controller.topics(); QCOMPARE(test.controller.topicsProjectionCountForTest(), topicsBaseline + 4); } + + // #866 fix round (finding on 1f77ced0): a projection that INSERTS a new row in + // front of surviving rows that simultaneously re-rank must not duplicate or + // crash. The move pass may not index the raw target before excluding the + // insertions: for [A, B] -> [X, B, A] it left the survivors unordered, the + // insertion pass then duplicated B, and the content pass read past the + // projection. Survivors must be ordered against the target's surviving keys + // first, only then may new rows be inserted. + void sidebarModelOrdersSurvivorsBeforeInsertingNewRows() + { + Fixture test; + const auto streamB = QStringLiteral("88888888-8888-4888-8888-0000000008b0"); + const auto streamX = QStringLiteral("88888888-8888-4888-8888-0000000008c0"); + const auto dto = [](const QString &id, const QString &name, const QString &stamp) { + return QJsonObject{{"uuid", id}, {"project_id", projectId}, {"name", name}, + {"encryption", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"updated_at", stamp}}; + }; + const auto firstList = QJsonArray{dto(streamId, "Alpha", "2026-01-02T10:00:00Z"), + dto(streamB, "Beta", "2026-01-01T10:00:00Z")}; + const auto secondList = QJsonArray{dto(streamX, "Delta", "2026-01-04T10:00:00Z"), + dto(streamB, "Beta", "2026-01-03T10:00:00Z"), + dto(streamId, "Alpha", "2026-01-02T10:00:00Z")}; + bool refreshed = false; + test.streams = [&](const Request &request) { + if (request.method == "GET" && request.target.path().endsWith("/streams/")) + return Response{refreshed ? secondList : firstList}; + return Response{firstList.first().toObject()}; + }; + QVERIFY(test.start({}, 2)); + auto *model = test.controller.sidebarStreamListModel(); QVERIFY(model); + const auto rowKeys = [model] { + QStringList keys; + for (int i = 0; i < model->rowCount(); ++i) + keys << model->streamIdAt(i); + return keys; + }; + const auto projectionKeys = [&test] { + QStringList keys; + for (const auto &value : test.controller.sidebarStreams()) + keys << value.toMap().value(QStringLiteral("id")).toString(); + return keys; + }; + QCOMPARE(rowKeys(), projectionKeys()); + const QStringList expectedFirst{streamId, streamB}; + QCOMPARE(rowKeys(), expectedFirst); + // One announcement moves the projection [A, B] -> [X, B, A]: X (newest) + // is inserted at the head while B overtakes A. + refreshed = true; + test.controller.refresh(); + QTRY_COMPARE_WITH_TIMEOUT(test.controller.streams().size(), 3, 5000); + // The diff survived the combined insert+reorder: no duplicated survivor, + // no dropped row, and the model order equals the projection order. + QCOMPARE(rowKeys(), projectionKeys()); + const QStringList expectedSwap{streamX, streamB, streamId}; + QCOMPARE(rowKeys(), expectedSwap); + } }; QTEST_MAIN(ControllerSidebarTest) From 1fdbce2a20b45fafa06f6c552fe1cc071838b95b Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 13:16:20 +0300 Subject: [PATCH 14/20] test: register new window case in bucket timings The fix-round-1 window case sidebarHydrationReorderKeepsActiveSidebarDelegates had no recorded timing fragment, so native-window-buckets-sync failed in CI. Measured solo (1.5 s on WM'd display) and regenerated the bucket layout. --- packages/native/tests/bucket-timings/window/part26.txt | 1 + packages/native/tests/window-test-buckets.cmake | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/native/tests/bucket-timings/window/part26.txt b/packages/native/tests/bucket-timings/window/part26.txt index ec511c030..db948c941 100644 --- a/packages/native/tests/bucket-timings/window/part26.txt +++ b/packages/native/tests/bucket-timings/window/part26.txt @@ -13,6 +13,7 @@ pollBubbleOptionKeyboardActivation=1.42053 pollManagementMenuTracksActorAndState=6.64446 rightDrawerShellMatchesReferenceGeometry=0.849636 sidebarChatActionsCompleteFromMenu=40.3464 +sidebarHydrationReorderKeepsActiveSidebarDelegates=0.815703 startupDirectoryDoesNotPopulateHiddenPickers=4.97752 updaterActualMainShowsAndExecutesTheDownloadAndInstallActions=1.2757 windowNarrowAppearanceDrawerKeepsCoveredMessagesUnread=2.2667 diff --git a/packages/native/tests/window-test-buckets.cmake b/packages/native/tests/window-test-buckets.cmake index 186854d15..e03f403c2 100644 --- a/packages/native/tests/window-test-buckets.cmake +++ b/packages/native/tests/window-test-buckets.cmake @@ -625,6 +625,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_26 pollManagementMenuTracksActorAndState rightDrawerShellMatchesReferenceGeometry sidebarChatActionsCompleteFromMenu + sidebarHydrationReorderKeepsActiveSidebarDelegates startupDirectoryDoesNotPopulateHiddenPickers updaterActualMainShowsAndExecutesTheDownloadAndInstallActions windowNarrowAppearanceDrawerKeepsCoveredMessagesUnread From 86fd97a6f3865fc5c4cf467dfe4cc182ef0bf02f Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 13:57:44 +0300 Subject: [PATCH 15/20] test: churn-settle sidebar pins after move-aware re-rank (#860 fix round) --- packages/native/tests/native-window-test.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index a4b976841..dad05bcc7 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -40627,7 +40627,10 @@ private slots: QVERIFY(!visibleItem("sidebarLoadingCard")); QVERIFY(!visibleItem("sidebarErrorCard")); QVERIFY(!visibleItem("sidebarPartialBanner")); - if (stateCase == "search") QVERIFY(!visibleItem("stream-"+streamId)); + // Move-aware row re-ranks dispose the filtered delegate one view pass + // later than the query flip; give it the settle window like every + // other churn-tolerant pin (precedent #866 fix round). + if (stateCase == "search") QTRY_VERIFY_WITH_TIMEOUT(!visibleItem("stream-"+streamId), 5000); if (stateCase == "workspace") QVERIFY(controller.streams().isEmpty()); if (stateCase == "personal" || stateCase == "channels" || stateCase == "folder") QVERIFY(controller.sidebarStreams().isEmpty()); @@ -40685,7 +40688,7 @@ private slots: window->setProperty("sidebarQuery","nothing-matches"); QTRY_VERIFY_WITH_TIMEOUT(visibleItem("sidebarEmptyCard"),5000); QVERIFY(visibleItem("sidebarPartialBanner")); - QVERIFY(!visibleItem("stream-"+streamId)); + QTRY_VERIFY_WITH_TIMEOUT(!visibleItem("stream-"+streamId), 5000); auto *banner = visibleItem("sidebarPartialBanner"); auto *emptyCard = visibleItem("sidebarEmptyCard"); const qreal bannerBottom = banner->mapToItem(window->contentItem(),QPointF(0,banner->height())).y(); @@ -50119,7 +50122,7 @@ private slots: controller.selectFolder(allFolder); QTRY_COMPARE(controller.selectedFolder(), allFolder); QTRY_VERIFY(betaRow()); - QVERIFY(!separator()); QVERIFY(!status()); + QTRY_VERIFY_WITH_TIMEOUT(!separator(), 2000); QTRY_VERIFY_WITH_TIMEOUT(!status(), 2000); } // Issue #847 render pin for the "Other topics" separator (reference @@ -50474,9 +50477,11 @@ private slots: click(window, item(content, "projectLoginButton")); QTRY_COMPARE(controller.streams().size(), 1); preferences.setMode("light"); - click(window, item(content, "stream-" + streamId)); + // The preview pump re-ranks rows around first paint; clickCurrentItem + // re-resolves the delegate that a churn pass may recreate (existing helper). + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, item(content, "topic-" + topicId)); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.messages().size(), 2); QTRY_VERIFY(item(content, "message-content-" + messageId)); QVERIFY(item(content, "message-content-" + messageId)->property("text").toString().contains("Saved message before restart")); From 3096971ce2dd2320f83cf71a95d0e43653db7a84 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 15:31:32 +0300 Subject: [PATCH 16/20] test: harden mediaViewer entry clicks and search negative pins for granular moves Pre-tag gate triage on this lane: - mediaViewerBackdropClick.../mediaViewerVideoControlsAutoHide... went red on CI shards and reproduced run-1-only locally: the stream/topic delegate is mid-recreation when the opening click resolves (preview-pump re-rank churn). Opening clicks now gate on a re-fetched delegate and resolve the click target through clickCurrentItem after the readiness wait. - sidebarSearchArrowsCycleFilteredResults: the same-tick negative pins read one layout pass too early under granular rowsRemoved (delegates dispose one view pass later than the whole-list reassignment they replaced). Relaxed to QTRY_VERIFY per the documented granular-move recipe. Refs #860 --- packages/native/tests/native-window-test.cpp | 251 +++++++++++++++---- 1 file changed, 204 insertions(+), 47 deletions(-) diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index dad05bcc7..ce5e7a209 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -22366,9 +22366,16 @@ mv -Tf "$root/.current-new" "$root/current" QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 1); auto photo = [&] { return visibleItem(content, "inline-image-" + first); }; @@ -22444,9 +22451,16 @@ mv -Tf "$root/.current-new" "$root/current" QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 1); auto photo = [&] { return visibleItem(content, "inline-image-" + first); }; @@ -22517,9 +22531,16 @@ mv -Tf "$root/.current-new" "$root/current" QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 1); auto photo = [&] { return visibleItem(content, "inline-image-" + first); }; @@ -22667,9 +22688,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); QTRY_VERIFY(visibleItem(content, "inline-image-" + first)); @@ -22852,9 +22880,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); auto *viewer = controller.mediaViewer(); QVERIFY(viewer); clickActiveInlineImage(window, first); @@ -23039,9 +23074,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_VERIFY(visibleItem(content, "inline-image-" + first)); auto *viewer = controller.mediaViewer(); click(window, visibleItem(content, "inline-image-" + first)); @@ -23114,9 +23156,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); auto *viewer = controller.mediaViewer(); clickActiveInlineImage(window, first); @@ -23193,9 +23242,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -23352,9 +23408,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), video ? 2 : 3); auto *viewer = controller.mediaViewer(); @@ -23477,9 +23540,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -23638,9 +23708,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -23748,9 +23825,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -23854,9 +23938,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -23959,9 +24050,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24082,9 +24180,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24208,9 +24313,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24333,9 +24445,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24426,9 +24545,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24514,9 +24640,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); auto *viewer = controller.mediaViewer(); @@ -24587,9 +24720,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 1); // 1. Bubble thumbnail: the ISO-BMFF bytes decode through libheif and @@ -24721,9 +24861,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 1); auto *bubble = visibleItem(content, "inline-image-" + first); QVERIFY(bubble); @@ -24805,9 +24952,16 @@ NativeAvatarImage { QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); QTRY_COMPARE(controller.streams().size(), 1); QTRY_VERIFY(controller.channelMembersVerified()); auto *content = window->contentItem(); - click(window, visibleItem(content, "stream-" + streamId)); + // #860 re-rank churn: the preview pump may re-move rows (delegates are + // disposed one view pass) right after the list appears. Gate on a + // re-fetched delegate and let clickCurrentItem resolve the target only + // after the readiness wait, so a transient recreation cannot null the + // click (pre-tag gate: mediaViewer run-1 repros on this lane). + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "stream-" + streamId) != nullptr; })(), 4000); + clickCurrentItem(window, "stream-" + streamId); QTRY_COMPARE(controller.topics().size(), 1); - click(window, visibleItem(content, "topic-" + topicId)); + QTRY_VERIFY_WITH_TIMEOUT(([&]{ return visibleItem(content, "topic-" + topicId) != nullptr; })(), 4000); + clickCurrentItem(window, "topic-" + topicId); QTRY_COMPARE(controller.selectedTopic(), topicId); QTRY_COMPARE(controller.messages().size(), 2); QTRY_VERIFY(visibleItem(content, "inline-image-" + first)); @@ -47912,9 +48066,12 @@ private slots: QTRY_VERIFY_WITH_TIMEOUT(visibleItem(window->contentItem(), "topic-" + topicA1), 2000); QTRY_VERIFY_WITH_TIMEOUT(visibleItem(window->contentItem(), "topic-" + topicA2), 2000); // The unfiltered rows are gone, so focus can never land on them. - QVERIFY(!visibleItem(window->contentItem(), "stream-92000000-0000-4000-8000-00000000000b")); - QVERIFY(!visibleItem(window->contentItem(), "stream-92000000-0000-4000-8000-00000000000c")); - QVERIFY(!visibleItem(window->contentItem(), "topic-" + topicOff)); + // #860 granular moves dispose delegates one view pass after the model + // diff (whole-list reassignment used to dispose them synchronously), + // so the negative pins must allow the one-pass dispose window. + QTRY_VERIFY(!visibleItem(window->contentItem(), "stream-92000000-0000-4000-8000-00000000000b")); + QTRY_VERIFY(!visibleItem(window->contentItem(), "stream-92000000-0000-4000-8000-00000000000c")); + QTRY_VERIFY(!visibleItem(window->contentItem(), "topic-" + topicOff)); const auto focusName = [window] { auto *focused = window->activeFocusItem(); return focused ? focused->objectName() : QString(); From 8fa7afdb9546d226b379858776916052db5f972c Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 16:30:38 +0300 Subject: [PATCH 17/20] fix: fence the delayed row-preview retries to their originating session The network backoff and the late-disk retry captured only the uuid and checked authentication at fire time, so an account swap during the sleep could replay the previous session's uuid lookup under the new owner and origin. Both timers now capture the session generation (the retirement seam introduced in PR #292) plus the dispatch-time owner and return when either moved. Pinned by sidebarPreviewNetRetryIsFencedToItsSession (red before the fence: second dispatch under the new owner). --- packages/native/src/native-controller.cpp | 24 +++++-- .../tests/native-controller-sidebar-test.cpp | 64 +++++++++++++++++++ 2 files changed, 83 insertions(+), 5 deletions(-) diff --git a/packages/native/src/native-controller.cpp b/packages/native/src/native-controller.cpp index 3176fb257..026f9fd5c 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -20153,8 +20153,9 @@ void NativeController::pumpRowPreviewNetworkHydration() ++m_rowPreviewNetIssued; const QPointer guard(this); const auto fence = m_rowPreviewFence.value(uuid); + const auto dispatchGeneration = m_sessionGeneration; request("GET", messenger + "/messages/", {}, {{"project_id", project}, {"uuid", uuid}}, - [this, guard, uuid, owner, fence, project, cache, lease, netToken](const ApiResult &result) { + [this, guard, uuid, owner, fence, project, cache, lease, netToken, dispatchGeneration](const ApiResult &result) { if (!guard) return; // #866 review (exordy finding 1): a reply may only retire the in-flight marker // its own request still owns. After a session change the uuid may already have @@ -20180,8 +20181,16 @@ void NativeController::pumpRowPreviewNetworkHydration() // instead of a sticky negative memo that outlives the retry window. if (m_rowPreviewNetRetries.value(uuid) < rowPreviewNetworkRetries) { ++m_rowPreviewNetRetries[uuid]; - QTimer::singleShot(2000, this, [this, uuid] { - if (!authenticated() || m_rowPreviews.contains(uuid)) return; + // exordy finding (#866): the backoff is fenced to the session that + // scheduled it - the session generation plus the owner captured at + // dispatch. An account swap during the sleep retires the generation + // (signedOut bumps it), so the old uuid is never replayed under the + // new session and origin; an owner-only fence cannot see a swap the + // fixture mocks to an identical owner hash. + QTimer::singleShot(2000, this, [this, uuid, owner, dispatchGeneration] { + if (!authenticated() || m_sessionGeneration != dispatchGeneration + || creationOwnerKey() != owner) return; + if (m_rowPreviews.contains(uuid)) return; enqueueRowPreviewNet(uuid); scheduleRowPreviewNetworkHydration(); }); @@ -20215,8 +20224,13 @@ void NativeController::pumpRowPreviewNetworkHydration() // write races the lookup). The negative must not memoize over a late write, // so the miss buys a bounded number of delayed disk re-reads first. ++m_rowPreviewLateDiskRetries[uuid]; - QTimer::singleShot(1000, this, [this, uuid] { - if (!authenticated() || m_rowPreviews.contains(uuid)) return; + // exordy finding (#866): same session fence as the network backoff - + // a delayed disk re-read must not fire inside a different session and + // memoize over the new realm's rows. + QTimer::singleShot(1000, this, [this, uuid, owner, dispatchGeneration] { + if (!authenticated() || m_sessionGeneration != dispatchGeneration + || creationOwnerKey() != owner) return; + if (m_rowPreviews.contains(uuid)) return; if (m_rowPreviewInFlight.contains(uuid)) return; enqueueRowPreviewDisk(uuid); scheduleRowPreviewHydration(); diff --git a/packages/native/tests/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index c749b0c06..be22dc187 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1,4 +1,5 @@ #include +#include #include "support/native-test-harness.h" #include "support/controller-chat-creation-fixtures.h" #include "support/controller-navigation-fixtures.h" @@ -1322,6 +1323,69 @@ private slots: QTest::qWait(400); } + // #866 review (exordy finding 2): the delayed preview retry is fenced to the session + // that scheduled it. A transient network failure schedules a backoff re-enqueue that + // captured only the uuid; if the account is swapped while that backoff sleeps, the + // firing must not enqueue the previous session's uuid under the new owner, so the + // new realm never receives a lookup for a message it never held. + void sidebarPreviewNetRetryIsFencedToItsSession() + { + Fixture test; + test.aggregateMessages = true; + const auto pointer = QStringLiteral("88888888-8888-4888-8888-0000000000d2"); + const auto swapped = std::make_shared>(false); + const auto uuidHits = std::make_shared>(0); + test.streams = [](const Request &request) { + if (request.target.path().endsWith("/streams/")) + return Response{QJsonArray{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}}; + return Response{QJsonObject{{"uuid", streamId}, {"project_id", projectId}, + {"name", "Native channel"}, {"encryption", false}, {"unread_count", 0}, + {"active_unread_count", 0}, {"passive_unread_count", 0}, + {"last_message_uuid", QJsonValue::Null}, {"updated_at", "2026-01-02T10:00:05Z"}}}; + }; + test.topics = [pointer, swapped](const Request &) { + // The first session's catalog points at the message; the swapped session + // carries no pointer, so any uuid lookup observed after the swap can only + // have come from the stale backoff timer. + const QJsonValue last = swapped->load() ? QJsonValue(QJsonValue::Null) + : QJsonValue(pointer); + return Response{QJsonArray{QJsonObject{{"uuid", topicId}, {"project_id", projectId}, + {"stream_uuid", streamId}, {"name", "Retry fence probe"}, {"is_done", false}, + {"is_default", false}, {"unread_count", 0}, {"active_unread_count", 0}, + {"passive_unread_count", 0}, {"last_message_uuid", last}, + {"updated_at", "2026-01-02T10:00:05Z"}}}}; + }; + test.messages = [uuidHits](const Request &request) { + const auto uuid = QUrlQuery(request.target).queryItemValue("uuid"); + if (!uuid.isEmpty()) { + ++*uuidHits; + Response failed{QJsonArray{}}; + failed.status = 503; // transient: schedules the bounded backoff + return failed; + } + return Response{QJsonArray{}}; + }; + QVERIFY(test.start()); + QVERIFY(QTest::qWaitFor( + [&] { return test.controller.rowPreviewNetworkIssuedForTest() >= 1; }, 5000)); + QTest::qWait(300); + QCOMPARE(*uuidHits, 1); // the failing lookup landed once + // Swap accounts while the first backoff (2 s) is still sleeping. + swapped->store(true); + test.controller.logout(); + test.controller.login(test.server.origin().toString(), "second-user", "password", ""); + QTRY_COMPARE(test.controller.projects().size(), 1); + test.controller.openProject(projectId); + // The first backoff elapses inside the NEW session. An unfenced timer enqueues + // the stale uuid and dispatches it under the new owner's session. + QTest::qWait(3000); + QCOMPARE(test.controller.rowPreviewNetworkIssuedForTest(), 1); + QCOMPARE(*uuidHits, 1); // the new realm must never see the old uuid + } + // #866 review (exordy finding 2): the pumps consume foreground rows first - the // open route's stream (with its topics) and every expanded sidebar stream are // dispatched ahead of hidden catalog candidates, both at seed time and at every From 1094d5305a40be8219a3e92a7d114f673f6a0c87 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 16:30:38 +0300 Subject: [PATCH 18/20] fix: expire the sidebar move focus carry after the relayout settles The carry armed at rowsAboutToBeMoved re-aimed bubbled focus onto the pre-move item for as long as it stood, and nothing disarmed it once the move had completed - a later focus navigation could be forced back to the old row. The carry now expires 500 ms after the last restore pass: multi-pass relayout churn keeps it alive, a settled move releases it. Pinned by sidebarMoveFocusCarryExpiresAfterSettle (buckets regenerated for the new window case). --- packages/native/qml/Main.qml | 18 ++++- .../tests/bucket-timings/window/part12.txt | 1 + packages/native/tests/native-window-test.cpp | 74 +++++++++++++++++++ .../native/tests/window-test-buckets.cmake | 1 + 4 files changed, 93 insertions(+), 1 deletion(-) diff --git a/packages/native/qml/Main.qml b/packages/native/qml/Main.qml index 52c87d51b..b0e669b07 100644 --- a/packages/native/qml/Main.qml +++ b/packages/native/qml/Main.qml @@ -6334,6 +6334,17 @@ component NativeMentionChip: Item { policy: ScrollBar.AsNeeded } property var sidebarFocusCarry: null + // exordy finding (#866): a completed move must not leave a live carry. + // The carry re-aims bubbled focus onto the pre-move item; left armed + // forever, the next focus navigation anywhere in the sidebar would be + // forced back to the old row. It expires after the move's relayout + // goes quiet: every bubbled restore re-arms it, so multi-pass churn + // keeps the item, and once the move has truly settled the carry dies. + Timer { + id: sidebarFocusCarryExpiry + interval: 500 + onTriggered: streamList.sidebarFocusCarry = null + } // Issue #866 (finding 2) companion: a model row move re-parents the // delegate subtree; Qt's focus bubbling drops the moved row's active // focus and lands it on the delegate root after the view relayout. @@ -6354,6 +6365,7 @@ component NativeMentionChip: Item { for (let node = focused; node && node !== streamList; node = node.parent) { if (node.liveGuard !== undefined) { streamList.sidebarFocusCarry = { item: focused, guard: node.liveGuard } + sidebarFocusCarryExpiry.restart() return } } @@ -6417,8 +6429,12 @@ component NativeMentionChip: Item { // move), hand the bubbled focus to the item that held it // before the move, so focus provably never left the moved row. const carry = streamList.sidebarFocusCarry - if (carry && carry.guard.live) + if (carry && carry.guard.live) { carry.item.forceActiveFocus() + // Each restore re-arms the settle window: churn keeps the + // carry alive, a settled move lets it expire. + sidebarFocusCarryExpiry.restart() + } } Connections { target: root.controller diff --git a/packages/native/tests/bucket-timings/window/part12.txt b/packages/native/tests/bucket-timings/window/part12.txt index 104fbd35a..1ef8d9252 100644 --- a/packages/native/tests/bucket-timings/window/part12.txt +++ b/packages/native/tests/bucket-timings/window/part12.txt @@ -13,6 +13,7 @@ pollBubbleInlineAddOptionFlow=1.59044 pollCreateDialogEnforcesServerLimits=1.59584 quoteThumbnailScopeResetKeepsOneCurrentLease=0.110103 receivedStandaloneImagePaintsBetweenTextAndCaption=1.14385 +sidebarMoveFocusCarryExpiresAfterSettle=2.3981 sidebarRowsRenderPreviewAndTime=4.05802 sourceConversationInsetsAndAvatarFallback=7.72527 startupCacheEmptyStoreKeepsSignInVisible=1.24574 diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index ce5e7a209..52520f2e6 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -13434,6 +13434,80 @@ mv -Tf "$root/.current-new" "$root/current" QVERIFY(closed); } + void sidebarMoveFocusCarryExpiresAfterSettle() + { + // exordy finding (#866 round): a completed row move must not leave a live + // focus carry. The carry re-aims bubbled focus onto the pre-move item; if it + // stayed armed indefinitely, the next focus navigation anywhere in the + // sidebar would be forced back to the moved row. Once the move's relayout + // goes quiet the carry expires, so a LATER navigation sticks where the user + // put it. + WindowChannelFixture fixture; + const QString otherStream = "a3000000-0000-4000-8000-000000000001"; + const QString previewUuid = "81000000-0000-4000-8000-000000000001"; + const QString previewBody = QStringLiteral("Carry expiry preview"); + auto first = windowChannel(streamId, "Engineering"); + first["updated_at"] = QStringLiteral("2026-01-02T10:00:00Z"); + auto second = windowChannel(otherStream, "Support"); + second["last_message_uuid"] = previewUuid; + second["updated_at"] = QStringLiteral("2026-01-01T10:00:00Z"); + const auto previewRow = QJsonObject{ + {"uuid", previewUuid}, {"project_id", projectId}, {"author_uuid", userId}, + {"stream_uuid", otherStream}, {"topic_uuid", secondTopicId}, {"revision", 1}, + {"created_at", "2026-01-03T10:00:00.000Z"}, {"updated_at", "2026-01-03T10:00:00.000Z"}, + {"payload", QJsonObject{{"kind", "markdown"}, {"content", previewBody}}}}; + const auto fallback = fixture.server.handler; + auto held = std::make_shared>(); + fixture.server.handler = [=](const Request &request) -> Response { + const auto path = request.target.path(); + if (request.method == "GET" && path.endsWith("/streams/")) + return {QJsonArray{first, second}}; + if (request.method == "GET" && path.endsWith("/stream_topics/")) { + const auto id = QUrlQuery(request.target).queryItemValue("stream_uuid"); + return {QJsonArray{windowChannelTopic(id == streamId ? topicId : secondTopicId, id, "Topic")}}; + } + if (request.method == "GET" && path.endsWith("/messages/") + && QUrlQuery(request.target).queryItemValue("uuid") == previewUuid) { + Response response{QJsonArray{previewRow}}; + response.defer = [held](auto send) { *held = std::move(send); }; + return response; + } + return fallback(request); + }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativePreferences preferences(directory.filePath("carry-expiry.ini")); + ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + QQmlApplicationEngine engine; loadNativeUi(engine, &controller, &preferences); + auto *window = qobject_cast(engine.rootObjects().value(0)); QVERIFY(window); + auto close = qScopeGuard([&engine, guard = QPointer(window)] { + if (guard && !closeIncubatedTestWindow(engine, guard.data())) + QTest::qFail("Carry expiry teardown", __FILE__, __LINE__); + }); + window->resize(1440, 900); QVERIFY(QTest::qWaitForWindowExposed(window)); + window->requestActivate(); QVERIFY(QTest::qWaitForWindowActive(window)); + session.login(fixture.server.origin(), "synthetic-carry", "synthetic-password"); + QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); + QTRY_VERIFY(session.ready() && !controller.busy() && controller.streams().size() == 2); + QPointer movedRow; + QPointer quietRow; + QTRY_VERIFY_WITH_TIMEOUT((movedRow = visibleItem("stream-" + otherStream)) != nullptr, 5000); + QTRY_VERIFY_WITH_TIMEOUT((quietRow = visibleItem("stream-" + streamId)) != nullptr, 5000); + movedRow->forceActiveFocus(Qt::TabFocusReason); QTRY_VERIFY(movedRow->hasActiveFocus()); + QTRY_VERIFY(bool(*held)); // the lookup is in flight + (*held)(); *held = {}; + // The move lands and the carry restores focus to the moved row. + QTRY_VERIFY_WITH_TIMEOUT(movedRow->hasActiveFocus(), 5000); + // The relayout went quiet: the carry has expired (500 ms settle window). + QTest::qWait(1600); + // A later navigation must stick - an armed carry would force focus back to + // the moved row the moment this delegate root receives focus. + quietRow->forceActiveFocus(Qt::TabFocusReason); + QTRY_VERIFY_WITH_TIMEOUT(window->activeFocusItem() == quietRow, 1500); + const bool closed = closeIncubatedTestWindow(engine, window); + if (closed) close.dismiss(); + QVERIFY(closed); + } + void sidebarHydrationKeepsFocusOnOtherStream() { WindowChannelFixture fixture; diff --git a/packages/native/tests/window-test-buckets.cmake b/packages/native/tests/window-test-buckets.cmake index e03f403c2..1d625600f 100644 --- a/packages/native/tests/window-test-buckets.cmake +++ b/packages/native/tests/window-test-buckets.cmake @@ -295,6 +295,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_12 pollCreateDialogEnforcesServerLimits quoteThumbnailScopeResetKeepsOneCurrentLease receivedStandaloneImagePaintsBetweenTextAndCaption + sidebarMoveFocusCarryExpiresAfterSettle sidebarRowsRenderPreviewAndTime sourceConversationInsetsAndAvatarFallback startupCacheEmptyStoreKeepsSignInVisible From b0bf7a424a49b4e0a639067593f58cdfa680f035 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 18:35:12 +0300 Subject: [PATCH 19/20] fix: cancel the sidebar move focus carry on user input in the settle window exordy round 2 (thread 4708526165): focus must not be stolen during the 500 ms after a row move. Measured: the carry re-aim only fires for delegate-ROOT landings, which production produces only via Qt's own reparent fallback (the ring and clicks target the row button), and the churn restores land more than once - so the carry cannot be cleared on 'restore complete' without regressing finding 2. Instead, real user input inside the settle window (row click, search keyboard ring, wheel) now cancels the carry outright via streamList.disarmFocusCarry(), and the new window case pins: button-seam navigation sticks with the carry armed, a click cancels it synchronously, and a later root-level focus move sticks past the window. Solo witness: RED on the disarm assert before the QML change, green x3 after. --- packages/native/qml/Main.qml | 18 +++ packages/native/tests/native-window-test.cpp | 120 +++++++++++++++++++ 2 files changed, 138 insertions(+) diff --git a/packages/native/qml/Main.qml b/packages/native/qml/Main.qml index b0e669b07..2da88f9eb 100644 --- a/packages/native/qml/Main.qml +++ b/packages/native/qml/Main.qml @@ -5310,6 +5310,8 @@ component NativeMentionChip: Item { const delegate = streamList.itemAtIndex(target.row) const item = delegate ? root.findSidebarSearchRow(delegate, target.objectName) : null if (item) { + // The ring moving is navigation intent (see the sidebar focus carry). + streamList.disarmFocusCarry() root.scrollSidebarSearchRowIntoView(item, step) item.forceActiveFocus(Qt.TabFocusReason) return true @@ -6328,12 +6330,25 @@ component NativeMentionChip: Item { sidebarAnchorSettle.stop() root.sidebarScrollAnchor = null } + // Wheel is deliberate input too: a scroll during the settle + // window means the user navigated, not the move churn. + if (moved) + streamList.disarmFocusCarry() } } ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded } property var sidebarFocusCarry: null + // Real user input inside the settle window is navigation intent: the + // next focus move belongs to the user, so the carry is cancelled + // outright (#866 round 2: focus must not be re-aimed after the user + // navigated). Row clicks, the search keyboard ring and wheel input + // call this before they move focus or selection. + function disarmFocusCarry() { + sidebarFocusCarryExpiry.stop() + streamList.sidebarFocusCarry = null + } // exordy finding (#866): a completed move must not leave a live carry. // The carry re-aims bubbled focus onto the pre-move item; left armed // forever, the next focus navigation anywhere in the sidebar would be @@ -6551,6 +6566,9 @@ component NativeMentionChip: Item { horizontalPadding: streamDelegate.compactDensity ? 8 : 10 verticalPadding: streamDelegate.compactDensity ? 6 : 10 onClicked: { + // A row click is user navigation intent: cancel any move + // focus carry before the selection may move focus. + streamList.disarmFocusCarry(); root.controller.closeDrafts(); // Reference sidebar-workspace.ui.tsx:455: the latestTopic body // link is `stream.preview?.route ?? stream.route`; the native diff --git a/packages/native/tests/native-window-test.cpp b/packages/native/tests/native-window-test.cpp index 52520f2e6..8b655b0f4 100644 --- a/packages/native/tests/native-window-test.cpp +++ b/packages/native/tests/native-window-test.cpp @@ -13508,6 +13508,126 @@ mv -Tf "$root/.current-new" "$root/current" QVERIFY(closed); } + void sidebarMoveFocusCarryYieldsToNavigationWithinSettleWindow() + { + // exordy finding (#866 round 2, thread 4708526165): focus must not be stolen + // "during the 500 ms after a row move". Measured on this tree: (a) navigation + // through the seams production actually uses - the keyboard ring and clicks + // target the row's NativeButton, never the delegate root - already sticks + // inside the window (segment A pins that); (b) the carry's re-aim only ever + // fires for focus landing on a delegate ROOT, which in production only Qt's + // own move-reparent fallback produces - that re-aim must survive until the + // churn is quiet (restoration was measured to land TWICE in a row: a churn + // pass follows the first restore, so clearing the carry on "restore complete" + // regresses finding 2). Segment B pins the remaining intent rule: real user + // input inside the window (a row click) cancels the carry outright, so any + // focus move after it sticks even at root level. + WindowChannelFixture fixture; + const QString otherStream = "a3000000-0000-4000-8000-000000000001"; + const QString thirdStream = "a4000000-0000-4000-8000-000000000002"; + const QString thirdTopicId = "44444444-4444-4444-8444-444444444444"; + const QString previewUuid = "81000000-0000-4000-8000-000000000001"; + const QString previewBody = QStringLiteral("In-window navigation preview"); + auto first = windowChannel(streamId, "Engineering"); + first["updated_at"] = QStringLiteral("2026-01-02T10:00:00Z"); + auto second = windowChannel(otherStream, "Support"); + second["last_message_uuid"] = previewUuid; + second["updated_at"] = QStringLiteral("2026-01-01T10:00:00Z"); + const auto third = windowChannel(thirdStream, "Design"); + const auto previewRow = QJsonObject{ + {"uuid", previewUuid}, {"project_id", projectId}, {"author_uuid", userId}, + {"stream_uuid", otherStream}, {"topic_uuid", secondTopicId}, {"revision", 1}, + {"created_at", "2026-01-03T10:00:00.000Z"}, {"updated_at", "2026-01-03T10:00:00.000Z"}, + {"payload", QJsonObject{{"kind", "markdown"}, {"content", previewBody}}}}; + const auto fallback = fixture.server.handler; + auto held = std::make_shared>(); + fixture.server.handler = [=](const Request &request) -> Response { + const auto path = request.target.path(); + if (request.method == "GET" && path.endsWith("/streams/")) + return {QJsonArray{first, second, third}}; + if (request.method == "GET" && path.endsWith("/stream_topics/")) { + const auto id = QUrlQuery(request.target).queryItemValue("stream_uuid"); + const auto topic = id == streamId ? topicId : id == thirdStream ? thirdTopicId : secondTopicId; + return {QJsonArray{windowChannelTopic(topic, id, "Topic")}}; + } + if (request.method == "GET" && path.endsWith("/messages/") + && QUrlQuery(request.target).queryItemValue("uuid") == previewUuid) { + Response response{QJsonArray{previewRow}}; + response.defer = [held](auto send) { *held = std::move(send); }; + return response; + } + return fallback(request); + }; + QTemporaryDir directory; QVERIFY(directory.isValid()); + NativePreferences preferences(directory.filePath("carry-nav.ini")); + ApiClient api(nullptr, true); Session session(&api); NativeController controller(&api, &session); + QQmlApplicationEngine engine; loadNativeUi(engine, &controller, &preferences); + auto *window = qobject_cast(engine.rootObjects().value(0)); QVERIFY(window); + auto close = qScopeGuard([&engine, guard = QPointer(window)] { + if (guard && !closeIncubatedTestWindow(engine, guard.data())) + QTest::qFail("Carry navigation teardown", __FILE__, __LINE__); + }); + window->resize(1440, 900); QVERIFY(QTest::qWaitForWindowExposed(window)); + window->requestActivate(); QVERIFY(QTest::qWaitForWindowActive(window)); + session.login(fixture.server.origin(), "synthetic-carry-nav", "synthetic-password"); + QTRY_COMPARE(session.projects().size(), 1); session.selectProject(projectId); + QTRY_VERIFY(session.ready() && !controller.busy() && controller.streams().size() == 3); + auto *streamList = visibleItem("streamList"); QVERIFY(streamList); + auto *listContent = streamList->property("contentItem").value(); QVERIFY(listContent); + // The focus carry re-aims delegate-ROOT focus events (the churn signature); + // the "stream-" handle lives on the row button, so climb to the root item. + const auto delegateRoot = [&](QQuickItem *inner) { + auto *node = inner; + while (node && node->parentItem() && node->parentItem() != listContent) + node = node->parentItem(); + return node; + }; + QPointer movedButton, movedRow, quietRow, clickButton; + QTRY_VERIFY_WITH_TIMEOUT((movedButton = visibleItem("stream-" + otherStream)) != nullptr, 5000); + QTRY_VERIFY_WITH_TIMEOUT((quietRow = delegateRoot(visibleItem("stream-" + streamId))) != nullptr, 5000); + QTRY_VERIFY_WITH_TIMEOUT((clickButton = visibleItem("stream-" + thirdStream)) != nullptr, 5000); + movedRow = delegateRoot(movedButton); + QVERIFY(movedRow && movedRow != quietRow); + movedRow->forceActiveFocus(Qt::TabFocusReason); QTRY_VERIFY(movedRow->hasActiveFocus()); + QTRY_VERIFY(bool(*held)); // the lookup is in flight + (*held)(); *held = {}; + // The re-rank move fires asynchronously behind the coalesced preview pump. + // Catch the armed carry while the settle window is open (armed at the move, + // 500 ms expiry re-armed by every churn restore). + QTRY_VERIFY_WITH_TIMEOUT(!streamList->property("sidebarFocusCarry").isNull(), 5000); + // The churn has quieted with the moved row holding focus (the original #866 + // finding-2 guarantee). Every churn restore re-arms the settle window, so + // right after quiescence the carry is still live; if it had already expired + // this witness would be vacuous - assert it. + QTRY_VERIFY_WITH_TIMEOUT(movedRow->hasActiveFocus(), 5000); + QVERIFY2(!streamList->property("sidebarFocusCarry").isNull(), + "witness: the settle window must still be open after the churn"); + // Segment A - production seam unchanged: keyboard-ring-style navigation to + // another row's BUTTON sticks inside the settle window (the ring and clicks + // never target the delegate root, so the carry never sees them). Synchronous + // asserts so the 500 ms window cannot expire mid-sequence. + clickButton->forceActiveFocus(Qt::TabFocusReason); + QCOMPARE(window->activeFocusItem(), clickButton.data()); + QVERIFY2(!streamList->property("sidebarFocusCarry").isNull(), + "witness: button-seam navigation must not be what cancels the carry"); + // Segment B - intent rule: a row CLICK inside the settle window is real + // navigation; the click handler cancels the carry outright, so even a + // root-level focus move right afterwards sticks onto its own target. + QTest::mouseClick(window, Qt::LeftButton, {}, + clickButton->mapToScene(clickButton->boundingRect().center()).toPoint()); + QVERIFY2(streamList->property("sidebarFocusCarry").isNull(), + "a row click inside the settle window must cancel the focus carry synchronously"); + quietRow->forceActiveFocus(Qt::TabFocusReason); + QCOMPARE(window->activeFocusItem(), quietRow.data()); + // And it sticks past the settle window: nothing may re-steal focus later. + QTest::qWait(800); + QVERIFY2(window->activeFocusItem() == quietRow, + "User input inside the settle window must cancel the move focus carry"); + const bool closed = closeIncubatedTestWindow(engine, window); + if (closed) close.dismiss(); + QVERIFY(closed); + } + void sidebarHydrationKeepsFocusOnOtherStream() { WindowChannelFixture fixture; From 6e26adc28f6041eb6d27504233b5fd2e33485026 Mon Sep 17 00:00:00 2001 From: cassi Date: Thu, 26 Nov 2026 18:36:03 +0300 Subject: [PATCH 20/20] test: register the settle-window carry case in the window buckets --- packages/native/tests/bucket-timings/window/part21.txt | 1 + packages/native/tests/window-test-buckets.cmake | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/native/tests/bucket-timings/window/part21.txt b/packages/native/tests/bucket-timings/window/part21.txt index 77b8e4f24..71e26576c 100644 --- a/packages/native/tests/bucket-timings/window/part21.txt +++ b/packages/native/tests/bucket-timings/window/part21.txt @@ -13,5 +13,6 @@ rightDrawerIgnoresDuplicateTopScreenPush=0.414873 rightDrawerPromotesExistingLayersInsteadOfDuplicating=0.450946 rightDrawerResetIsSkippedWithoutAuthenticatedSession=0.425836 sidebarHydrationKeepsFocusOnOtherStream=0.766063 +sidebarMoveFocusCarryYieldsToNavigationWithinSettleWindow=1.64084 sidebarSearchArrowsCycleFilteredResults=1.60359 windowChannelInfoNotificationBusyRecoversOnStreamSwitch=1.3264 diff --git a/packages/native/tests/window-test-buckets.cmake b/packages/native/tests/window-test-buckets.cmake index 1d625600f..1922103b5 100644 --- a/packages/native/tests/window-test-buckets.cmake +++ b/packages/native/tests/window-test-buckets.cmake @@ -522,6 +522,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_21 rightDrawerPromotesExistingLayersInsteadOfDuplicating rightDrawerResetIsSkippedWithoutAuthenticatedSession sidebarHydrationKeepsFocusOnOtherStream + sidebarMoveFocusCarryYieldsToNavigationWithinSettleWindow sidebarSearchArrowsCycleFilteredResults windowChannelInfoNotificationBusyRecoversOnStreamSwitch )