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

rokucommunity / vscode-brightscript-language / 30124549797

24 Jul 2026 08:33PM UTC coverage: 60.816% (+0.9%) from 59.908%
30124549797

Pull #862

github

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

2707 of 4855 branches covered (55.76%)

Branch coverage included in aggregate %.

299 of 337 new or added lines in 7 files covered. (88.72%)

11 existing lines in 3 files now uncovered.

4164 of 6443 relevant lines covered (64.63%)

46.97 hits per line

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

56.42
/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 (skip timer-driven `stale`); otherwise do a
240
        // normal staleness-gated broadcast. The picker never SUBMITS reconcile orders of its own,
241
        // but it does FULFILL queued/live ones (below) so work ordered while no view was visible
242
        // isn't left waiting.
243
        const pendingBroadcast = this.deviceManager.getPendingBroadcast();
6✔
244
        let hasScanned: boolean;
245
        if (pendingBroadcast && pendingBroadcast.reason !== 'stale') {
6!
NEW
246
            this.deviceManager.takePendingBroadcast();
×
NEW
247
            hasScanned = this.deviceManager.broadcast(true);
×
248
        } else {
249
            hasScanned = this.deviceManager.broadcast();
6✔
250
        }
251

252
        // On open, also fulfill a queued reconcile order (skip timer-driven `stale`)
253
        const pendingReconcile = this.deviceManager.getPendingReconcile();
6✔
254
        if (pendingReconcile && pendingReconcile.reason !== 'stale') {
6✔
255
            this.deviceManager.takePendingReconcile();
1✔
256
            this.deviceManager.reconcile(pendingReconcile.reason === 'refresh-clicked');
1✔
257
        }
258

259
        this.deviceManager.on('broadcast-ordered', (order) => {
6✔
NEW
260
            if (order.reason === 'stale') {
×
NEW
261
                return;
×
262
            }
263
            // Suppress the 7s fallback even if another visible consumer takes this order —
264
            // a scan is happening either way
265
            hasScanned = true;
×
266
            if (scanTimeoutId) {
×
267
                clearTimeout(scanTimeoutId);
×
268
                scanTimeoutId = null;
×
269
            }
NEW
270
            if (!this.deviceManager.takePendingBroadcast()) {
×
NEW
271
                return;
×
272
            }
NEW
273
            this.deviceManager.broadcast(true);
×
274
        }, disposables);
275

276
        this.deviceManager.on('reconcile-ordered', (order) => {
6✔
277
            if (order.reason === 'stale') {
1!
NEW
278
                return;
×
279
            }
280
            if (!this.deviceManager.takePendingReconcile()) {
1!
NEW
281
                return;
×
282
            }
283
            this.deviceManager.reconcile(order.reason === 'refresh-clicked');
1✔
284
        }, disposables);
285

286
        scanTimeoutId = setTimeout(() => {
6✔
287
            if (hasScanned) {
6!
288
                return;
6✔
289
            }
NEW
290
            this.deviceManager.broadcast();
×
291
        }, scanTimeoutMs);
292

293
        function dispose() {
294
            for (const disposable of disposables) {
6✔
295
                disposable.dispose();
42✔
296
            }
297
        }
298

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

345
        quickPick.onDidChangeSelection((selection) => {
6✔
346
            // only save the selectedDevice if the user explicitly clicks on an item
347
            // use the selected device in onDidAccept
348
            selectedDevice = selection[0];
1✔
349
        });
350

351
        let activeChangesSinceRefresh = 0;
6✔
352
        let activeItem: QuickPickItem;
353

354
        // remember the currently active item so we can maintain active selection when refreshing the list
355
        quickPick.onDidChangeActive((items) => {
6✔
356
            // reset our activeChanges tracker since users cannot cause items.length to be 0 (meaning a refresh has just happened)
357
            if (items.length === 0) {
×
358
                activeChangesSinceRefresh = 0;
×
359
                return;
×
360
            }
361
            if (activeChangesSinceRefresh > 0) {
×
362
                activeItem = items[0];
×
363
            }
364
            activeChangesSinceRefresh++;
×
365
        });
366

367
        const itemCache = new Map<string, QuickPickHostItem>();
6✔
368
        if (options?.defaultValue) {
6!
369
            quickPick.value = options?.defaultValue;
×
370
        }
371
        quickPick.show();
6✔
372

373
        //set a timeout to automatically start scanning for devices after a short delay
374
        const SCAN_FOR_DEVICES = 'Scan for Devices';
6✔
375
        const CLEAR_DEVICE_LIST = 'Clear Device List';
6✔
376
        const ENABLE_DEVICE_DISCOVERY = 'Enable Device Discovery';
6✔
377
        const DISABLE_DEVICE_DISCOVERY = 'Disable Device Discovery';
6✔
378
        const FILTER_DEVICES = 'Filter Devices';
6✔
379

380
        const refreshList = () => {
6✔
381
            const filters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
6✔
382
            const items = this.createHostQuickPickList(
6✔
383
                applyDeviceFilters(this.deviceManager.getAllDevices(), filters),
384
                this.deviceManager.getLastUsedDeviceIp(),
385
                itemCache
386
            );
387
            quickPick.items = items;
6✔
388
            const discoveryEnabled = vscodeContextManager.get('brightscript.deviceDiscovery.enabled') === true;
6✔
389
            // Buttons render left-to-right; the rightmost button is the most prominent.
390
            quickPick.buttons = [
6✔
391
                {
392
                    iconPath: new vscode.ThemeIcon('filter'),
393
                    tooltip: FILTER_DEVICES
394
                },
395
                {
396
                    iconPath: discoveryEnabled ? icons.radioTower : icons.radioTowerOff,
6!
397
                    tooltip: discoveryEnabled ? DISABLE_DEVICE_DISCOVERY : ENABLE_DEVICE_DISCOVERY
6!
398
                },
399
                {
400
                    iconPath: new vscode.ThemeIcon('clear-all'),
401
                    tooltip: CLEAR_DEVICE_LIST
402
                },
403
                {
404
                    iconPath: new vscode.ThemeIcon('refresh'),
405
                    tooltip: SCAN_FOR_DEVICES
406
                }
407
            ];
408

409
            // clear the activeItem if we can't find it in the list
410
            if (!quickPick.items.includes(activeItem)) {
6!
411
                activeItem = undefined;
6✔
412
            }
413

414
            // if the user manually selected an item, re-focus that item now that we refreshed the list
415
            if (activeItem) {
6!
416
                quickPick.activeItems = [activeItem];
×
417
            }
418
            // quickPick.show();
419
        };
420

421
        //anytime the device list changes, update the list
422
        this.deviceManager.on('devices-changed', refreshList, disposables);
6✔
423

424
        //refresh the list when the toggle icon's source setting changes, or when any of the
425
        //device-quick-pick filter facets change (so other windows toggling a filter affect this picker)
426
        disposables.push(
6✔
427
            vscode.workspace.onDidChangeConfiguration(e => {
428
                if (
×
429
                    e.affectsConfiguration('brightscript.deviceDiscovery.enabled') ||
×
430
                    e.affectsConfiguration(DEVICE_QUICK_PICK_FILTERS_SECTION)
431
                ) {
432
                    refreshList();
×
433
                }
434
            })
435
        );
436

437
        //while the filter submenu is showing, the parent picker briefly hides — don't treat that as a dismissal
438
        let filterSubmenuOpen = false;
6✔
439
        quickPick.onDidHide(() => {
6✔
440
            if (filterSubmenuOpen) {
4!
441
                return;
×
442
            }
443
            dispose();
4✔
444
            deferred.reject(new Error('No host was selected'));
4✔
445
        });
446

447
        const openFilterSubmenu = () => {
6✔
448
            filterSubmenuOpen = true;
×
449
            this.showFilterSubmenu().finally(() => {
×
450
                filterSubmenuOpen = false;
×
451
                // Re-render items before re-showing — without this the parent picker
452
                // appears empty after a hide/show cycle when no settings changed during the submenu.
453
                refreshList();
×
454
                quickPick.show();
×
455
            });
456
        };
457

458
        quickPick.onDidTriggerButton(button => {
6✔
459
            if (button.tooltip === SCAN_FOR_DEVICES) {
×
460
                //an explicit "scan" click is the refresh-clicked trigger — submit orders;
461
                //this picker (or another visible view) fulfills them immediately
NEW
462
                this.deviceManager.submitBroadcast('refresh-clicked');
×
NEW
463
                this.deviceManager.submitReconcile('refresh-clicked');
×
464
            } else if (button.tooltip === CLEAR_DEVICE_LIST) {
×
NEW
465
                this.deviceManager.clearCurrentDeviceList();
×
466
                void util.showTimedNotification('Clearing device list');
×
467
            } else if (button.tooltip === ENABLE_DEVICE_DISCOVERY) {
×
468
                void util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', true);
×
469
            } else if (button.tooltip === DISABLE_DEVICE_DISCOVERY) {
×
470
                void util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', false);
×
471
            } else if (button.tooltip === FILTER_DEVICES) {
×
472
                openFilterSubmenu();
×
473
            }
474
        });
475

476
        //run the list refresh once to show the popup
477
        refreshList();
6✔
478
        const result = await deferred.promise;
6✔
479
        dispose();
2✔
480
        if (result.manual === true) {
2✔
481
            return this.promptForHostManual();
1✔
482
        } else {
483
            return { host: result.ip, deviceInfo: result.deviceInfo };
1✔
484
        }
485
    }
486

487
    /**
488
     * Generate the item list for the `this.promptForHost()` call
489
     */
490
    private createHostQuickPickList(
491
        devices: RokuDevice[],
492
        lastUsedDeviceIp: string | undefined,
493
        cache = new Map<string, QuickPickHostItem>()
7✔
494
    ) {
495
        //the collection of items we will eventually return
496
        let items: QuickPickHostItem[] = [];
13✔
497

498
        //find the lastUsedDevice from the devices list
499
        const lastUsedDevice = lastUsedDeviceIp ? devices.find(x => x.ip === lastUsedDeviceIp) : undefined;
13✔
500
        //remove the lastUsedDevice from the devices list so we can more easily reason with the rest of the list
501
        devices = devices.filter(x => x.ip !== lastUsedDeviceIp);
13✔
502

503
        // Ensure the most recently used device is at the top of the list
504
        if (lastUsedDevice) {
13✔
505
            //add a separator for "last used"
506
            items.push({
3✔
507
                label: 'last used',
508
                kind: vscode.QuickPickItemKind.Separator
509
            });
510

511
            //add the device
512
            items.push({
3✔
513
                label: this.deviceManager.getDeviceDisplayName(lastUsedDevice, true),
514
                device: lastUsedDevice,
515
                iconPath: this.deviceManager.getIconPath(lastUsedDevice)
516
            } as any);
517
        }
518

519
        //add all other devices
520
        if (devices.length > 0) {
13✔
521
            items.push({
4✔
522
                label: lastUsedDevice ? 'other devices' : 'devices',
4✔
523
                kind: vscode.QuickPickItemKind.Separator
524
            });
525

526
            //add each device
527
            for (const device of devices) {
4✔
528
                //add the device
529
                items.push({
8✔
530
                    label: this.deviceManager.getDeviceDisplayName(device, true),
531
                    device: device,
532
                    iconPath: this.deviceManager.getIconPath(device)
533
                });
534
            }
535
        }
536

537
        //include a divider between devices and "manual" option (only if we have devices)
538
        if (lastUsedDevice || devices.length) {
13✔
539
            items.push({ label: ' ', kind: vscode.QuickPickItemKind.Separator });
5✔
540
        }
541

542
        // allow user to manually type an IP address
543
        items.push(
13✔
544
            {
545
                label: manualLabel,
546
                device: { id: manualHostItemId },
547
                iconPath: new vscode.ThemeIcon('keyboard')
548
            } as any,
549
            {
550
                label: scanForDevicesLabel,
551
                device: { id: scanForDevicesItemId },
552
                iconPath: new vscode.ThemeIcon('radio-tower')
553
            } as any
554
        );
555

556
        // replace items with their cached versions if found (to maintain references)
557
        for (let i = 0; i < items.length; i++) {
13✔
558
            const item = items[i];
49✔
559
            if (cache.has(item.label)) {
49!
560
                items[i] = cache.get(item.label);
×
561
                items[i].device = item.device;
×
562
                items[i].iconPath = item.iconPath;
×
563
            } else {
564
                cache.set(item.label, item);
49✔
565
            }
566
        }
567

568
        return items;
13✔
569
    }
570

571
    /**
572
     * Open a checkbox-style quick pick (canSelectMany) listing each filter facet.
573
     * Follows VS Code's standard multi-select pattern: Space toggles checkboxes,
574
     * Enter commits the current selection to user settings, Escape cancels. A title-bar
575
     * Reset button resets the picker's selection to defaults (still committed on Enter).
576
     */
577
    private showFilterSubmenu(): Promise<void> {
578
        return new Promise<void>((resolve) => {
×
579
            const RESET_FILTERS = 'Reset Filters';
×
580
            const filterPick = vscode.window.createQuickPick<QuickPickFilterItem>();
×
581
            filterPick.title = 'Filter Devices';
×
582
            filterPick.placeholder = 'Space to toggle, Enter to apply, Escape to cancel';
×
583
            filterPick.canSelectMany = true;
×
584
            filterPick.buttons = [{
×
585
                iconPath: new vscode.ThemeIcon('discard'),
586
                tooltip: RESET_FILTERS
587
            }];
588

589
            const buildItems = (filters: DeviceFilters): QuickPickFilterItem[] => {
×
590
                const result: QuickPickFilterItem[] = [];
×
591
                for (let groupIndex = 0; groupIndex < DEVICE_FILTER_GROUPS.length; groupIndex++) {
×
592
                    if (groupIndex > 0) {
×
593
                        result.push({ label: '', kind: vscode.QuickPickItemKind.Separator });
×
594
                    }
595
                    for (const facetKey of DEVICE_FILTER_GROUPS[groupIndex]) {
×
596
                        result.push({
×
597
                            label: DEVICE_FILTER_LABELS[facetKey],
598
                            picked: filters[facetKey],
599
                            facetKey: facetKey
600
                        });
601
                    }
602
                }
603
                return result;
×
604
            };
605

606
            // Initial load — render items from current settings and pre-select the picked ones
607
            const initialFilters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
608
            const items = buildItems(initialFilters);
×
609
            filterPick.items = items;
×
610
            filterPick.selectedItems = items.filter(i => i.picked);
×
611

612
            filterPick.onDidTriggerButton((button) => {
×
613
                if (button.tooltip !== RESET_FILTERS) {
×
614
                    return;
×
615
                }
616
                // Reset the picker's selection to the in-code defaults — user still has to
617
                // press Enter to commit or Escape to discard, matching the rest of the flow.
618
                filterPick.selectedItems = items.filter(item => {
×
619
                    return item.facetKey ? DEFAULT_DEVICE_FILTERS[item.facetKey] : false;
×
620
                });
621
            });
622

623
            filterPick.onDidAccept(async () => {
×
624
                const selectedFacets = new Set<keyof DeviceFilters>();
×
625
                for (const item of filterPick.selectedItems) {
×
626
                    if (item.facetKey) {
×
627
                        selectedFacets.add(item.facetKey);
×
628
                    }
629
                }
630
                const currentFilters = loadDeviceFilters(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
631
                const config = vscode.workspace.getConfiguration(DEVICE_QUICK_PICK_FILTERS_SECTION);
×
632
                const writes: Thenable<unknown>[] = [];
×
633
                for (const facetKey of DEVICE_FILTER_KEYS) {
×
634
                    const nextValue = selectedFacets.has(facetKey);
×
635
                    if (nextValue === currentFilters[facetKey]) {
×
636
                        continue;
×
637
                    }
638
                    const valueToWrite = nextValue === DEFAULT_DEVICE_FILTERS[facetKey] ? undefined : nextValue;
×
639
                    writes.push(config.update(facetKey, valueToWrite, vscode.ConfigurationTarget.Global));
×
640
                }
641
                if (writes.length > 0) {
×
642
                    try {
×
643
                        await Promise.all(writes);
×
644
                    } catch {
645
                        // best-effort persistence
646
                    }
647
                }
648
                filterPick.hide();
×
649
            });
650

651
            filterPick.onDidHide(() => {
×
652
                filterPick.dispose();
×
653
                resolve();
×
654
            });
655

656
            filterPick.show();
×
657
        });
658
    }
659
}
660

661
type QuickPickFilterItem = QuickPickItem & { facetKey?: keyof DeviceFilters };
662

663
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