summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/tests/engagementTelemetry/browser/browser_glean_telemetry_exposure_edge_cases.js
blob: 725240c9b180c239bd46c40ce6c82c067d08fd7e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

// Tests edge cases related to the exposure event and view updates.

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.sys.mjs",
  UrlbarResult: "resource:///modules/UrlbarResult.sys.mjs",
  UrlbarUtils: "resource:///modules/UrlbarUtils.sys.mjs",
  UrlbarView: "resource:///modules/UrlbarView.sys.mjs",
});

const MAX_RESULT_COUNT = 10;

let gProvider;

add_setup(async function () {
  await initExposureTest();

  await SpecialPowers.pushPrefEnv({
    set: [
      // Make absolutely sure the panel stays open during the test. There are
      // spurious blurs on WebRender TV tests as the test starts that cause the
      // panel to close and the query to be canceled, resulting in intermittent
      // failures without this.
      ["ui.popup.disable_autohide", true],

      // Set maxRichResults for sanity.
      ["browser.urlbar.maxRichResults", MAX_RESULT_COUNT],
    ],
  });

  await Services.fog.testFlushAllChildren();
  Services.fog.testResetFOG();

  gProvider = new TestProvider();
  UrlbarProvidersManager.registerProvider(gProvider);

  // This test specifically checks the view's behavior before and after it
  // removes stale rows, so it needs to control when that occurs. There are two
  // times the view removes stale rows: (1) when the stale-rows timer fires, (2)
  // when a query finishes. We prevent (1) from occuring by increasing the
  // timer's timeout so it never fires during the test. We'll rely on (2) to
  // trigger stale rows removal.
  let originalRemoveStaleRowsTimeout = UrlbarView.removeStaleRowsTimeout;
  UrlbarView.removeStaleRowsTimeout = 30000;

  registerCleanupFunction(() => {
    UrlbarView.removeStaleRowsTimeout = originalRemoveStaleRowsTimeout;
    UrlbarProvidersManager.unregisterProvider(gProvider);
  });
});

// Does the following:
//
// 1. Starts and finishes a query that fills up the view
// 2. Starts a second query with results that cannot replace rows from the first
//    query and that therefore must be appended and hidden
// 3. Cancels the second query before it finishes (so that stale rows are not
//    removed)
//
// Results in the second query should not trigger an exposure. They can never be
// visible in the view since the second query is canceled before stale rows are
// removed.
add_task(async function noExposure() {
  for (let showExposureResults of [true, false]) {
    await do_noExposure(showExposureResults);
  }
});

async function do_noExposure(showExposureResults) {
  info("Starting do_noExposure: " + JSON.stringify({ showExposureResults }));

  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.exposureResults", "history"],
      ["browser.urlbar.showExposureResults", showExposureResults],
    ],
  });

  // Make the provider return enough search suggestions to fill the view.
  gProvider.results = [];
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    gProvider.results.push(
      new UrlbarResult(
        UrlbarUtils.RESULT_TYPE.SEARCH,
        UrlbarUtils.RESULT_SOURCE.SEARCH,
        {
          suggestion: "suggestion " + i,
          engine: Services.search.defaultEngine.name,
        }
      )
    );
  }

  // Do the first query to fill the view with search suggestions.
  info("Doing first query");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 1",
  });

  // Now make the provider return a history result and bookmark. If
  // `showExposureResults` is true, the history result will be added to the view
  // but it should be hidden since the view is already full. If it's false, it
  // shouldn't be added at all. The bookmark will always be added, which will
  // tell us when the view has been updated either way. (It also will be hidden
  // since the view is already full.)
  let historyUrl = "https://example.com/history";
  let bookmarkUrl = "https://example.com/bookmark";
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.HISTORY,
      { url: historyUrl }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      { url: bookmarkUrl }
    ),
  ];

  // When the provider's `startQuery()` is called, let it add its results but
  // don't let it return. That will cause the view to be updated with the new
  // results but prevent it from showing hidden rows since the query won't
  // finish (so stale rows won't be removed).
  let queryResolver = Promise.withResolvers();
  gProvider.finishQueryPromise = queryResolver.promise;

  // Observe when the view appends the bookmark row. This will tell us when the
  // view has been updated with the provider's new results. The bookmark row
  // will be hidden since the view is already full with search suggestions.
  let lastRowPromise = promiseLastRowAppended(
    row => row.result.payload.url == bookmarkUrl
  );

  // Now start the second query but don't await it.
  info("Starting second query");
  let queryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 2",
    reopenOnBlur: false,
  });

  // Wait for the view to be updated.
  info("Waiting for last row");
  let lastRow = await lastRowPromise;
  info("Done waiting for last row");

  Assert.ok(
    BrowserTestUtils.isHidden(lastRow),
    "The new bookmark row should be hidden since the view is full"
  );

  // Make sure the view is full of visible rows as expected, plus the one or two
  // hidden rows for the history and/or bookmark results.
  let expected = [
    {
      source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: bookmarkUrl,
    },
  ];
  if (showExposureResults) {
    expected.unshift({
      source: UrlbarUtils.RESULT_SOURCE.HISTORY,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: historyUrl,
    });
  }
  let rows = UrlbarTestUtils.getResultsContainer(window);
  Assert.equal(
    rows.children.length,
    MAX_RESULT_COUNT + expected.length,
    "The view has the expected number of rows"
  );

  // Check the visible rows.
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    let row = rows.children[i];
    Assert.ok(BrowserTestUtils.isVisible(row), `rows[${i}] should be visible`);
    Assert.ok(
      row.result.type == UrlbarUtils.RESULT_TYPE.SEARCH,
      `rows[${i}].result.type should be SEARCH`
    );
    // The heuristic won't have a suggestion so skip it.
    if (i > 0) {
      Assert.ok(
        row.result.payload.suggestion,
        `rows[${i}] should have a suggestion`
      );
    }
  }

  // Check the hidden history and/or bookmark rows.
  for (let i = 0; i < expected.length; i++) {
    let { source, type, url } = expected[i];
    let row = rows.children[MAX_RESULT_COUNT + i];
    Assert.ok(row, `rows[${i}] should exist`);
    Assert.ok(BrowserTestUtils.isHidden(row), `rows[${i}] should be hidden`);
    Assert.equal(
      row.result.type,
      type,
      `rows[${i}].result.type should be as expected`
    );
    Assert.equal(
      row.result.source,
      source,
      `rows[${i}].result.source should be as expected`
    );
    Assert.equal(
      row.result.payload.url,
      url,
      `rows[${i}] URL should be as expected`
    );
  }

  // Close the view. Blur the urlbar to end the session.
  info("Closing view and blurring");
  await UrlbarTestUtils.promisePopupClose(window);
  gURLBar.blur();

  // No exposure should have been recorded since the history result could never
  // be visible.
  assertExposureTelemetry([]);

  // Clean up.
  queryResolver.resolve();
  await queryPromise;
  await SpecialPowers.popPrefEnv();
  Services.fog.testResetFOG();
  gProvider.finishQueryPromise = null;
}

// Does the following:
//
// 1. Starts and finishes a query that underfills the view
// 2. Starts a second query
// 3. Waits for rows from the second query to be appended. They will be
//    immediately visible since the first query underfilled the view.
// 4. Either cancels the second query (so stale rows are not removed) or waits
//    for it to finish (so stale rows are removed)
//
// Results in the second query should trigger an exposure since they are made
// visible in step 3. Step 4 should not actually matter.
add_task(async function exposure_append_underfilled() {
  for (let showExposureResults of [true, false]) {
    for (let cancelSecondQuery of [true, false]) {
      await do_exposure_append_underfilled({
        showExposureResults,
        cancelSecondQuery,
      });
    }
  }
});

async function do_exposure_append_underfilled({
  showExposureResults,
  cancelSecondQuery,
}) {
  info(
    "Starting do_exposure_append: " +
      JSON.stringify({ showExposureResults, cancelSecondQuery })
  );

  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.exposureResults", "search_suggest"],
      ["browser.urlbar.showExposureResults", showExposureResults],
    ],
  });

  // Make the provider return no results at first.
  gProvider.results = [];

  // Do the first query to open the view.
  info("Doing first query");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 1",
  });

  // Now make the provider return a search suggestion and a bookmark. If
  // `showExposureResults` is true, the suggestion should be added to the view
  // and be visible immediately. If it's false, it shouldn't be added at
  // all. The bookmark will always be added, which will tell us when the view
  // has been updated either way.
  let newSuggestion = "new suggestion";
  let bookmarkUrl = "https://example.com/bookmark";
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.SEARCH,
      UrlbarUtils.RESULT_SOURCE.SEARCH,
      {
        suggestion: newSuggestion,
        engine: Services.search.defaultEngine.name,
      }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      { url: bookmarkUrl }
    ),
  ];

  // When the provider's `startQuery()` is called, let it add its results but
  // don't let it return. That will cause the view to be updated with the new
  // results but let us test the specific case where the query doesn't finish
  // (so stale rows are not removed).
  let queryResolver = Promise.withResolvers();
  gProvider.finishQueryPromise = queryResolver.promise;

  // Observe when the view appends the bookmark row. This will tell us when the
  // view has been updated with the provider's new results.
  let lastRowPromise = promiseLastRowAppended(
    row => row.result.payload.url == bookmarkUrl
  );

  // Now start the second query but don't await it.
  info("Starting second query");
  let queryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 2",
    reopenOnBlur: false,
  });

  // Wait for the view to be updated.
  info("Waiting for last row");
  let lastRow = await lastRowPromise;
  info("Done waiting for last row");

  Assert.ok(
    BrowserTestUtils.isVisible(lastRow),
    "The new bookmark row should be visible since the view is not full"
  );

  // Check the new suggestion row.
  let rows = UrlbarTestUtils.getResultsContainer(window);
  let newSuggestionRow = [...rows.children].find(
    r => r.result.payload.suggestion == newSuggestion
  );
  if (showExposureResults) {
    Assert.ok(
      newSuggestionRow,
      "The new suggestion row should have been added"
    );
    Assert.ok(
      BrowserTestUtils.isVisible(newSuggestionRow),
      "The new suggestion row should be visible"
    );
  } else {
    Assert.ok(
      !newSuggestionRow,
      "The new suggestion row should not have been added"
    );
  }

  if (!cancelSecondQuery) {
    // Finish the query.
    queryResolver.resolve();
    await queryPromise;
  }

  // Close the view. Blur the urlbar to end the session.
  info("Closing view and blurring");
  await UrlbarTestUtils.promisePopupClose(window);
  gURLBar.blur();

  // If `showExposureResults` is true, the new search suggestion should have
  // been shown; if it's false, it would have been shown. Either way, it should
  // have triggered an exposure.
  assertExposureTelemetry([{ results: "search_suggest" }]);

  // Clean up.
  queryResolver.resolve();
  await queryPromise;
  await SpecialPowers.popPrefEnv();
  Services.fog.testResetFOG();
  gProvider.finishQueryPromise = null;
}

// Does the following:
//
// 1. Starts and finishes a query
// 2. Starts a second query with a result that can replace an existing row from
//    the previous query
// 3. Either cancels the second query (so stale rows are not removed) or waits
//    for it to finish (so stale rows are removed)
//
// The result in the second query should trigger an exposure since it's made
// visible in step 2. Step 3 should not actually matter.
add_task(async function exposure_replace() {
  for (let showExposureResults of [true, false]) {
    for (let cancelSecondQuery of [true, false]) {
      await do_exposure_replace({ showExposureResults, cancelSecondQuery });
    }
  }
});

async function do_exposure_replace({ showExposureResults, cancelSecondQuery }) {
  info(
    "Starting do_exposure_replace: " +
      JSON.stringify({ showExposureResults, cancelSecondQuery })
  );

  // Make the provider return a search suggestion.
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.SEARCH,
      UrlbarUtils.RESULT_SOURCE.SEARCH,
      {
        suggestion: "suggestion",
        engine: Services.search.defaultEngine.name,
      }
    ),
  ];

  // Do the first query to show the suggestion.
  info("Doing first query");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 1",
  });

  // Set exposure results to search suggestions and hide them. We can't do this
  // before now because that would hide the search suggestions in the first
  // query, and here we're specifically testing the case where a new row
  // replaces an old row, which is only allowed for rows of the same type.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.exposureResults", "search_suggest"],
      ["browser.urlbar.showExposureResults", showExposureResults],
    ],
  });

  // Now make the provider return another search suggestion and a bookmark. If
  // `showExposureResults` is true, the new suggestion should replace the old
  // one in the view and be visible immediately. If it's false, it shouldn't be
  // added at all. The bookmark will always be added, which will tell us when
  // the view has been updated either way.
  let newSuggestion = "new suggestion";
  let bookmarkUrl = "https://example.com/bookmark";
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.SEARCH,
      UrlbarUtils.RESULT_SOURCE.SEARCH,
      {
        suggestion: newSuggestion,
        engine: Services.search.defaultEngine.name,
      }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      { url: bookmarkUrl }
    ),
  ];

  // When the provider's `startQuery()` is called, let it add its results but
  // don't let it return. That will cause the view to be updated with the new
  // results but let us test the specific case where the query doesn't finish
  // (so stale rows are not removed).
  let queryResolver = Promise.withResolvers();
  gProvider.finishQueryPromise = queryResolver.promise;

  // Observe when the view appends the bookmark row. This will tell us when the
  // view has been updated with the provider's new results.
  let lastRowPromise = promiseLastRowAppended(
    row => row.result.payload.url == bookmarkUrl
  );

  // Now start the second query but don't await it.
  info("Starting second query");
  let queryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 2",
    reopenOnBlur: false,
  });

  // Wait for the view to be updated.
  info("Waiting for last row");
  let lastRow = await lastRowPromise;
  info("Done waiting for last row");

  Assert.ok(
    BrowserTestUtils.isVisible(lastRow),
    "The new bookmark row should be visible since the view is not full"
  );

  // Check the new suggestion row.
  let rows = UrlbarTestUtils.getResultsContainer(window);
  let newSuggestionRow = [...rows.children].find(
    r => r.result.payload.suggestion == newSuggestion
  );
  if (showExposureResults) {
    Assert.ok(
      newSuggestionRow,
      "The new suggestion row should have replaced the old one"
    );
    Assert.ok(
      BrowserTestUtils.isVisible(newSuggestionRow),
      "The new suggestion row should be visible"
    );
  } else {
    Assert.ok(
      !newSuggestionRow,
      "The new suggestion row should not have been added"
    );
  }

  if (!cancelSecondQuery) {
    // Finish the query.
    queryResolver.resolve();
    await queryPromise;
  }

  // Close the view. Blur the urlbar to end the session.
  info("Closing view and blurring");
  await UrlbarTestUtils.promisePopupClose(window);
  gURLBar.blur();

  // If `showExposureResults` is true, the new search suggestion should have
  // been shown; if it's false, it would have been shown. Either way, it should
  // have triggered an exposure.
  assertExposureTelemetry([{ results: "search_suggest" }]);

  // Clean up.
  queryResolver.resolve();
  await queryPromise;
  await SpecialPowers.popPrefEnv();
  Services.fog.testResetFOG();
  gProvider.finishQueryPromise = null;
}

// Does the following:
//
// 1. Starts and finishes a query that fills up the view
// 2. Starts a second query with a result that cannot replace any rows from the
//    first query and that therefore must be appended and hidden
// 3. Finishes the second query
//
// The result in the second query should trigger an exposure since it's made
// visible in step 3.
add_task(async function exposure_append_full() {
  for (let showExposureResults of [true, false]) {
    await do_exposure_append_full(showExposureResults);
  }
});

async function do_exposure_append_full(showExposureResults) {
  info(
    "Starting do_exposure_append_full: " +
      JSON.stringify({ showExposureResults })
  );

  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.exposureResults", "history"],
      ["browser.urlbar.showExposureResults", showExposureResults],
    ],
  });

  // Make the provider return enough search suggestions to fill the view.
  gProvider.results = [];
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    gProvider.results.push(
      new UrlbarResult(
        UrlbarUtils.RESULT_TYPE.SEARCH,
        UrlbarUtils.RESULT_SOURCE.SEARCH,
        {
          suggestion: "suggestion " + i,
          engine: Services.search.defaultEngine.name,
        }
      )
    );
  }

  // Do the first query to fill the view with search suggestions.
  info("Doing first query");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 1",
  });

  // Now make the provider return a history result and bookmark. If
  // `showExposureResults` is true, the history result will be added to the view
  // but it should be hidden since the view is already full. If it's false, it
  // shouldn't be added at all. The bookmark will always be added, which will
  // tell us when the view has been updated either way. (It also will be hidden
  // since the view is already full.)
  let historyUrl = "https://example.com/history";
  let bookmarkUrl = "https://example.com/bookmark";
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.HISTORY,
      { url: historyUrl }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      { url: bookmarkUrl }
    ),
  ];

  // When the provider's `startQuery()` is called, let it add its results but
  // don't let it return. That will cause the view to be updated with the new
  // results but prevent it from showing hidden rows since the query won't
  // finish (so stale rows won't be removed).
  let queryResolver = Promise.withResolvers();
  gProvider.finishQueryPromise = queryResolver.promise;

  // Observe when the view appends the bookmark row. This will tell us when the
  // view has been updated with the provider's new results. The bookmark row
  // will be hidden since the view is already full with search suggestions.
  let lastRowPromise = promiseLastRowAppended(
    row => row.result.payload.url == bookmarkUrl
  );

  // Now start the second query but don't await it.
  info("Starting second query");
  let queryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 2",
    reopenOnBlur: false,
  });

  // Wait for the view to be updated.
  info("Waiting for last row");
  let lastRow = await lastRowPromise;
  info("Done waiting for last row");

  Assert.ok(
    BrowserTestUtils.isHidden(lastRow),
    "The new bookmark row should be hidden since the view is full"
  );

  // Make sure the view is full of visible rows as expected, plus the one or two
  // hidden rows for the history and bookmark results.
  let expected = [
    {
      source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: bookmarkUrl,
    },
  ];
  if (showExposureResults) {
    expected.unshift({
      source: UrlbarUtils.RESULT_SOURCE.HISTORY,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: historyUrl,
    });
  }
  let rows = UrlbarTestUtils.getResultsContainer(window);
  Assert.equal(
    rows.children.length,
    MAX_RESULT_COUNT + expected.length,
    "The view has the expected number of rows"
  );

  // Check the visible rows.
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    let row = rows.children[i];
    Assert.ok(BrowserTestUtils.isVisible(row), `rows[${i}] should be visible`);
    Assert.ok(
      row.result.type == UrlbarUtils.RESULT_TYPE.SEARCH,
      `rows[${i}].result.type should be SEARCH`
    );
    // The heuristic won't have a suggestion so skip it.
    if (i > 0) {
      Assert.ok(
        row.result.payload.suggestion,
        `rows[${i}] should have a suggestion`
      );
    }
  }

  // Check the hidden history and bookmark rows.
  for (let i = 0; i < expected.length; i++) {
    let { source, type, url } = expected[i];
    let row = rows.children[MAX_RESULT_COUNT + i];
    Assert.ok(row, `rows[${i}] should exist`);
    Assert.ok(BrowserTestUtils.isHidden(row), `rows[${i}] should be hidden`);
    Assert.equal(
      row.result.type,
      type,
      `rows[${i}].result.type should be as expected`
    );
    Assert.equal(
      row.result.source,
      source,
      `rows[${i}].result.source should be as expected`
    );
    Assert.equal(
      row.result.payload.url,
      url,
      `rows[${i}] URL should be as expected`
    );
  }

  // Now let the query finish (so stale rows are removed).
  queryResolver.resolve();
  info("Waiting for second query to finish");
  await queryPromise;
  info("Second query finished");

  rows = UrlbarTestUtils.getResultsContainer(window);
  Assert.equal(
    rows.children.length,
    // + 1 for the heurustic.
    1 + expected.length,
    "The view has the expected number of rows"
  );

  // Check the visible rows (except the heuristic).
  for (let i = 0; i < expected.length; i++) {
    let { source, type, url } = expected[i];
    let index = i + 1;
    let row = rows.children[index];
    Assert.ok(row, `rows[${index}] should exist`);
    Assert.ok(
      BrowserTestUtils.isVisible(row),
      `rows[${index}] should be visible`
    );
    Assert.equal(
      row.result.type,
      type,
      `rows[${index}].result.type should be as expected`
    );
    Assert.equal(
      row.result.source,
      source,
      `rows[${index}].result.source should be as expected`
    );
    Assert.equal(
      row.result.payload.url,
      url,
      `rows[${index}] URL should be as expected`
    );
  }

  // Close the view. Blur the urlbar to end the session.
  info("Closing view and blurring");
  await UrlbarTestUtils.promisePopupClose(window);
  gURLBar.blur();

  // An exposure for the history result should have been recorded.
  assertExposureTelemetry([{ results: "history" }]);

  // Clean up.
  await SpecialPowers.popPrefEnv();
  Services.fog.testResetFOG();
  gProvider.finishQueryPromise = null;
}

// Does the following:
//
// 1. Starts and finishes a query that fills up the view
// 2. Starts a second query with results that cannot replace rows from the first
//    query and that therefore must be appended and hidden
// 3. Before the second query finishes (i.e., before stale rows are removed),
//    starts and finishes a third query (after which stale rows are removed)
//
// Results in the third query should trigger an exposure since they become
// visible when the query finishes (and stale rows are removed) in step 3.
// Results in the second query should not trigger an exposure since they could
// never be visible since the query is canceled before stale rows are removed.
add_task(async function exposure_append_full_twice() {
  for (let showExposureResults of [true, false]) {
    await do_exposure_append_full_twice(showExposureResults);
  }
});

async function do_exposure_append_full_twice(showExposureResults) {
  info(
    "Starting do_exposure_append_full_twice: " +
      JSON.stringify({ showExposureResults })
  );

  // Exposure results are history and tab.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["browser.urlbar.exposureResults", "history,tab"],
      ["browser.urlbar.showExposureResults", showExposureResults],
    ],
  });

  // Make the provider return enough search suggestions to fill the view.
  gProvider.results = [];
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    gProvider.results.push(
      new UrlbarResult(
        UrlbarUtils.RESULT_TYPE.SEARCH,
        UrlbarUtils.RESULT_SOURCE.SEARCH,
        {
          suggestion: "suggestion " + i,
          engine: Services.search.defaultEngine.name,
        }
      )
    );
  }

  // Do the first query to fill the view with search suggestions.
  info("Doing first query");
  await UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 1",
  });

  // Now make the provider return a history result, tab, and bookmark. If
  // `showExposureResults` is true, the history and tab results will be added to
  // the view but they should be hidden since the view is already full. If it's
  // false, they shouldn't be added at all. The bookmark will always be added,
  // which will tell us when the view has been updated either way. (It also will
  // be hidden since the view is already full.)
  let historyUrl = "https://example.com/history";
  let tabUrl = "https://example.com/tab";
  let bookmarkUrl = "https://example.com/bookmark";
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.HISTORY,
      { url: historyUrl }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
      UrlbarUtils.RESULT_SOURCE.TABS,
      { url: tabUrl }
    ),
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      { url: bookmarkUrl }
    ),
  ];

  // When the provider's `startQuery()` is called, let it add its results but
  // don't let it return. That will cause the view to be updated with the new
  // results but prevent it from showing hidden rows since the query won't
  // finish (so stale rows won't be removed).
  let secondQueryResolver = Promise.withResolvers();
  gProvider.finishQueryPromise = secondQueryResolver.promise;

  // Observe when the view appends the bookmark row. This will tell us when the
  // view has been updated with the provider's new results. The bookmark row
  // will be hidden since the view is already full with search suggestions.
  let lastRowPromise = promiseLastRowAppended(
    row => row.result.payload.url == bookmarkUrl
  );

  // Now start the second query but don't await it.
  info("Starting second query");
  let secondQueryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 2",
    reopenOnBlur: false,
  });

  // Wait for the view to be updated.
  info("Waiting for last row");
  let lastRow = await lastRowPromise;
  info("Done waiting for last row");

  Assert.ok(
    BrowserTestUtils.isHidden(lastRow),
    "The new bookmark row should be hidden since the view is full"
  );

  // Make sure the view is full of visible rows as expected, plus the one or
  // three hidden rows for the history, tab, and bookmark results.
  let expected = [
    {
      source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: bookmarkUrl,
    },
  ];
  if (showExposureResults) {
    expected.unshift(
      {
        source: UrlbarUtils.RESULT_SOURCE.HISTORY,
        type: UrlbarUtils.RESULT_TYPE.URL,
        url: historyUrl,
      },
      {
        source: UrlbarUtils.RESULT_SOURCE.TABS,
        type: UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
        url: tabUrl,
      }
    );
  }
  let rows = UrlbarTestUtils.getResultsContainer(window);
  Assert.equal(
    rows.children.length,
    MAX_RESULT_COUNT + expected.length,
    "The view has the expected number of rows"
  );

  // Check the visible rows.
  for (let i = 0; i < MAX_RESULT_COUNT; i++) {
    let row = rows.children[i];
    Assert.ok(BrowserTestUtils.isVisible(row), `rows[${i}] should be visible`);
    Assert.ok(
      row.result.type == UrlbarUtils.RESULT_TYPE.SEARCH,
      `rows[${i}].result.type should be SEARCH`
    );
    // The heuristic won't have a suggestion so skip it.
    if (i > 0) {
      Assert.ok(
        row.result.payload.suggestion,
        `rows[${i}] should have a suggestion`
      );
    }
  }

  // Check the hidden history, tab, and bookmark rows.
  for (let i = 0; i < expected.length; i++) {
    let { source, type, url } = expected[i];
    let row = rows.children[MAX_RESULT_COUNT + i];
    Assert.ok(row, `rows[${i}] should exist`);
    Assert.ok(BrowserTestUtils.isHidden(row), `rows[${i}] should be hidden`);
    Assert.equal(
      row.result.type,
      type,
      `rows[${i}].result.type should be as expected`
    );
    Assert.equal(
      row.result.source,
      source,
      `rows[${i}].result.source should be as expected`
    );
    Assert.equal(
      row.result.payload.url,
      url,
      `rows[${i}] URL should be as expected`
    );
  }

  // Now make the provider return only a history result.
  gProvider.results = [
    new UrlbarResult(
      UrlbarUtils.RESULT_TYPE.URL,
      UrlbarUtils.RESULT_SOURCE.HISTORY,
      { url: historyUrl }
    ),
  ];

  // Without waiting for the second query to finish (i.e., before stale rows are
  // removed), do a third query and allow it to finish (so stale rows are
  // removed). An exposure should be recorded for the history result since it's
  // present in the third query. An exposure should not be recorded for the tab
  // result because it could not have been visible since the second query did
  // not finish.

  let thirdQueryStartedPromise = new Promise(resolve => {
    let queryListener = {
      onQueryStarted: () => {
        gURLBar.controller.removeQueryListener(queryListener);
        resolve();
      },
    };
    gURLBar.controller.addQueryListener(queryListener);
  });

  info("Starting third query");
  let thirdQueryPromise = UrlbarTestUtils.promiseAutocompleteResultPopup({
    window,
    value: "test 3",
    reopenOnBlur: false,
  });

  // The test provider's `startQuery()` is still awaiting its
  // `finishQueryPromise`, so we need to resolve it so the provider can respond
  // to the third query. But before we do that, we need to make sure the third
  // query has started and canceled the second query because otherwise the
  // second query could finish and cause stale rows to be removed.
  info("Waiting for third query to start");
  await thirdQueryStartedPromise;
  info("Resolving provider's finishQueryPromise");
  secondQueryResolver.resolve();

  // Now wait for the third query to finish.
  info("Waiting for third query to finish");
  await thirdQueryPromise;

  expected = [];
  if (showExposureResults) {
    expected.unshift({
      source: UrlbarUtils.RESULT_SOURCE.HISTORY,
      type: UrlbarUtils.RESULT_TYPE.URL,
      url: historyUrl,
    });
  }

  rows = UrlbarTestUtils.getResultsContainer(window);
  Assert.equal(
    rows.children.length,
    // + 1 for the heurustic.
    1 + expected.length,
    "The view has the expected number of rows"
  );

  // Check the history row.
  for (let i = 0; i < expected.length; i++) {
    let { source, type, url } = expected[i];
    let index = i + 1;
    let row = rows.children[index];
    Assert.ok(row, `rows[${index}] should exist`);
    Assert.ok(
      BrowserTestUtils.isVisible(row),
      `rows[${index}] should be visible`
    );
    Assert.equal(
      row.result.type,
      type,
      `rows[${index}].result.type should be as expected`
    );
    Assert.equal(
      row.result.source,
      source,
      `rows[${index}].result.source should be as expected`
    );
    Assert.equal(
      row.result.payload.url,
      url,
      `rows[${index}] URL should be as expected`
    );
  }

  // Close the view. Blur the urlbar to end the session.
  info("Closing view and blurring");
  await UrlbarTestUtils.promisePopupClose(window);
  gURLBar.blur();

  // An exposure only for the history result should have been recorded. If an
  // exposure was also incorrectly recorded for the tab result, this will fail
  // with "history,tab" instead of only "history".
  assertExposureTelemetry([{ results: "history" }]);

  // Clean up.
  await secondQueryPromise;
  await SpecialPowers.popPrefEnv();
  Services.fog.testResetFOG();
  gProvider.finishQueryPromise = null;
}

/**
 * A test provider that doesn't finish startQuery() until `finishQueryPromise`
 * is resolved.
 */
class TestProvider extends UrlbarTestUtils.TestProvider {
  finishQueryPromise = null;

  async startQuery(context, addCallback) {
    for (let result of this.results) {
      addCallback(this, result);
    }
    await this.finishQueryPromise;
  }
}

function promiseLastRowAppended(predicate) {
  return new Promise(resolve => {
    let rows = UrlbarTestUtils.getResultsContainer(window);
    let observer = new MutationObserver(() => {
      let lastRow = rows.children[rows.children.length - 1];
      info(
        "Observed mutation, lastRow.result is: " +
          JSON.stringify(lastRow.result)
      );
      if (predicate(lastRow)) {
        observer.disconnect();
        resolve(lastRow);
      }
    });
    observer.observe(rows, { childList: true });
  });
}