From 2d20ebeb296ec4c417991c90cc797fa9442a5b82 Mon Sep 17 00:00:00 2001 From: Alex Denford SBL Date: Wed, 18 Nov 2026 16:34:48 -0700 Subject: [PATCH 1/5] watcher for cpuprofile captures folder --- README.md | 1 + src/extension.ts | 5 +- src/panels/home-view-provider.test.ts | 360 ++++++++++++++++++ src/panels/home-view-provider.ts | 103 ++++- webview-ui/src/home_panel/App.tsx | 2 + .../home_panel/handlers/ProfilerHandlers.tsx | 5 +- 6 files changed, 462 insertions(+), 14 deletions(-) create mode 100644 src/panels/home-view-provider.test.ts diff --git a/README.md b/README.md index 9d5dfaf..b1e7373 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,7 @@ Add shortcuts for your favorite Minecraft commands. ##### Script Profiler After setting a local path for saving captures, use `Start Profiler` and `Stop Profiler` to create performance captures of your actively running add-on. +While the home panel is visible, the Captures list automatically updates when `.cpuprofile` files are added to or removed from the selected folder, including changes made outside VS Code. #### Diagnostics Window When attatched to a game server running Minecraft 1.21.10 or above, the debugger can display high level statistics to help diagnose performance issues. diff --git a/src/extension.ts b/src/extension.ts index 21c43c5..b870017 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -20,7 +20,10 @@ export function activate(context: vscode.ExtensionContext): void { // home view const homeViewProvider = new HomeViewProvider(context.extensionUri, eventEmitter); - context.subscriptions.push(vscode.window.registerWebviewViewProvider(HomeViewProvider.viewType, homeViewProvider)); + context.subscriptions.push( + homeViewProvider, + vscode.window.registerWebviewViewProvider(HomeViewProvider.viewType, homeViewProvider), + ); // register a configuration provider for the 'minecraft-js' debug type const configProvider = new ConfigProvider(); diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts new file mode 100644 index 0000000..6a9e3f4 --- /dev/null +++ b/src/panels/home-view-provider.test.ts @@ -0,0 +1,360 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +import { EventEmitter } from 'stream'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { HomeViewProvider } from './home-view-provider'; + +const mocks = vi.hoisted(() => ({ + readdir: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null, files: string[]) => void) => void>(), + unlink: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null) => void) => void>(), + createWatcher: vi.fn<() => vscode.FileSystemWatcher>(), +})); + +vi.mock('fs', () => ({ + readdir: mocks.readdir, + unlink: mocks.unlink, +})); + +vi.mock('vscode', () => ({ + Disposable: class { + constructor(private readonly callback: () => void) {} + dispose() { + this.callback(); + } + }, + RelativePattern: class { + constructor(readonly base: string, readonly pattern: string) {} + }, + Uri: { + file: (fsPath: string) => ({ fsPath }), + }, + workspace: { + createFileSystemWatcher: mocks.createWatcher, + }, +})); + +vi.mock('../utilities/getUri', () => ({ + getUri: () => 'test-resource', +})); + +function createEvent() { + const listeners = new Set<(value: T) => void>(); + const event = vi.fn>((listener, thisArgs, disposables) => { + const callback = (value: T) => listener.call(thisArgs, value); + listeners.add(callback); + const disposable = new vscode.Disposable(() => listeners.delete(callback)); + disposables?.push(disposable); + return disposable; + }); + return { + event, + fire: (value: T) => listeners.forEach(listener => listener(value)), + clear: () => listeners.clear(), + }; +} + +function createWatcher() { + const created = createEvent(); + const deleted = createEvent(); + const changed = createEvent(); + const watcher = { + ignoreCreateEvents: false, + ignoreChangeEvents: true, + ignoreDeleteEvents: false, + onDidCreate: created.event, + onDidDelete: deleted.event, + onDidChange: changed.event, + dispose: vi.fn(() => { + created.clear(); + deleted.clear(); + changed.clear(); + }), + } satisfies vscode.FileSystemWatcher; + return { watcher, created, deleted }; +} + +function createView() { + let visible = true; + const received = createEvent(); + const visibility = createEvent(); + const disposed = createEvent(); + const postMessage = vi.fn(() => Promise.resolve(true)); + const view = { + get visible() { return visible; }, + viewType: HomeViewProvider.viewType, + show: vi.fn(), + onDidChangeVisibility: visibility.event, + onDidDispose: disposed.event, + webview: { + html: '', + options: {}, + cspSource: 'test', + postMessage, + asWebviewUri: vi.fn((uri: vscode.Uri) => uri), + onDidReceiveMessage: received.event, + }, + } satisfies vscode.WebviewView; + return { + view, + received, + disposed, + postMessage, + setVisible(value: boolean) { + visible = value; + visibility.fire(); + }, + }; +} + +describe('HomeViewProvider capture watching', () => { + const capturesPath = 'D:\\captures'; + const otherPath = 'D:\\other-captures'; + let provider: HomeViewProvider; + let emitter: EventEmitter; + let ui: ReturnType; + let watchers: ReturnType[]; + + function setCapturesPath(capturesBasePath: string) { + ui.received.fire({ type: 'refresh-captures', capturesBasePath }); + } + + beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + watchers = []; + mocks.createWatcher.mockImplementation(() => { + const watcher = createWatcher(); + watchers.push(watcher); + return watcher.watcher; + }); + mocks.readdir.mockImplementation((_path, callback) => { + callback(null, ['initial.cpuprofile', 'notes.txt']); + }); + emitter = new EventEmitter(); + provider = new HomeViewProvider(vscode.Uri.file('D:\\extension'), emitter); + ui = createView(); + provider.resolveWebviewView(ui.view); + }); + + afterEach(() => { + provider.dispose(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('does not watch or read an unset captures path', () => { + setCapturesPath(''); + + expect(mocks.createWatcher).not.toHaveBeenCalled(); + expect(mocks.readdir).not.toHaveBeenCalled(); + }); + + it('watches only profile additions and deletions and immediately lists existing captures', () => { + setCapturesPath(capturesPath); + + expect(mocks.createWatcher).toHaveBeenCalledWith( + expect.objectContaining({ base: capturesPath, pattern: '*.cpuprofile' }), + false, + true, + false, + ); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['initial.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it.each(['created', 'deleted'] as const)('refreshes after a profile is %s externally', event => { + setCapturesPath(capturesPath); + const files = event === 'created' ? ['initial.cpuprofile', 'external.cpuprofile'] : []; + mocks.readdir.mockImplementation((_path, callback) => callback(null, files)); + + watchers[0][event].fire(vscode.Uri.file(`${capturesPath}\\external.cpuprofile`)); + vi.advanceTimersByTime(100); + + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: files, + newCaptureFileName: undefined, + }); + }); + + it('debounces bursts of create and delete events', () => { + setCapturesPath(capturesPath); + const uri = vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`); + watchers[0].created.fire(uri); + vi.advanceTimersByTime(50); + watchers[0].deleted.fire(uri); + vi.advanceTimersByTime(99); + expect(mocks.readdir).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(1); + expect(mocks.readdir).toHaveBeenCalledTimes(2); + }); + + it('replaces the watcher and discards reads from the old captures path', () => { + mocks.readdir.mockImplementation(() => undefined); + setCapturesPath(capturesPath); + setCapturesPath(otherPath); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(watchers).toHaveLength(2); + expect(mocks.readdir).toHaveBeenLastCalledWith(otherPath, expect.any(Function)); + + mocks.readdir.mock.calls[1][1](null, ['current.cpuprofile']); + mocks.readdir.mock.calls[0][1](null, ['stale.cpuprofile']); + expect(ui.postMessage).toHaveBeenCalledOnce(); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['current.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it('stops watching and cancels pending refreshes when the captures path is cleared', () => { + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + setCapturesPath(''); + vi.advanceTimersByTime(100); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('stops watching while hidden and refreshes changes made while hidden on reopening', () => { + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + ui.setVisible(false); + vi.advanceTimersByTime(100); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + + mocks.readdir.mockImplementation((_path, callback) => callback(null, ['added-while-hidden.cpuprofile'])); + ui.setVisible(true); + + expect(watchers).toHaveLength(2); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['added-while-hidden.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it('does not start watching a path restored while the view is hidden until it becomes visible', () => { + ui.setVisible(false); + setCapturesPath(capturesPath); + expect(mocks.createWatcher).not.toHaveBeenCalled(); + expect(mocks.readdir).not.toHaveBeenCalled(); + + ui.setVisible(true); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + }); + + it.each(['view', 'provider'] as const)('cleans up watchers, timers, reads and listeners on %s disposal', target => { + mocks.readdir.mockImplementation(() => undefined); + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + + if (target === 'view') { + ui.disposed.fire(); + } else { + provider.dispose(); + } + mocks.readdir.mock.calls[0][1](null, ['stale.cpuprofile']); + vi.advanceTimersByTime(100); + setCapturesPath(otherPath); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(emitter.listenerCount('new-profiler-capture')).toBe(0); + expect(vi.getTimerCount()).toBe(0); + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(ui.postMessage).not.toHaveBeenCalled(); + }); + + it('cleans up the previous view when the home view is resolved again', () => { + setCapturesPath(capturesPath); + const oldUi = ui; + ui = createView(); + provider.resolveWebviewView(ui.view); + oldUi.received.fire({ type: 'refresh-captures', capturesBasePath: otherPath }); + setCapturesPath(otherPath); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(watchers).toHaveLength(2); + expect(emitter.listenerCount('new-profiler-capture')).toBe(1); + }); + + it('ignores out-of-order reads without losing new-capture selection', () => { + mocks.readdir.mockImplementation(() => undefined); + setCapturesPath(capturesPath); + emitter.emit('new-profiler-capture', capturesPath, 'new.cpuprofile'); + watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\new.cpuprofile`)); + vi.advanceTimersByTime(100); + + mocks.readdir.mock.calls[2][1](null, ['new.cpuprofile']); + mocks.readdir.mock.calls[1][1](null, ['new.cpuprofile']); + mocks.readdir.mock.calls[0][1](null, []); + + expect(ui.postMessage).toHaveBeenCalledOnce(); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['new.cpuprofile'], + newCaptureFileName: 'new.cpuprofile', + }); + }); + + it('ignores new-capture events for other folders', () => { + setCapturesPath(capturesPath); + emitter.emit('new-profiler-capture', otherPath, 'other.cpuprofile'); + + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(ui.postMessage).toHaveBeenCalledOnce(); + }); + + it('retains new-capture selection while hidden until the view is shown', () => { + setCapturesPath(capturesPath); + ui.setVisible(false); + emitter.emit('new-profiler-capture', capturesPath, 'new.cpuprofile'); + expect(mocks.readdir).toHaveBeenCalledOnce(); + + mocks.readdir.mockImplementation((_path, callback) => callback(null, ['new.cpuprofile'])); + ui.setVisible(true); + + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['new.cpuprofile'], + newCaptureFileName: 'new.cpuprofile', + }); + }); + + it('reports read failures explicitly so an inaccessible folder does not leave stale captures', () => { + const error = new Error('Directory is unavailable'); + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined); + mocks.readdir.mockImplementation((_path, callback) => callback(error, [])); + setCapturesPath(capturesPath); + + expect(log).toHaveBeenCalledWith('Error reading captures directory:', error); + expect(ui.postMessage).toHaveBeenLastCalledWith({ type: 'capture-files-refresh-failed' }); + }); + + it('still refreshes after a capture is deleted through the UI', () => { + setCapturesPath(capturesPath); + mocks.unlink.mockImplementation((_path, callback) => callback(null)); + mocks.readdir.mockImplementation((_path, callback) => callback(null, [])); + ui.received.fire({ type: 'delete-capture-file', capturesBasePath: capturesPath, fileName: 'initial.cpuprofile' }); + + expect(mocks.unlink).toHaveBeenCalledWith(`${capturesPath}\\initial.cpuprofile`, expect.any(Function)); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: [], + newCaptureFileName: undefined, + }); + }); +}); diff --git a/src/panels/home-view-provider.ts b/src/panels/home-view-provider.ts index 55ee401..68908c7 100644 --- a/src/panels/home-view-provider.ts +++ b/src/panels/home-view-provider.ts @@ -8,12 +8,18 @@ import { getUri } from '../utilities/getUri'; import { EventEmitter } from 'stream'; import { MinecraftCapabilities } from '../session'; -export class HomeViewProvider implements vscode.WebviewViewProvider { +export class HomeViewProvider implements vscode.WebviewViewProvider, vscode.Disposable { public static readonly viewType = 'minecraft-debugger-home-panel'; private readonly _extensionUri: vscode.Uri; private _eventEmitter: EventEmitter; private _view?: vscode.WebviewView; + private _disposables: vscode.Disposable[] = []; + private _capturesBasePath = ''; + private _capturesWatcher?: vscode.FileSystemWatcher; + private _capturesRefreshTimer?: ReturnType; + private _capturesRefreshId = 0; + private _newCaptureFileName?: string; constructor(extensionUri: vscode.Uri, eventEmitter: EventEmitter) { this._extensionUri = extensionUri; @@ -39,6 +45,7 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { } public resolveWebviewView(webviewView: vscode.WebviewView): void { + this.dispose(); this._view = webviewView; this._view.webview.options = { @@ -49,9 +56,18 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { this._view.webview.html = this._getHtmlForWebview(this._view.webview, this._extensionUri); // listen for events from the debugger Session - this._eventEmitter.on('new-profiler-capture', (captureBasePath: string, newCaptureFileName: string) => { - this._refreshProfilerCaptures(captureBasePath, newCaptureFileName); - }); + const onNewProfilerCapture = (captureBasePath: string, newCaptureFileName: string) => { + if (captureBasePath === this._capturesBasePath) { + this._refreshProfilerCaptures(newCaptureFileName); + } + }; + this._eventEmitter.on('new-profiler-capture', onNewProfilerCapture); + this._disposables.push(new vscode.Disposable(() => { + this._eventEmitter.off('new-profiler-capture', onNewProfilerCapture); + })); + + this._view.onDidChangeVisibility(() => this._updateCapturesWatcher(), null, this._disposables); + this._view.onDidDispose(() => this.dispose(), null, this._disposables); // listen for events from the home panel webview this._view.webview.onDidReceiveMessage(async message => { @@ -88,7 +104,11 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { break; } case 'refresh-captures': { - this._refreshProfilerCaptures(message.capturesBasePath); + if (this._capturesBasePath !== message.capturesBasePath) { + this._newCaptureFileName = undefined; + } + this._capturesBasePath = message.capturesBasePath; + this._updateCapturesWatcher(); break; } case 'request-debugger-status': { @@ -108,7 +128,18 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { break; } } - }); + }, null, this._disposables); + } + + public dispose(): void { + this._stopCapturesWatcher(); + for (const disposable of this._disposables) { + disposable.dispose(); + } + this._disposables = []; + this._view = undefined; + this._capturesBasePath = ''; + this._newCaptureFileName = undefined; } private async _browseCapturesBasePath() { @@ -128,21 +159,67 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { vscode.commands.executeCommand('vscode.open', uri); } - private _refreshProfilerCaptures(capturesBasePath: string, newCaptureFileName?: string) { - if (!capturesBasePath) { + private _updateCapturesWatcher(): void { + this._stopCapturesWatcher(); + if (!this._view?.visible || !this._capturesBasePath) { return; } - fs.readdir(capturesBasePath, (err, files) => { + + this._capturesWatcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(this._capturesBasePath, '*.cpuprofile'), + false, + true, + false, + ); + const refreshCaptures = () => { + if (this._capturesRefreshTimer !== undefined) { + clearTimeout(this._capturesRefreshTimer); + } + this._capturesRefreshTimer = setTimeout(() => { + this._capturesRefreshTimer = undefined; + this._refreshProfilerCaptures(); + }, 100); + }; + this._capturesWatcher.onDidCreate(refreshCaptures); + this._capturesWatcher.onDidDelete(refreshCaptures); + this._refreshProfilerCaptures(); + } + + private _stopCapturesWatcher(): void { + this._capturesWatcher?.dispose(); + this._capturesWatcher = undefined; + if (this._capturesRefreshTimer !== undefined) { + clearTimeout(this._capturesRefreshTimer); + this._capturesRefreshTimer = undefined; + } + ++this._capturesRefreshId; + } + + private _refreshProfilerCaptures(newCaptureFileName?: string) { + if (newCaptureFileName) { + this._newCaptureFileName = newCaptureFileName; + } + const view = this._view; + if (!view?.visible || !this._capturesBasePath) { + return; + } + const refreshId = ++this._capturesRefreshId; + fs.readdir(this._capturesBasePath, (err, files) => { + if (refreshId !== this._capturesRefreshId) { + return; + } if (err) { console.error('Error reading captures directory:', err); + view.webview.postMessage({ type: 'capture-files-refresh-failed' }); return; } const allCaptureFileNames = files.filter(file => path.extname(file) === '.cpuprofile'); - this._view?.webview.postMessage({ + view.webview.postMessage({ type: 'capture-files-refreshed', allCaptureFileNames: allCaptureFileNames, - newCaptureFileName: newCaptureFileName, + newCaptureFileName: this._newCaptureFileName, }); + this._newCaptureFileName = undefined; }); } @@ -153,7 +230,9 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { console.error('Error deleting capture file:', err); return; } - this._refreshProfilerCaptures(capturesBasePath); + if (capturesBasePath === this._capturesBasePath) { + this._refreshProfilerCaptures(); + } }); } diff --git a/webview-ui/src/home_panel/App.tsx b/webview-ui/src/home_panel/App.tsx index efee20d..9a2d96e 100644 --- a/webview-ui/src/home_panel/App.tsx +++ b/webview-ui/src/home_panel/App.tsx @@ -100,6 +100,8 @@ const App = () => { if (message.newCaptureFileName) { setSelectedCaptureItem({ fileName: message.newCaptureFileName }); } + } else if (message.type === 'capture-files-refresh-failed') { + setCaptureItems([]); } else if (message.type === 'debugger-status') { if (!message.isConnected) { setProfilerCapturing(false); diff --git a/webview-ui/src/home_panel/handlers/ProfilerHandlers.tsx b/webview-ui/src/home_panel/handlers/ProfilerHandlers.tsx index a4cc24f..a2b5876 100644 --- a/webview-ui/src/home_panel/handlers/ProfilerHandlers.tsx +++ b/webview-ui/src/home_panel/handlers/ProfilerHandlers.tsx @@ -41,8 +41,11 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle vscode.postMessage({ type: 'refresh-captures', capturesBasePath: capturesBasePath }); }, [capturesBasePath]); - // update the scrolling list when captures are refreshed + // update the scrolling list and selection when captures are refreshed useEffect(() => { + setSelectedCaptureItem(selected => + captureItems.some(item => item.fileName === selected?.fileName) ? selected : undefined + ); if (scrollingListRef.current) { scrollingListRef.current.scrollTop = 0; } From 4f8154d020065a7469e9a67c3e3fc218a626cbfe Mon Sep 17 00:00:00 2001 From: Alex Denford SBL Date: Wed, 18 Nov 2026 17:04:20 -0700 Subject: [PATCH 2/5] added open folder button, updated tests --- README.md | 1 + src/panels/home-view-provider.test.ts | 68 +++++++++++++++++++ src/panels/home-view-provider.ts | 24 +++++++ webview-ui/src/home_panel/App.css | 6 ++ webview-ui/src/home_panel/App.tsx | 2 + .../home_panel/controls/ProfilerSection.tsx | 10 +++ .../home_panel/handlers/ProfilerHandlers.tsx | 6 ++ 7 files changed, 117 insertions(+) diff --git a/README.md b/README.md index b1e7373..ef46467 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,7 @@ Add shortcuts for your favorite Minecraft commands. ##### Script Profiler After setting a local path for saving captures, use `Start Profiler` and `Stop Profiler` to create performance captures of your actively running add-on. +Use `Open Folder` beside the captures path to open that folder in your system file explorer (File Explorer on Windows). While the home panel is visible, the Captures list automatically updates when `.cpuprofile` files are added to or removed from the selected folder, including changes made outside VS Code. #### Diagnostics Window diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts index 6a9e3f4..d1b7268 100644 --- a/src/panels/home-view-provider.test.ts +++ b/src/panels/home-view-provider.test.ts @@ -9,11 +9,15 @@ const mocks = vi.hoisted(() => ({ readdir: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null, files: string[]) => void) => void>(), unlink: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null) => void) => void>(), createWatcher: vi.fn<() => vscode.FileSystemWatcher>(), + stat: vi.fn<(path: string) => Promise<{ isDirectory: () => boolean }>>(), + openExternal: vi.fn<(uri: vscode.Uri) => Promise>(), + showErrorMessage: vi.fn(), })); vi.mock('fs', () => ({ readdir: mocks.readdir, unlink: mocks.unlink, + promises: { stat: mocks.stat }, })); vi.mock('vscode', () => ({ @@ -32,6 +36,8 @@ vi.mock('vscode', () => ({ workspace: { createFileSystemWatcher: mocks.createWatcher, }, + env: { openExternal: mocks.openExternal }, + window: { showErrorMessage: mocks.showErrorMessage }, })); vi.mock('../utilities/getUri', () => ({ @@ -131,6 +137,8 @@ describe('HomeViewProvider capture watching', () => { mocks.readdir.mockImplementation((_path, callback) => { callback(null, ['initial.cpuprofile', 'notes.txt']); }); + mocks.stat.mockResolvedValue({ isDirectory: () => true }); + mocks.openExternal.mockResolvedValue(true); emitter = new EventEmitter(); provider = new HomeViewProvider(vscode.Uri.file('D:\\extension'), emitter); ui = createView(); @@ -143,6 +151,66 @@ describe('HomeViewProvider capture watching', () => { vi.restoreAllMocks(); }); + describe('opening the captures folder', () => { + async function openFolder(capturesBasePath: unknown) { + const [handler] = ui.received.event.mock.calls[0]; + await handler({ type: 'open-captures-folder', capturesBasePath }); + } + + it('opens the captures folder with the system file explorer without requiring a debugger connection', async () => { + const folder = 'D:\\captures with spaces'; + await openFolder(folder); + + expect(mocks.stat).toHaveBeenCalledWith(folder); + expect(mocks.openExternal).toHaveBeenCalledWith(vscode.Uri.file(folder)); + expect(mocks.showErrorMessage).not.toHaveBeenCalled(); + }); + + it.each([undefined, '', ' '])('reports an unset captures path (%s)', async capturesBasePath => { + await openFolder(capturesBasePath); + + expect(mocks.stat).not.toHaveBeenCalled(); + expect(mocks.openExternal).not.toHaveBeenCalled(); + expect(mocks.showErrorMessage).toHaveBeenCalledWith('Set a captures path before opening the folder.'); + }); + + it('reports an inaccessible or missing folder', async () => { + mocks.stat.mockRejectedValue(new Error('Directory is unavailable')); + await openFolder(capturesPath); + + expect(mocks.openExternal).not.toHaveBeenCalled(); + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: Directory is unavailable', + ); + }); + + it('rejects a captures path that points to a file', async () => { + mocks.stat.mockResolvedValue({ isDirectory: () => false }); + await openFolder(capturesPath); + + expect(mocks.openExternal).not.toHaveBeenCalled(); + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: The captures path is not a folder.', + ); + }); + + it('reports when the system file explorer cannot be opened', async () => { + mocks.openExternal.mockResolvedValue(false); + await openFolder(capturesPath); + + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: The system file explorer could not be opened.', + ); + }); + + it('reports errors opening the system file explorer', async () => { + mocks.openExternal.mockRejectedValue(new Error('Access denied')); + await openFolder(capturesPath); + + expect(mocks.showErrorMessage).toHaveBeenCalledWith('Unable to open the captures folder: Access denied'); + }); + }); + it('does not watch or read an unset captures path', () => { setCapturesPath(''); diff --git a/src/panels/home-view-provider.ts b/src/panels/home-view-provider.ts index 68908c7..f298f24 100644 --- a/src/panels/home-view-provider.ts +++ b/src/panels/home-view-provider.ts @@ -119,6 +119,10 @@ export class HomeViewProvider implements vscode.WebviewViewProvider, vscode.Disp await this._browseCapturesBasePath(); break; } + case 'open-captures-folder': { + await this._openCapturesFolder(message.capturesBasePath); + break; + } case 'open-capture-file': { this._openCaptureFile(message.capturesBasePath, message.fileName); break; @@ -153,6 +157,26 @@ export class HomeViewProvider implements vscode.WebviewViewProvider, vscode.Disp } } + private async _openCapturesFolder(capturesBasePath: string): Promise { + if (typeof capturesBasePath !== 'string' || capturesBasePath.trim() === '') { + vscode.window.showErrorMessage('Set a captures path before opening the folder.'); + return; + } + + try { + const stats = await fs.promises.stat(capturesBasePath); + if (!stats.isDirectory()) { + throw new Error('The captures path is not a folder.'); + } + if (!await vscode.env.openExternal(vscode.Uri.file(capturesBasePath))) { + throw new Error('The system file explorer could not be opened.'); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + vscode.window.showErrorMessage(`Unable to open the captures folder: ${detail}`); + } + } + private _openCaptureFile(capturesBasePath: string, fileName: string) { const fullPath = path.join(capturesBasePath, fileName); const uri = vscode.Uri.file(fullPath); diff --git a/webview-ui/src/home_panel/App.css b/webview-ui/src/home_panel/App.css index 2f5e4c2..17b014b 100644 --- a/webview-ui/src/home_panel/App.css +++ b/webview-ui/src/home_panel/App.css @@ -145,9 +145,15 @@ .capture-path-input { flex: 1; + min-width: 0; margin-right: 10px; } +.open-captures-folder-button { + flex-shrink: 0; + margin-left: 6px; +} + .capture-scrolling-list-box { max-height: 200px; overflow-y: auto; diff --git a/webview-ui/src/home_panel/App.tsx b/webview-ui/src/home_panel/App.tsx index 9a2d96e..09aed74 100644 --- a/webview-ui/src/home_panel/App.tsx +++ b/webview-ui/src/home_panel/App.tsx @@ -57,6 +57,7 @@ const App = () => { selectedCaptureItem, setSelectedCaptureItem, onCaptureBasePathEdited, + onOpenCapturesFolder, onSelectCaptureItem, onDeleteCaptureItem, onStartProfiler, @@ -142,6 +143,7 @@ const App = () => { capturesBasePath={capturesBasePath} onCaptureBasePathBrowseButtonPressed={onCaptureBasePathBrowseButtonPressed} onCaptureBasePathEdited={onCaptureBasePathEdited} + onOpenCapturesFolder={onOpenCapturesFolder} scrollingListRef={scrollingListRef} captureItems={captureItems} selectedCaptureItem={selectedCaptureItem} diff --git a/webview-ui/src/home_panel/controls/ProfilerSection.tsx b/webview-ui/src/home_panel/controls/ProfilerSection.tsx index a388e31..fb65a32 100644 --- a/webview-ui/src/home_panel/controls/ProfilerSection.tsx +++ b/webview-ui/src/home_panel/controls/ProfilerSection.tsx @@ -7,6 +7,7 @@ import { CaptureItem } from '../handlers/ProfilerHandlers'; interface ProfilerSectionProps { capturesBasePath: string; onCaptureBasePathBrowseButtonPressed: () => void; + onOpenCapturesFolder: () => void; onCaptureBasePathEdited: (event: React.ChangeEvent) => void; scrollingListRef: React.RefObject; captureItems: CaptureItem[]; @@ -23,6 +24,7 @@ interface ProfilerSectionProps { const ProfilerSection: React.FC = ({ capturesBasePath, onCaptureBasePathBrowseButtonPressed, + onOpenCapturesFolder, onCaptureBasePathEdited, scrollingListRef, captureItems, @@ -49,6 +51,14 @@ const ProfilerSection: React.FC = ({ Browse + + Open Folder +
void; // callbacks onCaptureBasePathEdited: (event: React.ChangeEvent) => void; + onOpenCapturesFolder: () => void; onSelectCaptureItem: (captureItem: CaptureItem) => void; onDeleteCaptureItem: (toDelete: CaptureItem) => void; onStartProfiler: () => void; @@ -56,6 +57,10 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle setCapturesBasePath(event.target.value); }, []); + const onOpenCapturesFolder = useCallback(() => { + vscode.postMessage({ type: 'open-captures-folder', capturesBasePath }); + }, [capturesBasePath]); + // when a capture file is selected from the list const onSelectCaptureItem = useCallback((captureItem: CaptureItem) => { setSelectedCaptureItem(captureItem); @@ -102,6 +107,7 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle selectedCaptureItem, setSelectedCaptureItem, onCaptureBasePathEdited, + onOpenCapturesFolder, onSelectCaptureItem, onDeleteCaptureItem, onStartProfiler, From 4e79edd6ae3338a131032bb7214d639202be9b82 Mon Sep 17 00:00:00 2001 From: Alex Denford SBL Date: Thu, 19 Nov 2026 13:26:35 -0700 Subject: [PATCH 3/5] fixing linux path issues causing test failures --- src/panels/home-view-provider.test.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts index d1b7268..cd57b22 100644 --- a/src/panels/home-view-provider.test.ts +++ b/src/panels/home-view-provider.test.ts @@ -1,6 +1,7 @@ // Copyright (C) Microsoft Corporation. All rights reserved. import { EventEmitter } from 'stream'; +import * as path from 'path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { HomeViewProvider } from './home-view-provider'; @@ -114,8 +115,8 @@ function createView() { } describe('HomeViewProvider capture watching', () => { - const capturesPath = 'D:\\captures'; - const otherPath = 'D:\\other-captures'; + const capturesPath = path.resolve('captures'); + const otherPath = path.resolve('other-captures'); let provider: HomeViewProvider; let emitter: EventEmitter; let ui: ReturnType; @@ -140,7 +141,7 @@ describe('HomeViewProvider capture watching', () => { mocks.stat.mockResolvedValue({ isDirectory: () => true }); mocks.openExternal.mockResolvedValue(true); emitter = new EventEmitter(); - provider = new HomeViewProvider(vscode.Uri.file('D:\\extension'), emitter); + provider = new HomeViewProvider(vscode.Uri.file(path.resolve('extension')), emitter); ui = createView(); provider.resolveWebviewView(ui.view); }); @@ -158,7 +159,7 @@ describe('HomeViewProvider capture watching', () => { } it('opens the captures folder with the system file explorer without requiring a debugger connection', async () => { - const folder = 'D:\\captures with spaces'; + const folder = path.resolve('captures with spaces'); await openFolder(folder); expect(mocks.stat).toHaveBeenCalledWith(folder); @@ -239,7 +240,7 @@ describe('HomeViewProvider capture watching', () => { const files = event === 'created' ? ['initial.cpuprofile', 'external.cpuprofile'] : []; mocks.readdir.mockImplementation((_path, callback) => callback(null, files)); - watchers[0][event].fire(vscode.Uri.file(`${capturesPath}\\external.cpuprofile`)); + watchers[0][event].fire(vscode.Uri.file(path.join(capturesPath, 'external.cpuprofile'))); vi.advanceTimersByTime(100); expect(ui.postMessage).toHaveBeenLastCalledWith({ @@ -251,7 +252,7 @@ describe('HomeViewProvider capture watching', () => { it('debounces bursts of create and delete events', () => { setCapturesPath(capturesPath); - const uri = vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`); + const uri = vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile')); watchers[0].created.fire(uri); vi.advanceTimersByTime(50); watchers[0].deleted.fire(uri); @@ -283,7 +284,7 @@ describe('HomeViewProvider capture watching', () => { it('stops watching and cancels pending refreshes when the captures path is cleared', () => { setCapturesPath(capturesPath); - watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); setCapturesPath(''); vi.advanceTimersByTime(100); @@ -295,7 +296,7 @@ describe('HomeViewProvider capture watching', () => { it('stops watching while hidden and refreshes changes made while hidden on reopening', () => { setCapturesPath(capturesPath); - watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); ui.setVisible(false); vi.advanceTimersByTime(100); @@ -327,7 +328,7 @@ describe('HomeViewProvider capture watching', () => { it.each(['view', 'provider'] as const)('cleans up watchers, timers, reads and listeners on %s disposal', target => { mocks.readdir.mockImplementation(() => undefined); setCapturesPath(capturesPath); - watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\capture.cpuprofile`)); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); if (target === 'view') { ui.disposed.fire(); @@ -363,7 +364,7 @@ describe('HomeViewProvider capture watching', () => { mocks.readdir.mockImplementation(() => undefined); setCapturesPath(capturesPath); emitter.emit('new-profiler-capture', capturesPath, 'new.cpuprofile'); - watchers[0].created.fire(vscode.Uri.file(`${capturesPath}\\new.cpuprofile`)); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'new.cpuprofile'))); vi.advanceTimersByTime(100); mocks.readdir.mock.calls[2][1](null, ['new.cpuprofile']); @@ -418,7 +419,7 @@ describe('HomeViewProvider capture watching', () => { mocks.readdir.mockImplementation((_path, callback) => callback(null, [])); ui.received.fire({ type: 'delete-capture-file', capturesBasePath: capturesPath, fileName: 'initial.cpuprofile' }); - expect(mocks.unlink).toHaveBeenCalledWith(`${capturesPath}\\initial.cpuprofile`, expect.any(Function)); + expect(mocks.unlink).toHaveBeenCalledWith(path.join(capturesPath, 'initial.cpuprofile'), expect.any(Function)); expect(ui.postMessage).toHaveBeenLastCalledWith({ type: 'capture-files-refreshed', allCaptureFileNames: [], From 73411beac31f2d1b1554257fa42d1385ea78e445 Mon Sep 17 00:00:00 2001 From: Alex Denford SBL Date: Fri, 20 Nov 2026 12:58:51 -0700 Subject: [PATCH 4/5] feedback --- src/panels/home-view-provider.test.ts | 49 --------------------------- src/panels/home-view-provider.ts | 2 +- 2 files changed, 1 insertion(+), 50 deletions(-) diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts index cd57b22..eea9890 100644 --- a/src/panels/home-view-provider.test.ts +++ b/src/panels/home-view-provider.test.ts @@ -158,23 +158,6 @@ describe('HomeViewProvider capture watching', () => { await handler({ type: 'open-captures-folder', capturesBasePath }); } - it('opens the captures folder with the system file explorer without requiring a debugger connection', async () => { - const folder = path.resolve('captures with spaces'); - await openFolder(folder); - - expect(mocks.stat).toHaveBeenCalledWith(folder); - expect(mocks.openExternal).toHaveBeenCalledWith(vscode.Uri.file(folder)); - expect(mocks.showErrorMessage).not.toHaveBeenCalled(); - }); - - it.each([undefined, '', ' '])('reports an unset captures path (%s)', async capturesBasePath => { - await openFolder(capturesBasePath); - - expect(mocks.stat).not.toHaveBeenCalled(); - expect(mocks.openExternal).not.toHaveBeenCalled(); - expect(mocks.showErrorMessage).toHaveBeenCalledWith('Set a captures path before opening the folder.'); - }); - it('reports an inaccessible or missing folder', async () => { mocks.stat.mockRejectedValue(new Error('Directory is unavailable')); await openFolder(capturesPath); @@ -347,38 +330,6 @@ describe('HomeViewProvider capture watching', () => { expect(ui.postMessage).not.toHaveBeenCalled(); }); - it('cleans up the previous view when the home view is resolved again', () => { - setCapturesPath(capturesPath); - const oldUi = ui; - ui = createView(); - provider.resolveWebviewView(ui.view); - oldUi.received.fire({ type: 'refresh-captures', capturesBasePath: otherPath }); - setCapturesPath(otherPath); - - expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); - expect(watchers).toHaveLength(2); - expect(emitter.listenerCount('new-profiler-capture')).toBe(1); - }); - - it('ignores out-of-order reads without losing new-capture selection', () => { - mocks.readdir.mockImplementation(() => undefined); - setCapturesPath(capturesPath); - emitter.emit('new-profiler-capture', capturesPath, 'new.cpuprofile'); - watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'new.cpuprofile'))); - vi.advanceTimersByTime(100); - - mocks.readdir.mock.calls[2][1](null, ['new.cpuprofile']); - mocks.readdir.mock.calls[1][1](null, ['new.cpuprofile']); - mocks.readdir.mock.calls[0][1](null, []); - - expect(ui.postMessage).toHaveBeenCalledOnce(); - expect(ui.postMessage).toHaveBeenLastCalledWith({ - type: 'capture-files-refreshed', - allCaptureFileNames: ['new.cpuprofile'], - newCaptureFileName: 'new.cpuprofile', - }); - }); - it('ignores new-capture events for other folders', () => { setCapturesPath(capturesPath); emitter.emit('new-profiler-capture', otherPath, 'other.cpuprofile'); diff --git a/src/panels/home-view-provider.ts b/src/panels/home-view-provider.ts index f298f24..c9582ec 100644 --- a/src/panels/home-view-provider.ts +++ b/src/panels/home-view-provider.ts @@ -202,7 +202,7 @@ export class HomeViewProvider implements vscode.WebviewViewProvider, vscode.Disp this._capturesRefreshTimer = setTimeout(() => { this._capturesRefreshTimer = undefined; this._refreshProfilerCaptures(); - }, 100); + }, 1000); }; this._capturesWatcher.onDidCreate(refreshCaptures); this._capturesWatcher.onDidDelete(refreshCaptures); From 1b8e5b9e383547aacc337fd6c4a177178d2297ff Mon Sep 17 00:00:00 2001 From: Alex Denford SBL Date: Fri, 20 Nov 2026 14:03:36 -0700 Subject: [PATCH 5/5] Update home-view-provider.test.ts --- src/panels/home-view-provider.test.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts index eea9890..efbb444 100644 --- a/src/panels/home-view-provider.test.ts +++ b/src/panels/home-view-provider.test.ts @@ -224,7 +224,9 @@ describe('HomeViewProvider capture watching', () => { mocks.readdir.mockImplementation((_path, callback) => callback(null, files)); watchers[0][event].fire(vscode.Uri.file(path.join(capturesPath, 'external.cpuprofile'))); - vi.advanceTimersByTime(100); + vi.advanceTimersByTime(999); + expect(mocks.readdir).toHaveBeenCalledOnce(); + vi.advanceTimersByTime(1); expect(ui.postMessage).toHaveBeenLastCalledWith({ type: 'capture-files-refreshed', @@ -239,7 +241,7 @@ describe('HomeViewProvider capture watching', () => { watchers[0].created.fire(uri); vi.advanceTimersByTime(50); watchers[0].deleted.fire(uri); - vi.advanceTimersByTime(99); + vi.advanceTimersByTime(999); expect(mocks.readdir).toHaveBeenCalledTimes(1); vi.advanceTimersByTime(1); @@ -269,7 +271,7 @@ describe('HomeViewProvider capture watching', () => { setCapturesPath(capturesPath); watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); setCapturesPath(''); - vi.advanceTimersByTime(100); + vi.advanceTimersByTime(1000); expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); expect(mocks.createWatcher).toHaveBeenCalledOnce(); @@ -281,7 +283,7 @@ describe('HomeViewProvider capture watching', () => { setCapturesPath(capturesPath); watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); ui.setVisible(false); - vi.advanceTimersByTime(100); + vi.advanceTimersByTime(1000); expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); expect(mocks.readdir).toHaveBeenCalledOnce(); @@ -319,7 +321,7 @@ describe('HomeViewProvider capture watching', () => { provider.dispose(); } mocks.readdir.mock.calls[0][1](null, ['stale.cpuprofile']); - vi.advanceTimersByTime(100); + vi.advanceTimersByTime(1000); setCapturesPath(otherPath); expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce();