From 7919a11cfee482fad302e9000fd56e0809657d95 Mon Sep 17 00:00:00 2001 From: tomas Date: Fri, 13 Nov 2026 03:56:44 +0000 Subject: [PATCH 1/6] feat(app-preview): answer appData() from the newest successful run GET /notebooks/:notebookId/app-data now answers from the newest successful preview run of the notebook, with Deepnote's body { appData, agentBlockSummary, runCreatedAt } and its two 404 messages. appData is the first application/json output that is an object. The agent summary is the first agent block's markdown, or its stream text, since runtime-core emits an agent's answer as stream output. dataframe() is now the only stub that warns. --- README.md | 2 +- .../deepnote/appPreview/appPreviewApi.node.ts | 89 +++++++++++++++++-- .../appPreviewApi.node.unit.test.ts | 1 - ...appPreviewCommandHandler.node.unit.test.ts | 4 - .../appPreviewSession.node.unit.test.ts | 8 +- 5 files changed, 88 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 05ae6d1a1..99c8f022c 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Run `Deepnote: Preview App` from the Command Palette, or right-click a folder in - Its code can write files and store dataframes, and what it writes is kept after the run. - A run keeps going until its notebook finishes, even after you close the preview. Reloading or closing the VS Code window stops it. - Each run's results are saved as a `.snapshot.deepnote` file in VS Code's storage for the workspace, outside the project, and are cleared the first time the app preview starts after the window reloads. -- The page's other calls to Deepnote reach a local stand-in that does not support them yet: `appData()` rejects with a message saying so, and VS Code shows a warning the first time the app calls it. +- `appData()` answers from that notebook's newest successful `run()` in the preview: the first JSON object the run displayed (an `application/json` output), the first agent block's answer, and when the run started. Until a run succeeds, it rejects with Deepnote's message. The preview keeps its list of runs in memory, so reloading or closing the VS Code window clears them. - Previewing needs a trusted workspace and the desktop app. ### Database integrations diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index 5cd2432d9..13063ef66 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -2,11 +2,14 @@ import { getInputBlockValueOverrideValidationError, isInputBlock, type DeepnoteF // TODO: Import from `@deepnote/cloud` once it exports the API's generated types. The mock package is only a // devDependency, which is fine for a type-only import because the build erases it. import type { operations } from '@deepnote/cloud-mock'; +import type { IOutput, IStream } from '@deepnote/runtime-core'; import { timingSafeEqual } from 'crypto'; import express, { type NextFunction, type Request, type Response } from 'express'; import { CancellationTokenSource } from 'vscode'; import { z } from 'zod'; +import { concatMultilineString } from '../../../platform/common/utils'; +import { isObject } from '../../../platform/common/utils/sysTypes'; import { generateUuid } from '../../../platform/common/uuid'; import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; import { logger } from '../../../platform/logging'; @@ -22,7 +25,7 @@ import type { SnapshotBlock } from './types'; -export type AppPreviewOperation = 'appData()' | 'dataframe()'; +export type AppPreviewOperation = 'dataframe()'; export interface AppPreviewApiOptions { token: string; @@ -36,6 +39,8 @@ export interface AppPreviewApiOptions { const UNAUTHORIZED_MESSAGE = 'Unauthorized'; const NOT_AVAILABLE_MESSAGE = 'This endpoint is not available to app viewer tokens'; const NOTEBOOK_NOT_FOUND_MESSAGE = 'Notebook not found'; +const NO_RUN_RESULTS_MESSAGE = 'You have no run results for this notebook yet. Run the notebook to load them.'; +const NO_JSON_OUTPUT_MESSAGE = 'Your latest run has no JSON output.'; const RUN_NOT_FOUND_MESSAGE = 'Run not found'; const PREVIEW_STOPPED_MESSAGE = 'The app preview has stopped'; const INTERNAL_ERROR_MESSAGE = 'Internal server error'; @@ -65,6 +70,35 @@ function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } +/** + * Deepnote's `agentBlockSummary`: the first agent block's first markdown output. runtime-core emits an agent's answer + * as stream output instead, so without markdown it is the block's stream text. + */ +function firstAgentBlockSummary(blocks: SnapshotBlock[]): string | null { + const agent = blocks.find((block) => block.type === 'agent'); + if (!agent) { + return null; + } + + const markdown = agent.outputs + .map((output) => mimeData(output, 'text/markdown')) + .find((data): data is string => typeof data === 'string'); + if (markdown !== undefined) { + return markdown; + } + const streams = agent.outputs.filter((output): output is IStream => output.output_type === 'stream'); + + return streams.length > 0 ? streams.map((output) => concatMultilineString(output.text)).join('') : null; +} + +/** Deepnote's `appData`: the first `application/json` output that is an object, not an array or `null`. */ +function firstJsonObject(blocks: SnapshotBlock[]): Record | undefined { + return blocks + .flatMap((block) => block.outputs) + .map((output) => mimeData(output, 'application/json')) + .find(isObject); +} + /** The input check Deepnote's `POST /v2/runs` makes before it accepts a run. */ function inputsError(notebook: DeepnoteNotebook, inputs: Record): string | undefined { const inputBlocks = notebook.blocks.filter(isInputBlock); @@ -95,6 +129,27 @@ function isAuthorized(authorizationHeader: string | undefined, token: string): b return actual.length === expected.length && timingSafeEqual(actual, expected); } +function mimeData(output: IOutput, mimeType: string): unknown { + const data: unknown = output.data; + + return isObject(data) ? data[mimeType] : undefined; +} + +function newestSuccessfulRun(runs: Map, notebookId: string): PreviewRun | undefined { + let newest: PreviewRun | undefined; + for (const run of runs.values()) { + if ( + run.notebookId === notebookId && + run.status === 'success' && + (!newest || run.createdAt >= newest.createdAt) + ) { + newest = run; + } + } + + return newest; +} + /** Deepnote's 400 message for a body that fails its schema. */ function readableErrors(error: z.ZodError): string { return error.issues @@ -140,10 +195,11 @@ function toAppViewerNotebook({ file, notebook }: WorkspaceNotebook): AppViewerNo /** * The local stand-in for Deepnote's app viewer API, mounted at `/v2` on the preview server. * Requests without the preview's bearer token get 401. `GET /notebooks/:notebookId` answers from the workspace's - * notebooks, and `POST /runs` runs one with `runner`, which `GET /runs/:runId` then reports on. The other routes - * Deepnote's client calls or is about to call get 501, and every other route gets 403, as Deepnote answers app viewer - * tokens. A body that cannot be read, such as malformed JSON, gets its 4xx; any other failure is logged and gets a JSON - * 500. + * notebooks, and `POST /runs` runs one with `runner`, which `GET /runs/:runId` then reports on. + * `GET /notebooks/:notebookId/app-data` answers from the notebook's newest successful run. The dataframe route, which + * the version of Deepnote's client that adds `dataframe()` calls, gets 501, and every other route gets 403, as Deepnote + * answers app viewer tokens. A body that cannot be read, such as malformed JSON, gets its 4xx; any other failure is + * logged and gets a JSON 500. */ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewApi { const router = express.Router(); @@ -207,7 +263,28 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp } res.json({ notebook: toAppViewerNotebook(found) }); }); - router.get('/notebooks/:notebookId/app-data', unsupported('appData()')); + router.get('/notebooks/:notebookId/app-data', async (req: Request<{ notebookId: string }>, res: Response) => { + const { notebookId } = req.params; + if (!(await options.findNotebook(notebookId))) { + res.status(404).json({ message: NOTEBOOK_NOT_FOUND_MESSAGE }); + + return; + } + const run = newestSuccessfulRun(runs, notebookId); + if (!run) { + res.status(404).json({ message: NO_RUN_RESULTS_MESSAGE }); + + return; + } + const blocks = run.snapshotStatus === 'available' ? toSnapshotBlocks(await options.runFiles.read(run.runId)) : []; + const appData = firstJsonObject(blocks); + if (!appData) { + res.status(404).json({ message: NO_JSON_OUTPUT_MESSAGE }); + + return; + } + res.json({ appData, agentBlockSummary: firstAgentBlockSummary(blocks), runCreatedAt: run.createdAt }); + }); router.post('/runs', express.json(), async (req: Request, res: Response) => { const parsed = createRunBodySchema.safeParse(req.body, { // Deepnote's error map, so a missing field reads `is required`. diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index 25d5efaaa..352109f8b 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -511,7 +511,6 @@ suite('createAppPreviewApi', () => { } const stubs: [string, string, AppPreviewOperation][] = [ - ['GET', '/notebooks/nb-1/app-data', 'appData()'], ['GET', '/projects/p-1/dataframes/sales%20by%20month', 'dataframe()'] ]; for (const [method, path, operation] of stubs) { diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts index 829b702bf..792e6f01c 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts @@ -316,14 +316,10 @@ suite('AppPreviewCommandHandler', () => { fetch(`${serverUrl()}v2${urlPath}`, { headers: { authorization: `Bearer ${token}` } }); const dataframe = () => api('/projects/project-1/dataframes/sales'); - assert.strictEqual((await api('/notebooks/nb-1/app-data')).status, 501); assert.strictEqual((await dataframe()).status, 501); // A repeated call must not warn again. assert.strictEqual((await dataframe()).status, 501); - verify( - win().showWarningMessage('The app in app called appData(), which the local preview does not support yet.') - ).once(); verify( win().showWarningMessage('The app in app called dataframe(), which the local preview does not support yet.') ).once(); diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts index 21c0ed22e..9cb7d9e90 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts @@ -368,16 +368,16 @@ suite('AppPreviewSession', () => { const session = await startSession(); const { token } = await requestToken(session); - const stub = await request(session, '/v2/notebooks/nb-1/app-data', { + const stub = await request(session, '/v2/projects/project-1/dataframes/sales', { headers: { authorization: `Bearer ${token}` } }); assert.strictEqual(stub.status, 501); assert.deepStrictEqual(JSON.parse(stub.body.toString()), { - message: 'appData() is not supported in the local preview yet.' + message: 'dataframe() is not supported in the local preview yet.' }); - sinon.assert.calledOnceWithExactly(onUnsupported, 'appData()'); + sinon.assert.calledOnceWithExactly(onUnsupported, 'dataframe()'); - assert.strictEqual((await request(session, '/v2/notebooks/nb-1/app-data')).status, 401); + assert.strictEqual((await request(session, '/v2/projects/project-1/dataframes/sales')).status, 401); }); test("answers a notebook that two files share from the session's current project folder", async () => { From 2d972a3dd544fd0f6484935c52a90dfab2286a00 Mon Sep 17 00:00:00 2001 From: tomas Date: Fri, 13 Nov 2026 04:00:34 +0000 Subject: [PATCH 2/6] test(e2e): show a previewed page's appData() before and after a run A new test previews a page that calls appData() before a run, which rejects with Deepnote's no-results message, then run(), then appData() again, which answers the run's JSON output and its createdAt. appData() no longer reaches a stub, and the hosted client has no dataframe(), so the checks for the preview's "not supported" warnings go, along with the shared page's second appData() call. --- test/e2e/fixtures/app-preview-app-data/app.js | 24 ++++ .../fixtures/app-preview-app-data/index.html | 17 +++ test/e2e/fixtures/app-preview/app.js | 1 - test/e2e/fixtures/app-preview/index.html | 1 - .../suite/appPreview/previewApp.e2e.test.ts | 114 ++++++------------ 5 files changed, 81 insertions(+), 76 deletions(-) create mode 100644 test/e2e/fixtures/app-preview-app-data/app.js create mode 100644 test/e2e/fixtures/app-preview-app-data/index.html diff --git a/test/e2e/fixtures/app-preview-app-data/app.js b/test/e2e/fixtures/app-preview-app-data/app.js new file mode 100644 index 000000000..1e0c5b94e --- /dev/null +++ b/test/e2e/fixtures/app-preview-app-data/app.js @@ -0,0 +1,24 @@ +// Shows on the page what appData() returned before and after a run, so the E2E test and its screenshot can read it. +function show(id, text) { + document.getElementById(id).textContent = text; +} + +async function call(id, label, fn) { + try { + show(id, `${label}: ${await fn()}`); + } catch (error) { + show(id, `${label} rejected: ${error.message}`); + } +} + +const notebook = window.Deepnote.connect().notebook('e2e-runs-notebook'); + +(async () => { + await call('before-run', 'appData() before a run', async () => JSON.stringify(await notebook.appData())); + await call('run', "run({ region: 'Asia' })", async () => { + const { run } = await notebook.run({ region: 'Asia' }); + + return `${run.status}, created at ${run.createdAt}`; + }); + await call('after-run', 'appData() after the run', async () => JSON.stringify(await notebook.appData())); +})(); diff --git a/test/e2e/fixtures/app-preview-app-data/index.html b/test/e2e/fixtures/app-preview-app-data/index.html new file mode 100644 index 000000000..176e2291f --- /dev/null +++ b/test/e2e/fixtures/app-preview-app-data/index.html @@ -0,0 +1,17 @@ + + + + + App data fixture + + + +

Sales results

+
    +
  • appData() before a run: pending
  • +
  • run({ region: 'Asia' }): pending
  • +
  • appData() after the run: pending
  • +
+ + + diff --git a/test/e2e/fixtures/app-preview/app.js b/test/e2e/fixtures/app-preview/app.js index 5b7961777..8073ba9ce 100644 --- a/test/e2e/fixtures/app-preview/app.js +++ b/test/e2e/fixtures/app-preview/app.js @@ -69,7 +69,6 @@ const notebook = connection.notebook('e2e-preview-notebook'); connection.notebook('e2e-missing-notebook').inputs() ); await call('app-data', 'appData()', () => notebook.appData()); - await call('app-data-again', 'appData() again', () => notebook.appData()); const deepnoteRequests = performance .getEntriesByType('resource') .filter((entry) => new URL(entry.name).hostname.endsWith('deepnote.com')); diff --git a/test/e2e/fixtures/app-preview/index.html b/test/e2e/fixtures/app-preview/index.html index 098210cd9..3037d9f1e 100644 --- a/test/e2e/fixtures/app-preview/index.html +++ b/test/e2e/fixtures/app-preview/index.html @@ -16,7 +16,6 @@

Sales dashboard

  • inputs(): pending
  • inputs() of an unknown notebook: pending
  • appData(): pending
  • -
  • appData() again: pending
  • requests to deepnote.com: pending
  • diff --git a/test/e2e/suite/appPreview/previewApp.e2e.test.ts b/test/e2e/suite/appPreview/previewApp.e2e.test.ts index 88c2eb1ab..20eafc8bc 100644 --- a/test/e2e/suite/appPreview/previewApp.e2e.test.ts +++ b/test/e2e/suite/appPreview/previewApp.e2e.test.ts @@ -9,16 +9,7 @@ import { expect } from 'chai'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { - By, - EditorView, - InputBox, - NotificationType, - SideBarView, - VSBrowser, - Workbench, - type ViewItem -} from 'vscode-extension-tester'; +import { By, EditorView, InputBox, SideBarView, VSBrowser, Workbench, type ViewItem } from 'vscode-extension-tester'; import { KERNEL_CONNECT_TIMEOUT, @@ -35,6 +26,7 @@ import { const FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview'); const RUNS_FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview-runs'); +const APP_DATA_FIXTURE_APP = path.resolve(process.cwd(), 'test', 'e2e', 'fixtures', 'app-preview-app-data'); const INPUTS_NOTEBOOK_FIXTURE = 'app-preview-inputs.deepnote'; const RUNS_NOTEBOOK_FIXTURES = ['app-preview-runs.deepnote', 'app-preview-runs-init.deepnote']; const SYNCED_APP = path.join('Sales', '.files', '_deepnote_static'); @@ -43,9 +35,12 @@ const RELOAD_TITLE = 'Reload fixture'; const REUSE_TITLE = 'Reuse fixture'; const INPUTS_TITLE = 'Inputs fixture'; const RUNS_TITLE = 'Runs fixture'; +const APP_DATA_TITLE = 'App data fixture'; const PREVIEW_URL = /^http:\/\/127\.0\.0\.1:\d+\//; -const NOT_SUPPORTED = 'which the local preview does not support yet.'; const INPUTS_RESOLVED = 'inputs() resolved: '; +const APP_DATA_AFTER_RUN = 'appData() after the run: '; + +const NO_RUN_RESULTS = 'You have no run results for this notebook yet. Run the notebook to load them.'; const NOTEBOOK_INPUTS = [ { blockId: 'e2e-region-input', name: 'region', type: 'input-text', value: 'Europe', label: 'Region' }, @@ -78,8 +73,7 @@ function expectedReport(title: string): unknown[] { 'logo: 48x48', NOTEBOOK_INPUTS, 'inputs() of an unknown notebook rejected: Notebook not found', - 'appData() rejected: appData() is not supported in the local preview yet.', - 'appData() again rejected: appData() is not supported in the local preview yet.', + `appData() rejected: ${NO_RUN_RESULTS}`, 'requests to deepnote.com: 0' ]; } @@ -90,11 +84,7 @@ function withParsedInputs(report: string[]): unknown[] { ); } -function appDataWarning(folderName: string): string { - return `The app in ${folderName} called appData(), which the local preview does not support yet.`; -} - -async function readReport(): Promise { +async function readReport(timeout = WORKBENCH_TIMEOUT): Promise { const driver = VSBrowser.instance.driver; let report: string[] = []; try { @@ -108,7 +98,7 @@ async function readReport(): Promise { return report.length > 0 && report.every((line) => !line.endsWith('pending')); }, - WORKBENCH_TIMEOUT, + timeout, 'the preview page did not finish its client calls' ); } catch (error) { @@ -170,36 +160,6 @@ async function runWithRegion( return { status, result: result === '' ? null : JSON.parse(result) }; } -/** Leaves the Notifications Center open, so the next screenshot shows the warnings. */ -async function previewWarnings(count: number): Promise { - const center = await new Workbench().openNotificationsCenter(); - let warnings: string[] = []; - try { - await VSBrowser.instance.driver.wait( - async () => { - const notifications = await center.getNotifications(NotificationType.Warning).catch(() => []); - const messages = await Promise.all(notifications.map((n) => n.getMessage().catch(() => ''))); - warnings = messages.filter((message) => message.endsWith(NOT_SUPPORTED)); - - return warnings.length >= count; - }, - WORKBENCH_TIMEOUT, - `fewer than ${count} preview warnings arrived` - ); - } catch (error) { - await center.close().catch(() => undefined); - throw new Error(`${(error as Error).message}. Seen: ${JSON.stringify(warnings)}`); - } - - return warnings; -} - -async function clearNotifications(): Promise { - const center = await new Workbench().openNotificationsCenter(); - await center.clearAllNotifications(); - await center.close().catch(() => undefined); -} - async function findRootExplorerItem(label: string): Promise { await openActivityBarView('Explorer'); let found: ViewItem | undefined; @@ -289,8 +249,8 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow /** * Each test, and each attempt Mocha retries, gets a folder no earlier attempt previewed: the extension keeps one - * preview session per folder while it runs, a session warns about each unsupported operation only once, and two - * tests edit their page. The page titles tell the integrated browser windows apart. + * preview session per folder while it runs, and two tests edit their page. The page titles tell the integrated + * browser windows apart. */ function addAppFolder(title: string): string { const appDir = fs.mkdtempSync(path.join(workspaceDir, 'app-')); @@ -330,7 +290,6 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow it("opens the folder from the Explorer in the integrated browser, with its assets and the bundled copy of Deepnote's client", async function () { const screenshot = createScreenshotter(this); const appDir = addAppFolder('Preview fixture'); - await clearNotifications(); await selectDeepnoteContextMenu(await findRootExplorerItem(path.basename(appDir)), 'Preview App'); @@ -342,19 +301,13 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow }); expect(report).to.deep.equal(expectedReport('Sales dashboard')); expect(await new EditorView().getOpenEditorTitles()).to.deep.equal(['Preview fixture']); - - expect(await previewWarnings(1)).to.deep.equal([appDataWarning(path.basename(appDir))]); - await screenshot('app-data-warning'); }); - it('shows an edit after a reload, and does not warn again', async function () { + it('shows an edit after a reload', async function () { const screenshot = createScreenshotter(this); const appDir = addAppFolder(RELOAD_TITLE); - await clearNotifications(); await selectDeepnoteContextMenu(await findRootExplorerItem(path.basename(appDir)), 'Preview App'); await onIntegratedBrowserPage(RELOAD_TITLE, readReport); - await previewWarnings(1); - await clearNotifications(); const indexFile = path.join(appDir, 'index.html'); fs.writeFileSync( @@ -370,10 +323,6 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow }); expect(report).to.deep.equal(expectedReport('Sales dashboard, edited')); - const center = await new Workbench().openNotificationsCenter(); - const warnings = await center.getNotifications(NotificationType.Warning); - expect(warnings).to.have.length(0); - await center.close(); }); it('answers inputs() from the .deepnote file as saved on disk, after an edit and a reload', async function () { @@ -414,7 +363,6 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow it("runs the workspace notebook with each run's inputs, after its init notebook, and reports its result or its error", async function () { const screenshot = createScreenshotter(this); - await clearNotifications(); const appDir = fs.mkdtempSync(path.join(workspaceDir, 'runs-app-')); fs.cpSync(RUNS_FIXTURE_APP, appDir, { recursive: true }); @@ -435,14 +383,35 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow // The notebook displays its result before the block that raises, in Deepnote's block order. { status: 'error, ValueError: Choose a region first', result: { region: '', init_region: false } } ]); + }); - const center = await new Workbench().openNotificationsCenter(); - const messages = await Promise.all( - (await center.getNotifications(NotificationType.Warning)).map((notification) => notification.getMessage()) - ); - expect(messages.filter((message) => message.endsWith(NOT_SUPPORTED))).to.deep.equal([]); - await screenshot('no-run-warning'); - await center.close(); + it("answers appData() from the notebook's newest successful run: none before a run, then its JSON output", async function () { + const screenshot = createScreenshotter(this); + const appDir = fs.mkdtempSync(path.join(workspaceDir, 'app-data-app-')); + fs.cpSync(APP_DATA_FIXTURE_APP, appDir, { recursive: true }); + const startedAt = Date.now(); + + await selectDeepnoteContextMenu(await findRootExplorerItem(path.basename(appDir)), 'Preview App'); + + const report = await onIntegratedBrowserPage(APP_DATA_TITLE, async () => { + const read = await readReport(KERNEL_CONNECT_TIMEOUT); + await screenshot('app-data-after-run'); + + return read; + }); + const lines = report.map((line) => { + const text = String(line); + + return text.startsWith(APP_DATA_AFTER_RUN) ? JSON.parse(text.slice(APP_DATA_AFTER_RUN.length)) : text; + }); + const createdAt = /, created at (\S+)$/.exec(String(lines[2]))?.[1]; + expect(lines).to.deep.equal([ + 'Sales results', + `appData() before a run rejected: ${NO_RUN_RESULTS}`, + `run({ region: 'Asia' }): success, created at ${createdAt}`, + { appData: { region: 'Asia', init_region: false }, agentBlockSummary: null, runCreatedAt: createdAt } + ]); + expect(Date.parse(createdAt ?? ''), `the run's createdAt, ${createdAt}`).to.be.within(startedAt, Date.now()); }); it('switches to the open tab and reloads it when the same folder is previewed again', async function () { @@ -481,7 +450,6 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow const screenshot = createScreenshotter(this); const syncedDir = fs.mkdtempSync(path.join(workspaceDir, 'synced-')); copyRetitledApp(path.join(syncedDir, SYNCED_APP), SYNCED_TITLE); - await clearNotifications(); await previewFromCommandPalette(path.join(syncedDir, SYNCED_APP)); @@ -493,7 +461,5 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow }); expect(report).to.deep.equal(expectedReport('Sales dashboard')); - expect(await previewWarnings(1)).to.deep.equal([appDataWarning('_deepnote_static')]); - await screenshot('synced-app-warnings'); }); }); From d2c1ac021ad7cd59302030e682a9244eea0f89eb Mon Sep 17 00:00:00 2001 From: tomas Date: Mon, 23 Nov 2026 17:33:50 +0000 Subject: [PATCH 3/6] fix(app-preview): type the appData() body's JSON checks Wrap isObject in a guard typed as Record. Its own `obj is any` guard turned off type checking in the functions that build the appData() body. --- src/notebooks/deepnote/appPreview/appPreviewApi.node.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index 13063ef66..84064e2a1 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -96,7 +96,7 @@ function firstJsonObject(blocks: SnapshotBlock[]): Record | und return blocks .flatMap((block) => block.outputs) .map((output) => mimeData(output, 'application/json')) - .find(isObject); + .find(isJsonObject); } /** The input check Deepnote's `POST /v2/runs` makes before it accepts a run. */ @@ -129,10 +129,15 @@ function isAuthorized(authorizationHeader: string | undefined, token: string): b return actual.length === expected.length && timingSafeEqual(actual, expected); } +// isObject's own guard is `obj is any`, which would switch off type checking where it narrows. +function isJsonObject(value: unknown): value is Record { + return isObject(value); +} + function mimeData(output: IOutput, mimeType: string): unknown { const data: unknown = output.data; - return isObject(data) ? data[mimeType] : undefined; + return isJsonObject(data) ? data[mimeType] : undefined; } function newestSuccessfulRun(runs: Map, notebookId: string): PreviewRun | undefined { From 7f36b0158bd23d76602efd6b06fc1bb737afc0be Mon Sep 17 00:00:00 2001 From: tomas Date: Mon, 23 Nov 2026 18:11:29 +0000 Subject: [PATCH 4/6] feat(app-preview): keep each notebook's latest run for appData() across window reloads Each successful run's file is also copied to /appPreview/latest/.snapshot.deepnote, which the per-window clear of runs/ leaves alone. GET /notebooks/:notebookId/app-data reads only that copy, never the in-memory runs, so appData() still answers after the window reloads, as Deepnote answers from its stored run snapshots. runCreatedAt is the file's execution.startedAt. Copies are made one at a time, and a run older than the notebook's last copied one is skipped, so when runs overlap the run created last wins. The copy settles before GET /runs/:runId reports the success, so appData() called after run() resolves answers from that run. A success whose run file was not written leaves the previous copy in place. The E2E no longer calls appData() before its run: the runs test before it leaves a copy for the same notebook, and so does a retry. --- README.md | 2 +- .../deepnote/appPreview/appPreviewApi.node.ts | 41 ++-- .../appPreviewApi.node.unit.test.ts | 185 ++++++++++++++++++ .../appPreview/appPreviewRunFiles.node.ts | 57 +++++- .../appPreviewRunFiles.node.unit.test.ts | 96 +++++++++ test/e2e/fixtures/app-preview-app-data/app.js | 3 +- .../fixtures/app-preview-app-data/index.html | 1 - .../suite/appPreview/previewApp.e2e.test.ts | 5 +- 8 files changed, 357 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 99c8f022c..d282dae15 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Run `Deepnote: Preview App` from the Command Palette, or right-click a folder in - Its code can write files and store dataframes, and what it writes is kept after the run. - A run keeps going until its notebook finishes, even after you close the preview. Reloading or closing the VS Code window stops it. - Each run's results are saved as a `.snapshot.deepnote` file in VS Code's storage for the workspace, outside the project, and are cleared the first time the app preview starts after the window reloads. -- `appData()` answers from that notebook's newest successful `run()` in the preview: the first JSON object the run displayed (an `application/json` output), the first agent block's answer, and when the run started. Until a run succeeds, it rejects with Deepnote's message. The preview keeps its list of runs in memory, so reloading or closing the VS Code window clears them. +- `appData()` answers from that notebook's last successful `run()`: the first JSON object the run displayed (an `application/json` output), the first agent block's answer, and when the run started. Until a run succeeds, it rejects with Deepnote's message. A copy of each notebook's last successful run is saved in the same storage and kept when the window reloads, so `appData()` still answers after a reload. - Previewing needs a trusted workspace and the desktop app. ### Database integrations diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index 84064e2a1..f1e5356fd 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -140,21 +140,6 @@ function mimeData(output: IOutput, mimeType: string): unknown { return isJsonObject(data) ? data[mimeType] : undefined; } -function newestSuccessfulRun(runs: Map, notebookId: string): PreviewRun | undefined { - let newest: PreviewRun | undefined; - for (const run of runs.values()) { - if ( - run.notebookId === notebookId && - run.status === 'success' && - (!newest || run.createdAt >= newest.createdAt) - ) { - newest = run; - } - } - - return newest; -} - /** Deepnote's 400 message for a body that fails its schema. */ function readableErrors(error: z.ZodError): string { return error.issues @@ -201,10 +186,10 @@ function toAppViewerNotebook({ file, notebook }: WorkspaceNotebook): AppViewerNo * The local stand-in for Deepnote's app viewer API, mounted at `/v2` on the preview server. * Requests without the preview's bearer token get 401. `GET /notebooks/:notebookId` answers from the workspace's * notebooks, and `POST /runs` runs one with `runner`, which `GET /runs/:runId` then reports on. - * `GET /notebooks/:notebookId/app-data` answers from the notebook's newest successful run. The dataframe route, which - * the version of Deepnote's client that adds `dataframe()` calls, gets 501, and every other route gets 403, as Deepnote - * answers app viewer tokens. A body that cannot be read, such as malformed JSON, gets its 4xx; any other failure is - * logged and gets a JSON 500. + * `GET /notebooks/:notebookId/app-data` answers from the notebook's latest successful run that `runFiles` saved. The + * dataframe route, which the version of Deepnote's client that adds `dataframe()` calls, gets 501, and every other + * route gets 403, as Deepnote answers app viewer tokens. A body that cannot be read, such as malformed JSON, gets its + * 4xx; any other failure is logged and gets a JSON 500. */ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewApi { const router = express.Router(); @@ -235,7 +220,11 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp outcome.file && (await options.runFiles.write(run.runId, outcome.file)) ? 'available' : 'unavailable'; - // Set after the write settles, so that a poll never sees a finished run whose file is being written. + if (outcome.status === 'success' && snapshotStatus === 'available') { + await options.runFiles.updateLatest(run.notebookId, run.runId, run.createdAt); + } + // Set after the files settle, so that a poll never sees a finished run whose file is being written, nor + // a success that appData() does not answer from yet. run.status = outcome.status; run.error = outcome.error; run.snapshotStatus = snapshotStatus; @@ -275,20 +264,24 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp return; } - const run = newestSuccessfulRun(runs, notebookId); - if (!run) { + const file = await options.runFiles.readLatest(notebookId); + if (!file) { res.status(404).json({ message: NO_RUN_RESULTS_MESSAGE }); return; } - const blocks = run.snapshotStatus === 'available' ? toSnapshotBlocks(await options.runFiles.read(run.runId)) : []; + const blocks = toSnapshotBlocks(file); const appData = firstJsonObject(blocks); if (!appData) { res.status(404).json({ message: NO_JSON_OUTPUT_MESSAGE }); return; } - res.json({ appData, agentBlockSummary: firstAgentBlockSummary(blocks), runCreatedAt: run.createdAt }); + res.json({ + appData, + agentBlockSummary: firstAgentBlockSummary(blocks), + runCreatedAt: file.execution?.startedAt ?? null + }); }); router.post('/runs', express.json(), async (req: Request, res: Response) => { const parsed = createRunBodySchema.safeParse(req.body, { diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index 352109f8b..3730c730d 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -1,3 +1,5 @@ +import type { DeepnoteBlock, DeepnoteFile } from '@deepnote/blocks'; +import type { IDisplayData, IOutput, IStream } from '@deepnote/runtime-core'; import { assert } from 'chai'; import express from 'express'; import * as http from 'http'; @@ -92,6 +94,30 @@ const RUN_FILE = createDeepnoteFile({ }) }); +function codeBlock(id: string, outputs: IOutput[]): DeepnoteBlock { + return createDeepnoteBlock({ id, sortingKey: id, outputs }); +} + +function agentBlock(id: string, outputs: IOutput[]): DeepnoteBlock { + return { + id, + type: 'agent', + blockGroup: 'g', + sortingKey: id, + content: '', + metadata: { deepnote_agent_model: 'auto' }, + outputs + }; +} + +function display(data: IDisplayData['data']): IDisplayData { + return { output_type: 'display_data', data, metadata: {} }; +} + +function stdout(text: string): IStream { + return { output_type: 'stream', name: 'stdout', text }; +} + suite('createAppPreviewApi', () => { let server: http.Server; let baseUrl: string; @@ -117,6 +143,8 @@ suite('createAppPreviewApi', () => { runFiles = mock(AppPreviewRunFiles); when(runFiles.write(anything(), anything())).thenResolve(true); when(runFiles.read(anything())).thenResolve(RUN_FILE); + when(runFiles.updateLatest(anything(), anything(), anything())).thenResolve(); + when(runFiles.readLatest(anything())).thenResolve(undefined); api = createAppPreviewApi({ token: TOKEN, findNotebook, @@ -320,6 +348,7 @@ suite('createAppPreviewApi', () => { completedAt: '2026-01-02T03:05:10.000Z' }); verify(runFiles.write(runId, RUN_FILE)).once(); + verify(runFiles.updateLatest('nb-1', runId, NOW)).once(); sinon.assert.notCalled(onUnsupported); }); @@ -343,6 +372,7 @@ suite('createAppPreviewApi', () => { }); assert.isString(finished.completedAt); verify(runFiles.write(anything(), anything())).times(writes); + verify(runFiles.updateLatest(anything(), anything(), anything())).never(); }); } @@ -374,6 +404,26 @@ suite('createAppPreviewApi', () => { }); }); + test("GET /runs/:runId reports a success as running until its notebook's latest results are updated", async () => { + const updateStarted = createDeferred(); + const updated = createDeferred(); + when(runFiles.updateLatest(anything(), anything(), anything())).thenCall(() => { + updateStarted.resolve(); + + return updated.promise; + }); + const { runId, outcome } = await startRun(); + const [, , onRunning] = capture(runner.run).last(); + onRunning(); + + outcome.resolve({ status: 'success', error: null, file: RUN_FILE }); + await updateStarted.promise; + + assert.deepInclude(await getRun(runId), { status: 'running', snapshotStatus: 'pending', completedAt: null }); + updated.resolve(); + assert.deepInclude(await waitForStatus(runId, 'success'), { snapshotStatus: 'available' }); + }); + test('GET /runs/:runId reports a success whose file could not be written with its snapshot unavailable', async () => { when(runFiles.write(anything(), anything())).thenResolve(false); @@ -385,6 +435,7 @@ suite('createAppPreviewApi', () => { snapshotStatus: 'unavailable', snapshotBlocks: null }); + verify(runFiles.updateLatest(anything(), anything(), anything())).never(); }); test('GET /runs/:runId answers a JSON 500, and logs the error, when the run file cannot be read', async () => { @@ -510,6 +561,140 @@ suite('createAppPreviewApi', () => { }); } + suite('GET /notebooks/:notebookId/app-data', () => { + const NO_RUN_RESULTS = { + message: 'You have no run results for this notebook yet. Run the notebook to load them.' + }; + const LATEST_STARTED_AT = '2026-01-01T09:00:00.000Z'; + + function latestFile(blocks: DeepnoteBlock[]): DeepnoteFile { + return createDeepnoteFile({ + execution: { startedAt: LATEST_STARTED_AT, finishedAt: '2026-01-01T09:00:04.000Z' }, + project: createDeepnoteProject({ notebooks: [createDeepnoteNotebook({ id: 'nb-1', blocks })] }) + }); + } + + function jsonBlock(json: Record): DeepnoteBlock { + return codeBlock('chart', [display({ 'application/json': json })]); + } + + function getAppData(notebookId = 'nb-1'): Promise { + return call('GET', `/notebooks/${notebookId}/app-data`); + } + + test('answers 404 when the notebook has no latest results, though this preview ran it', async () => { + await finishRun('success'); + + await assertJson(await getAppData(), 404, NO_RUN_RESULTS); + }); + + test("answers the latest results' first JSON object and when that run started, not this preview's own run", async () => { + await finishRun('success'); + when(runFiles.readLatest('nb-1')).thenResolve(latestFile([jsonBlock({ total: 2 })])); + + await assertJson(await getAppData(), 200, { + appData: { total: 2 }, + agentBlockSummary: null, + runCreatedAt: LATEST_STARTED_AT + }); + sinon.assert.notCalled(onUnsupported); + }); + + test('answers the first JSON object across blocks and their outputs, skipping a JSON array and null', async () => { + when(runFiles.readLatest('nb-1')).thenResolve( + latestFile([ + codeBlock('regions', [ + stdout('loading'), + { output_type: 'display_data', data: { 'application/json': null }, metadata: {} }, + display({ 'application/json': ['north'] }) + ]), + codeBlock('chart', [ + display({ 'text/plain': 'chart' }), + display({ 'application/json': { total: 3 } }), + display({ 'application/json': { total: 4 } }) + ]), + jsonBlock({ total: 5 }) + ]) + ); + + await assertJson(await getAppData(), 200, { + appData: { total: 3 }, + agentBlockSummary: null, + runCreatedAt: LATEST_STARTED_AT + }); + }); + + test('answers 404 when the latest results have no JSON object, though their text and stream look like one', async () => { + when(runFiles.readLatest('nb-1')).thenResolve( + latestFile([ + codeBlock('chart', [ + stdout('{"total": 2}'), + display({ 'text/plain': '{"total": 2}', 'application/json': ['total'] }) + ]) + ]) + ); + + await assertJson(await getAppData(), 404, { message: 'Your latest run has no JSON output.' }); + }); + + const agentSummaries: [string, DeepnoteBlock[], string | null][] = [ + [ + 'its first markdown output, ahead of its stream text', + [ + agentBlock('agent', [ + stdout('Looking at sales'), + display({ 'text/markdown': '**Sales grew.**' }), + display({ 'text/markdown': 'More detail' }) + ]) + ], + '**Sales grew.**' + ], + [ + "its stream text when it has no markdown output, not a later agent block's markdown", + [ + agentBlock('agent', [stdout('Sales grew '), stdout('by 5%.')]), + agentBlock('second-agent', [display({ 'text/markdown': 'Second answer' })]) + ], + 'Sales grew by 5%.' + ], + [ + 'null when it has neither a markdown nor a stream output', + [agentBlock('agent', [display({ 'text/plain': 'Sales grew.' })])], + null + ], + [ + 'null when no block is an agent block, though a code block displays markdown', + [codeBlock('notes', [display({ 'text/markdown': '# Notes' })])], + null + ] + ]; + for (const [condition, blocks, summary] of agentSummaries) { + test(`summarizes the first agent block as ${condition}`, async () => { + when(runFiles.readLatest('nb-1')).thenResolve(latestFile([...blocks, jsonBlock({ total: 3 })])); + + await assertJson(await getAppData(), 200, { + appData: { total: 3 }, + agentBlockSummary: summary, + runCreatedAt: LATEST_STARTED_AT + }); + }); + } + + test('answers 404 for an ID no workspace notebook has, without reading any results', async () => { + await assertJson(await getAppData('nb-deleted'), 404, { message: 'Notebook not found' }); + verify(runFiles.readLatest(anything())).never(); + }); + + test('answers a JSON 500, and logs the error, when the latest results cannot be read', async () => { + const logError = sinon.stub(logger, 'error'); + const readFailure = new Error('The latest results do not parse'); + when(runFiles.readLatest(anything())).thenReject(readFailure); + + await assertJson(await getAppData(), 500, { message: 'Internal server error' }); + sinon.assert.calledOnceWithExactly(logError, sinon.match.string, readFailure); + }); + }); + const stubs: [string, string, AppPreviewOperation][] = [ ['GET', '/projects/p-1/dataframes/sales%20by%20month', 'dataframe()'] ]; diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts index 2f996ed05..333b8e07d 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts @@ -1,4 +1,5 @@ import type { DeepnoteFile } from '@deepnote/blocks'; +import { encodeNotebookIdForFilename } from '@deepnote/convert'; import { Uri, workspace } from 'vscode'; import { isFileNotFoundError } from '../../../platform/common/platform/errors'; @@ -7,17 +8,24 @@ import { logger } from '../../../platform/logging'; import { encodeSnapshotFile, ensureSnapshotsDirectory, SNAPSHOT_FILE_SUFFIX } from '../snapshots/snapshotFiles'; const APP_PREVIEW_FOLDER = 'appPreview'; +const LATEST_FOLDER = 'latest'; const RUNS_FOLDER = 'runs'; /** - * The app preview's run files, `/appPreview/runs/.snapshot.deepnote`. Create one per window: - * constructing it starts clearing the runs folder in the background, and every write waits for that clear. + * The app preview's run files, `/appPreview/runs/.snapshot.deepnote`, and a copy of each notebook's + * latest successful run, `/appPreview/latest/.snapshot.deepnote`, the ID encoded for a file + * name. Create one per window: constructing it starts clearing the runs folder in the background, and every write + * waits for that clear. The latest copies are never cleared, so they outlive the window. */ export class AppPreviewRunFiles { private readonly clearing: Promise; + private readonly latestCreatedAt = new Map(); + private readonly latestDir: Uri; + private latestUpdates: Promise = Promise.resolve(); private readonly runsDir: Uri; constructor(storageUri: Uri) { + this.latestDir = Uri.joinPath(storageUri, APP_PREVIEW_FOLDER, LATEST_FOLDER); this.runsDir = Uri.joinPath(storageUri, APP_PREVIEW_FOLDER, RUNS_FOLDER); this.clearing = this.clear(); } @@ -27,6 +35,29 @@ export class AppPreviewRunFiles { return readDeepnoteProjectFile(this.fileOf(runId)); } + /** Reads the latest copy of `notebookId`; resolves `undefined` when it has none, and rejects on any other failure. */ + public async readLatest(notebookId: string): Promise { + try { + return await readDeepnoteProjectFile(this.latestFileOf(notebookId)); + } catch (error) { + if (error instanceof Error && isFileNotFoundError(error)) { + return undefined; + } + throw error; + } + } + + /** + * Copies the file of `runId` to the latest copy of `notebookId`, unless a run of the notebook created after + * `createdAt` was copied already, so overlapping runs leave the one created last. Copies are made one at a time; + * resolves once this one settles, never rejects. + */ + public updateLatest(notebookId: string, runId: string, createdAt: string): Promise { + this.latestUpdates = this.latestUpdates.then(() => this.copyToLatest(notebookId, runId, createdAt)); + + return this.latestUpdates; + } + /** Writes `file` as the file of `runId` once the clear settles; resolves whether it was written, never rejects. */ public async write(runId: string, file: DeepnoteFile): Promise { await this.clearing; @@ -56,7 +87,29 @@ export class AppPreviewRunFiles { } } + private async copyToLatest(notebookId: string, runId: string, createdAt: string): Promise { + const copiedCreatedAt = this.latestCreatedAt.get(notebookId); + // toISOString() timestamps are fixed-width UTC, so they compare chronologically as strings. + if (copiedCreatedAt !== undefined && createdAt < copiedCreatedAt) { + return; + } + if (!(await ensureSnapshotsDirectory(this.latestDir))) { + return; + } + + try { + await workspace.fs.copy(this.fileOf(runId), this.latestFileOf(notebookId), { overwrite: true }); + this.latestCreatedAt.set(notebookId, createdAt); + } catch (error) { + logger.error(`AppPreviewRunFiles: Could not save run ${runId} as its notebook's latest results`, error); + } + } + private fileOf(runId: string): Uri { return Uri.joinPath(this.runsDir, `${runId}${SNAPSHOT_FILE_SUFFIX}`); } + + private latestFileOf(notebookId: string): Uri { + return Uri.joinPath(this.latestDir, `${encodeNotebookIdForFilename(notebookId)}${SNAPSHOT_FILE_SUFFIX}`); + } } diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts index 47317de17..074736677 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts @@ -13,12 +13,14 @@ import { createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; +import { encodeSnapshotFile } from '../snapshots/snapshotFiles'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; use(chaiAsPromised); const STORAGE = Uri.file('/storage'); const RUN_FILE_PATH = '/storage/appPreview/runs/run-1.snapshot.deepnote'; +const LATEST_FILE_PATH = '/storage/appPreview/latest/nb%2F1.snapshot.deepnote'; const RUN_FILE = createDeepnoteFile({ execution: { startedAt: '2026-01-02T03:04:05.000Z', finishedAt: '2026-01-02T03:04:09.000Z' }, @@ -47,6 +49,12 @@ suite('AppPreviewRunFiles', () => { assert.strictEqual(capture(mockFs.writeFile).last()[0].fsPath, RUN_FILE_PATH); } + function copiedPaths(call: number): [string, string] { + const [source, target] = capture(mockFs.copy).byCallIndex(call); + + return [source.fsPath, target.fsPath]; + } + setup(() => { resetVSCodeMocks(); mockFs = mock(); @@ -54,6 +62,7 @@ suite('AppPreviewRunFiles', () => { when(mockFs.stat(anything())).thenReject(FileSystemError.FileNotFound()); when(mockFs.createDirectory(anything())).thenResolve(); when(mockFs.writeFile(anything(), anything())).thenResolve(); + when(mockFs.copy(anything(), anything(), anything())).thenResolve(); when(mockFs.readFile(anything())).thenReject(FileSystemError.FileNotFound()); when(mockedVSCodeNamespaces.workspace.fs).thenReturn(instance(mockFs)); }); @@ -152,4 +161,91 @@ suite('AppPreviewRunFiles', () => { test('rejects reading a run that has no file', async () => { await assert.isRejected(new AppPreviewRunFiles(STORAGE).read('run-unknown')); }); + + test("copies a run's file over its notebook's latest copy, named by the encoded notebook ID", async () => { + await new AppPreviewRunFiles(STORAGE).updateLatest('nb/1', 'run-1', '2026-01-02T03:04:05.000Z'); + + verify(mockFs.copy(anything(), anything(), anything())).once(); + assert.deepStrictEqual(copiedPaths(0), [RUN_FILE_PATH, LATEST_FILE_PATH]); + assert.deepStrictEqual(capture(mockFs.copy).last()[2], { overwrite: true }); + }); + + test("keeps each notebook's run created last when an older run finishes after it, even while its copy is in flight", async () => { + const runFiles = new AppPreviewRunFiles(STORAGE); + + await Promise.all([ + runFiles.updateLatest('nb/1', 'run-newer', '2026-01-02T03:05:05.000Z'), + runFiles.updateLatest('nb/1', 'run-older', '2026-01-02T03:04:05.000Z'), + runFiles.updateLatest('nb-2', 'run-other-notebook', '2026-01-02T03:04:05.000Z') + ]); + + verify(mockFs.copy(anything(), anything(), anything())).twice(); + assert.deepStrictEqual(copiedPaths(0), [ + '/storage/appPreview/runs/run-newer.snapshot.deepnote', + LATEST_FILE_PATH + ]); + assert.deepStrictEqual(copiedPaths(1), [ + '/storage/appPreview/runs/run-other-notebook.snapshot.deepnote', + '/storage/appPreview/latest/nb-2.snapshot.deepnote' + ]); + }); + + test('logs an error naming the run when the copy fails, and still copies an older run of the notebook after it', async () => { + const logError = sinon.stub(logger, 'error'); + const copyFailure = new Error('Disk full'); + when(mockFs.copy(anything(), anything(), anything())) + .thenReject(copyFailure) + .thenResolve(); + const runFiles = new AppPreviewRunFiles(STORAGE); + + await runFiles.updateLatest('nb/1', 'run-newer', '2026-01-02T03:05:05.000Z'); + await runFiles.updateLatest('nb/1', 'run-older', '2026-01-02T03:04:05.000Z'); + + sinon.assert.calledOnce(logError); + assert.include(logError.firstCall.args[0], 'run-newer'); + assert.strictEqual(logError.firstCall.args[1], copyFailure); + verify(mockFs.copy(anything(), anything(), anything())).twice(); + assert.deepStrictEqual(copiedPaths(1), [ + '/storage/appPreview/runs/run-older.snapshot.deepnote', + LATEST_FILE_PATH + ]); + }); + + test('copies nothing when the latest folder cannot be created', async () => { + when(mockFs.createDirectory(anything())).thenReject(new Error('Permission denied')); + + await new AppPreviewRunFiles(STORAGE).updateLatest('nb/1', 'run-1', '2026-01-02T03:04:05.000Z'); + + verify(mockFs.copy(anything(), anything(), anything())).never(); + }); + + test("reads a notebook's latest copy, named by the encoded notebook ID", async () => { + when(mockFs.readFile(anything())).thenReturn(Promise.resolve(encodeSnapshotFile(RUN_FILE))); + + const file = await new AppPreviewRunFiles(STORAGE).readLatest('nb/1'); + + assert.strictEqual(capture(mockFs.readFile).last()[0].fsPath, LATEST_FILE_PATH); + assert.deepStrictEqual(file?.execution, { + startedAt: '2026-01-02T03:04:05.000Z', + finishedAt: '2026-01-02T03:04:09.000Z' + }); + }); + + test('keeps the latest copies of earlier windows when it deletes their runs', async () => { + await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE); + + verify(mockFs.delete(anything(), anything())).once(); + assert.strictEqual(capture(mockFs.delete).last()[0].fsPath, '/storage/appPreview/runs'); + }); + + test('resolves undefined reading the latest copy of a notebook that has none', async () => { + assert.isUndefined(await new AppPreviewRunFiles(STORAGE).readLatest('nb/1')); + }); + + test('rejects reading a latest copy that cannot be read for another reason', async () => { + const readFailure = new Error('Permission denied'); + when(mockFs.readFile(anything())).thenReject(readFailure); + + await assert.isRejected(new AppPreviewRunFiles(STORAGE).readLatest('nb/1'), readFailure); + }); }); diff --git a/test/e2e/fixtures/app-preview-app-data/app.js b/test/e2e/fixtures/app-preview-app-data/app.js index 1e0c5b94e..d1ea2cc05 100644 --- a/test/e2e/fixtures/app-preview-app-data/app.js +++ b/test/e2e/fixtures/app-preview-app-data/app.js @@ -1,4 +1,4 @@ -// Shows on the page what appData() returned before and after a run, so the E2E test and its screenshot can read it. +// Shows on the page what appData() returned after a run, so the E2E test and its screenshot can read it. function show(id, text) { document.getElementById(id).textContent = text; } @@ -14,7 +14,6 @@ async function call(id, label, fn) { const notebook = window.Deepnote.connect().notebook('e2e-runs-notebook'); (async () => { - await call('before-run', 'appData() before a run', async () => JSON.stringify(await notebook.appData())); await call('run', "run({ region: 'Asia' })", async () => { const { run } = await notebook.run({ region: 'Asia' }); diff --git a/test/e2e/fixtures/app-preview-app-data/index.html b/test/e2e/fixtures/app-preview-app-data/index.html index 176e2291f..aca35e953 100644 --- a/test/e2e/fixtures/app-preview-app-data/index.html +++ b/test/e2e/fixtures/app-preview-app-data/index.html @@ -8,7 +8,6 @@

    Sales results

      -
    • appData() before a run: pending
    • run({ region: 'Asia' }): pending
    • appData() after the run: pending
    diff --git a/test/e2e/suite/appPreview/previewApp.e2e.test.ts b/test/e2e/suite/appPreview/previewApp.e2e.test.ts index 20eafc8bc..984c30e0c 100644 --- a/test/e2e/suite/appPreview/previewApp.e2e.test.ts +++ b/test/e2e/suite/appPreview/previewApp.e2e.test.ts @@ -385,7 +385,7 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow ]); }); - it("answers appData() from the notebook's newest successful run: none before a run, then its JSON output", async function () { + it("answers appData() from the notebook's latest successful run: its JSON output and when the run started", async function () { const screenshot = createScreenshotter(this); const appDir = fs.mkdtempSync(path.join(workspaceDir, 'app-data-app-')); fs.cpSync(APP_DATA_FIXTURE_APP, appDir, { recursive: true }); @@ -404,10 +404,9 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow return text.startsWith(APP_DATA_AFTER_RUN) ? JSON.parse(text.slice(APP_DATA_AFTER_RUN.length)) : text; }); - const createdAt = /, created at (\S+)$/.exec(String(lines[2]))?.[1]; + const createdAt = /, created at (\S+)$/.exec(String(lines[1]))?.[1]; expect(lines).to.deep.equal([ 'Sales results', - `appData() before a run rejected: ${NO_RUN_RESULTS}`, `run({ region: 'Asia' }): success, created at ${createdAt}`, { appData: { region: 'Asia', init_region: false }, agentBlockSummary: null, runCreatedAt: createdAt } ]); From 4d3b5c0c8ee211a898d683b66331943e0f3809fe Mon Sep 17 00:00:00 2001 From: tomas Date: Tue, 24 Nov 2026 11:24:28 +0000 Subject: [PATCH 5/6] refactor(app-preview): rename AppPreviewOperation to AppPreviewUnsupportedOperation --- src/notebooks/deepnote/appPreview/appPreviewApi.node.ts | 8 ++++---- .../deepnote/appPreview/appPreviewApi.node.unit.test.ts | 8 ++++---- .../deepnote/appPreview/appPreviewCommandHandler.node.ts | 4 ++-- .../deepnote/appPreview/appPreviewSession.node.ts | 4 ++-- .../appPreview/appPreviewSession.node.unit.test.ts | 6 +++--- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index f1e5356fd..54295a0b1 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -25,12 +25,12 @@ import type { SnapshotBlock } from './types'; -export type AppPreviewOperation = 'dataframe()'; +export type AppPreviewUnsupportedOperation = 'dataframe()'; export interface AppPreviewApiOptions { token: string; findNotebook(notebookId: string): Promise; - onUnsupported(operation: AppPreviewOperation): void; + onUnsupported(operation: AppPreviewUnsupportedOperation): void; runFiles: AppPreviewRunFiles; runner: IAppPreviewRunner; } @@ -53,7 +53,7 @@ const createRunBodySchema = z.strictObject({ detachedRunStorageMode: z.enum(['read_write', 'readonly']).optional() }); -function notSupportedMessage(operation: AppPreviewOperation): string { +function notSupportedMessage(operation: AppPreviewUnsupportedOperation): string { return `${operation} is not supported in the local preview yet.`; } @@ -197,7 +197,7 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp const unfinished = new Set(); let isDisposed = false; - const unsupported = (operation: AppPreviewOperation) => (_req: Request, res: Response) => { + const unsupported = (operation: AppPreviewUnsupportedOperation) => (_req: Request, res: Response) => { options.onUnsupported(operation); res.status(501).json({ message: notSupportedMessage(operation) }); }; diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index 3730c730d..0ae7ac494 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -17,7 +17,7 @@ import { createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; -import { createAppPreviewApi, type AppPreviewOperation } from './appPreviewApi.node'; +import { createAppPreviewApi, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import type { WorkspaceNotebook } from './appPreviewWorkspace.node'; import type { AppPreviewApi, AppPreviewRunOutcome, IAppPreviewRunner, SnapshotBlock } from './types'; @@ -125,7 +125,7 @@ suite('createAppPreviewApi', () => { let runner: IAppPreviewRunner; let runFiles: AppPreviewRunFiles; let findNotebook: sinon.SinonStub<[string], Promise>; - let onUnsupported: sinon.SinonStub<[AppPreviewOperation], void>; + let onUnsupported: sinon.SinonStub<[AppPreviewUnsupportedOperation], void>; setup(async () => { runner = mock(); @@ -139,7 +139,7 @@ suite('createAppPreviewApi', () => { findNotebook = sinon .stub<[string], Promise>() .callsFake(async (notebookId) => notebooks.get(notebookId)); - onUnsupported = sinon.stub<[AppPreviewOperation], void>(); + onUnsupported = sinon.stub<[AppPreviewUnsupportedOperation], void>(); runFiles = mock(AppPreviewRunFiles); when(runFiles.write(anything(), anything())).thenResolve(true); when(runFiles.read(anything())).thenResolve(RUN_FILE); @@ -695,7 +695,7 @@ suite('createAppPreviewApi', () => { }); }); - const stubs: [string, string, AppPreviewOperation][] = [ + const stubs: [string, string, AppPreviewUnsupportedOperation][] = [ ['GET', '/projects/p-1/dataframes/sales%20by%20month', 'dataframe()'] ]; for (const [method, path, operation] of stubs) { diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts index 754c9fad8..c013ddf8c 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts @@ -7,7 +7,7 @@ import { IDisposableRegistry, IExtensionContext } from '../../../platform/common import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; import { logger } from '../../../platform/logging'; import { basename } from '../../../platform/vscode-path/resources'; -import type { AppPreviewOperation } from './appPreviewApi.node'; +import type { AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession } from './appPreviewSession.node'; import { resolvePreviewProject } from './appPreviewWorkspace.node'; @@ -136,7 +136,7 @@ export class AppPreviewCommandHandler implements IExtensionSyncActivationService } private async startSession(folder: Uri): Promise { - const warned = new Set(); + const warned = new Set(); this.runFiles ??= new AppPreviewRunFiles( this.extensionContext.storageUri ?? this.extensionContext.globalStorageUri ); diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts index b45c347fe..64d5b4281 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts @@ -7,7 +7,7 @@ import { IDisposable } from '../../../platform/common/types'; import { generateUuid } from '../../../platform/common/uuid'; import { logger } from '../../../platform/logging'; import { extname, extUri } from '../../../platform/vscode-path/resources'; -import { createAppPreviewApi, type AppPreviewOperation } from './appPreviewApi.node'; +import { createAppPreviewApi, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import type { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { findNotebookById } from './appPreviewWorkspace.node'; import type { AppPreviewApi, IAppPreviewRunner } from './types'; @@ -23,7 +23,7 @@ export interface AppPreviewSessionOptions { runFiles: AppPreviewRunFiles; runner: IAppPreviewRunner; scripts: { appClient: Uri }; - onUnsupported(operation: AppPreviewOperation): void; + onUnsupported(operation: AppPreviewUnsupportedOperation): void; } const LOOPBACK_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]']; diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts index 9cb7d9e90..43774e902 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts @@ -12,7 +12,7 @@ import * as path from '../../../platform/vscode-path/path'; import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; import { createDeepnoteFile, createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; -import type { AppPreviewOperation } from './appPreviewApi.node'; +import type { AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession, type AppPreviewProject } from './appPreviewSession.node'; import type { AppPreviewRunOutcome, IAppPreviewRunner } from './types'; @@ -94,7 +94,7 @@ suite('AppPreviewSession', () => { let appFolder: string; let clientScript: string; let sessions: AppPreviewSession[]; - let onUnsupported: sinon.SinonStub<[AppPreviewOperation], void>; + let onUnsupported: sinon.SinonStub<[AppPreviewUnsupportedOperation], void>; let runner: IAppPreviewRunner; async function startSession( @@ -123,7 +123,7 @@ suite('AppPreviewSession', () => { setup(() => { resetVSCodeMocks(); - onUnsupported = sinon.stub<[AppPreviewOperation], void>(); + onUnsupported = sinon.stub<[AppPreviewUnsupportedOperation], void>(); runner = mock(); sessions = []; tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-')); From 691be02d564cfb345f985e4d88d6feab44390f3c Mon Sep 17 00:00:00 2001 From: tomas Date: Tue, 24 Nov 2026 11:24:53 +0000 Subject: [PATCH 6/6] test(app-preview): check messages through the constants that produce them Export the API's error messages, notSupportedMessage and the runner's INIT_NOTEBOOK_FAILED_PREFIX, and assert the app preview unit tests' messages through them and the DeepnoteAppPreview localized strings, so a reworded message doesn't need its tests updated. --- .../deepnote/appPreview/appPreviewApi.node.ts | 18 +++---- .../appPreviewApi.node.unit.test.ts | 49 +++++++++++-------- ...appPreviewCommandHandler.node.unit.test.ts | 11 ++--- .../appPreview/appPreviewRunner.node.ts | 2 +- .../appPreviewRunner.node.unit.test.ts | 19 ++++--- .../appPreviewSession.node.unit.test.ts | 6 +-- 6 files changed, 55 insertions(+), 50 deletions(-) diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts index 54295a0b1..6615a331a 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -36,14 +36,14 @@ export interface AppPreviewApiOptions { } // Protocol strings: app code receives them, so they stay English like Deepnote's API messages. -const UNAUTHORIZED_MESSAGE = 'Unauthorized'; -const NOT_AVAILABLE_MESSAGE = 'This endpoint is not available to app viewer tokens'; -const NOTEBOOK_NOT_FOUND_MESSAGE = 'Notebook not found'; -const NO_RUN_RESULTS_MESSAGE = 'You have no run results for this notebook yet. Run the notebook to load them.'; -const NO_JSON_OUTPUT_MESSAGE = 'Your latest run has no JSON output.'; -const RUN_NOT_FOUND_MESSAGE = 'Run not found'; -const PREVIEW_STOPPED_MESSAGE = 'The app preview has stopped'; -const INTERNAL_ERROR_MESSAGE = 'Internal server error'; +export const UNAUTHORIZED_MESSAGE = 'Unauthorized'; +export const NOT_AVAILABLE_MESSAGE = 'This endpoint is not available to app viewer tokens'; +export const NOTEBOOK_NOT_FOUND_MESSAGE = 'Notebook not found'; +export const NO_RUN_RESULTS_MESSAGE = 'You have no run results for this notebook yet. Run the notebook to load them.'; +export const NO_JSON_OUTPUT_MESSAGE = 'Your latest run has no JSON output.'; +export const RUN_NOT_FOUND_MESSAGE = 'Run not found'; +export const PREVIEW_STOPPED_MESSAGE = 'The app preview has stopped'; +export const INTERNAL_ERROR_MESSAGE = 'Internal server error'; type AppViewerNotebook = operations['getNotebook']['responses'][200]['content']['application/json']['notebook']; @@ -53,7 +53,7 @@ const createRunBodySchema = z.strictObject({ detachedRunStorageMode: z.enum(['read_write', 'readonly']).optional() }); -function notSupportedMessage(operation: AppPreviewUnsupportedOperation): string { +export function notSupportedMessage(operation: AppPreviewUnsupportedOperation): string { return `${operation} is not supported in the local preview yet.`; } diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index 0ae7ac494..9f4c9aebf 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -17,7 +17,19 @@ import { createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; -import { createAppPreviewApi, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; +import { + createAppPreviewApi, + INTERNAL_ERROR_MESSAGE, + NO_JSON_OUTPUT_MESSAGE, + NO_RUN_RESULTS_MESSAGE, + NOT_AVAILABLE_MESSAGE, + NOTEBOOK_NOT_FOUND_MESSAGE, + notSupportedMessage, + PREVIEW_STOPPED_MESSAGE, + RUN_NOT_FOUND_MESSAGE, + UNAUTHORIZED_MESSAGE, + type AppPreviewUnsupportedOperation +} from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import type { WorkspaceNotebook } from './appPreviewWorkspace.node'; import type { AppPreviewApi, AppPreviewRunOutcome, IAppPreviewRunner, SnapshotBlock } from './types'; @@ -259,7 +271,7 @@ suite('createAppPreviewApi', () => { }); test('GET /notebooks/:notebookId answers 404 for an ID no workspace notebook has', async () => { - await assertJson(await call('GET', '/notebooks/nb-missing'), 404, { message: 'Notebook not found' }); + await assertJson(await call('GET', '/notebooks/nb-missing'), 404, { message: NOTEBOOK_NOT_FOUND_MESSAGE }); sinon.assert.notCalled(onUnsupported); }); @@ -268,7 +280,7 @@ suite('createAppPreviewApi', () => { const lookupFailure = new Error('findFiles failed in /home/user/project'); findNotebook.rejects(lookupFailure); - await assertJson(await call('GET', '/notebooks/nb-1'), 500, { message: 'Internal server error' }); + await assertJson(await call('GET', '/notebooks/nb-1'), 500, { message: INTERNAL_ERROR_MESSAGE }); assert.deepStrictEqual( logError.getCalls().map((logged) => logged.args[1]), [lookupFailure] @@ -444,7 +456,7 @@ suite('createAppPreviewApi', () => { const readFailure = new Error('The run file does not parse'); when(runFiles.read(anything())).thenReject(readFailure); - await assertJson(await call('GET', `/runs/${runId}`), 500, { message: 'Internal server error' }); + await assertJson(await call('GET', `/runs/${runId}`), 500, { message: INTERNAL_ERROR_MESSAGE }); assert.deepStrictEqual( logError.getCalls().map((logged) => logged.args[1]), [readFailure] @@ -470,7 +482,7 @@ suite('createAppPreviewApi', () => { }); test('GET /runs/:runId answers 404 for a run ID the preview has not started', async () => { - await assertJson(await call('GET', '/runs/run-1'), 404, { message: 'Run not found' }); + await assertJson(await call('GET', '/runs/run-1'), 404, { message: RUN_NOT_FOUND_MESSAGE }); }); test('dispose() cancels the unfinished runs, and records how the runner ended them', async () => { @@ -503,7 +515,7 @@ suite('createAppPreviewApi', () => { api.dispose(); lookup.resolve({ file: SALES_FILE, fileUri: SALES_FILE_URI, notebook: SALES_FILE.project.notebooks[1] }); - await assertJson(await response, 503, { message: 'The app preview has stopped' }); + await assertJson(await response, 503, { message: PREVIEW_STOPPED_MESSAGE }); verify(runner.run(anything(), anything(), anything())).never(); }); @@ -517,7 +529,7 @@ suite('createAppPreviewApi', () => { ['with an empty input name', { notebookId: 'nb-1', inputs: { '': 'x' } }, 'inputs. invalid key in record'], ['with a number as an input value', { notebookId: 'nb-1', inputs: { a: 1 } }, 'inputs.a invalid input'], ['with an unknown key', { notebookId: 'nb-1', x: 1 }, 'Unrecognized key: "x"'], - ['for an unknown notebook', { notebookId: 'nb-missing' }, 'Notebook not found'], + ['for an unknown notebook', { notebookId: 'nb-missing' }, NOTEBOOK_NOT_FOUND_MESSAGE], [ 'with an input only another notebook of the file defines', { notebookId: 'nb-1', inputs: { limit: '5' } }, @@ -562,9 +574,6 @@ suite('createAppPreviewApi', () => { } suite('GET /notebooks/:notebookId/app-data', () => { - const NO_RUN_RESULTS = { - message: 'You have no run results for this notebook yet. Run the notebook to load them.' - }; const LATEST_STARTED_AT = '2026-01-01T09:00:00.000Z'; function latestFile(blocks: DeepnoteBlock[]): DeepnoteFile { @@ -585,7 +594,7 @@ suite('createAppPreviewApi', () => { test('answers 404 when the notebook has no latest results, though this preview ran it', async () => { await finishRun('success'); - await assertJson(await getAppData(), 404, NO_RUN_RESULTS); + await assertJson(await getAppData(), 404, { message: NO_RUN_RESULTS_MESSAGE }); }); test("answers the latest results' first JSON object and when that run started, not this preview's own run", async () => { @@ -634,7 +643,7 @@ suite('createAppPreviewApi', () => { ]) ); - await assertJson(await getAppData(), 404, { message: 'Your latest run has no JSON output.' }); + await assertJson(await getAppData(), 404, { message: NO_JSON_OUTPUT_MESSAGE }); }); const agentSummaries: [string, DeepnoteBlock[], string | null][] = [ @@ -681,7 +690,7 @@ suite('createAppPreviewApi', () => { } test('answers 404 for an ID no workspace notebook has, without reading any results', async () => { - await assertJson(await getAppData('nb-deleted'), 404, { message: 'Notebook not found' }); + await assertJson(await getAppData('nb-deleted'), 404, { message: NOTEBOOK_NOT_FOUND_MESSAGE }); verify(runFiles.readLatest(anything())).never(); }); @@ -690,7 +699,7 @@ suite('createAppPreviewApi', () => { const readFailure = new Error('The latest results do not parse'); when(runFiles.readLatest(anything())).thenReject(readFailure); - await assertJson(await getAppData(), 500, { message: 'Internal server error' }); + await assertJson(await getAppData(), 500, { message: INTERNAL_ERROR_MESSAGE }); sinon.assert.calledOnceWithExactly(logError, sinon.match.string, readFailure); }); }); @@ -700,9 +709,7 @@ suite('createAppPreviewApi', () => { ]; for (const [method, path, operation] of stubs) { test(`${method} ${path} answers 501 for ${operation}`, async () => { - await assertJson(await call(method, path), 501, { - message: `${operation} is not supported in the local preview yet.` - }); + await assertJson(await call(method, path), 501, { message: notSupportedMessage(operation) }); sinon.assert.calledOnceWithExactly(onUnsupported, operation); }); } @@ -715,15 +722,17 @@ suite('createAppPreviewApi', () => { ]; for (const [condition, authorization] of rejectedAuthorizations) { test(`answers 401 to ${condition}, without reaching a handler`, async () => { - await assertJson(await call('GET', '/notebooks/nb-1', authorization), 401, { message: 'Unauthorized' }); - await assertJson(await call('POST', '/runs', authorization), 401, { message: 'Unauthorized' }); + await assertJson(await call('GET', '/notebooks/nb-1', authorization), 401, { + message: UNAUTHORIZED_MESSAGE + }); + await assertJson(await call('POST', '/runs', authorization), 401, { message: UNAUTHORIZED_MESSAGE }); sinon.assert.notCalled(findNotebook); sinon.assert.notCalled(onUnsupported); }); } test('answers 403 to every other route', async () => { - const notAvailable = { message: 'This endpoint is not available to app viewer tokens' }; + const notAvailable = { message: NOT_AVAILABLE_MESSAGE }; await assertJson(await call('GET', '/projects/p-1'), 403, notAvailable); await assertJson(await call('DELETE', '/runs/run-1'), 403, notAvailable); await assertJson(await call('POST', '/notebooks/nb-1'), 403, notAvailable); diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts index 792e6f01c..1f3cdf838 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts @@ -9,6 +9,7 @@ import { Commands } from '../../../platform/common/constants'; import { IDisposable, IExtensionContext } from '../../../platform/common/types'; import { createDeferred } from '../../../platform/common/utils/async'; import { dispose } from '../../../platform/common/utils/lifecycle'; +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; import * as path from '../../../platform/vscode-path/path'; import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; @@ -191,8 +192,8 @@ suite('AppPreviewCommandHandler', () => { canSelectFiles: false, canSelectMany: false, defaultUri: Uri.file(tmp).fsPath, - title: 'Choose the app folder to preview', - openLabel: 'Preview' + title: DeepnoteAppPreview.chooseFolderTitle, + openLabel: DeepnoteAppPreview.preview } ); verify(commands().executeCommand(SIMPLE_BROWSER_OPEN, anything(), anything())).once(); @@ -276,7 +277,7 @@ suite('AppPreviewCommandHandler', () => { await previewApp(Uri.file(appFolder)); - verify(win().showErrorMessage('Could not start the app preview: listen EACCES')).once(); + verify(win().showErrorMessage(DeepnoteAppPreview.startFailed('listen EACCES'))).once(); verify(commands().executeCommand(SIMPLE_BROWSER_OPEN, anything(), anything())).never(); verify(env().openExternal(anything())).never(); @@ -320,8 +321,6 @@ suite('AppPreviewCommandHandler', () => { // A repeated call must not warn again. assert.strictEqual((await dataframe()).status, 501); - verify( - win().showWarningMessage('The app in app called dataframe(), which the local preview does not support yet.') - ).once(); + verify(win().showWarningMessage(DeepnoteAppPreview.operationNotSupported('dataframe()', 'app'))).once(); }); }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts index b0c27b6b8..29cddc1e9 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts @@ -21,7 +21,7 @@ import { blocksInNotebookOrder } from './appPreviewWorkspace.node'; import type { AppPreviewInputValue, AppPreviewRunOutcome, AppPreviewRunRequest, IAppPreviewRunner } from './types'; // Deepnote's run error for a failing init block, so app code sees the same message as in Deepnote. -const INIT_NOTEBOOK_FAILED_PREFIX = 'Init notebook failed: '; +export const INIT_NOTEBOOK_FAILED_PREFIX = 'Init notebook failed: '; const STOPPED: AppPreviewRunOutcome = { status: 'stopped', error: null, file: null }; diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts index 0c0d77b98..5b96176a6 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts @@ -27,6 +27,7 @@ import { type IDeepnoteToolkitDependencyService } from '../../../kernels/deepnote/types'; import { createDeferred, type Deferred } from '../../../platform/common/utils/async'; +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; import { logger } from '../../../platform/logging'; import type { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; @@ -43,7 +44,7 @@ import { DEEPNOTE_CLOUD_INIT_BLOCK, WINDOWS_INIT_BLOCK } from '../deepnoteTestHelpers'; -import { AppPreviewRunner } from './appPreviewRunner.node'; +import { AppPreviewRunner, INIT_NOTEBOOK_FAILED_PREFIX } from './appPreviewRunner.node'; import type { AppPreviewRunOutcome, AppPreviewRunRequest } from './types'; const CREATED_AT = '2026-11-22T10:00:00.000Z'; @@ -517,7 +518,7 @@ suite('AppPreviewRunner', () => { { success: false, outputs: [errorOutput], error: new Error('The kernel died') }, 'The kernel died' ], - ['no error', { success: false, outputs: [] }, 'Block table failed.'] + ['no error', { success: false, outputs: [] }, DeepnoteAppPreview.blockFailed('table')] ]; for (const [condition, tableResult, message] of failures) { test(`fails with the block's message for ${condition}, keeping the outputs so far`, async () => { @@ -564,7 +565,7 @@ suite('AppPreviewRunner', () => { assert.isNull(outcome.error); }); - test('fails with the init block\'s message after "Init notebook failed: ", without running the notebook', async () => { + test("fails with the init block's message after Deepnote's init failure prefix, without running the notebook", async () => { const withInit = write( 'with-init.deepnote', projectFile( @@ -583,7 +584,7 @@ suite('AppPreviewRunner', () => { const outcome = await run(withInit, 'nb-1'); assert.strictEqual(outcome.status, 'error'); - assert.strictEqual(outcome.error, 'Init notebook failed: ValueError: no data'); + assert.strictEqual(outcome.error, `${INIT_NOTEBOOK_FAILED_PREFIX}ValueError: no data`); assert.deepStrictEqual(outcome.file?.execution, { startedAt: CREATED_AT, finishedAt: FINISHED_AT }); assert.deepStrictEqual(runFileBlocks(outcome), [{ id: 'chart', type: 'code', outputs: [], metadata: {} }]); assert.deepStrictEqual(notebookIdsPerCall(1), [['nb-init']]); @@ -597,21 +598,19 @@ suite('AppPreviewRunner', () => { assert.deepStrictEqual(outcome, { status: 'internal_error', - error: 'No Python interpreter is selected for the notebook. Select one in VS Code, then run the app again.', + error: DeepnoteAppPreview.noInterpreter, file: null }); sinon.assert.notCalled(createEngine); }); - const toolkitNotInstalled = - "deepnote-toolkit is not installed in the notebook's Python interpreter. Install it from VS Code, then run the app again."; const declined: [DeepnoteToolkitDependencyResponse, string][] = [ - [DeepnoteToolkitDependencyResponse.cancel, toolkitNotInstalled], + [DeepnoteToolkitDependencyResponse.cancel, DeepnoteAppPreview.toolkitNotInstalled], [ DeepnoteToolkitDependencyResponse.selectDifferentInterpreter, - 'Open the notebook in VS Code and run Deepnote: Select Interpreter for Notebook, then run the app again.' + DeepnoteAppPreview.selectDifferentInterpreter ], - [DeepnoteToolkitDependencyResponse.failed, toolkitNotInstalled] + [DeepnoteToolkitDependencyResponse.failed, DeepnoteAppPreview.toolkitNotInstalled] ]; for (const [response, message] of declined) { test(`is an internal error, without a server, when the toolkit install answers ${DeepnoteToolkitDependencyResponse[response]}`, async () => { diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts index 43774e902..bc68e42be 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts @@ -12,7 +12,7 @@ import * as path from '../../../platform/vscode-path/path'; import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; import { createDeepnoteFile, createDeepnoteNotebook, createDeepnoteProject } from '../deepnoteTestHelpers'; -import type { AppPreviewUnsupportedOperation } from './appPreviewApi.node'; +import { notSupportedMessage, type AppPreviewUnsupportedOperation } from './appPreviewApi.node'; import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession, type AppPreviewProject } from './appPreviewSession.node'; import type { AppPreviewRunOutcome, IAppPreviewRunner } from './types'; @@ -372,9 +372,7 @@ suite('AppPreviewSession', () => { headers: { authorization: `Bearer ${token}` } }); assert.strictEqual(stub.status, 501); - assert.deepStrictEqual(JSON.parse(stub.body.toString()), { - message: 'dataframe() is not supported in the local preview yet.' - }); + assert.deepStrictEqual(JSON.parse(stub.body.toString()), { message: notSupportedMessage('dataframe()') }); sinon.assert.calledOnceWithExactly(onUnsupported, 'dataframe()'); assert.strictEqual((await request(session, '/v2/projects/project-1/dataframes/sales')).status, 401);