summaryrefslogtreecommitdiffstats
path: root/browser/components/firefoxview/tests/browser/browser_tab_pickup_device_added_telemetry.js
blob: ce770900777ca8720f977625f7853fd859288a9d (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

registerCleanupFunction(async function () {
  await clearAllParentTelemetryEvents();
  cleanup_tab_pickup();
});

function setupWithFxaDevices() {
  const sandbox = (gSandbox = setupSyncFxAMocks({
    state: UIState.STATUS_SIGNED_IN,
    fxaDevices: [
      {
        id: 1,
        name: "My desktop",
        isCurrentDevice: true,
        type: "desktop",
      },
      {
        id: 2,
        name: "Other device",
        isCurrentDevice: false,
        type: "mobile",
      },
    ],
  }));
  return sandbox;
}

const mockDesktopTab1 = {
  client: "6c12bonqXZh8",
  device: "My desktop",
  deviceType: "desktop",
  type: "tab",
  title: "Example2",
  url: "https://example.com",
  icon: "https://example/favicon.png",
  lastUsed: Math.floor((Date.now() - 1000 * 60) / 1000), // This is one minute from now, which is below the threshold for 'Just now'
};

const mockDesktopTab2 = {
  client: "6c12bonqXZh8",
  device: "My desktop",
  deviceType: "desktop",
  type: "tab",
  title: "Sandboxes - Sinon.JS",
  url: "https://sinonjs.org/releases/latest/sandbox/",
  icon: "https://sinonjs.org/assets/images/favicon.png",
  lastUsed: 1655391592, // Thu Jun 16 2022 14:59:52 GMT+0000
};

const mockMobileTab1 = {
  client: "9d0y686hBXel",
  device: "My phone",
  deviceType: "mobile",
  type: "tab",
  title: "Element",
  url: "https://chat.mozilla.org/#room:mozilla.org",
  icon: "https://chat.mozilla.org/vector-icons/favicon.ico",
  lastUsed: 1664571288,
};

const NO_TABS_EVENTS = [
  ["firefoxview", "entered", "firefoxview", undefined],
  ["firefoxview", "synced_tabs", "tabs", undefined, { count: "0" }],
];
const SINGLE_TAB_EVENTS = [
  ["firefoxview", "entered", "firefoxview", undefined],
  ["firefoxview", "synced_tabs", "tabs", undefined, { count: "1" }],
];
const DEVICE_ADDED_NO_TABS_EVENTS = [
  ["firefoxview", "synced_tabs", "tabs", undefined, undefined],
  ["firefoxview", "synced_tabs_empty", "since_device_added", undefined],
];
const DEVICE_ADDED_TABS_EVENTS = [
  ["firefoxview", "synced_tabs", "tabs", undefined, undefined],
];

async function whenResolved(functionSpy, functionLabel) {
  info(`Waiting for ${functionLabel} to be called`);
  await TestUtils.waitForCondition(
    () => functionSpy.called,
    `Waiting for ${functionLabel} to be called`
  );
  is(
    functionSpy.getCall(0).returnValue.constructor.name,
    "Promise",
    `${functionLabel} returned a promise`
  );
  info(`Waiting for the promise returned by ${functionLabel} to be resolved`);
  await functionSpy.getCall(0).returnValue;
  info(`${functionLabel} promise resolved`);
}

async function test_device_added({
  initialRecentTabsResult,
  expectedInitialTelementryEvents,
  expectedDeviceAddedTelementryEvents,
}) {
  const recentTabsResult = initialRecentTabsResult;
  await clearAllParentTelemetryEvents();
  const sandbox = setupWithFxaDevices();
  const syncedTabsMock = sandbox.stub(SyncedTabs, "getRecentTabs");

  syncedTabsMock.callsFake(() => {
    info(
      `Stubbed SyncedTabs.getRecentTabs returning a promise that resolves to ${recentTabsResult.length} tabs\n`
    );
    return Promise.resolve(recentTabsResult);
  });

  ok(
    !isFirefoxViewTabSelected(),
    "Before we call withFirefoxView, about:firefoxview tab is not selected"
  );
  ok(
    !TabsSetupFlowManager.hasVisibleViews,
    "Initially hasVisibleViews is false"
  );

  await withFirefoxView({}, async browser => {
    info("inside withFirefoxView taskFn, waiting for setupListState");
    const { document } = browser.contentWindow;
    const stopWaitingSpy = sandbox.spy(
      TabsSetupFlowManager,
      "stopWaitingForTabs"
    );
    const signedInChangeSpy = sandbox.spy(
      TabsSetupFlowManager,
      "onSignedInChange"
    );

    await setupListState(browser);
    info("setupListState finished");

    // ensure any tab syncs triggered by Fxa sign-in are complete before proceeding
    await whenResolved(signedInChangeSpy, "onSignedInChange");
    if (!recentTabsResult.length) {
      info("No synced tabs so we wait for the result of the sync we trigger");
      await whenResolved(stopWaitingSpy, "stopWaitingForTabs");
      info("stopWaitingForTabs finished");
    }

    const isTablistVisible = !!initialRecentTabsResult.length;
    testVisibility(browser, {
      expectedVisible: {
        "ol.synced-tabs-list": isTablistVisible,
        "#synced-tabs-placeholder": !isTablistVisible,
      },
    });
    const syncedTabsItems = document.querySelectorAll(
      "ol.synced-tabs-list > li:not(.synced-tab-li-placeholder)"
    );
    info(
      "list items: " +
        Array.from(syncedTabsItems)
          .map(li => `li.${li.className}`)
          .join(", ")
    );
    is(
      syncedTabsItems.length,
      initialRecentTabsResult.length,
      `synced-tabs-list should have initial count of ${initialRecentTabsResult.length} non-placeholder list items`
    );

    // confirm telemetry is in expected state?
    info(
      "Checking telemetry against expectedInitialTelementryEvents: " +
        JSON.stringify(expectedInitialTelementryEvents, null, 2)
    );
    TelemetryTestUtils.assertEvents(
      expectedInitialTelementryEvents,
      { category: "firefoxview" },
      { clear: true, process: "parent" }
    );

    // add a new mock device
    info("Adding a new mock fxa dedvice");
    gMockFxaDevices.push({
      id: 1,
      name: "My primary phone",
      isCurrentDevice: false,
      type: "mobile",
    });

    const startWaitingSpy = sandbox.spy(
      TabsSetupFlowManager,
      "startWaitingForNewDeviceTabs"
    );
    // Notify of the newly added device
    info("Notifying devicelist_updated with the new mobile device");
    Services.obs.notifyObservers(null, "fxaccounts:devicelist_updated");

    // Some time passes here waiting for sync to get data from that device
    // we expect new-device handling to kick in. If there are 0 tabs we'll signal we're waiting,
    // create a timestamp and only clear it when there are > 0 tabs.
    // If there are already > 0 tabs, we'll basically do nothing, showing any new tabs when they arrive
    await whenResolved(startWaitingSpy, "startWaitingForNewDeviceTabs");

    info(
      "Initial tabs count: " +
        recentTabsResult.length +
        ", assert on _noTabsVisibleFromAddedDeviceTimestamp: " +
        TabsSetupFlowManager._noTabsVisibleFromAddedDeviceTimestamp
    );
    if (recentTabsResult.length) {
      ok(
        !TabsSetupFlowManager._noTabsVisibleFromAddedDeviceTimestamp,
        "Should not be waiting if there were > 0 tabs initially"
      );
    } else {
      ok(
        TabsSetupFlowManager._noTabsVisibleFromAddedDeviceTimestamp,
        "Should be waiting if there were 0 tabs initially"
      );
    }

    // Add tab data from this new device and notify of the changed data
    recentTabsResult.push(mockMobileTab1);
    stopWaitingSpy.resetHistory();

    info("Notifying tabs.changed with the new mobile device's tabs");
    Services.obs.notifyObservers(null, "services.sync.tabs.changed");

    // handling the tab.change and clearing the timestamp is necessarily async
    // as counting synced tabs via getRecentTabs() is async.
    // There may not be any outcome depending on the tab state, so we just wait
    // for stopWaitingForTabs to get called and its promise to resolve
    info("Waiting for the stopWaitingSpy to be called");
    await whenResolved(stopWaitingSpy, "stopWaitingForTabs");
    await TestUtils.waitForTick(); // allow time for the telemetry event to get recorded

    info(
      "We've added a synced tab and updated the tab list, got snapshotEvents:" +
        JSON.stringify(
          Services.telemetry.snapshotEvents(
            Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS,
            false
          ),
          null,
          2
        )
    );
    // confirm no telemetry was recorded for tabs from the newly-added device
    // as the tab list was never empty
    info(
      "Checking telemetry against expectedDeviceAddedTelementryEvents: " +
        JSON.stringify(expectedDeviceAddedTelementryEvents, null, 2)
    );
    TelemetryTestUtils.assertEvents(
      expectedDeviceAddedTelementryEvents,
      { category: "firefoxview" },
      { clear: true, process: "parent" }
    );
  });
  sandbox.restore();
  cleanup_tab_pickup();
}

add_task(async function test_device_added_with_existing_tabs() {
  /* Confirm that no telemetry is recorded when a new device is added while the synced tabs list has tabs */
  await test_device_added({
    initialRecentTabsResult: [mockDesktopTab1],
    expectedInitialTelementryEvents: SINGLE_TAB_EVENTS,
    expectedDeviceAddedTelementryEvents: DEVICE_ADDED_TABS_EVENTS,
  });
});

add_task(async function test_device_added_with_empty_list() {
  /* Confirm that telemetry is recorded when a device is added and the synced tabs list
     is empty until its tabs get synced
  */
  await test_device_added({
    initialRecentTabsResult: [],
    expectedInitialTelementryEvents: NO_TABS_EVENTS,
    expectedDeviceAddedTelementryEvents: DEVICE_ADDED_NO_TABS_EVENTS,
  });
});