• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / vscode-brightscript-language / 30128190245

24 Jul 2026 09:34PM UTC coverage: 60.923% (+1.0%) from 59.908%
30128190245

Pull #862

github

web-flow
Merge ce624f8ea into e465804e3
Pull Request #862: Device discovery simplification

2714 of 4855 branches covered (55.9%)

Branch coverage included in aggregate %.

296 of 325 new or added lines in 7 files covered. (91.08%)

11 existing lines in 3 files now uncovered.

4163 of 6433 relevant lines covered (64.71%)

47.42 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

56.64
/src/managers/UserInputManager.ts
1
import { Deferred } from 'brighterscript';
1✔
2
import type { DeviceInfoRaw } from 'roku-deploy';
3
import type {
4
    Disposable,
5
    QuickPickItem
6
} from 'vscode';
7
import * as vscode from 'vscode';
1✔
8
import type { ConfiguredDevice, DeviceManager, HostWithDeviceInfo, RokuDevice } from '../deviceDiscovery/DeviceManager';
9
import type { CredentialStore } from './CredentialStore';
10
import { icons } from '../icons';
1✔
11
import { vscodeContextManager } from './VscodeContextManager';
1✔
12
import { util } from '../util';
1✔
13
import {
1✔
14
    DEFAULT_DEVICE_FILTERS,
15
    DEVICE_FILTER_GROUPS,
16
    DEVICE_FILTER_KEYS,
17
    DEVICE_FILTER_LABELS,
18
    applyDeviceFilters,
19
    loadDeviceFilters,
20
    type DeviceFilters
21
} from '../deviceFilters';
22

23
const DEVICE_QUICK_PICK_FILTERS_SECTION = 'brightscript.deviceQuickPick.filters';
1✔
24

25
/**
26
 * An id to represent the "Enter manually" option in the host picker
27
 */
28
export const manualHostItemId = `${Number.MAX_SAFE_INTEGER}`;
1✔
29
const manualLabel = 'Enter manually';
1✔
30
/**
31
 * An id to represent the "Scan for devices" option in the host picker
32
 */
33
export const scanForDevicesItemId = `${Number.MAX_SAFE_INTEGER - 1}`;
1✔
34
const scanForDevicesLabel = 'Scan for devices';
1✔
35

36
/**
37
 * The outcome of resolving a developer password for a device.
38
 */
39
export type DevicePasswordResolution =
40
    | { status: 'ok'; password: string }
41
    | { status: 'unreachable' }
42
    | { status: 'cancelled' };
43

44
export class UserInputManager {
1✔
45

46
    public constructor(
47
        private deviceManager: DeviceManager,
100✔
48
        private credentialStore: CredentialStore
100✔
49
    ) { }
50

51
    public async promptForHostManual(): Promise<HostWithDeviceInfo | undefined> {
52
        while (true) {
2✔
53
            const value = await vscode.window.showInputBox({
2✔
54
                placeHolder: 'Please enter the IP address of your Roku device',
55
                value: ''
56
            });
57
            if (!value) {
2✔
58
                return undefined;
1✔
59
            }
60
            const probed = await vscode.window.withProgress(
1✔
61
                { location: vscode.ProgressLocation.Notification, title: `Contacting ${value}...` },
62
                async () => {
63
                    return this.deviceManager.validateAndAddDevice(value);
1✔
64
                }
65
            );
66
            if (probed) {
1!
67
                //probing gathers the device info the same way as the picker; return it alongside the host
68
                return { host: probed.ip, deviceInfo: probed.deviceInfo };
1✔
69
            }
70
            await vscode.window.showErrorMessage(`Unable to connect to a Roku at ${value}. Check the IP and confirm developer mode is enabled.`);
×
71
        }
72
    }
73

74
    /**
75
     * Resolve a developer password that the device at `host` accepts.
76
     *
77
     * Every known candidate is tried in order (stored credential, configured
78
     * `brightscript.devices[].password`, the default device password, and any caller-provided
79
     * `extraCandidates`), each validated against the device. The first accepted candidate wins.
80
     * If none are accepted, the user is prompted, re-prompting after each rejection until they
81
     * enter a working password or cancel. An accepted password refreshes the credential store
82
     * entry when one already exists; callers that keep a global password fallback persist that
83
     * themselves.
84
     *
85
     * @returns `ok` with the accepted password, `unreachable` when the device can't be contacted,
86
     *          or `cancelled` when the user dismisses the prompt.
87
     */
88
    public async resolveDevicePassword(options: { host: string; serialNumber: string | undefined; extraCandidates?: Array<string | undefined> }): Promise<DevicePasswordResolution> {
89
        const { host, serialNumber } = options;
34✔
90
        const candidates = await this.collectDevicePasswordCandidates(serialNumber, options.extraCandidates);
34✔
91

92
        for (const candidate of candidates) {
34✔
93
            const validation = await this.deviceManager.validateDevicePassword(host, candidate);
37✔
94
            if (validation === 'ok') {
37✔
95
                await this.persistDevicePassword(serialNumber, candidate);
24✔
96
                return { status: 'ok', password: candidate };
24✔
97
            }
98
            if (validation === 'unreachable') {
13✔
99
                return { status: 'unreachable' };
2✔
100
            }
101
            // 'bad-password' — fall through to the next candidate
102
        }
103

104
        // No stored / configured candidate was accepted. Prompt, re-prompting after each
105
        // bad-password attempt until the user enters a working one or cancels (empty / Esc).
106
        let placeholder = candidates.length > 0
8✔
107
            ? 'The password was rejected by the device. Try again, or press Esc to cancel.'
108
            : 'The Roku development webserver password.';
109
        while (true) {
8✔
110
            const value = await this.promptForDevicePassword(placeholder);
11✔
111
            if (!value) {
11✔
112
                return { status: 'cancelled' };
3✔
113
            }
114
            const validation = await this.deviceManager.validateDevicePassword(host, value);
8✔
115
            if (validation === 'ok') {
8✔
116
                await this.persistDevicePassword(serialNumber, value);
5✔
117
                return { status: 'ok', password: value };
5✔
118
            }
119
            if (validation === 'unreachable') {
3!
120
                return { status: 'unreachable' };
×
121
            }
122
            placeholder = 'The password was rejected by the device. Try again, or press Esc to cancel.';
3✔
123
        }
124
    }
125

126
    /**
127
     * Build the ordered, de-duplicated list of candidate passwords to try when resolving
128
     * credentials for a device. Variable placeholders and empty values are filtered out so the
129
     * validation loop only sees real passwords. `extraCandidates` are appended after the
130
     * standard sources (e.g. launch-config values for a debug session).
131
     */
132
    private async collectDevicePasswordCandidates(serialNumber: string | undefined, extraCandidates?: Array<string | undefined>): Promise<string[]> {
133
        const candidates: string[] = [];
42✔
134
        const addCandidate = (value: string | undefined | null) => {
42✔
135
            const trimmed = value?.trim();
148✔
136
            // eslint-disable-next-line no-template-curly-in-string
137
            if (!trimmed || trimmed === '${promptForPassword}' || trimmed === '${activeHostPassword}') {
148✔
138
                return;
87✔
139
            }
140
            candidates.push(trimmed);
61✔
141
        };
142

143
        if (serialNumber) {
42✔
144
            addCandidate(await this.credentialStore.getPassword(serialNumber));
29✔
145

146
            const scanScope = (devices: ConfiguredDevice[] | undefined) => {
29✔
147
                for (const entry of devices ?? []) {
58✔
148
                    if (entry.serialNumber === serialNumber) {
1!
149
                        addCandidate(entry.password);
1✔
150
                    }
151
                }
152
            };
153
            const rootInspection = vscode.workspace.getConfiguration('brightscript').inspect<ConfiguredDevice[]>('devices');
29✔
154
            scanScope(rootInspection?.globalValue);
29!
155
            scanScope(rootInspection?.workspaceValue);
29!
156
            for (const folder of vscode.workspace.workspaceFolders ?? []) {
29!
157
                const folderInspection = vscode.workspace.getConfiguration('brightscript', folder.uri).inspect<ConfiguredDevice[]>('devices');
×
158
                scanScope(folderInspection?.workspaceFolderValue);
×
159
            }
160
        }
161

162
        addCandidate(this.deviceManager.getDefaultPassword());
42✔
163
        for (const extra of extraCandidates ?? []) {
42✔
164
            addCandidate(extra);
76✔
165
        }
166

167
        // Dedupe while preserving insertion order so a password referenced by multiple
168
        // sources is only validated once.
169
        return Array.from(new Set(candidates));
42✔
170
    }
171

172
    /**
173
     * Persist an accepted password by refreshing the credential store, but only when an entry
174
     * already exists for this serial (storing a brand-new entry is an explicit opt-in elsewhere).
175
     */
176
    private async persistDevicePassword(serialNumber: string | undefined, password: string): Promise<void> {
177
        if (serialNumber && (await this.credentialStore.getPassword(serialNumber)) !== undefined) {
29✔
178
            await this.credentialStore.setPassword(serialNumber, password);
4✔
179
        }
180
    }
181

182
    /**
183
     * Password input dialog. Returns the typed value, or undefined on Esc / hide.
184
     */
185
    private async promptForDevicePassword(placeholder: string): Promise<string | undefined> {
186
        const input = vscode.window.createInputBox();
×
187
        input.placeholder = placeholder;
×
188
        input.password = true;
×
189
        try {
×
190
            return await new Promise<string | undefined>(resolve => {
×
191
                input.onDidAccept(() => {
×
192
                    resolve(input.value);
×
193
                    input.hide();
×
194
                });
195
                input.onDidHide(() => {
×
196
                    resolve(undefined);
×
197
                });
198
                input.show();
×
199
            });
200
        } finally {
201
            input.dispose();
×
202
        }
203
    }
204

205
    /**
206
     * Prompt the user to pick a host from a list of devices
207
     */
208
    public async promptForHost(options?: { defaultValue?: string }): Promise<HostWithDeviceInfo | undefined> {
209

210
        const deferred = new Deferred<{ ip: string; deviceInfo: DeviceInfoRaw; manual?: false } | { manual: true }>();
6✔
211
        const disposables: Array<Disposable> = [];
6✔
212

213
        //create the quickpick item
214
        const quickPick = vscode.window.createQuickPick();
6✔
215
        disposables.push(quickPick);
6✔
216
        quickPick.placeholder = `Please Select a Roku or manually type an IP address`;
6✔
217
        quickPick.keepScrollPosition = true;
6✔
218

219
        // Track multiple busy sources (scan, health check) with a counter
220
        let busyCount = 0;
6✔
221
        const setBusy = (isBusy: boolean) => {
6✔
222
            busyCount += isBusy ? 1 : -1;
2✔
223
            busyCount = Math.max(0, busyCount); // Prevent negative
2✔
224
            quickPick.busy = busyCount > 0;
2✔
225
        };
226

227
        // Subscribe to scan events before triggering a broadcast so we catch the scan-started event
228
        this.deviceManager.on('scan-started', () => {
6✔
229
            setBusy(true);
×
230
        }, disposables);
231

232
        this.deviceManager.on('scan-ended', () => {
6✔
233
            setBusy(false);
×
234
        }, disposables);
235

236
        const scanTimeoutMs = 7_000;
6✔
237
        let scanTimeoutId: NodeJS.Timeout | null = null;
6✔
238

239
        // On open, fulfill a queued broadcast order (a `stale` order is left queued for the tree
240
        // view); when there's nothing to fulfill, do a normal staleness-gated broadcast so a
241
        // picker opened on a long-quiet session still gets fresh data. The picker never SUBMITS
242
        // reconcile orders of its own, but it does FULFILL queued/live ones (below) so work
243
        // ordered while no view was visible isn't left waiting.
244
        let hasScanned = this.deviceManager.fulfillPendingBroadcast({ except: ['stale'] });
6✔
245
        if (!hasScanned) {
6!
246
            hasScanned = this.deviceManager.broadcast();
6✔
247
        }
248

249
        // On open, also fulfill a queued reconcile order (`stale` stays queued)
250
        this.deviceManager.fulfillPendingReconcile({ except: ['stale'] });
6✔
251

252
        this.deviceManager.on('broadcast-ordered', (order) => {
6✔
NEW
253
            if (order.reason === 'stale') {
×
NEW
254
                return;
×
255
            }
256
            // Suppress the 7s fallback even if another visible consumer fulfills this order —
257
            // a scan is happening either way
258
            hasScanned = true;
×
259
            if (scanTimeoutId) {
×
260
                clearTimeout(scanTimeoutId);
×
261
                scanTimeoutId = null;
×
262
            }
NEW
263
            this.deviceManager.fulfillPendingBroadcast({ except: ['stale'] });
×
264
        }, disposables);
265

266
        this.deviceManager.on('reconcile-ordered', () => {
6✔
267
            this.deviceManager.fulfillPendingReconcile({ except: ['stale'] });
1✔
268
        }, disposables);
269

270
        scanTimeoutId = setTimeout(() => {
6✔
271
            if (hasScanned) {
6!
272
                return;
6✔
273
            }
NEW
274
            this.deviceManager.broadcast();
×
275
        }, scanTimeoutMs);
276

277
        function dispose() {
278
            for (const disposable of disposables) {
6✔
279
                disposable.dispose();
42✔
280
            }
281
        }
282

283
        //detect if the user types an IP address into the picker and presses enter.
284
        let selectedDevice: vscode.QuickPickItem | undefined;
285
        quickPick.onDidAccept(async () => {
6✔
286
            if (selectedDevice) {
2✔
287
                if (selectedDevice.kind !== vscode.QuickPickItemKind.Separator) {
1!
288
                    if (selectedDevice.label === manualLabel) {
1!
289
                        deferred.resolve({ manual: true });
1✔
290
                    } else if (selectedDevice.label === scanForDevicesLabel) {
×
291
                        //an explicit "scan" click is the refresh-clicked trigger — submit orders;
292
                        //this picker (or another visible view) fulfills them immediately
NEW
293
                        this.deviceManager.submitBroadcast('refresh-clicked');
×
NEW
294
                        this.deviceManager.submitReconcile('refresh-clicked');
×
UNCOV
295
                        return;
×
296
                    } else {
297
                        const device = (selectedDevice as any).device as RokuDevice;
×
298
                        // if the selected device isn't healthy, show an error and keep the picker open so they can select a different device
299
                        setBusy(true);
×
300
                        const isHealthy = await this.deviceManager.healthCheckDevice(device, true, false);
×
301
                        setBusy(false);
×
302
                        if (!isHealthy) {
×
303
                            await vscode.window.showErrorMessage(`The selected device (${device.ip}) is not responding.`);
×
304
                            return;
×
305
                        }
306
                        this.deviceManager.setLastUsedDeviceIp(device.ip);
×
307
                        deferred.resolve({ ip: device.ip, deviceInfo: device.deviceInfo });
×
308
                    }
309
                    quickPick.dispose();
1✔
310
                }
311
                selectedDevice = undefined;
1✔
312
                // If the user has typed a value, probe the IP before resolving so
313
                // the caller only ever receives a reachable device.
314
            } else if (quickPick.value) {
1!
315
                const typedValue = quickPick.value;
1✔
316
                setBusy(true);
1✔
317
                const probed = await this.deviceManager.validateAndAddDevice(typedValue);
1✔
318
                setBusy(false);
1✔
319
                if (!probed) {
1!
320
                    await vscode.window.showErrorMessage(`Unable to connect to a Roku at ${typedValue}. Check the IP and confirm developer mode is enabled.`);
×
321
                    return;
×
322
                }
323
                this.deviceManager.setLastUsedDeviceIp(probed.ip);
1✔
324
                deferred.resolve({ ip: probed.ip, deviceInfo: probed.deviceInfo });
1✔
325
                quickPick.dispose();
1✔
326
            }
327
        });
328

329
        quickPick.onDidChangeSelection((selection) => {
6✔
330
            // only save the selectedDevice if the user explicitly clicks on an item
331
            // use the selected device in onDidAccept
332
            selectedDevice = selection[0];
1✔
333
        });
334

335
        let activeChangesSinceRefresh = 0;
6✔
336
        let activeItem: QuickPickItem;
337

338
        // remember the currently active item so we can maintain active selection when refreshing the list
339
        quickPick.onDidChangeActive((items) => {
6✔
340
            // reset our activeChanges tracker since users cannot cause items.length to be 0 (meaning a refresh has just happened)
341
            if (items.length === 0) {
×
342
                activeChangesSinceRefresh = 0;
×
343
                return;
×
344
            }
345
            if (activeChangesSinceRefresh > 0) {
×
346
                activeItem = items[0];
×
347
            }
348
            activeChangesSinceRefresh++;
×
349
        });
350

351
        const itemCache = new Map<string, QuickPickHostItem>();
6✔
352
        if (options?.defaultValue) {
6!
353
            quickPick.value = options?.defaultValue;
×
354
        }
355
        quickPick.show();
6✔
356

357
        //set a timeout to automatically start scanning for devices after a short delay
358
        const SCAN_FOR_DEVICES = 'Scan for Devices';
6✔
359
        const CLEAR_DEVICE_LIST = 'Clear Device List';
6✔
360
        const ENABLE_DEVICE_DISCOVERY = 'Enable Device Discovery';
6✔
361
        const DISABLE_DEVICE_DISCOVERY = 'Disable Device Discovery';
6✔
362
        const FILTER_DEVICES = 'Filter Devices';
6✔
363

364
        const refreshList = () => {
6✔
365
            const filters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
6✔
366
            const items = this.createHostQuickPickList(
6✔
367
                applyDeviceFilters(this.deviceManager.getAllDevices(), filters),
368
                this.deviceManager.getLastUsedDeviceIp(),
369
                itemCache
370
            );
371
            quickPick.items = items;
6✔
372
            const discoveryEnabled = vscodeContextManager.get('brightscript.deviceDiscovery.enabled') === true;
6✔
373
            // Buttons render left-to-right; the rightmost button is the most prominent.
374
            quickPick.buttons = [
6✔
375
                {
376
                    iconPath: new vscode.ThemeIcon('filter'),
377
                    tooltip: FILTER_DEVICES
378
                },
379
                {
380
                    iconPath: discoveryEnabled ? icons.radioTower : icons.radioTowerOff,
6!
381
                    tooltip: discoveryEnabled ? DISABLE_DEVICE_DISCOVERY : ENABLE_DEVICE_DISCOVERY
6!
382
                },
383
                {
384
                    iconPath: new vscode.ThemeIcon('clear-all'),
385
                    tooltip: CLEAR_DEVICE_LIST
386
                },
387
                {
388
                    iconPath: new vscode.ThemeIcon('refresh'),
389
                    tooltip: SCAN_FOR_DEVICES
390
                }
391
            ];
392

393
            // clear the activeItem if we can't find it in the list
394
            if (!quickPick.items.includes(activeItem)) {
6!
395
                activeItem = undefined;
6✔
396
            }
397

398
            // if the user manually selected an item, re-focus that item now that we refreshed the list
399
            if (activeItem) {
6!
400
                quickPick.activeItems = [activeItem];
×
401
            }
402
            // quickPick.show();
403
        };
404

405
        //anytime the device list changes, update the list
406
        this.deviceManager.on('devices-changed', refreshList, disposables);
6✔
407

408
        //refresh the list when the toggle icon's source setting changes, or when any of the
409
        //device-quick-pick filter facets change (so other windows toggling a filter affect this picker)
410
        disposables.push(
6✔
411
            vscode.workspace.onDidChangeConfiguration(e => {
412
                if (
×
413
                    e.affectsConfiguration('brightscript.deviceDiscovery.enabled') ||
×
414
                    e.affectsConfiguration(DEVICE_QUICK_PICK_FILTERS_SECTION)
415
                ) {
416
                    refreshList();
×
417
                }
418
            })
419
        );
420

421
        //while the filter submenu is showing, the parent picker briefly hides — don't treat that as a dismissal
422
        let filterSubmenuOpen = false;
6✔
423
        quickPick.onDidHide(() => {
6✔
424
            if (filterSubmenuOpen) {
4!
425
                return;
×
426
            }
427
            dispose();
4✔
428
            deferred.reject(new Error('No host was selected'));
4✔
429
        });
430

431
        const openFilterSubmenu = () => {
6✔
432
            filterSubmenuOpen = true;
×
433
            this.showFilterSubmenu().finally(() => {
×
434
                filterSubmenuOpen = false;
×
435
                // Re-render items before re-showing — without this the parent picker
436
                // appears empty after a hide/show cycle when no settings changed during the submenu.
437
                refreshList();
×
438
                quickPick.show();
×
439
            });
440
        };
441

442
        quickPick.onDidTriggerButton(button => {
6✔
443
            if (button.tooltip === SCAN_FOR_DEVICES) {
×
444
                //an explicit "scan" click is the refresh-clicked trigger — submit orders;
445
                //this picker (or another visible view) fulfills them immediately
NEW
446
                this.deviceManager.submitBroadcast('refresh-clicked');
×
NEW
447
                this.deviceManager.submitReconcile('refresh-clicked');
×
448
            } else if (button.tooltip === CLEAR_DEVICE_LIST) {
×
NEW
449
                this.deviceManager.clearCurrentDeviceList();
×
450
                void util.showTimedNotification('Clearing device list');
×
451
            } else if (button.tooltip === ENABLE_DEVICE_DISCOVERY) {
×
452
                void util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', true);
×
453
            } else if (button.tooltip === DISABLE_DEVICE_DISCOVERY) {
×
454
                void util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', false);
×
455
            } else if (button.tooltip === FILTER_DEVICES) {
×
456
                openFilterSubmenu();
×
457
            }
458
        });
459

460
        //run the list refresh once to show the popup
461
        refreshList();
6✔
462
        const result = await deferred.promise;
6✔
463
        dispose();
2✔
464
        if (result.manual === true) {
2✔
465
            return this.promptForHostManual();
1✔
466
        } else {
467
            return { host: result.ip, deviceInfo: result.deviceInfo };
1✔
468
        }
469
    }
470

471
    /**
472
     * Generate the item list for the `this.promptForHost()` call
473
     */
474
    private createHostQuickPickList(
475
        devices: RokuDevice[],
476
        lastUsedDeviceIp: string | undefined,
477
        cache = new Map<string, QuickPickHostItem>()
7✔
478
    ) {
479
        //the collection of items we will eventually return
480
        let items: QuickPickHostItem[] = [];
13✔
481

482
        //find the lastUsedDevice from the devices list
483
        const lastUsedDevice = lastUsedDeviceIp ? devices.find(x => x.ip === lastUsedDeviceIp) : undefined;
13✔
484
        //remove the lastUsedDevice from the devices list so we can more easily reason with the rest of the list
485
        devices = devices.filter(x => x.ip !== lastUsedDeviceIp);
13✔
486

487
        // Ensure the most recently used device is at the top of the list
488
        if (lastUsedDevice) {
13✔
489
            //add a separator for "last used"
490
            items.push({
3✔
491
                label: 'last used',
492
                kind: vscode.QuickPickItemKind.Separator
493
            });
494

495
            //add the device
496
            items.push({
3✔
497
                label: this.deviceManager.getDeviceDisplayName(lastUsedDevice, true),
498
                device: lastUsedDevice,
499
                iconPath: this.deviceManager.getIconPath(lastUsedDevice)
500
            } as any);
501
        }
502

503
        //add all other devices
504
        if (devices.length > 0) {
13✔
505
            items.push({
4✔
506
                label: lastUsedDevice ? 'other devices' : 'devices',
4✔
507
                kind: vscode.QuickPickItemKind.Separator
508
            });
509

510
            //add each device
511
            for (const device of devices) {
4✔
512
                //add the device
513
                items.push({
8✔
514
                    label: this.deviceManager.getDeviceDisplayName(device, true),
515
                    device: device,
516
                    iconPath: this.deviceManager.getIconPath(device)
517
                });
518
            }
519
        }
520

521
        //include a divider between devices and "manual" option (only if we have devices)
522
        if (lastUsedDevice || devices.length) {
13✔
523
            items.push({ label: ' ', kind: vscode.QuickPickItemKind.Separator });
5✔
524
        }
525

526
        // allow user to manually type an IP address
527
        items.push(
13✔
528
            {
529
                label: manualLabel,
530
                device: { id: manualHostItemId },
531
                iconPath: new vscode.ThemeIcon('keyboard')
532
            } as any,
533
            {
534
                label: scanForDevicesLabel,
535
                device: { id: scanForDevicesItemId },
536
                iconPath: new vscode.ThemeIcon('radio-tower')
537
            } as any
538
        );
539

540
        // replace items with their cached versions if found (to maintain references)
541
        for (let i = 0; i < items.length; i++) {
13✔
542
            const item = items[i];
49✔
543
            if (cache.has(item.label)) {
49!
544
                items[i] = cache.get(item.label);
×
545
                items[i].device = item.device;
×
546
                items[i].iconPath = item.iconPath;
×
547
            } else {
548
                cache.set(item.label, item);
49✔
549
            }
550
        }
551

552
        return items;
13✔
553
    }
554

555
    /**
556
     * Open a checkbox-style quick pick (canSelectMany) listing each filter facet.
557
     * Follows VS Code's standard multi-select pattern: Space toggles checkboxes,
558
     * Enter commits the current selection to user settings, Escape cancels. A title-bar
559
     * Reset button resets the picker's selection to defaults (still committed on Enter).
560
     */
561
    private showFilterSubmenu(): Promise<void> {
562
        return new Promise<void>((resolve) => {
×
563
            const RESET_FILTERS = 'Reset Filters';
×
564
            const filterPick = vscode.window.createQuickPick<QuickPickFilterItem>();
×
565
            filterPick.title = 'Filter Devices';
×
566
            filterPick.placeholder = 'Space to toggle, Enter to apply, Escape to cancel';
×
567
            filterPick.canSelectMany = true;
×
568
            filterPick.buttons = [{
×
569
                iconPath: new vscode.ThemeIcon('discard'),
570
                tooltip: RESET_FILTERS
571
            }];
572

573
            const buildItems = (filters: DeviceFilters): QuickPickFilterItem[] => {
×
574
                const result: QuickPickFilterItem[] = [];
×
575
                for (let groupIndex = 0; groupIndex < DEVICE_FILTER_GROUPS.length; groupIndex++) {
×
576
                    if (groupIndex > 0) {
×
577
                        result.push({ label: '', kind: vscode.QuickPickItemKind.Separator });
×
578
                    }
579
                    for (const facetKey of DEVICE_FILTER_GROUPS[groupIndex]) {
×
580
                        result.push({
×
581
                            label: DEVICE_FILTER_LABELS[facetKey],
582
                            picked: filters[facetKey],
583
                            facetKey: facetKey
584
                        });
585
                    }
586
                }
587
                return result;
×
588
            };
589

590
            // Initial load — render items from current settings and pre-select the picked ones
591
            const initialFilters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
592
            const items = buildItems(initialFilters);
×
593
            filterPick.items = items;
×
594
            filterPick.selectedItems = items.filter(i => i.picked);
×
595

596
            filterPick.onDidTriggerButton((button) => {
×
597
                if (button.tooltip !== RESET_FILTERS) {
×
598
                    return;
×
599
                }
600
                // Reset the picker's selection to the in-code defaults — user still has to
601
                // press Enter to commit or Escape to discard, matching the rest of the flow.
602
                filterPick.selectedItems = items.filter(item => {
×
603
                    return item.facetKey ? DEFAULT_DEVICE_FILTERS[item.facetKey] : false;
×
604
                });
605
            });
606

607
            filterPick.onDidAccept(async () => {
×
608
                const selectedFacets = new Set<keyof DeviceFilters>();
×
609
                for (const item of filterPick.selectedItems) {
×
610
                    if (item.facetKey) {
×
611
                        selectedFacets.add(item.facetKey);
×
612
                    }
613
                }
614
                const currentFilters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
615
                const config = vscode.workspace.getConfiguration(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
616
                const writes: Thenable<unknown>[] = [];
×
617
                for (const facetKey of DEVICE_FILTER_KEYS) {
×
618
                    const nextValue = selectedFacets.has(facetKey);
×
619
                    if (nextValue === currentFilters[facetKey]) {
×
620
                        continue;
×
621
                    }
622
                    const valueToWrite = nextValue === DEFAULT_DEVICE_FILTERS[facetKey] ? undefined : nextValue;
×
623
                    writes.push(config.update(facetKey, valueToWrite, vscode.ConfigurationTarget.Global));
×
624
                }
625
                if (writes.length > 0) {
×
626
                    try {
×
627
                        await Promise.all(writes);
×
628
                    } catch {
629
                        // best-effort persistence
630
                    }
631
                }
632
                filterPick.hide();
×
633
            });
634

635
            filterPick.onDidHide(() => {
×
636
                filterPick.dispose();
×
637
                resolve();
×
638
            });
639

640
            filterPick.show();
×
641
        });
642
    }
643
}
644

645
type QuickPickFilterItem = QuickPickItem & { facetKey?: keyof DeviceFilters };
646

647
type QuickPickHostItem = QuickPickItem & { device?: RokuDevice; iconPath?: vscode.ThemeIcon | { light: vscode.Uri; dark: vscode.Uri } };
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc