Repository navigation
Expand file tree
/
Copy pathConversationVirtualizationTest.cpp
More file actions
7507 lines (7201 loc) · 334 KB
/
Copy pathConversationVirtualizationTest.cpp
File metadata and controls
7507 lines (7201 loc) · 334 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
#include "AccessibilityEventProbe.h"
#include "TimingPolicy.h"
#include "codex/middle/ConversationCards.h"
#include "codex/middle/ConversationView.h"
#include "codex/ui/UiStyle.h"
#include <QAccessible>
#include <QAbstractTextDocumentLayout>
#include <QApplication>
#include <QClipboard>
#include <QColor>
#include <QElapsedTimer>
#include <QDesktopServices>
#include <QFontInfo>
#include <QImage>
#include <QKeyEvent>
#include <QLabel>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPersistentModelIndex>
#include <QPlainTextEdit>
#include <QPointer>
#include <QPointingDevice>
#include <QPushButton>
#include <QRegion>
#include <QScrollBar>
#include <QStyle>
#include <QStyleFactory>
#include <QTextBlock>
#include <QTextBrowser>
#include <QTextCursor>
#include <QThread>
#include <QToolButton>
#include <QUrl>
#include <QWheelEvent>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_set>
namespace codexui::codex::middle {
namespace {
class DesktopLinkProbe final : public QObject {
Q_OBJECT
public:
DesktopLinkProbe() { QDesktopServices::setUrlHandler("https", this, "open"); }
~DesktopLinkProbe() override { QDesktopServices::unsetUrlHandler("https"); }
QStringList urls;
public slots:
void open(const QUrl &url) { urls.push_back(url.toString()); }
};
#if defined(__SANITIZE_ADDRESS__)
constexpr qint64 InstrumentedTimingScale = 4;
#elif defined(__has_feature)
#if __has_feature(address_sanitizer)
constexpr qint64 InstrumentedTimingScale = 4;
#else
constexpr qint64 InstrumentedTimingScale = 1;
#endif
#else
constexpr qint64 InstrumentedTimingScale = 1;
#endif
bool expect(bool condition, const char *message) {
if (!condition)
std::cerr << "FAILED: " << message << '\n';
return condition;
}
bool changed(ConversationView::ReconciliationResult result) {
return result == ConversationView::ReconciliationResult::Changed;
}
bool admitted(ConversationView::SnapshotDisposition disposition) {
return disposition == ConversationView::SnapshotDisposition::Admitted;
}
VisibleCardData message(std::size_t serial, std::string text = {}) {
const std::string suffix = std::to_string(serial);
if (text.empty())
text = "Answer " + suffix;
return {AuthoritativeItemKey{"virtual-thread", "turn-" + suffix,
"item-" + suffix},
CardKind::AgentMessage,
"virtual-thread",
"turn-" + suffix,
"item-" + suffix,
AgentMessageData{std::move(text), "final_answer"}};
}
ConversationSnapshot conversation(std::size_t count,
std::size_t firstSerial = 0) {
ConversationSnapshot result;
result.threadId = "virtual-thread";
result.sections.reserve(count);
for (std::size_t offset = 0; offset < count; ++offset) {
VisibleCardData card = message(firstSerial + offset);
TurnSection section;
section.key = "section-" + std::to_string(firstSerial + offset);
section.turnId = card.turnId;
section.cards.push_back(std::move(card));
result.sections.push_back(std::move(section));
}
return result;
}
std::optional<PresentationImpact> applyPresentation(ConversationView &view,
VisibleCardData card) {
ConversationDelta delta;
delta.threadId = card.threadId;
delta.presentations.push_back(std::move(card));
return view.applyConversationDelta(std::move(delta));
}
bool applyStructural(ConversationView &view, ConversationRowChange change) {
ConversationDelta delta;
delta.threadId = change.placement.card.threadId;
delta.rows.push_back(std::move(change));
return view.applyConversationDelta(std::move(delta)).has_value();
}
bool removeProjected(ConversationView &view, nodegraph::NodeRef target) {
ConversationDelta delta;
delta.threadId = view.presentedThreadId();
delta.removals.push_back(std::move(target));
return view.applyConversationDelta(std::move(delta)).has_value();
}
bool appendProjected(ConversationView &view, ConversationRowPlacement tail) {
ConversationRowChange change;
change.placement = std::move(tail);
if (const ConversationItemModel::Row *last = view.conversationModel()->row(
view.conversationModel()->rowCount() - 1))
change.previousCardKey = last->card.key;
ConversationDelta delta;
delta.threadId = change.placement.card.threadId;
delta.rows.push_back(std::move(change));
return view.applyConversationDelta(std::move(delta)).has_value();
}
ConversationSnapshot pinnedTurnPage(std::size_t firstActivity,
std::size_t activityCount) {
ConversationSnapshot result;
result.threadId = "virtual-thread";
TurnSection section;
section.key = "shared-turn-section";
section.turnId = "shared-turn";
VisibleCardData root{
AuthoritativeItemKey{"virtual-thread", "shared-turn", "root"},
CardKind::UserMessage,
"virtual-thread",
"shared-turn",
"root",
UserMessageData{"Continue"}};
section.rootCardKey = root.key;
section.cards.push_back(std::move(root));
for (std::size_t serial = firstActivity;
serial < firstActivity + activityCount; ++serial) {
const std::string suffix = std::to_string(serial);
section.cards.push_back(
{AuthoritativeItemKey{"virtual-thread", "shared-turn",
"item-" + suffix},
CardKind::AgentMessage, "virtual-thread", "shared-turn",
"item-" + suffix, AgentMessageData{"Answer " + suffix, "final_answer"}});
}
result.sections.push_back(std::move(section));
return result;
}
void settle(int passes = 4) {
while (passes-- > 0)
QApplication::processEvents(QEventLoop::AllEvents, 20);
}
class ViewportPaintRegionProbe final : public QObject {
public:
explicit ViewportPaintRegionProbe(QWidget *viewport) : viewport_(viewport) {
viewport_->installEventFilter(this);
}
~ViewportPaintRegionProbe() override { viewport_->removeEventFilter(this); }
void start() {
painted_ = {};
paintEvents_ = 0;
active_ = true;
}
QRegion stop() {
active_ = false;
return painted_;
}
[[nodiscard]] int paintEvents() const noexcept { return paintEvents_; }
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
if (active_ && watched == viewport_ && event->type() == QEvent::Paint) {
++paintEvents_;
painted_ += static_cast<QPaintEvent *>(event)->region();
}
return false;
}
private:
QWidget *viewport_ = nullptr;
QRegion painted_;
int paintEvents_ = 0;
bool active_ = false;
};
class CommandOutputFirstPaintProbe final : public QObject {
public:
~CommandOutputFirstPaintProbe() override {
if (viewport_)
viewport_->removeEventFilter(this);
}
void watch(CommandOutputView *output) {
output_ = output;
viewport_ = output ? output->viewport() : nullptr;
if (viewport_)
viewport_->installEventFilter(this);
}
[[nodiscard]] bool seen() const noexcept { return seen_; }
[[nodiscard]] bool followedTail() const noexcept { return followedTail_; }
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
if (!seen_ && watched == viewport_ && event->type() == QEvent::Paint) {
seen_ = true;
followedTail_ = output_ && output_->followsLatest() &&
output_->verticalScrollBar()->maximum() > 0 &&
output_->verticalScrollBar()->value() ==
output_->verticalScrollBar()->maximum();
}
return false;
}
private:
QPointer<CommandOutputView> output_;
QPointer<QWidget> viewport_;
bool seen_ = false;
bool followedTail_ = false;
};
class WheelDeliveryProbe final : public QObject {
public:
explicit WheelDeliveryProbe(QObject *receiver) : receiver_(receiver) {
receiver_->installEventFilter(this);
}
~WheelDeliveryProbe() override { receiver_->removeEventFilter(this); }
[[nodiscard]] bool seen() const noexcept { return seen_; }
[[nodiscard]] ulong timestamp() const noexcept { return timestamp_; }
[[nodiscard]] Qt::MouseEventSource source() const noexcept { return source_; }
[[nodiscard]] const QPointingDevice *device() const noexcept {
return device_;
}
protected:
bool eventFilter(QObject *watched, QEvent *event) override {
if (watched == receiver_ && event->type() == QEvent::Wheel) {
const auto *wheel = static_cast<QWheelEvent *>(event);
seen_ = true;
timestamp_ = wheel->timestamp();
source_ = wheel->source();
device_ = wheel->pointingDevice();
}
return false;
}
private:
QObject *receiver_ = nullptr;
bool seen_ = false;
ulong timestamp_ = 0;
Qt::MouseEventSource source_ = Qt::MouseEventNotSynthesized;
const QPointingDevice *device_ = nullptr;
};
template <typename Predicate>
bool waitUntil(Predicate &&predicate, int timeoutMilliseconds) {
QElapsedTimer deadline;
deadline.start();
while (!predicate() && deadline.elapsed() < timeoutMilliseconds) {
QApplication::processEvents(QEventLoop::AllEvents, 10);
QThread::msleep(1);
}
return predicate();
}
ConversationSnapshot singleMessageConversation(const std::string &threadId,
const std::string &text) {
VisibleCardData card{AuthoritativeItemKey{threadId, "turn", "message"},
CardKind::AgentMessage,
threadId,
"turn",
"message",
AgentMessageData{text, "final_answer"}};
ConversationSnapshot snapshot;
snapshot.threadId = threadId;
snapshot.sections.push_back(
{"section", "turn", {std::move(card)}, std::nullopt});
return snapshot;
}
ConversationSnapshot commandConversation(const std::string &threadId,
std::size_t count) {
ConversationSnapshot snapshot;
snapshot.threadId = threadId;
snapshot.sections.reserve(count);
for (std::size_t row = 0; row < count; ++row) {
const std::string suffix = std::to_string(row);
VisibleCardData card{
AuthoritativeItemKey{threadId, "turn-" + suffix, "command-" + suffix},
CardKind::CommandExecution,
threadId,
"turn-" + suffix,
"command-" + suffix,
CommandExecutionData{"printf retained", "done", "/tmp", 0, 1},
nodegraph::NodeStatus::Completed};
snapshot.sections.push_back(
{"section-" + suffix, card.turnId, {std::move(card)}, std::nullopt});
}
return snapshot;
}
std::pair<std::string, int> firstVisible(ConversationView &view) {
for (int y = 0; y < view.viewport()->height(); ++y) {
const QModelIndex index =
view.indexAt(QPoint(view.viewport()->width() / 2, y));
if (!index.isValid())
continue;
return {index.data(ConversationItemModel::StableKeyRole)
.toString()
.toStdString(),
view.visualRect(index).top()};
}
return {};
}
ConversationCard *materializedCard(ConversationView &view,
const std::string &key) {
for (ConversationCard *card :
view.viewport()->findChildren<ConversationCard *>(
QString{}, Qt::FindDirectChildrenOnly))
if (stableKey(card->data().key) == key)
return card;
return nullptr;
}
bool residencyWindowCovered(ConversationView &view) {
const int height = view.viewport()->height();
const QRect window = view.viewport()->rect().adjusted(0, -height, 0, height);
for (int row = 0; row < view.conversationModel()->rowCount(); ++row) {
const QModelIndex index = view.conversationModel()->index(row);
const ConversationItemModel::Row *modelRow =
view.conversationModel()->row(row);
if (modelRow && view.visualRect(index).intersects(window) &&
!materializedCard(view, modelRow->stableKey))
return false;
}
return true;
}
bool viewportCovered(ConversationView &view) {
for (int row = 0; row < view.conversationModel()->rowCount(); ++row) {
const QModelIndex index = view.conversationModel()->index(row);
const ConversationItemModel::Row *modelRow =
view.conversationModel()->row(row);
if (modelRow &&
view.visualRect(index).intersects(view.viewport()->rect()) &&
!materializedCard(view, modelRow->stableKey))
return false;
}
return true;
}
bool waitForResidency(ConversationView &view, int timeoutMilliseconds = 3000) {
return waitUntil(
[&view] {
return !view.structuralStagingActive() && residencyWindowCovered(view);
},
timeoutMilliseconds);
}
bool viewportProportionalFoundation() {
ConversationView view;
view.resize(820, 600);
view.show();
settle();
ConversationSnapshot snapshot = conversation(10'000);
bool result = expect(changed(view.reconcile(snapshot)),
"ten-thousand-row authority is accepted");
result &= expect(waitForResidency(view),
"initial overscan admission reaches a bounded fixed point");
const int initialWidgets = view.materializedCardCount();
result &= expect(view.conversationModel()->rowCount() == 10'000,
"the item model indexes all canonical rows");
result &= expect(initialWidgets <= 48,
"initial QWidget count is bounded by the viewport");
result &= expect(view.findChildren<ConversationCard *>().size() <= 48,
"history has no placeholder or hidden QWidget per row");
result &= expect(view.isAtBottom(),
"initial selection reveals a complete following tail");
const QModelIndex measuredOffscreen = view.conversationModel()->index(0);
const std::string offscreenKey =
measuredOffscreen.data(ConversationItemModel::StableKeyRole)
.toString()
.toStdString();
view.verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);
view.verticalScrollBar()->setValue(view.verticalScrollBar()->minimum());
settle();
result &= expect(materializedCard(view, offscreenKey) != nullptr,
"the future offscreen row first acquires an exact native "
"renderer height");
const int middle = view.verticalScrollBar()->maximum() / 2;
view.verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);
view.verticalScrollBar()->setValue(middle);
result &= expect(waitForResidency(view),
"paused navigation admits its bounded overscan window");
const auto anchorBefore = firstVisible(view);
result &= expect(!anchorBefore.first.empty() &&
view.mode() == ConversationView::Mode::Paused,
"manual navigation establishes a painted paused anchor");
const int beforeAppendWidgets = view.materializedCardCount();
ConversationSnapshot prepended = snapshot;
VisibleCardData inserted = message(10'000);
TurnSection insertedSection;
insertedSection.key = "section-10000";
insertedSection.turnId = inserted.turnId;
insertedSection.cards.push_back(std::move(inserted));
prepended.sections.insert(prepended.sections.begin(),
std::move(insertedSection));
result &= expect(changed(view.reconcile(prepended)),
"a structural insertion reconciles precisely");
result &= expect(waitForResidency(view),
"structural insertion restores bounded overscan residency");
const auto anchorAfter = firstVisible(view);
result &= expect(anchorAfter == anchorBefore,
"insertion above preserves identity and exact pixel offset");
result &= expect(view.horizontalScrollBar()->value() == 0 &&
view.materializedCardCount() <=
std::max(48, beforeAppendWidgets + 4),
"structural insertion preserves both axes and widget bound");
const QModelIndex offscreen =
view.conversationModel()->indexForStableKey(offscreenKey);
result &= expect(materializedCard(view, offscreenKey) == nullptr,
"chosen offscreen row has no QWidget");
VisibleCardData offscreenUpdate =
*view.conversationModel()->card(offscreen.row());
std::get<AgentMessageData>(offscreenUpdate.payload).text +=
std::string(1200, 'x');
const qulonglong constructionsBefore =
view.property("conversationCardConstructions").toULongLong();
const auto offscreenImpact =
applyPresentation(view, std::move(offscreenUpdate));
settle();
result &=
expect(offscreenImpact == PresentationImpact::GeometryChanged &&
materializedCard(view, offscreenKey) == nullptr &&
firstVisible(view) == anchorBefore &&
view.property("conversationCardConstructions").toULongLong() ==
constructionsBefore,
"offscreen content replaces a stale exact height with a bounded "
"estimate while preserving the viewport anchor");
const auto visibleIdentity = firstVisible(view);
const QModelIndex visibleIndex =
view.conversationModel()->indexForStableKey(visibleIdentity.first);
ConversationCard *const visibleCard =
materializedCard(view, visibleIdentity.first);
VisibleCardData visibleUpdate =
*view.conversationModel()->card(visibleIndex.row());
std::get<AgentMessageData>(visibleUpdate.payload).text +=
std::string(240, 'x');
const qulonglong offscreenBefore =
view.property("targetedOffscreenCardUpdates").toULongLong();
const qulonglong visibleConstructionsBefore =
view.property("conversationCardConstructions").toULongLong();
const auto visibleImpact = applyPresentation(view, std::move(visibleUpdate));
settle();
result &= expect(
visibleCard &&
materializedCard(view, visibleIdentity.first) == visibleCard &&
visibleImpact == PresentationImpact::GeometryChanged &&
view.property("targetedOffscreenCardUpdates").toULongLong() ==
offscreenBefore &&
view.property("conversationCardConstructions").toULongLong() ==
visibleConstructionsBefore,
"one visible stream update keeps and updates its authoritative card");
result &= expect(firstVisible(view).second == visibleIdentity.second,
"visible height change preserves the exact painted anchor");
const VisibleCardData currentVisible = *view.conversationModel()->card(
view.conversationModel()->indexForStableKey(visibleIdentity.first).row());
for (TurnSection §ion : prepended.sections)
for (VisibleCardData &card : section.cards)
if (stableKey(card.key) == visibleIdentity.first)
card = currentVisible;
view.scrollTo(offscreen, QAbstractItemView::PositionAtTop);
ConversationCard *returned = materializedCard(view, offscreenKey);
const QRect returnedGeometry = returned ? returned->geometry() : QRect{};
settle();
result &= expect(returned && returned->geometry() == returnedGeometry,
"returning to an invalidated offscreen row settles its real "
"renderer before the frame is exposed");
const int exactOffscreenExtent =
view.visualRect(view.conversationModel()->indexForStableKey(offscreenKey))
.height();
ConversationSnapshot rescanned = prepended;
VisibleCardData rescannedCard = *view.conversationModel()->card(
view.conversationModel()->indexForStableKey(offscreenKey).row());
std::get<AgentMessageData>(rescannedCard.payload).text +=
std::string(1200, 'y');
for (TurnSection §ion : rescanned.sections)
for (VisibleCardData &card : section.cards)
if (stableKey(card.key) == offscreenKey)
card = rescannedCard;
view.verticalScrollBar()->setValue(view.verticalScrollBar()->maximum() / 2);
result &= expect(waitForResidency(view),
"the rescan anchor's overscan reaches a fixed point");
const auto rescanAnchor = firstVisible(view);
const qulonglong rescanConstructions =
view.property("conversationCardConstructions").toULongLong();
result &= expect(materializedCard(view, offscreenKey) == nullptr &&
changed(view.reconcile(rescanned)),
"a whole-snapshot update changes the released row");
settle();
result &= expect(
materializedCard(view, offscreenKey) == nullptr &&
firstVisible(view) == rescanAnchor &&
view.visualRect(
view.conversationModel()->indexForStableKey(offscreenKey))
.height() != exactOffscreenExtent &&
view.property("conversationCardConstructions").toULongLong() ==
rescanConstructions,
"whole-snapshot reconciliation invalidates only the offscreen scalar "
"height and preserves the painted anchor");
const QModelIndex rescannedIndex =
view.conversationModel()->indexForStableKey(offscreenKey);
view.scrollTo(rescannedIndex, QAbstractItemView::PositionAtTop);
ConversationCard *rescannedRenderer = materializedCard(view, offscreenKey);
const QRect rescannedGeometry =
rescannedRenderer ? rescannedRenderer->geometry() : QRect{};
settle();
result &= expect(
rescannedRenderer && rescannedRenderer->geometry() == rescannedGeometry,
"the reconciled offscreen row exposes its exact renderer geometry in "
"one frame");
return result;
}
bool exactStructuralRowsPreserveTheViewport() {
nodegraph::NodeGraph graph;
std::vector<nodegraph::NodeRef> targets;
nodegraph::NodeRef insertedTarget;
{
auto write = graph.write();
for (int row = 0; row < 10'000; ++row)
targets.push_back(write.upsert(
{nodegraph::NodeKind::Item, "exact-row-" + std::to_string(row)}));
insertedTarget =
write.upsert({nodegraph::NodeKind::Item, "exact-row-inserted"});
static_cast<void>(write.finish());
}
ConversationSnapshot snapshot = conversation(targets.size());
for (std::size_t row = 0; row < targets.size(); ++row)
snapshot.sections[row].cards.front().target = targets[row];
ConversationView view;
view.resize(820, 420);
view.show();
bool result = expect(changed(view.reconcile(std::move(snapshot))),
"exact structural row fixture reconciles");
settle();
view.verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);
view.verticalScrollBar()->setValue(view.verticalScrollBar()->maximum() / 2);
result &= expect(waitForResidency(view),
"exact-structure fixture starts from settled overscan "
"residency");
const auto anchorBeforeTransaction = firstVisible(view);
VisibleCardData inserted = message(10'001, "Inserted in the middle");
inserted.target = insertedTarget;
ConversationRowChange insertion;
insertion.placement = {inserted, "section-inserted", false, false, false};
insertion.previousCardKey = message(7).key;
insertion.nextCardKey = message(8).key;
const qulonglong resetsBefore =
view.conversationModel()->property("modelResetCount").toULongLong();
const qulonglong identityRebuildsBefore =
view.conversationModel()
->property("modelIndexRebuildCount")
.toULongLong();
const qulonglong sectionRebuildsBefore =
view.property("conversationSectionRangeRebuilds").toULongLong();
const qulonglong heightRebuildsBefore =
view.property("conversationHeightIndexRebuilds").toULongLong();
ViewportPaintRegionProbe paintProbe(view.viewport());
paintProbe.start();
ConversationRowChange movement;
movement.placement = {message(2), "section-2", false, false, false};
movement.placement.card.target = targets[2];
movement.previousCardKey = message(9'999).key;
ConversationDelta transaction;
transaction.threadId = view.presentedThreadId();
transaction.rows = {std::move(insertion), std::move(movement)};
transaction.removals.push_back(targets.front());
const bool applied =
view.applyConversationDelta(std::move(transaction)).has_value();
settle();
const QRegion offscreenPaint = paintProbe.stop();
const int offscreenPaintEvents = paintProbe.paintEvents();
if (offscreenPaintEvents > 2)
std::cerr << "offscreen structural paint events=" << offscreenPaintEvents
<< " region=" << offscreenPaint.boundingRect().x() << ','
<< offscreenPaint.boundingRect().y() << ' '
<< offscreenPaint.boundingRect().width() << 'x'
<< offscreenPaint.boundingRect().height() << '\n';
const QModelIndex insertedIndex =
view.conversationModel()->indexForTarget(insertedTarget);
const VisibleCardData *beforeInserted =
view.conversationModel()->card(insertedIndex.row() - 1);
const VisibleCardData *afterInserted =
view.conversationModel()->card(insertedIndex.row() + 1);
result &=
expect(applied && insertedIndex.isValid() && insertedIndex.row() > 0 &&
beforeInserted && beforeInserted->target == targets[7] &&
afterInserted && afterInserted->target == targets[8] &&
view.conversationModel()->indexForTarget(targets[2]).row() ==
view.conversationModel()->rowCount() - 1,
"one transaction did not commit its exact insert and move order");
result &= expect(
!view.conversationModel()->indexForTarget(targets.front()).isValid(),
"the exact removal retires its target identity");
result &= expect(firstVisible(view) == anchorBeforeTransaction,
"the multi-operation transaction retains its pixel anchor");
result &= expect(
view.conversationModel()->property("modelResetCount").toULongLong() ==
resetsBefore &&
view.conversationModel()
->property("modelExactInsertCount")
.toULongLong() == 1 &&
view.conversationModel()
->property("modelExactMoveCount")
.toULongLong() == 1 &&
view.conversationModel()
->property("modelExactRemoveCount")
.toULongLong() == 1,
"the transaction emits one exact insert, move, and removal without a "
"reset");
result &= expect(
view.conversationModel()
->property("modelIndexRebuildCount")
.toULongLong() == identityRebuildsBefore &&
view.property("conversationSectionRangeRebuilds").toULongLong() ==
sectionRebuildsBefore &&
view.property("conversationHeightIndexRebuilds").toULongLong() ==
heightRebuildsBefore,
"exact structural operations preserve identity, section, and height "
"indexes");
result &=
expect(offscreenPaintEvents <= 2,
"Qt bounds the multi-signal transaction to two coalesced paints");
result &= expect(offscreenPaint.subtracted(view.viewport()->rect()).isEmpty(),
"offscreen transaction paint remains viewport bounded");
result &= expect(view.materializedCardCount() <= 48,
"the exact transaction retains bounded widget residency");
view.verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);
settle();
const QModelIndex visibleIndex =
view.conversationModel()->indexForTarget(targets[1]);
const QRect visibleBefore = view.visualRect(visibleIndex);
paintProbe.start();
const bool removedVisible = removeProjected(view, targets[1]);
settle();
const QRegion visiblePaint = paintProbe.stop();
const int visiblePaintEvents = paintProbe.paintEvents();
result &= expect(
removedVisible && visibleBefore.intersects(view.viewport()->rect()) &&
visiblePaintEvents >= 1 && visiblePaintEvents <= 2 &&
visiblePaint.intersects(visibleBefore) &&
visiblePaint.subtracted(view.viewport()->rect()).isEmpty(),
"a visible exact removal repaints its viewport-bounded suffix");
return result;
}
bool rejectedDeltaTransactionsAreAtomic() {
nodegraph::NodeGraph graph;
nodegraph::NodeRef firstTarget;
nodegraph::NodeRef secondTarget;
nodegraph::NodeRef conflictingTarget;
nodegraph::NodeRef promptTarget;
nodegraph::NodeRef authoritativeTarget;
nodegraph::NodeRef dependentATarget;
nodegraph::NodeRef dependentBTarget;
{
auto write = graph.write();
firstTarget =
write.upsert({nodegraph::NodeKind::Item, "atomic-presentation-first"});
secondTarget =
write.upsert({nodegraph::NodeKind::Item, "atomic-presentation-second"});
conflictingTarget = write.upsert(
{nodegraph::NodeKind::Item, "atomic-presentation-conflict"});
promptTarget =
write.upsert({nodegraph::NodeKind::Item, "atomic-local-prompt"});
authoritativeTarget = write.upsert(
{nodegraph::NodeKind::Item, "atomic-authoritative-prompt"});
dependentATarget =
write.upsert({nodegraph::NodeKind::Item, "atomic-dependent-a"});
dependentBTarget =
write.upsert({nodegraph::NodeKind::Item, "atomic-dependent-b"});
static_cast<void>(write.finish());
}
ConversationSnapshot presentationSnapshot = conversation(2);
presentationSnapshot.sections[0].cards[0].target = firstTarget;
presentationSnapshot.sections[1].cards[0].target = secondTarget;
ConversationView presentationView;
presentationView.resize(820, 420);
presentationView.show();
bool result = expect(
changed(presentationView.reconcile(std::move(presentationSnapshot))),
"the atomic presentation fixture reconciles");
settle();
const VisibleCardData firstBefore =
*presentationView.conversationModel()->card(0);
const VisibleCardData secondBefore =
*presentationView.conversationModel()->card(1);
ConversationCard *const firstCard =
materializedCard(presentationView, stableKey(firstBefore.key));
ConversationCard *const secondCard =
materializedCard(presentationView, stableKey(secondBefore.key));
const QRect firstGeometry = firstCard ? firstCard->geometry() : QRect{};
const QRect secondGeometry = secondCard ? secondCard->geometry() : QRect{};
const QImage pixelsBefore = presentationView.viewport()->grab().toImage();
const qulonglong dataChanges = presentationView.conversationModel()
->property("modelDataChangeCount")
.toULongLong();
const qulonglong geometryPasses =
presentationView.property("conversationLocalGeometryPasses")
.toULongLong();
VisibleCardData valid = firstBefore;
std::get<AgentMessageData>(valid.payload).text = "must not be committed";
VisibleCardData invalid = secondBefore;
invalid.target = conflictingTarget;
ConversationDelta presentations;
presentations.threadId = presentationView.presentedThreadId();
presentations.presentations = {std::move(valid), std::move(invalid)};
const auto presentationResult =
presentationView.applyConversationDelta(std::move(presentations));
settle();
result &= expect(
!presentationResult &&
*presentationView.conversationModel()->card(0) == firstBefore &&
*presentationView.conversationModel()->card(1) == secondBefore &&
materializedCard(presentationView, stableKey(firstBefore.key)) ==
firstCard &&
materializedCard(presentationView, stableKey(secondBefore.key)) ==
secondCard &&
(!firstCard || firstCard->geometry() == firstGeometry) &&
(!secondCard || secondCard->geometry() == secondGeometry) &&
presentationView.viewport()->grab().toImage() == pixelsBefore &&
presentationView.conversationModel()
->property("modelDataChangeCount")
.toULongLong() == dataChanges &&
presentationView.property("conversationLocalGeometryPasses")
.toULongLong() == geometryPasses,
"an incompatible later presentation rejects the whole batch without "
"model, renderer, geometry, pixel, or work changes");
const std::string thread = "atomic-structural";
VisibleCardData local{LocalPromptKey{901},
CardKind::LocalPrompt,
thread,
"turn-prompt",
"local",
LocalPromptData{901, "Atomic prompt"}};
local.target = promptTarget;
VisibleCardData other{AuthoritativeItemKey{thread, "turn-other", "other"},
CardKind::AgentMessage,
thread,
"turn-other",
"other",
AgentMessageData{"Other row", "final_answer"}};
other.target = secondTarget;
ConversationSnapshot structuralSnapshot;
structuralSnapshot.threadId = thread;
structuralSnapshot.sections.push_back(
{"prompt-section", "turn-prompt", {local}, local.key});
structuralSnapshot.sections.push_back(
{"other-section", "turn-other", {other}, other.key});
ConversationView structuralView;
structuralView.resize(820, 420);
structuralView.show();
int acknowledgements = 0;
nodegraph::NodeRef acknowledged;
structuralView.setPromptMaterializedAction([&](nodegraph::NodeRef target) {
++acknowledgements;
acknowledged = std::move(target);
return true;
});
result &= expect(changed(structuralView.reconcile(structuralSnapshot)),
"the atomic structural fixture reconciles");
settle();
const QImage structuralPixels = structuralView.viewport()->grab().toImage();
const qulonglong exactMoves = structuralView.conversationModel()
->property("modelExactMoveCount")
.toULongLong();
const qulonglong exactRemovals = structuralView.conversationModel()
->property("modelExactRemoveCount")
.toULongLong();
VisibleCardData promoted = local;
promoted.kind = CardKind::UserMessage;
promoted.itemId = "authoritative";
promoted.payload = UserMessageData{"Atomic prompt", {}};
promoted.target = authoritativeTarget;
ConversationRowChange promotion{
{promoted, "prompt-section", true, false, false}, {}, other.key};
VisibleCardData conflicting = other;
conflicting.key = AuthoritativeItemKey{thread, "turn-other", "different-key"};
ConversationRowChange invalidRow{
{std::move(conflicting), "other-section", true, false, false},
promoted.key,
{}};
ConversationDelta structural;
structural.threadId = thread;
structural.rows = {std::move(promotion), std::move(invalidRow)};
structural.removals.push_back(promptTarget);
const auto structuralResult =
structuralView.applyConversationDelta(std::move(structural));
settle();
const QModelIndex localIndex =
structuralView.conversationModel()->indexForStableKey(
stableKey(local.key));
result &= expect(
!structuralResult && localIndex.isValid() &&
structuralView.conversationModel()->card(localIndex.row())->kind ==
CardKind::LocalPrompt &&
structuralView.conversationModel()->card(localIndex.row())->target ==
promptTarget &&
structuralView.conversationModel()->rowCount() == 2 &&
acknowledgements == 0 &&
structuralView.viewport()->grab().toImage() == structuralPixels &&
structuralView.conversationModel()
->property("modelExactMoveCount")
.toULongLong() == exactMoves &&
structuralView.conversationModel()
->property("modelExactRemoveCount")
.toULongLong() == exactRemovals,
"a conflicting later row rejects promotion and retirement without "
"partial mutation or acknowledgement");
ConversationSnapshot authoritative;
authoritative.threadId = thread;
authoritative.materializedPrompts.push_back({promoted.key, promptTarget});
authoritative.sections.push_back(
{"prompt-section", "turn-prompt", {promoted}, promoted.key});
authoritative.sections.push_back(
{"other-section", "turn-other", {other}, other.key});
result &= expect(
changed(structuralView.reconcile(authoritative)) &&
acknowledgements == 1 && acknowledged == promptTarget,
"the subsequent authoritative frame promotes and acknowledges exactly "
"once");
VisibleCardData dependentA{
AuthoritativeItemKey{thread, "dependent-a", "root"},
CardKind::UserMessage,
thread,
"dependent-a",
"root",
UserMessageData{"Dependent A", {}}};
dependentA.target = dependentATarget;
VisibleCardData dependentB{
AuthoritativeItemKey{thread, "dependent-b", "root"},
CardKind::UserMessage,
thread,
"dependent-b",
"root",
UserMessageData{"Dependent B", {}}};
dependentB.target = dependentBTarget;
ConversationDelta unresolvedDependency;
unresolvedDependency.threadId = thread;
unresolvedDependency.rows.push_back(
{{dependentA, "dependent-a-section", true, false, false},
dependentB.key,
{}});
unresolvedDependency.rows.push_back(
{{dependentB, "dependent-b-section", true, false, false},
AuthoritativeItemKey{thread, "outside", "before"},
AuthoritativeItemKey{thread, "outside", "after"}});
const int rowsBeforeDependency =
structuralView.conversationModel()->rowCount();
const qulonglong appendsBeforeDependency =
structuralView.conversationModel()
->property("modelTailAppendCount")
.toULongLong();
const QImage pixelsBeforeDependency =
structuralView.viewport()->grab().toImage();
result &= expect(
!structuralView.applyConversationDelta(std::move(unresolvedDependency))
.has_value() &&
structuralView.conversationModel()->rowCount() ==
rowsBeforeDependency &&
structuralView.conversationModel()
->property("modelTailAppendCount")
.toULongLong() == appendsBeforeDependency &&
structuralView.viewport()->grab().toImage() == pixelsBeforeDependency,
"an unresolved in-batch neighbor rejects the whole structural plan");
VisibleCardData unrepresented{
AuthoritativeItemKey{thread, "old-turn", "old-item"},
CardKind::AgentMessage,
thread,
"old-turn",
"old-item",
AgentMessageData{"Outside the resident suffix", "final_answer"}};
unrepresented.target = conflictingTarget;
ConversationDelta outside;
outside.threadId = thread;
outside.rows.push_back({{unrepresented, "old-section", false, true, false},
AuthoritativeItemKey{thread, "older", "before"},
AuthoritativeItemKey{thread, "older", "after"}});
const int rowsBeforeOutside = structuralView.conversationModel()->rowCount();
const QImage pixelsBeforeMissingRows =
structuralView.viewport()->grab().toImage();
result &= expect(
!structuralView.applyConversationDelta(std::move(outside)).has_value() &&
structuralView.conversationModel()->rowCount() == rowsBeforeOutside &&
structuralView.viewport()->grab().toImage() ==
pixelsBeforeMissingRows,
"a structural row with missing canonical neighbors rejects atomically");
ConversationDelta outsideBeginning;
outsideBeginning.threadId = thread;
outsideBeginning.rows.push_back(
{{unrepresented, "old-section", false, true, false},
{},
AuthoritativeItemKey{thread, "older", "unrepresented-next"}});
result &= expect(
!structuralView.applyConversationDelta(std::move(outsideBeginning))
.has_value() &&
structuralView.conversationModel()->rowCount() == rowsBeforeOutside &&
structuralView.viewport()->grab().toImage() ==
pixelsBeforeMissingRows,
"an absent canonical-beginning row rejects when its successor is "
"missing");
const QImage pixelsBeforeMissingLandmarks =
structuralView.viewport()->grab().toImage();
VisibleCardData missingYou = unrepresented;
missingYou.key = AuthoritativeItemKey{thread, "old-turn", "missing-you"};
missingYou.kind = CardKind::UserMessage;
missingYou.itemId = "missing-you";
missingYou.payload = UserMessageData{"Retain this loaded You landmark", {}};
ConversationDelta missingYouDelta;
missingYouDelta.threadId = thread;
missingYouDelta.rows.push_back(
{{std::move(missingYou), "old-section", false, true, false},
AuthoritativeItemKey{thread, "older", "before"},
AuthoritativeItemKey{thread, "older", "after"}});
result &= expect(
!structuralView.applyConversationDelta(std::move(missingYouDelta))
.has_value() &&
structuralView.conversationModel()->rowCount() == rowsBeforeOutside &&
structuralView.viewport()->grab().toImage() ==
pixelsBeforeMissingLandmarks,
"a disconnected loaded You row requests an authoritative snapshot "
"instead of disappearing from the complete model");
VisibleCardData missingRoot = unrepresented;
missingRoot.key =
AuthoritativeItemKey{thread, "missing-root-turn", "missing-root"};
missingRoot.turnId = "missing-root-turn";
missingRoot.itemId = "missing-root";
ConversationDelta missingRootDelta;
missingRootDelta.threadId = thread;
missingRootDelta.rows.push_back(