Repository navigation
Expand file tree
/
Copy pathNodeGraphConversationUiTest.cpp
More file actions
1361 lines (1298 loc) · 56.5 KB
/
Copy pathNodeGraphConversationUiTest.cpp
File metadata and controls
1361 lines (1298 loc) · 56.5 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 "codex/middle/ConversationCards.h"
#include "codex/middle/ConversationView.h"
#include "codex/nodegraph/ProtocolUpdater.h"
#include "codex/nodegraph/WorkerLogic.h"
#include "codex/ui/NodeGraphUiAdapter.h"
#include <QApplication>
#include <QAccessible>
#include <QColor>
#include <QDateTime>
#include <QElapsedTimer>
#include <QImage>
#include <QPersistentModelIndex>
#include <QScrollBar>
#include <QTextCursor>
#include <QThread>
#include <QTimer>
#include <QToolButton>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <string>
namespace codexui::codex {
namespace {
using nodegraph::NodeKind;
using nodegraph::NodeRef;
using nodegraph::NodeState;
bool require(bool condition, const char *message) {
if (condition)
return true;
std::cerr << message << '\n';
return false;
}
bool changed(middle::ConversationView::ReconciliationResult result) {
return result == middle::ConversationView::ReconciliationResult::Changed;
}
bool finishStaging(middle::ConversationView &view) {
QElapsedTimer elapsed;
elapsed.start();
while (view.structuralStagingActive() && elapsed.elapsed() < 3000) {
QApplication::processEvents(QEventLoop::AllEvents, 10);
QThread::msleep(1);
}
return !view.structuralStagingActive();
}
NodeState state(std::string id, std::string type = {}, std::string text = {}) {
NodeState value;
value.fields.emplace("id", std::move(id));
if (!type.empty())
value.fields.emplace("type", std::move(type));
if (!text.empty())
value.fields.emplace("text", std::move(text));
return value;
}
std::optional<middle::ConversationDelta>
projectDelta(ui::NodeGraphUiAdapter &adapter, const NodeRef &thread,
std::initializer_list<NodeRef> items, bool structural) {
const std::vector<NodeRef> values(items);
return adapter.conversationDelta(thread, values, structural);
}
struct Fixture {
nodegraph::NodeGraph graph;
NodeRef thread;
int turnSerial = 0;
Fixture() {
auto write = graph.write();
thread = write.upsert({NodeKind::Thread, "thread-ui"}, state("thread-ui"));
static_cast<void>(write.finish());
}
void appendTurn(std::string answerText) {
const int serial = turnSerial++;
const std::string turnId = "turn-" + std::to_string(serial);
const std::string promptId = "prompt-" + std::to_string(serial);
const std::string answerId = "answer-" + std::to_string(serial);
auto write = graph.write();
NodeRef turn = write.upsert({NodeKind::Turn, turnId}, state(turnId));
NodeRef prompt = write.upsert(
{NodeKind::Item, promptId},
state(promptId, "userMessage", "prompt " + std::to_string(serial)));
NodeRef answer =
write.upsert({NodeKind::Item, answerId},
state(answerId, "agentMessage", std::move(answerText)));
write.setParent(thread, turn);
write.setParent(turn, prompt);
write.setParent(turn, answer);
write.relate(turn, nodegraph::RelationKind::TurnRootItem, prompt);
static_cast<void>(write.finish());
}
};
QModelIndex firstPaintedIndex(middle::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())
return index;
}
return {};
}
bool oldUiConsumesAdapterSnapshotsAtomically() {
Fixture fixture;
for (int index = 0; index < 24; ++index)
fixture.appendTurn("answer " + std::to_string(index));
ui::NodeGraphUiAdapter adapter(fixture.graph);
middle::ConversationView view;
view.resize(760, 560);
view.show();
QApplication::processEvents();
const auto initial = adapter.conversation(fixture.thread);
if (!require(initial.has_value(), "initial adapter read failed") ||
!require(changed(view.reconcile(*initial)),
"initial UI reconciliation was empty"))
return false;
QApplication::processEvents();
if (!require(view.conversationModel()->rowCount() == 48,
"selected history was not indexed in one reconciliation") ||
!require(view.findChildren<QWidget *>(
QStringLiteral("conversationCardPlaceholder"))
.empty(),
"old UI unexpectedly retained graph placeholders") ||
!require(view.verticalScrollBar()->value() ==
view.verticalScrollBar()->maximum(),
"initial following position is not the final bottom"))
return false;
int owners = 0;
for (int row = 0; row < view.conversationModel()->rowCount(); ++row)
if (view.conversationModel()
->index(row)
.data(middle::ConversationItemModel::TurnRootRole)
.toBool())
++owners;
if (!require(owners == 24, "not every turn has exactly one owning card"))
return false;
fixture.appendTurn("new following answer");
const auto appended = adapter.conversation(fixture.thread);
if (!require(appended.has_value(), "appended adapter read failed") ||
!require(changed(view.reconcile(*appended)),
"new cards were not presented"))
return false;
QApplication::processEvents();
return require(view.conversationModel()->rowCount() == 50,
"new cards failed to enter the item view immediately") &&
require(view.verticalScrollBar()->value() ==
view.verticalScrollBar()->maximum(),
"following update did not settle at its final bottom");
}
bool pausedViewportKeepsItsPaintedAnchor() {
Fixture fixture;
for (int index = 0; index < 30; ++index)
fixture.appendTurn(std::string(180, static_cast<char>('a' + index % 20)));
ui::NodeGraphUiAdapter adapter(fixture.graph);
middle::ConversationView view;
view.resize(760, 520);
view.show();
const auto initial = adapter.conversation(fixture.thread);
if (!initial || !changed(view.reconcile(*initial)))
return false;
QApplication::processEvents();
view.verticalScrollBar()->setValue(view.verticalScrollBar()->maximum() / 2);
view.verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
QApplication::processEvents();
const QModelIndex anchor = firstPaintedIndex(view);
if (!require(anchor.isValid(), "paused viewport has no painted anchor"))
return false;
const std::string key =
anchor.data(middle::ConversationItemModel::StableKeyRole)
.toString()
.toStdString();
const int y = view.visualRect(anchor).top();
fixture.appendTurn("offscreen tail");
const auto appended = adapter.conversation(fixture.thread);
if (!appended || !changed(view.reconcile(*appended)))
return false;
QApplication::processEvents();
const QModelIndex retained = view.conversationModel()->indexForStableKey(key);
return require(retained.isValid() && view.visualRect(retained).top() == y,
"paused incoming tail moved the painted anchor");
}
bool promptMorphPreservesExactTargetAndWidget() {
nodegraph::NodeGraph graph;
NodeRef thread;
NodeRef turn;
NodeRef providerTurn;
NodeRef prompt;
{
auto write = graph.write();
thread = write.upsert({NodeKind::Thread, "thread-prompt"},
state("thread-prompt"));
turn = write.upsert({NodeKind::Turn, "turn-prompt"}, state("turn-prompt"));
NodeState promptState = state("local-prompt", "localPrompt", "hello");
promptState.fields.emplace("submissionId", std::uint64_t{41});
promptState.fields.emplace("dispatchState", "inFlight");
prompt =
write.upsert({NodeKind::Item, "local-prompt"}, std::move(promptState));
write.setParent(thread, turn);
write.setParent(turn, prompt);
write.relate(turn, nodegraph::RelationKind::TurnRootItem, prompt);
static_cast<void>(write.finish());
}
ui::NodeGraphUiAdapter adapter(graph);
middle::ConversationView view;
view.resize(700, 480);
view.show();
int acknowledgements = 0;
NodeRef acknowledged;
view.setPromptMaterializedAction([&](NodeRef target) {
++acknowledgements;
acknowledged = std::move(target);
return true;
});
auto snapshot = adapter.conversation(thread);
if (!snapshot || !changed(view.reconcile(*snapshot)))
return false;
if (!require(finishStaging(view),
"local prompt did not finish its staged presentation"))
return false;
const auto before = view.findChildren<middle::ConversationCard *>();
if (!require(before.size() == 1, "local prompt did not render once") ||
!require(acknowledgements == 0,
"local prompt acknowledged before authoritative identity"))
return false;
middle::ConversationCard *stable = before.front();
middle::MarkdownTextView *const body =
stable->findChild<middle::MarkdownTextView *>();
QTextDocument *const document = body ? body->document() : nullptr;
const std::string promptKey =
middle::stableKey(middle::LocalPromptKey{41});
const QPersistentModelIndex persistentIndex(
view.conversationModel()->indexForStableKey(promptKey));
QAccessibleInterface *const accessibleCard =
QAccessible::queryAccessibleInterface(stable);
if (!require(body && document && persistentIndex.isValid() && accessibleCard,
"local prompt interaction identities were unavailable"))
return false;
view.setCurrentIndex(persistentIndex);
view.selectionModel()->select(persistentIndex,
QItemSelectionModel::ClearAndSelect |
QItemSelectionModel::Rows);
QTextCursor selection(document);
selection.setPosition(0);
selection.setPosition(
std::min(3, std::max(0, document->characterCount() - 1)),
QTextCursor::KeepAnchor);
body->setTextCursor(selection);
body->setFocus(Qt::TabFocusReason);
QApplication::processEvents();
const QString selectedText = body->textCursor().selectedText();
NodeRef authoritative;
{
auto write = graph.write();
write.setField(prompt, "dispatchState", "awaitingMaterialization");
providerTurn =
write.upsert({NodeKind::Turn, "provider-turn-prompt"},
state("provider-turn-prompt"));
authoritative =
write.upsert({NodeKind::Item, "authoritative-prompt"},
state("authoritative-prompt", "userMessage", "hello"));
write.setField(authoritative, "localSubmissionId", std::uint64_t{41});
write.setParent(thread, providerTurn);
write.setParent(providerTurn, authoritative);
write.relate(providerTurn, nodegraph::RelationKind::TurnRootItem,
authoritative);
write.relate(authoritative, nodegraph::RelationKind::PromptMaterialization,
prompt);
static_cast<void>(write.finish());
}
const auto materialized =
projectDelta(adapter, thread, {authoritative, prompt}, true);
if (!require(materialized.has_value(),
"prompt morph did not produce a structural projection"))
return false;
if (!require(view.applyConversationDelta(*materialized).has_value(),
"prompt morph structural projection was rejected"))
return false;
QApplication::processEvents();
const auto after = view.findChildren<middle::ConversationCard *>();
if (!require(after.size() == 1, "prompt morph created a duplicate card") ||
!require(after.front() == stable, "prompt morph replaced its widget") ||
!require(stable->findChild<middle::MarkdownTextView *>() == body &&
body->document() == document &&
body->textCursor().selectedText() == selectedText &&
QApplication::focusWidget() == body &&
persistentIndex.isValid() &&
view.currentIndex() == persistentIndex &&
view.selectionModel()->isSelected(persistentIndex) &&
QAccessible::queryAccessibleInterface(stable) ==
accessibleCard,
"prompt promotion replaced interaction, document, model, or "
"accessibility identity") ||
!require(acknowledgements == 1,
"prompt morph did not acknowledge exactly once") ||
!require(acknowledged == prompt,
"prompt morph discarded its exact NodeRef target"))
return false;
if (!require(after.front()->data().target == authoritative,
"prompt morph did not adopt its authoritative NodeRef"))
return false;
const auto replayed = view.applyConversationDelta(*materialized);
if (!require(replayed.has_value() && acknowledgements == 1,
"unchanged prompt projection was rejected or acknowledged "
"twice"))
return false;
const int promotedTop = stable->mapTo(view.viewport(), QPoint{}).y();
{
auto write = graph.write();
write.remove(prompt);
static_cast<void>(write.finish());
}
snapshot = adapter.conversation(thread);
if (!require(snapshot.has_value(),
"local retirement did not project the authoritative card"))
return false;
if (!require(view.reconcile(*snapshot) !=
middle::ConversationItemModel::StructuralChangeResult::Rejected,
"local retirement snapshot was rejected"))
return false;
QApplication::processEvents();
const auto retired = view.findChildren<middle::ConversationCard *>();
bool result = require(retired.size() == 1 && retired.front() == stable,
"local retirement replaced the promoted QWidget");
result &= require(retired.size() == 1 &&
retired.front()->data().target == authoritative,
"local retirement did not transfer the action target");
result &= require(retired.size() == 1 &&
retired.front()->mapTo(view.viewport(), QPoint{}).y() ==
promotedTop,
"local retirement moved the promoted card");
result &= require(
retired.size() == 1 &&
retired.front()->findChild<middle::MarkdownTextView *>() == body &&
body->document() == document &&
body->textCursor().selectedText() == selectedText &&
QApplication::focusWidget() == body && persistentIndex.isValid() &&
view.currentIndex() == persistentIndex &&
view.selectionModel()->isSelected(persistentIndex) &&
QAccessible::queryAccessibleInterface(retired.front()) ==
accessibleCard,
"local retirement replaced promoted interaction or accessibility state");
result &= require(acknowledgements == 1,
"local retirement acknowledged the prompt again");
return result;
}
bool coalescedPromptMaterializationAcknowledgesAnUnseenLocalRow() {
nodegraph::NodeGraph graph;
NodeRef thread;
NodeRef local;
NodeRef authoritative;
{
auto write = graph.write();
thread = write.upsert({NodeKind::Thread, "coalesced-prompt-thread"},
state("coalesced-prompt-thread"));
NodeRef localTurn =
write.upsert({NodeKind::Turn, "coalesced-local-turn"},
state("coalesced-local-turn"));
NodeRef providerTurn =
write.upsert({NodeKind::Turn, "coalesced-provider-turn"},
state("coalesced-provider-turn"));
NodeState localState =
state("coalesced-local", "localPrompt", "Coalesced prompt");
localState.fields.emplace("submissionId", std::uint64_t{91});
localState.fields.emplace("dispatchState", "awaitingMaterialization");
local = write.upsert({NodeKind::Item, "coalesced-local"},
std::move(localState));
authoritative =
write.upsert({NodeKind::Item, "coalesced-authoritative"},
state("coalesced-authoritative", "userMessage",
"Coalesced prompt"));
write.setField(authoritative, "localSubmissionId", std::uint64_t{91});
write.setParent(thread, localTurn);
write.setParent(thread, providerTurn);
write.setParent(localTurn, local);
write.setParent(providerTurn, authoritative);
write.relate(localTurn, nodegraph::RelationKind::TurnRootItem, local);
write.relate(providerTurn, nodegraph::RelationKind::TurnRootItem,
authoritative);
write.relate(authoritative,
nodegraph::RelationKind::PromptMaterialization, local);
static_cast<void>(write.finish());
}
ui::NodeGraphUiAdapter adapter(graph);
middle::ConversationView view;
middle::ConversationSnapshot empty;
empty.threadId = "coalesced-prompt-thread";
if (!changed(view.reconcile(std::move(empty))) || !finishStaging(view))
return false;
int acknowledgements = 0;
NodeRef acknowledged;
view.setPromptMaterializedAction([&](NodeRef target) {
++acknowledgements;
acknowledged = std::move(target);
return true;
});
const auto delta =
projectDelta(adapter, thread, {authoritative, local}, true);
if (!require(delta && delta->rows.size() == 1 &&
delta->removals == std::vector<NodeRef>{local},
"coalesced materialization did not project one authoritative "
"row and one hidden local removal"))
return false;
const auto applied = view.applyConversationDelta(*delta);
const middle::ConversationItemModel::Row *row =
view.conversationModel()->row(0);
if (!require(applied.has_value() &&
view.conversationModel()->rowCount() == 1 && row &&
row->card.kind == middle::CardKind::UserMessage &&
row->card.target == authoritative &&
acknowledgements == 1 && acknowledged == local,
"an exact delta did not acknowledge its unseen local prompt"))
return false;
middle::ConversationView replacementView;
int replacementAcknowledgements = 0;
NodeRef replacementAcknowledged;
replacementView.setPromptMaterializedAction([&](NodeRef target) {
++replacementAcknowledgements;
replacementAcknowledged = std::move(target);
return true;
});
const auto replacement = adapter.conversation(thread);
if (!require(replacement.has_value(),
"coalesced materialization had no authoritative snapshot"))
return false;
const auto replaced = replacementView.reconcile(*replacement);
const middle::ConversationItemModel::Row *replacementRow =
replacementView.conversationModel()->row(0);
if (!require(
replaced != middle::ConversationItemModel::StructuralChangeResult::Rejected &&
replacementView.conversationModel()->rowCount() == 1 &&
replacementRow &&
replacementRow->card.kind == middle::CardKind::UserMessage &&
replacementRow->card.target == authoritative &&
replacementAcknowledgements == 1 && replacementAcknowledged == local,
"an authoritative replacement did not acknowledge its unseen local "
"prompt"))
return false;
return require(
replacementView.reconcile(*replacement) ==
middle::ConversationItemModel::StructuralChangeResult::Unchanged &&
replacementAcknowledgements == 1,
"an unchanged authoritative replacement acknowledged the prompt twice");
}
bool nonFirstTurnRootPreservesProviderOrderAndNestsOnlyFollowingRows() {
nodegraph::NodeGraph graph;
NodeRef thread;
NodeRef turn;
NodeRef reasoning;
{
auto write = graph.write();
thread = write.upsert({NodeKind::Thread, "late-root-thread"},
state("late-root-thread"));
turn = write.upsert({NodeKind::Turn, "late-root-turn"},
state("late-root-turn"));
reasoning = write.upsert(
{NodeKind::Item, "early-reasoning"},
state("early-reasoning", "reasoning", "Before the prompt"));
write.setParent(thread, turn);
write.setParent(turn, reasoning);
static_cast<void>(write.finish());
}
ui::NodeGraphUiAdapter adapter(graph);
middle::ConversationView view;
view.resize(700, 480);
view.show();
auto snapshot = adapter.conversation(thread);
if (!snapshot || !changed(view.reconcile(*snapshot)) || !finishStaging(view))
return false;
const qulonglong resets =
view.conversationModel()->property("modelResetCount").toULongLong();
NodeRef root;
NodeRef answer;
{
auto write = graph.write();
root = write.upsert({NodeKind::Item, "late-root"},
state("late-root", "userMessage", "Prompt"));
answer = write.upsert({NodeKind::Item, "late-answer"},
state("late-answer", "agentMessage", "Answer"));
write.setParent(turn, root);
write.setParent(turn, answer);
write.relate(turn, nodegraph::RelationKind::TurnRootItem, root);
static_cast<void>(write.finish());
}
const auto delta = projectDelta(adapter, thread, {answer, root}, true);
if (!require(delta.has_value(),
"non-first Turn root did not produce an exact delta"))
return false;
if (!require(view.applyConversationDelta(*delta).has_value(),
"non-first Turn root required an authoritative fallback"))
return false;
const auto *first = view.conversationModel()->row(0);
const auto *second = view.conversationModel()->row(1);
const auto *third = view.conversationModel()->row(2);
if (!require(
first && second && third && first->card.target == reasoning &&
second->card.target == root && third->card.target == answer &&
!first->turnRoot && !first->nested && second->turnRoot &&
!second->nested && !third->turnRoot && third->nested &&
view.conversationModel()->property("modelResetCount").toULongLong() ==
resets,
"provider order or root-relative nesting changed during exact delivery"))
return false;
middle::ConversationCard *rootCard = nullptr;
for (middle::ConversationCard *card :
view.findChildren<middle::ConversationCard *>())
if (card->data().target == root)
rootCard = card;
QToolButton *const disclosure =
rootCard ? rootCard->findChild<QToolButton *>(
QStringLiteral("cardDisclosureButton"))
: nullptr;
if (disclosure)
disclosure->click();
QApplication::processEvents();
return require(
disclosure && rootCard->isCollapsed() &&
!view.visualRect(view.conversationModel()->index(0)).isEmpty() &&
!view.visualRect(view.conversationModel()->index(1)).isEmpty() &&
view.visualRect(view.conversationModel()->index(2)).isEmpty(),
"folding a non-first root hid pre-root activity or retained its child");
}
bool controllerAndObserverExactDeltasConverge() {
nodegraph::NodeGraph controllerGraph;
nodegraph::NodeGraph observerGraph;
struct PreparedGraph {
NodeRef thread;
NodeRef localPrompt;
};
const auto prepare = [](nodegraph::NodeGraph &graph, bool controller) {
auto write = graph.write();
NodeRef thread =
write.upsert({NodeKind::Thread, "exact-provider-order-thread"},
state("exact-provider-order-thread"));
NodeRef turn = write.upsert(nodegraph::scopedTurnNodeId(
"exact-provider-order-thread", "exact-provider-order-turn"));
write.setField(turn, "protocolId", "exact-provider-order-turn");
write.setField(turn, "protocolThreadId", "exact-provider-order-thread");
NodeRef root = write.upsert(
nodegraph::scopedItemNodeId(turn->id(), "exact-provider-root"),
state("exact-provider-root", "userMessage", "Opening prompt"));
NodeRef activity = write.upsert(
nodegraph::scopedItemNodeId(turn->id(), "exact-provider-activity"),
state("exact-provider-activity", "agentMessage", "Activity"));
write.setField(root, "protocolId", "exact-provider-root");
write.setField(root, "protocolTurnId", "exact-provider-order-turn");
write.setField(activity, "protocolId", "exact-provider-activity");
write.setField(activity, "protocolTurnId", "exact-provider-order-turn");
write.setParent(thread, turn);
write.setParent(turn, root);
write.setParent(turn, activity);
write.relate(turn, nodegraph::RelationKind::TurnRootItem, root);
NodeRef localPrompt;
if (controller) {
NodeRef runtime = write.upsert({NodeKind::Runtime, "runtime"});
NodeState local =
state("exact-local-prompt", "localPrompt", "Steer here");
local.fields.emplace("local", true);
local.fields.emplace("submissionId", std::uint64_t{405});
local.fields.emplace("clientUserMessageId", "exact-client-id");
local.fields.emplace("dispatchState", "awaitingMaterialization");
local.fields.emplace("startsTurn", false);
localPrompt = write.upsert({NodeKind::Item, "exact-local-prompt"},
std::move(local));
write.setParent(turn, localPrompt);
write.relate(runtime, nodegraph::RelationKind::PendingPrompt,
localPrompt);
write.relate(thread, nodegraph::RelationKind::PendingPrompt,
localPrompt);
}
static_cast<void>(write.finish());
return PreparedGraph{thread, localPrompt};
};
const PreparedGraph controller = prepare(controllerGraph, true);
const PreparedGraph observer = prepare(observerGraph, false);
ui::NodeGraphUiAdapter controllerAdapter(controllerGraph);
ui::NodeGraphUiAdapter observerAdapter(observerGraph);
middle::ConversationView controllerView;
middle::ConversationView observerView;
const auto controllerInitial =
controllerAdapter.conversation(controller.thread);
const auto observerInitial = observerAdapter.conversation(observer.thread);
if (!require(controllerInitial && observerInitial &&
changed(controllerView.reconcile(*controllerInitial)) &&
changed(observerView.reconcile(*observerInitial)),
"controller/observer exact-order fixtures did not reconcile"))
return false;
int controllerAcknowledgements = 0;
int observerAcknowledgements = 0;
NodeRef acknowledged;
controllerView.setPromptMaterializedAction([&](NodeRef prompt) {
++controllerAcknowledgements;
acknowledged = std::move(prompt);
return true;
});
observerView.setPromptMaterializedAction([&](NodeRef) {
++observerAcknowledgements;
return true;
});
const auto notification = [] {
return nodegraph::DecodedMessage{
nodegraph::DecodedMessageKind::ServerNotification, "item/started",
std::nullopt,
nodegraph::Value::Object{
{"threadId", nodegraph::Value("exact-provider-order-thread")},
{"turnId", nodegraph::Value("exact-provider-order-turn")},
{"item",
nodegraph::Value(nodegraph::Value::Object{
{"id", nodegraph::Value("exact-provider-steering")},
{"type", nodegraph::Value("userMessage")},
{"clientId", nodegraph::Value("exact-client-id")},
{"text", nodegraph::Value("Steer here")}})}}};
};
nodegraph::ProtocolUpdater controllerUpdater(controllerGraph);
nodegraph::ProtocolUpdater observerUpdater(observerGraph);
const nodegraph::ApplyResult controllerChange =
controllerUpdater.apply(notification());
const nodegraph::ApplyResult observerChange =
observerUpdater.apply(notification());
const auto route = [](ui::NodeGraphUiAdapter &adapter,
const NodeRef &thread,
const nodegraph::GraphChange &change) {
return adapter.conversationRoute(
{change.revision, change.affected, change.removed, false,
change.childListsChanged, change.providerAuthorityRevision},
thread);
};
const ui::NodeGraphUiAdapter::ConversationRoute controllerRoute =
route(controllerAdapter, controller.thread, controllerChange.change);
const ui::NodeGraphUiAdapter::ConversationRoute observerRoute =
route(observerAdapter, observer.thread, observerChange.change);
if (!require(controllerRoute.affected && controllerRoute.structural &&
!controllerRoute.authorityReplacement &&
observerRoute.affected && observerRoute.structural &&
!observerRoute.authorityReplacement,
"a provider item notification unnecessarily requested a full "
"conversation replacement"))
return false;
const auto controllerDelta = controllerAdapter.conversationDelta(
controller.thread, controllerRoute.items, controllerRoute.structural);
const auto observerDelta = observerAdapter.conversationDelta(
observer.thread, observerRoute.items, observerRoute.structural);
if (!require(controllerDelta && observerDelta,
"controller/observer exact notification deltas were unavailable") ||
!require(controllerView.applyConversationDelta(*controllerDelta) &&
observerView.applyConversationDelta(*observerDelta),
"controller/observer exact notification deltas were rejected"))
return false;
const auto signature = [](const middle::ConversationView &view) {
std::vector<std::string> result;
for (int index = 0; index < view.conversationModel()->rowCount(); ++index) {
const middle::ConversationItemModel::Row *row =
view.conversationModel()->row(index);
if (!row)
continue;
result.push_back(
row->card.itemId + ':' +
(row->turnRoot ? "root" : (row->nested ? "nested" : "standalone")));
}
return result;
};
const std::vector<std::string> expected{
"exact-provider-root:root", "exact-provider-activity:nested",
"exact-provider-steering:nested"};
return require(signature(controllerView) == expected &&
signature(observerView) == expected,
"controller and observer exact routes diverged from provider "
"order or root-relative nesting") &&
require(controllerAcknowledgements == 1 &&
acknowledged == controller.localPrompt &&
observerAcknowledgements == 0,
"prompt materialization acknowledgement leaked across "
"controller/observer ownership");
}
bool steeringMorphAdoptsProviderOrderWithoutReplacingItsWidget() {
nodegraph::NodeGraph graph;
NodeRef thread;
NodeRef turn;
NodeRef root;
NodeRef steering;
NodeRef progress;
{
auto write = graph.write();
thread = write.upsert({NodeKind::Thread, "thread-steering"},
state("thread-steering"));
turn =
write.upsert({NodeKind::Turn, "turn-steering"}, state("turn-steering"));
root = write.upsert({NodeKind::Item, "root-steering"},
state("root-steering", "userMessage", "Start"));
NodeState local = state("local-steering", "localPrompt", "Steer here");
local.fields.emplace("submissionId", std::uint64_t{72});
local.fields.emplace("dispatchState", "inFlight");
local.fields.emplace("admittedAtMs",
QDateTime::currentMSecsSinceEpoch() - 1500);
local.fields.emplace("startsTurn", false);
steering =
write.upsert({NodeKind::Item, "local-steering"}, std::move(local));
progress =
write.upsert({NodeKind::Item, "later-progress"},
state("later-progress", "agentMessage", "Later progress"));
write.setParent(thread, turn);
write.setParent(turn, root);
write.setParent(turn, steering);
write.setParent(turn, progress);
write.relate(turn, nodegraph::RelationKind::TurnRootItem, root);
static_cast<void>(write.finish());
}
ui::NodeGraphUiAdapter adapter(graph);
middle::ConversationView view;
view.resize(700, 520);
view.show();
int acknowledgements = 0;
view.setPromptMaterializedAction([&](NodeRef target) {
++acknowledgements;
return target == steering;
});
auto snapshot = adapter.conversation(thread);
if (!snapshot || !changed(view.reconcile(*snapshot)))
return false;
QApplication::processEvents();
const auto findCard = [&view](const std::string &key) {
for (middle::ConversationCard *card :
view.findChildren<middle::ConversationCard *>())
if (middle::stableKey(card->data().key) == key)
return card;
return static_cast<middle::ConversationCard *>(nullptr);
};
middle::ConversationCard *stable =
findCard(middle::stableKey(middle::LocalPromptKey{72}));
const std::string progressKey =
middle::stableKey(middle::AuthoritativeItemKey{
"thread-steering", "turn-steering", "later-progress"});
const QModelIndex progressIndex =
view.conversationModel()->indexForStableKey(progressKey);
if (!require(stable && progressIndex.isValid() &&
stable->mapTo(view.viewport(), QPoint{}).y() <
view.visualRect(progressIndex).top(),
"steering did not begin ahead of its later activity"))
return false;
{
auto write = graph.write();
write.setField(steering, "dispatchState", "awaitingMaterialization");
static_cast<void>(write.finish());
}
const auto acknowledgedPrompt =
projectDelta(adapter, thread, {steering}, false);
if (!acknowledgedPrompt)
return false;
static_cast<void>(view.applyConversationDelta(*acknowledgedPrompt));
QApplication::processEvents();
QTimer *animation =
stable->findChild<QTimer *>(QStringLiteral("pendingAnimationTimer"));
if (!require(animation && animation->isActive() &&
stable->data().kind == middle::CardKind::LocalPrompt &&
acknowledgements == 0,
"successful steering acceptance must keep pending animation "
"until its authoritative item arrives"))
return false;
NodeRef authoritative;
{
auto write = graph.write();
authoritative =
write.upsert({NodeKind::Item, "provider-steering"},
state("provider-steering", "userMessage", "Steer here"));
write.setField(authoritative, "localSubmissionId", std::uint64_t{72});
write.setParent(turn, authoritative);
write.relate(authoritative, nodegraph::RelationKind::PromptMaterialization,
steering);
write.replaceChildren(
turn, std::array<NodeRef, 4>{root, steering, progress, authoritative});
static_cast<void>(write.finish());
}
const auto materialized =
projectDelta(adapter, thread, {authoritative, steering}, true);
if (!materialized)
return false;
if (!require(view.applyConversationDelta(*materialized).has_value(),
"provider-ordered steering materialization was rejected"))
return false;
QApplication::processEvents();
const int promotedTop = stable->mapTo(view.viewport(), QPoint{}).y();
const QModelIndex promotedProgressIndex =
view.conversationModel()->indexForStableKey(progressKey);
if (!require(stable->data().kind == middle::CardKind::UserMessage &&
animation && !animation->isActive() &&
acknowledgements == 1 &&
promotedProgressIndex.isValid() &&
promotedTop > view.visualRect(promotedProgressIndex).top(),
"authoritative steering materialization did not stop its "
"animation while adopting provider order in place"))
return false;
{
auto write = graph.write();
write.remove(steering);
static_cast<void>(write.finish());
}
snapshot = adapter.conversation(thread);
if (!snapshot)
return false;
if (!require(view.reconcile(*snapshot) !=
middle::ConversationItemModel::StructuralChangeResult::Rejected,
"steering retirement snapshot was rejected"))
return false;
QApplication::processEvents();
const QModelIndex retiredProgressIndex =
view.conversationModel()->indexForStableKey(progressKey);
return require(
findCard(middle::stableKey(middle::LocalPromptKey{72})) == stable &&
stable->data().target == authoritative &&
stable->mapTo(view.viewport(), QPoint{}).y() == promotedTop &&
retiredProgressIndex.isValid() &&
promotedTop > view.visualRect(retiredProgressIndex).top() &&
acknowledgements == 1,
"steering retirement recreated or moved its promoted provider row");
}
bool pendingSteeringFollowsIncomingItemsUntilHistoryEntry() {
using namespace nodegraph;
bool result = true;
for (const bool responseFirst : {false, true}) {
NodeGraph graph;
ThreadChannels channels;
WorkerLogic worker(graph, channels);
ui::NodeGraphUiAdapter adapter(graph);
middle::ConversationView view;
view.resize(760, 900);
view.show();
const auto notify = [&](std::string method, Value::Object payload) {
static_cast<void>(worker.apply({DecodedMessageKind::ServerNotification,
std::move(method),
{},
std::move(payload)}));
};
const auto item = [&](std::string id, std::string type,
std::string client = {}) {
Value::Object data{{"id", id},
{"type", type},
{"text", client.empty() ? id : "same steer"}};
if (!client.empty())
data.emplace("clientId", client);
notify("item/started", {{"threadId", "steering-live"},
{"turnId", "turn"},
{"item", std::move(data)}});
};
notify("thread/started",
{{"thread", Value::Object{{"id", "steering-live"}}}});
notify("turn/started",
{{"threadId", "steering-live"},
{"turn", Value::Object{{"id", "turn"}, {"status", "inProgress"}}}});
item("opening", "userMessage");
NodeRef thread;
{
auto read = graph.tryRead();
thread = read->find({NodeKind::Thread, "steering-live"});
}
static_cast<void>(channels.drainWorkerToQtWake());
WorkerToQtMessage message;
while (channels.tryReceiveForQt(message)) {
}
static_cast<void>(view.reconcile(*adapter.conversation(thread)));
view.setPromptMaterializedAction([&](NodeRef prompt) {
return messageAdmitted(worker.promptMaterialized(prompt));
});
const auto flush = [&] {
static_cast<void>(channels.drainWorkerToQtWake());
std::vector<NodeRef> changedItems;
bool structural = false;
while (channels.tryReceiveForQt(message)) {
if (const auto *event = std::get_if<GraphChanged>(&message)) {
const auto route = adapter.conversationRoute(*event, thread);
if (!route.affected)
continue;
structural |= route.structural;
for (const NodeRef &item : route.items)
if (std::ranges::find(changedItems, item) == changedItems.end())
changedItems.push_back(item);
}
}
if (!changedItems.empty()) {
auto delta =
adapter.conversationDelta(thread, changedItems, structural);
result &= require(
delta && view.applyConversationDelta(std::move(*delta)).has_value(),
"pending-tail protocol traffic must apply incrementally without "
"a snapshot fallback");
}
QApplication::processEvents();
};
const auto submit = [&] {
NodeAction action{thread, NodeActionKind::SubmitPrompt};
action.promptText = "same steer";
return worker.admitPrompt(std::move(action), {},
QDateTime::currentMSecsSinceEpoch() - 1500);
};
auto first = submit();
if (!first.command)
return false;
static_cast<void>(submit());
flush();
const auto card = [&](int id) -> middle::ConversationCard * {
for (auto *widget : view.findChildren<middle::ConversationCard *>())
if (middle::stableKey(widget->data().key) ==
"prompt:" + std::to_string(id))
return widget;
return nullptr;
};
auto *firstCard = card(1);
auto *secondCard = card(2);
if (!require(firstCard && secondCard,
"both queued steering cards are resident"))
return false;
const auto order = [&] {
std::vector<std::string> actual;
for (int i = 0; i < view.conversationModel()->rowCount(); ++i) {
const auto &data = view.conversationModel()->row(i)->card;
actual.push_back(data.itemId.empty() ? middle::stableKey(data.key)
: data.itemId);
}
return actual;
};
item("intervening", "agentMessage");
flush();
result &=
require(order() == std::vector<std::string>{"opening", "intervening",
"prompt:1", "prompt:2"},
"incoming history precedes all unconsumed steering in "
"submission order");
{
auto read = graph.tryRead();
const auto *index = read->inspectorIndex(thread);
result &= require(index && index->latestAgentMessage() &&
scalarTextFromValue(valueMember(
*read->state(index->latestAgentMessage()),
"text")) == "intervening",
"insertion before pending prompts updates the "
"Inspector's latest message index");
}
PromptTransition next;
if (responseFirst) {
next =
worker.completePrompt(first.command->localPrompt, true, {}, "turn");
flush();
auto *timer = firstCard->findChild<QTimer *>(
QStringLiteral("pendingAnimationTimer"));
result &= require(timer && timer->isActive(),
"request acceptance keeps pending steering animated");
}
const int beforePromotion = firstCard->y();
item("steering-1", "userMessage", first.command->clientUserMessageId);
flush();
result &= require(
card(1) == firstCard && firstCard->y() == beforePromotion &&
firstCard->data().kind == middle::CardKind::UserMessage &&
!firstCard
->findChild<QTimer *>(QStringLiteral("pendingAnimationTimer"))