From ce229c8dfd4a4ec29aecee0187edf35c2b2d5d3a Mon Sep 17 00:00:00 2001 From: eitsupi Date: Tue, 17 Nov 2026 16:16:20 +0000 Subject: [PATCH] test: report diagnostics for HTML widget and Workspace focus timeouts --- .github/workflows/main.yml | 3 +- src/test/common/failureDiagnostics.ts | 80 +++++++++ src/test/suite/htmlWidgetBrowser.test.ts | 205 ++++++++++++++++++----- src/test/suite/interactiveEditor.test.ts | 132 +++++++++++---- 4 files changed, 347 insertions(+), 73 deletions(-) create mode 100644 src/test/common/failureDiagnostics.ts diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 68f2e643e..53a2bcf98 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -135,8 +135,7 @@ jobs: name: extension-test-logs-${{ runner.os }} path: | .vscode-test/activation/** - .vscode-test/user-data/**/logs/**/exthost/exthost.log - .vscode-test/user-data/**/logs/**/exthost/output_logging_*/*.log + .vscode-test/user-data/**/logs/**/*.log retention-days: 7 build: runs-on: ubuntu-latest diff --git a/src/test/common/failureDiagnostics.ts b/src/test/common/failureDiagnostics.ts new file mode 100644 index 000000000..e9deb018e --- /dev/null +++ b/src/test/common/failureDiagnostics.ts @@ -0,0 +1,80 @@ +interface Stage { + calls: number; + pending: number; + totalMs: number; + lastMs?: number; + pendingSince?: number; + lastResult?: 'fulfilled' | 'rejected'; +} + +/** Observe existing promises without replacing them, adding waits, or logging on success. */ +export class FailureDiagnostics { + private readonly started = Date.now(); + private readonly stages = new Map(); + private reported = false; + + constructor( + private readonly name: string, + private readonly snapshot: () => unknown, + ) {} + + trace(name: string, operation: () => PromiseLike): PromiseLike { + const started = Date.now(); + const stage = this.stages.get(name) ?? { calls: 0, pending: 0, totalMs: 0 }; + this.stages.set(name, stage); + stage.calls++; + stage.pending++; + stage.pendingSince ??= started; + const finish = (result: 'fulfilled' | 'rejected') => { + stage.lastMs = Date.now() - started; + stage.totalMs += stage.lastMs; + stage.lastResult = result; + if (--stage.pending === 0) { + stage.pendingSince = undefined; + } + if (result === 'rejected') { + this.report(); + } + }; + try { + const pending = operation(); + void pending.then( + () => finish('fulfilled'), + () => finish('rejected'), + ); + return pending; + } catch (error) { + finish('rejected'); + throw error; + } + } + + /** Also called from teardown: a Mocha timeout does not reject the pending operation. */ + report(): void { + if (this.reported) { + return; + } + this.reported = true; + let state: unknown; + try { + state = this.snapshot(); + } catch (error) { + state = { snapshotError: String(error) }; + } + console.error( + `[test diagnostics] ${JSON.stringify({ + test: this.name, + elapsedMs: Date.now() - this.started, + stages: [...this.stages].map(([name, stage]) => ({ + name, + ...stage, + pendingMs: + stage.pendingSince === undefined + ? undefined + : Date.now() - stage.pendingSince, + })), + state, + })}`, + ); + } +} diff --git a/src/test/suite/htmlWidgetBrowser.test.ts b/src/test/suite/htmlWidgetBrowser.test.ts index 6e23f4128..16d70f9cd 100644 --- a/src/test/suite/htmlWidgetBrowser.test.ts +++ b/src/test/suite/htmlWidgetBrowser.test.ts @@ -16,6 +16,7 @@ import { import { extensionContext } from '../../extension'; import { mockExtensionContext } from '../common/mockvscode'; import { waitForValue } from '../common/sessionConnections'; +import { FailureDiagnostics } from '../common/failureDiagnostics'; const fixtureSandboxes = new Set(); const fixtureViewers = new Map< @@ -23,6 +24,97 @@ const fixtureViewers = new Map< ReturnType >(); +let widgetDiagnostics: FailureDiagnostics; +let diagnosticPanels: vscode.WebviewPanel[]; +let diagnosticMessages: Array<{ + panel: number; + message: string; + generation?: number; + href?: string; +}>; + +function observeWidgetPanel(panel: vscode.WebviewPanel): void { + const index = diagnosticPanels.push(panel) - 1; + const messages = diagnosticMessages; + const listener = panel.webview.onDidReceiveMessage((value: unknown) => { + const message = value as { message?: unknown; generation?: unknown; href?: unknown } | null; + if ( + !message || + (message.message !== 'widget/loaded' && message.message !== 'linkClicked') + ) { + return; + } + messages.push({ + panel: index, + message: message.message, + generation: typeof message.generation === 'number' ? message.generation : undefined, + href: typeof message.href === 'string' ? message.href.slice(0, 400) : undefined, + }); + if (messages.length > 16) { + messages.shift(); + } + }); + panel.onDidDispose(() => { + listener.dispose(); + }); +} + +function widgetSnapshot( + panels: vscode.WebviewPanel[], + messages: typeof diagnosticMessages, +): unknown { + const scriptFile = path.resolve(__dirname, '../../../dist/webviews/webview/index.js'); + let script: unknown; + try { + script = { file: scriptFile, bytes: fs.statSync(scriptFile).size }; + } catch (error) { + script = { file: scriptFile, error: String(error) }; + } + return { + script, + fixtureExtensionPath: extensionContext?.extensionPath ?? null, + activeTab: vscode.window.tabGroups.activeTabGroup.activeTab?.label, + messages, + panels: panels.map((panel, index) => { + try { + const injectedScript = panel.webview.html.match( + /]*data-generation=[^>]*>/i, + )?.[0]; + const entry = [...fixtureViewers.values()] + .flatMap((manager) => [...manager.viewers.values()]) + .find((entry) => entry.panel === panel); + return { + index, + title: panel.title, + active: panel.active, + visible: panel.visible, + injectedScript: injectedScript ?? null, + enableScripts: panel.webview.options.enableScripts, + localResourceRoots: panel.webview.options.localResourceRoots?.map((uri) => + uri.toString(), + ), + revision: + entry?.revision ?? + injectedScript?.match(/data-generation="(\d+)"/)?.[1] ?? + null, + loading: entry?.loading, + loadStatus: entry?.loadStatus, + }; + } catch (error) { + return { index, unavailable: String(error) }; + } + }), + }; +} + +function waitForWidget( + name: string, + condition: () => T | undefined, + timeout = 10000, +): PromiseLike { + return widgetDiagnostics.trace(name, () => waitForValue(condition, timeout)); +} + function createFixtureSandbox(): sinon.SinonSandbox { const sandbox = sinon.createSandbox(); fixtureSandboxes.add(sandbox); @@ -51,8 +143,10 @@ async function focusHtmlViewer(panel: vscode.WebviewPanel): Promise { panel.reveal(panel.viewColumn, false); // reveal() queues a workbench request. Await editor focus before running // commands, rather than relying on a possibly stale panel.active value. - await vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup'); - await waitForValue(() => + await widgetDiagnostics.trace('focus active editor group', () => + vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup'), + ); + await waitForWidget('HTML Viewer focus', () => panel.active && vscode.window.tabGroups.activeTabGroup.activeTab?.label === panel.title ? true : undefined, @@ -60,7 +154,19 @@ async function focusHtmlViewer(panel: vscode.WebviewPanel): Promise { } suite('HTML widget browser rendering', () => { - teardown(async () => { + setup(function () { + const panels: vscode.WebviewPanel[] = []; + const messages: typeof diagnosticMessages = []; + diagnosticPanels = panels; + diagnosticMessages = messages; + widgetDiagnostics = new FailureDiagnostics(this.currentTest!.fullTitle(), () => + widgetSnapshot(panels, messages), + ); + }); + teardown(async function () { + if (this.currentTest?.state === 'failed') { + widgetDiagnostics.report(); + } // Mocha timeouts do not cancel an async test body. Release its own // manager and mocks here, even if the body's finally block runs later. try { @@ -100,6 +206,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); panel.webview.onDidReceiveMessage( (message: { message?: string; generation?: number }) => { if ( @@ -123,18 +230,20 @@ suite('HTML widget browser rendering', () => { await showWebView(first, 'First', 'Two', context); const entry = [...manager.viewers.values()][0]; await focusHtmlViewer(entry.panel); - await waitForValue(() => + await waitForWidget('initial widget/loaded acknowledgement', () => acknowledgements.includes(entry.revision) ? true : undefined, ); await showWebView(blocked, 'Blocked', 'Two', context); const blockedGeneration = entry.revision; const html = entry.panel.webview.html; assert.strictEqual(entry.loading, true); - await waitForValue(() => (!entry.loading ? true : undefined)); - await waitForValue(() => (entry.loadStatus === 'unconfirmed' ? true : undefined)); + await waitForWidget('CSP navigation unlock', () => (!entry.loading ? true : undefined)); + await waitForWidget('CSP load status', () => + entry.loadStatus === 'unconfirmed' ? true : undefined, + ); // Only the active viewer updates the status item; hidden items retain their text. await focusHtmlViewer(entry.panel); - await waitForValue(() => + await waitForWidget('CSP loading status text', () => loadingStatus.text === 'HTML Viewer: Load not confirmed. Please wait or retry.' ? true : undefined, @@ -155,18 +264,20 @@ suite('HTML widget browser rendering', () => { ); await runHtmlViewerCommand('back'); assert.strictEqual(entry.state.index, 0); - await waitForValue(() => + await waitForWidget('back navigation acknowledgement', () => acknowledgements.includes(entry.revision) ? true : undefined, ); assert.ok(entry.panel.webview.html.includes('First output')); await focusHtmlViewer(entry.panel); await runHtmlViewerCommand('forward'); assert.strictEqual(entry.state.index, 1); - await waitForValue(() => (!entry.loading ? true : undefined)); + await waitForWidget('forward navigation unlock', () => + !entry.loading ? true : undefined, + ); await focusHtmlViewer(entry.panel); await runHtmlViewerCommand('remove'); assert.strictEqual(entry.state.history.length, 1); - await waitForValue(() => + await waitForWidget('remove navigation acknowledgement', () => acknowledgements.includes(entry.revision) ? true : undefined, ); } finally { @@ -199,6 +310,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); sandbox.stub(vscode.env, 'openExternal').callsFake((uri) => { @@ -236,7 +348,10 @@ suite('HTML widget browser rendering', () => { const file = path.join(directory, `${structure}.html`); fs.writeFileSync(file, html); await showWebView(file, 'History entry title', 'Two'); - const response = await waitForValue(() => result); + const response = await waitForWidget( + `document report (${structure})`, + () => result, + ); assert.strictEqual(response.path, '/document'); const observations = new URLSearchParams(response.query); assert.strictEqual(observations.get('title'), 'Authored R output', structure); @@ -289,6 +404,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); sandbox.stub(vscode.env, 'openExternal').callsFake((uri) => { @@ -342,7 +458,7 @@ suite('HTML widget browser rendering', () => { `, ); await showWebView(file, 'Authored base', 'Two'); - const response = await waitForValue(() => result); + const response = await waitForWidget('authored base resource report', () => result); assert.strictEqual(response.path, '/base'); const observations = new URLSearchParams(response.query); assert.strictEqual(observations.get('value'), 'authored base', fixture.href); @@ -425,6 +541,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); sandbox.stub(vscode.env, 'openExternal').callsFake((uri) => { @@ -467,7 +584,7 @@ suite('HTML widget browser rendering', () => { 'Two', session.getViewerSessionContext(source.sessionId), ); - const response = await waitForValue(() => result); + const response = await waitForWidget('resource scope report', () => result); assert.strictEqual( new URLSearchParams(response.query).get('access'), 'blocked', @@ -519,6 +636,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); const executeCommand = vscode.commands.executeCommand.bind(vscode.commands); @@ -564,7 +682,7 @@ suite('HTML widget browser rendering', () => { 'Two', session.getViewerSessionContext(source.sessionId), ); - const response = await waitForValue(() => result); + const response = await waitForWidget('Find key report', () => result); assert.strictEqual(response.path, '/find'); const observations = new URLSearchParams(response.query); for (const name of ['ctrl', 'cmd', 'handled']) { @@ -573,7 +691,9 @@ suite('HTML widget browser rendering', () => { for (const name of ['plain', 'shift', 'alt']) { assert.strictEqual(observations.get(name), 'false', name); } - await waitForValue(() => (findCommands === 2 ? true : undefined)); + await waitForWidget('native Find commands', () => + findCommands === 2 ? true : undefined, + ); assert.strictEqual( command.withArgs('editor.action.webvieweditor.showFind').callCount, 2, @@ -622,6 +742,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); sandbox.stub(vscode.env, 'openExternal').callsFake((uri) => { @@ -677,7 +798,7 @@ suite('HTML widget browser rendering', () => { 'Two', session.getViewerSessionContext(source.sessionId), ); - const response = await waitForValue(() => result); + const response = await waitForWidget('fragment navigation report', () => result); assert.strictEqual(response.path, '/fragments'); const observations = new URLSearchParams(response.query); for (const key of [ @@ -751,6 +872,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); // Delay replacement delivery to exercise the interval between the // options and HTML workbench messages, without delaying a clear. const webview = panel.webview; @@ -815,7 +937,7 @@ suite('HTML widget browser rendering', () => { const loaded = async (count: number) => { await Promise.all(writes); await focusHtmlViewer(panels[0]); - await waitForValue(() => + await waitForWidget(`history report ${count} and loading completion`, () => reports.length >= count && [...viewerManager.viewers.values()].some( (entry) => entry.panel === panels[0] && !entry.loading, @@ -934,6 +1056,7 @@ suite('HTML widget browser rendering', () => { sandbox.stub(vscode.window, 'createWebviewPanel').callsFake((...args) => { const panel = createPanel(...args); panels.push(panel); + observeWidgetPanel(panel); return panel; }); sandbox.stub(vscode.env, 'openExternal').callsFake((uri) => { @@ -983,20 +1106,23 @@ suite('HTML widget browser rendering', () => { const count = (name: string) => urls.filter((uri) => uri.path === `/${name}`).length; const loaded = async (name: string, previous: number) => { await focusHtmlViewer(panels.at(-1)!); - const uri = await waitForValue(() => { - const reports = urls.filter((uri) => uri.path === `/${name}`); - const latest = reports.at(-1); - const params = new URLSearchParams(latest?.query); - return reports.length > previous && - ['css', 'image', 'fetch', 'direct'].every( - (key) => params.get(key) === 'true', - ) && - [...viewerManager.viewers.values()].some( - (entry) => entry.panel === panels.at(-1) && !entry.loading, - ) - ? latest - : undefined; - }); + const uri = await waitForWidget( + `resource report for ${name} and loading completion`, + () => { + const reports = urls.filter((uri) => uri.path === `/${name}`); + const latest = reports.at(-1); + const params = new URLSearchParams(latest?.query); + return reports.length > previous && + ['css', 'image', 'fetch', 'direct'].every( + (key) => params.get(key) === 'true', + ) && + [...viewerManager.viewers.values()].some( + (entry) => entry.panel === panels.at(-1) && !entry.loading, + ) + ? latest + : undefined; + }, + ); const dimensions = new URLSearchParams(uri.query); assert.ok( Number(dimensions.get('width')) > 0 && Number(dimensions.get('height')) > 0, @@ -1100,6 +1226,7 @@ suite('HTML widget browser rendering', () => { const panel = createPanel(...args); if (panel.viewType === 'r.htmlViewer') { panels.push(panel); + observeWidgetPanel(panel); panel.webview.onDidReceiveMessage( (message: { message?: string; generation?: number }) => { if ( @@ -1162,7 +1289,7 @@ suite('HTML widget browser rendering', () => { tempdir: directory, wd: directory, }); - await waitForValue(() => (attached ? true : undefined)); + await waitForWidget('native session attachment', () => (attached ? true : undefined)); const first = path.join(directory, 'first.html'); const second = path.join(directory, 'second.html'); fs.writeFileSync( @@ -1174,7 +1301,7 @@ suite('HTML widget browser rendering', () => { 'Native second', ); notify('webview', { url: first, title: 'First' }); - const panel = await waitForValue(() => + const panel = await waitForWidget('native first output panel', () => panels[0]?.webview.html.includes('Native first') ? panels[0] : undefined, ); const run = async ( @@ -1185,7 +1312,9 @@ suite('HTML widget browser rendering', () => { Number(/data-generation="(\d+)"/.exec(viewer.webview.html)?.[1]); const ready = () => loaded.get(viewer) === generation(); await focusHtmlViewer(viewer); - await waitForValue(() => (ready() ? true : undefined)); + await waitForWidget(`native ${action} readiness`, () => + ready() ? true : undefined, + ); const key = { back: 'canGoBack', forward: 'canGoForward', @@ -1194,7 +1323,7 @@ suite('HTML widget browser rendering', () => { }[action]; // A browser acknowledgement can precede the workbench's toolbar // update. Wait for the native command to be enabled as well. - await waitForValue(() => + await waitForWidget(`native ${action} toolbar context`, () => ready() && viewer.active && contexts.get(`r.htmlViewer.${key}`) === true ? true : undefined, @@ -1203,7 +1332,7 @@ suite('HTML widget browser rendering', () => { await vscode.commands.executeCommand(`r.htmlViewer.${action}`); // Navigation must load a new document, rather than accepting the // previous page's acknowledgement if the command was ignored. - await waitForValue(() => + await waitForWidget(`native ${action} generation transition`, () => ready() && (action === 'info' || generation() > previousGeneration) ? true : undefined, @@ -1211,7 +1340,7 @@ suite('HTML widget browser rendering', () => { // Title changes reach the workbench asynchronously. Navigation // preserves focus, so check the viewer's group even if another // group becomes active before the next action refocuses it. - await waitForValue(() => + await waitForWidget('native viewer focus', () => vscode.window.tabGroups.all.find( (group) => group.viewColumn === viewer.viewColumn, )?.activeTab?.label === viewer.title @@ -1220,7 +1349,7 @@ suite('HTML widget browser rendering', () => { ); }; notify('webview', { url: second, title: 'Second' }); - await waitForValue(() => + await waitForWidget('native second output', () => panel.webview.html.includes('Native second') ? true : undefined, ); await run(panel, 'back'); diff --git a/src/test/suite/interactiveEditor.test.ts b/src/test/suite/interactiveEditor.test.ts index 097c5cd82..39bd703a0 100644 --- a/src/test/suite/interactiveEditor.test.ts +++ b/src/test/suite/interactiveEditor.test.ts @@ -10,6 +10,7 @@ import { promisify } from 'util'; import { createRequire } from 'module'; import { randomUUID } from 'crypto'; import { TestResources } from '../common/testResources'; +import { FailureDiagnostics } from '../common/failureDiagnostics'; import { SessionAgent } from '../../interactive/agentMain'; import { AgentClient } from '../../interactive/client'; import { InteractiveSerializer, DISPLAY_MIME } from '../../interactive/notebook'; @@ -239,10 +240,15 @@ suite('Interactive VS Code integration', function () { // the cleanup to finish before Mocha advances. const cleanupReserveMs = 5000; let runningTest: { test: Mocha.Runnable; started: number } | undefined; + let workspaceFocusDiagnostics: FailureDiagnostics | undefined; setup(function () { runningTest = this.currentTest && { test: this.currentTest, started: Date.now() }; }); - teardown(() => { + teardown(function () { + if (this.currentTest?.state === 'failed') { + workspaceFocusDiagnostics?.report(); + } + workspaceFocusDiagnostics = undefined; runningTest = undefined; }); const until = async ( @@ -3719,49 +3725,96 @@ par(mfrow=c(1,1))`, }); test('Workspace follows native focus and bound sources, and actions retain their displayed owner', async () => { const workspace = workspaceProvider; + let inspectedClient: AgentClient | undefined; + const diagnostics = new FailureDiagnostics('Workspace focus and displayed owner', () => ({ + activeEditor: vscode.window.activeTextEditor?.document.uri.toString() ?? null, + activeNotebook: vscode.window.activeNotebookEditor?.notebook.uri.toString() ?? null, + notebookSession: vscode.window.activeNotebookEditor?.notebook.metadata + .rSessionId as unknown, + owner: workspace().owner?.sessionId, + markerLength: workspace().data?.globalenv.workspace_marker?.length, + sessions: manifests.map(({ id, generation, status, rPid }) => ({ + id, + generation, + status, + rPid, + })), + inspectionClient: inspectedClient + ? { + connected: inspectedClient.connected, + control: inspectedClient.control, + session: inspectedClient.manifest.id, + generation: inspectedClient.manifest.generation, + status: inspectedClient.manifest.status, + } + : null, + })); + workspaceFocusDiagnostics = diagnostics; + const step = (name: string, operation: () => PromiseLike) => + diagnostics.trace(name, operation); const nodes = async (): Promise => { const provider = workspace(); - const root = (await provider.getChildren()).find((item) => item.id === 'globalenv'); - return (await provider.getChildren(root)) as GlobalEnvItem[]; + const root = (await step('workspace roots', () => provider.getChildren())).find( + (item) => item.id === 'globalenv', + ); + return (await step('workspace variables', () => + provider.getChildren(root), + )) as GlobalEnvItem[]; }; const focus = async (index: number): Promise => { - await vscode.commands.executeCommand('r.interactive.open', manifests[index]); + await step(`focus ${index}: r.interactive.open`, () => + vscode.commands.executeCommand('r.interactive.open', manifests[index]), + ); const notebook = vscode.workspace.notebookDocuments.find( (doc) => doc.metadata.rSessionId === manifests[index].id, ); assert.ok(notebook); - await vscode.commands.executeCommand( - 'interactive.open', - { preserveFocus: false }, - notebook.uri, + await step(`focus ${index}: interactive.open`, () => + vscode.commands.executeCommand( + 'interactive.open', + { preserveFocus: false }, + notebook.uri, + ), ); - await vscode.commands.executeCommand('interactive.input.focus'); - await until( - () => - workspace().owner?.sessionId === - `${manifests[index].id}:${manifests[index].generation}`, + await step(`focus ${index}: interactive.input.focus`, () => + vscode.commands.executeCommand('interactive.input.focus'), + ); + await step(`focus ${index}: owner`, () => + until( + () => + workspace().owner?.sessionId === + `${manifests[index].id}:${manifests[index].generation}`, + ), ); }; for (const index of [0, 1]) { await focus(index); - await vscode.commands.executeCommand( - 'r.runSelection', - `workspace_marker <- rep(${index}, ${index + 1}); workspace_list <- list(owner = ${index})`, + await step(`session ${index}: r.runSelection`, () => + vscode.commands.executeCommand( + 'r.runSelection', + `workspace_marker <- rep(${index}, ${index + 1}); workspace_list <- list(owner = ${index})`, + ), + ); + await step(`session ${index}: workspace marker`, () => + until(() => workspace().data?.globalenv.workspace_marker?.length === index + 1), ); - await until(() => workspace().data?.globalenv.workspace_marker?.length === index + 1); } await focus(0); const oldNode = (await nodes()).find((node) => node.label === 'workspace_marker'); assert.ok(oldNode); - const source = await vscode.workspace.openTextDocument({ - language: 'r', - content: 'workspace_marker', - }); - await vscode.window.showTextDocument(source); - await vscode.commands.executeCommand('r.interactive.bindDocument'); + const source = await step('open source document', () => + vscode.workspace.openTextDocument({ + language: 'r', + content: 'workspace_marker', + }), + ); + await step('show source document', () => vscode.window.showTextDocument(source)); + await step('bind source document', () => + vscode.commands.executeCommand('r.interactive.bindDocument'), + ); await focus(1); - await vscode.window.showTextDocument(source); - await until(() => workspace().owner === oldNode.owner); + await step('show source document', () => vscode.window.showTextDocument(source)); + await step('bound source owner', () => until(() => workspace().owner === oldNode.owner)); assert.strictEqual(workspace().data?.globalenv.workspace_marker.length, 1); const list = (await nodes()).find((node) => node.label === 'workspace_list'); assert.ok(list); @@ -3769,7 +3822,7 @@ par(mfrow=c(1,1))`, const ownerBefore = provider.owner?.sessionId; const generationBefore = (provider as unknown as { childPageGeneration: number }) .childPageGeneration; - const children = await provider.getChildren(list); + const children = await step('workspace list children', () => provider.getChildren(list)); const ownerAfter = provider.owner?.sessionId; const generationAfter = (provider as unknown as { childPageGeneration: number }) .childPageGeneration; @@ -3790,17 +3843,26 @@ par(mfrow=c(1,1))`, }), ); await focus(1); - await vscode.commands.executeCommand('r.workspaceViewer.remove', oldNode); + await step('remove displayed node', () => + vscode.commands.executeCommand('r.workspaceViewer.remove', oldNode), + ); const firstClient = new AgentClient(manifests[0]); - await firstClient.connect({ claim: false }); + inspectedClient = firstClient; + await step('inspection client connect', () => firstClient.connect({ claim: false })); try { let removed = false; const deadline = Date.now() + 10000; while (!removed && Date.now() < deadline) { - removed = !((await firstClient.snapshot()).workspace as WorkspaceData | undefined) - ?.globalenv.workspace_marker; + removed = !( + (await step('removal snapshot', () => firstClient.snapshot())).workspace as + | WorkspaceData + | undefined + )?.globalenv.workspace_marker; if (!removed) { - await new Promise((resolve) => setTimeout(resolve, 50)); + await step( + 'removal poll interval', + () => new Promise((resolve) => setTimeout(resolve, 50)), + ); } } assert.ok(removed, 'Remove applies to the displayed node owner'); @@ -3813,10 +3875,14 @@ par(mfrow=c(1,1))`, firstClient.close(); } // Closing/detaching an active view must not leave live-looking objects behind. - await vscode.commands.executeCommand('r.interactive.detach', manifests[1]); + await step('detach second session', () => + vscode.commands.executeCommand('r.interactive.detach', manifests[1]), + ); assert.strictEqual(workspace().owner, undefined); assert.deepStrictEqual(await nodes(), []); - await vscode.commands.executeCommand('r.interactive.open', manifests[0]); + await step('restore first session', () => + vscode.commands.executeCommand('r.interactive.open', manifests[0]), + ); }); test('native toolbar actions target their notebook while another session is active', async () => { await vscode.commands.executeCommand('r.interactive.open', manifests[0]);