diff --git a/packages/native/qml/Main.qml b/packages/native/qml/Main.qml index cafe4d92..2da88f9e 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 } @@ -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 @@ -6304,7 +6306,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 @@ -6325,11 +6330,62 @@ 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 + // 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. + // 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 } + sidebarFocusCarryExpiry.restart() + return + } + } + } + } delegate: Column { id: streamDelegate required property var modelData @@ -6349,7 +6405,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: [] }) @@ -6365,6 +6428,29 @@ 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() + // Each restore re-arms the settle window: churn keeps the + // carry alive, a settled move lets it expire. + sidebarFocusCarryExpiry.restart() + } + } Connections { target: root.controller function onSidebarTopicsChanged(stream) { @@ -6401,9 +6487,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 @@ -6480,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 @@ -6862,7 +6951,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 +7015,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 +7224,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 6dc0fc41..026f9fd5 100644 --- a/packages/native/src/native-controller.cpp +++ b/packages/native/src/native-controller.cpp @@ -7194,6 +7194,16 @@ 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(); + 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 @@ -9490,6 +9500,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 +12928,17 @@ 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_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(); @@ -14460,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: @@ -14513,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); } @@ -14556,6 +14578,70 @@ 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; + 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 (!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}); + 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)); @@ -15252,6 +15338,156 @@ 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: 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 == survivorOrder.at(i)) { + target = j; + break; + } + } + Q_ASSERT(target >= i); + if (target <= i) + continue; + beginMoveRows(QModelIndex(), target, target, QModelIndex(), i); + m_rows.move(target, i); + endMoveRows(); + } + // 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; + 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): @@ -15457,7 +15693,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; @@ -16838,6 +17074,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 +17310,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))) { @@ -19148,9 +19389,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 @@ -19203,6 +19448,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; @@ -19557,18 +19803,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; } } } @@ -19623,11 +19894,18 @@ 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; } + // 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 @@ -19648,25 +19926,44 @@ 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)) 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) { @@ -19676,7 +19973,18 @@ 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 + // L96-129), so the uuid waits in the retryable network stage instead of + // memoizing a miss that outlives its retry window. + enqueueRowPreviewNet(uuid); + scheduleRowPreviewNetworkHydration(); } else { storeRowPreview(uuid, RowPreview{}); // negative lookup: projections stay quiet } @@ -19686,7 +19994,15 @@ void NativeController::pumpRowPreviewHydration() if (!affectsRow) for (const auto &topic : m_topics) if (topic.lastMessage == uuid) { affectsRow = true; break; } - if (affectsRow) { emit streamsChanged(); emit topicsChanged(); } + // 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(); }); } // A bounded pass leaves the remainder queued for the next tick, so every row of a large @@ -19694,6 +20010,241 @@ 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_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 + // 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. + // #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) { + 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(); +} + +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; + // #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; + 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); + const auto dispatchGeneration = m_sessionGeneration; + request("GET", messenger + "/messages/", {}, {{"project_id", project}, {"uuid", uuid}}, + [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 + // 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(); + // 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]; + // 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(); + }); + } + // #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{}; + 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) { + // 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 + // 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]; + // 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(); + }); + } else { + storeRowPreview(uuid, RowPreview{}); // authoritative empty page: memo the miss + } + announceRowPreviewRows(uuid); + }); + } + // 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 { const auto *stream = currentStream(); diff --git a/packages/native/src/native-controller.h b/packages/native/src/native-controller.h index 660b98e7..8b6ecc18 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) @@ -177,6 +220,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) @@ -185,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. @@ -312,6 +364,35 @@ 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); + // 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; } + // #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. + 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; } @@ -511,8 +592,18 @@ 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; + // 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; @@ -1107,6 +1198,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(); @@ -2144,6 +2237,18 @@ 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(); + // 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 @@ -2206,12 +2311,58 @@ 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; + // 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 + // 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(); + // #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; 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; + 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 // 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/bucket-timings/window/part06.txt b/packages/native/tests/bucket-timings/window/part06.txt index 11792d27..e13a47a6 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/bucket-timings/window/part12.txt b/packages/native/tests/bucket-timings/window/part12.txt index 104fbd35..1ef8d925 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/bucket-timings/window/part21.txt b/packages/native/tests/bucket-timings/window/part21.txt index 77b8e4f2..71e26576 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/bucket-timings/window/part26.txt b/packages/native/tests/bucket-timings/window/part26.txt index ec511c03..db948c94 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/native-controller-sidebar-test.cpp b/packages/native/tests/native-controller-sidebar-test.cpp index bbcf1d06..be22dc18 100644 --- a/packages/native/tests/native-controller-sidebar-test.cpp +++ b/packages/native/tests/native-controller-sidebar-test.cpp @@ -1,3 +1,5 @@ +#include +#include #include "support/native-test-harness.h" #include "support/controller-chat-creation-fixtures.h" #include "support/controller-navigation-fixtures.h" @@ -6,6 +8,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: @@ -788,19 +798,303 @@ 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 + // 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(!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); + 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(readPreview.value("rowTime").toString(), expectedTime); + const auto streamRow = test.controller.streams().first().toMap(); + QCOMPARE(previewOf(test.controller, streamRow).value("previewText").toString(), QStringLiteral("Stream body")); + const auto emptyRow = topicRowOf(QStringLiteral("77777777-7777-4777-7777-0000000000e1")); + QCOMPARE(previewOf(test.controller, 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) + && !previewOf(test.controller, 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, 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. + 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 recoveredPreviewText = [&] { + for (const auto &row : std::as_const(test.controller).topics()) { + const auto map = row.toMap(); + if (map.value("id").toString() == topicId) + return previewOf(test.controller, map).value("previewText").toString(); + } + return QString{}; + }; + 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 @@ -854,11 +1148,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 @@ -958,6 +1253,144 @@ 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 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 + // 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 @@ -1001,9 +1434,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); @@ -1022,12 +1457,273 @@ 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 + } + + // 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 + // 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); + } + + 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) --- @@ -1103,7 +1799,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(""); } @@ -2119,6 +2816,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); @@ -2137,6 +2835,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; @@ -2149,7 +2854,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. @@ -2734,6 +3444,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); @@ -3185,6 +3900,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) diff --git a/packages/native/tests/native-e2ee-read-test.cpp b/packages/native/tests/native-e2ee-read-test.cpp index 51925bce..f3f21b93 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 113c1968..8b655b0f 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) @@ -7944,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)); @@ -7959,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{}); @@ -13239,6 +13249,385 @@ 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 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 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 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; @@ -16061,6 +16450,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 +17086,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 +17250,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. @@ -22168,9 +22560,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); }; @@ -22246,9 +22645,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); }; @@ -22319,9 +22725,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); }; @@ -22469,9 +22882,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)); @@ -22654,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_COMPARE(controller.selectedTopic(), topicId); auto *viewer = controller.mediaViewer(); QVERIFY(viewer); clickActiveInlineImage(window, first); @@ -22841,9 +23268,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)); @@ -22916,9 +23350,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); @@ -22995,9 +23436,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(); @@ -23154,9 +23602,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(); @@ -23279,9 +23734,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(); @@ -23440,9 +23902,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(); @@ -23550,9 +24019,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(); @@ -23656,9 +24132,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(); @@ -23761,9 +24244,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(); @@ -23884,9 +24374,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(); @@ -24010,9 +24507,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(); @@ -24135,9 +24639,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(); @@ -24228,9 +24739,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(); @@ -24316,9 +24834,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(); @@ -24389,9 +24914,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 @@ -24523,9 +25055,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); @@ -24607,9 +25146,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)); @@ -31496,6 +32042,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 +32245,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)); @@ -40427,7 +40975,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()); @@ -40485,7 +41036,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(); @@ -41083,7 +41634,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{}; }; @@ -41157,7 +41710,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); @@ -46474,7 +47028,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")); @@ -47704,9 +48260,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(); @@ -49914,7 +50473,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 @@ -50269,9 +50828,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")); diff --git a/packages/native/tests/window-test-buckets.cmake b/packages/native/tests/window-test-buckets.cmake index 73193a3f..1922103b 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 @@ -294,6 +295,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_12 pollCreateDialogEnforcesServerLimits quoteThumbnailScopeResetKeepsOneCurrentLease receivedStandaloneImagePaintsBetweenTextAndCaption + sidebarMoveFocusCarryExpiresAfterSettle sidebarRowsRenderPreviewAndTime sourceConversationInsetsAndAvatarFallback startupCacheEmptyStoreKeepsSignInVisible @@ -520,6 +522,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_21 rightDrawerPromotesExistingLayersInsteadOfDuplicating rightDrawerResetIsSkippedWithoutAuthenticatedSession sidebarHydrationKeepsFocusOnOtherStream + sidebarMoveFocusCarryYieldsToNavigationWithinSettleWindow sidebarSearchArrowsCycleFilteredResults windowChannelInfoNotificationBusyRecoversOnStreamSwitch ) @@ -624,6 +627,7 @@ set(WORKSPACE_NATIVE_WINDOW_BUCKET_26 pollManagementMenuTracksActorAndState rightDrawerShellMatchesReferenceGeometry sidebarChatActionsCompleteFromMenu + sidebarHydrationReorderKeepsActiveSidebarDelegates startupDirectoryDoesNotPopulateHiddenPickers updaterActualMainShowsAndExecutesTheDownloadAndInstallActions windowNarrowAppearanceDrawerKeepsCoveredMessagesUnread