From ea35a66f29498c1071212a2328a611c844324672 Mon Sep 17 00:00:00 2001 From: tomas Date: Sun, 22 Nov 2026 22:00:39 +0000 Subject: [PATCH 1/4] refactor(snapshots): share the snapshot folder and encoding helpers Move SnapshotService's private ensureSnapshotsDirectory into snapshotFiles.ts unchanged, and add encodeSnapshotFile, so that other writers of .snapshot.deepnote files reuse them. --- .../deepnote/snapshots/snapshotFiles.ts | 37 ++++++++++++++++++- .../deepnote/snapshots/snapshotService.ts | 37 ++----------------- 2 files changed, 39 insertions(+), 35 deletions(-) diff --git a/src/notebooks/deepnote/snapshots/snapshotFiles.ts b/src/notebooks/deepnote/snapshots/snapshotFiles.ts index 33fff46dde..a2ae481258 100644 --- a/src/notebooks/deepnote/snapshots/snapshotFiles.ts +++ b/src/notebooks/deepnote/snapshots/snapshotFiles.ts @@ -1,7 +1,10 @@ +import { serializeDeepnoteFile, type DeepnoteFile } from '@deepnote/blocks'; import { generateSnapshotFilename, parseSnapshotFilename, slugifyProjectName } from '@deepnote/convert'; -import { Uri } from 'vscode'; +import { FileType, Uri, workspace } from 'vscode'; +import { Utils } from 'vscode-uri'; import { InvalidProjectNameError } from '../../../platform/errors/invalidProjectNameError'; +import { logger } from '../../../platform/logging'; /** File suffix for snapshot files */ export const SNAPSHOT_FILE_SUFFIX = '.snapshot.deepnote'; @@ -55,3 +58,35 @@ export function extractProjectIdFromSnapshotUri(uri: Uri): string | undefined { return parsed?.projectId; } + +/** Encodes `file` as the UTF-8 YAML that snapshot files hold. */ +export function encodeSnapshotFile(file: DeepnoteFile): Uint8Array { + return new TextEncoder().encode(serializeDeepnoteFile(file)); +} + +/** Creates `snapshotsDir` if missing; logs an error and resolves `false` if it is not or cannot become a directory. */ +export async function ensureSnapshotsDirectory(snapshotsDir: Uri): Promise { + try { + const stat = await workspace.fs.stat(snapshotsDir); + + if (stat.type !== FileType.Directory) { + logger.error(`[Snapshot] Snapshots path exists but is not a directory: ${Utils.basename(snapshotsDir)}`); + + return false; + } + + return true; + } catch { + logger.debug(`[Snapshot] Creating snapshots directory: ${Utils.basename(snapshotsDir)}`); + + try { + await workspace.fs.createDirectory(snapshotsDir); + + return true; + } catch (error) { + logger.error(`[Snapshot] Failed to create snapshots directory: ${Utils.basename(snapshotsDir)}`, error); + + return false; + } + } +} diff --git a/src/notebooks/deepnote/snapshots/snapshotService.ts b/src/notebooks/deepnote/snapshots/snapshotService.ts index ce64336d8d..53ad8e569e 100644 --- a/src/notebooks/deepnote/snapshots/snapshotService.ts +++ b/src/notebooks/deepnote/snapshots/snapshotService.ts @@ -1,6 +1,5 @@ import { isExecutableBlock, - serializeDeepnoteFile, type DeepnoteBlock, type DeepnoteFile, type Environment, @@ -17,7 +16,6 @@ import fastDeepEqual from 'fast-deep-equal'; import { inject, injectable, optional } from 'inversify'; import { Disposable, - FileType, NotebookCell, NotebookCellKind, NotebookDocumentChangeEvent, @@ -44,7 +42,7 @@ import { IDeepnoteNotebookManager } from '../../types'; import { DeepnoteDataConverter } from '../deepnoteDataConverter'; import { IEnvironmentCapture } from './environmentCapture.node'; import { ExecutionMetadataTracker, type BlockExecutionMetadata } from './executionMetadataTracker'; -import { buildSnapshotPath } from './snapshotFiles'; +import { buildSnapshotPath, encodeSnapshotFile, ensureSnapshotsDirectory } from './snapshotFiles'; /** * Platform-layer interface for snapshot metadata service. @@ -529,34 +527,6 @@ export class SnapshotService implements ISnapshotMetadataService, IExtensionSync } } - private async ensureSnapshotsDirectory(snapshotsDir: Uri): Promise { - try { - const stat = await workspace.fs.stat(snapshotsDir); - - if (stat.type !== FileType.Directory) { - logger.error( - `[Snapshot] Snapshots path exists but is not a directory: ${Utils.basename(snapshotsDir)}` - ); - - return false; - } - - return true; - } catch { - logger.debug(`[Snapshot] Creating snapshots directory: ${Utils.basename(snapshotsDir)}`); - - try { - await workspace.fs.createDirectory(snapshotsDir); - - return true; - } catch (error) { - logger.error(`[Snapshot] Failed to create snapshots directory: ${Utils.basename(snapshotsDir)}`, error); - - return false; - } - } - } - private getComparableProjectContent(data: DeepnoteFile): object { return { version: data.version, @@ -1014,7 +984,7 @@ export class SnapshotService implements ISnapshotMetadataService, IExtensionSync } const snapshotsDir = Uri.joinPath(latestPath, '..'); - const dirExists = await this.ensureSnapshotsDirectory(snapshotsDir); + const dirExists = await ensureSnapshotsDirectory(snapshotsDir); if (!dirExists) { return; @@ -1049,8 +1019,7 @@ export class SnapshotService implements ISnapshotMetadataService, IExtensionSync } } - const yamlString = serializeDeepnoteFile(snapshotData); - const content = new TextEncoder().encode(yamlString); + const content = encodeSnapshotFile(snapshotData); return { latestPath, content }; } From 96f4678103866081abef393bd953c23bd226a2fe Mon Sep 17 00:00:00 2001 From: tomas Date: Sun, 22 Nov 2026 22:00:39 +0000 Subject: [PATCH 2/4] feat(app-preview): run local notebooks for run(), saving each run's results as a snapshot file POST /v2/runs runs the workspace notebook headlessly, after the project's init notebook, and GET /v2/runs/:runId reports it in Deepnote's run shape. Each run that ends as success or error is written to /appPreview/runs/.snapshot.deepnote, in VS Code's storage for the workspace, and GET reads its snapshotBlocks from that file. A run is reported finished only once its file is written. Memory keeps only the small run records of the current window. The first preview of a window clears the runs folder in the background, and writes wait for that clear. --- README.md | 8 +- .../deepnote/appPreview/appPreviewApi.node.ts | 201 ++++- .../appPreviewApi.node.unit.test.ts | 372 +++++++- .../appPreviewCommandHandler.node.ts | 11 +- ...appPreviewCommandHandler.node.unit.test.ts | 52 +- .../appPreview/appPreviewRunFiles.node.ts | 62 ++ .../appPreviewRunFiles.node.unit.test.ts | 158 ++++ .../appPreview/appPreviewRunner.node.ts | 249 ++++++ .../appPreviewRunner.node.unit.test.ts | 836 ++++++++++++++++++ .../appPreview/appPreviewSession.node.ts | 22 +- .../appPreviewSession.node.unit.test.ts | 52 +- src/notebooks/deepnote/appPreview/types.ts | 68 ++ .../deepnoteInitNotebookRunner.node.ts | 102 ++- ...epnoteInitNotebookRunner.node.unit.test.ts | 33 +- src/notebooks/deepnote/deepnoteTestHelpers.ts | 18 + src/notebooks/serviceRegistry.node.ts | 3 + src/platform/common/utils/localize.ts | 12 + src/test/mocks/deepnoteRuntimeCore.ts | 47 +- .../fixtures/app-preview-runs-init.deepnote | 28 + test/e2e/fixtures/app-preview-runs.deepnote | 40 + test/e2e/fixtures/app-preview-runs/app.js | 15 + test/e2e/fixtures/app-preview-runs/index.html | 21 + .../suite/appPreview/previewApp.e2e.test.ts | 61 ++ 23 files changed, 2383 insertions(+), 88 deletions(-) create mode 100644 src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts create mode 100644 src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts create mode 100644 src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts create mode 100644 src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts create mode 100644 src/notebooks/deepnote/appPreview/types.ts create mode 100644 test/e2e/fixtures/app-preview-runs-init.deepnote create mode 100644 test/e2e/fixtures/app-preview-runs.deepnote create mode 100644 test/e2e/fixtures/app-preview-runs/app.js create mode 100644 test/e2e/fixtures/app-preview-runs/index.html diff --git a/README.md b/README.md index 74f977713d..05ae6d1a1e 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,13 @@ Run `Deepnote: Preview App` from the Command Palette, or right-click a folder in - The folder is served the way Deepnote serves a published app, from a local address. Edit a file and reload the page to see the change. - The page's script tag for Deepnote's client (`https://deepnote.com/static/app-client/v1.js`) loads a copy of that client bundled with the extension instead, so the preview works without network access. - `inputs()` returns the input blocks of the notebook with that ID in the workspace's `.deepnote` files, as saved on disk, so save the notebook and reload the page to see a change. An ID that no workspace notebook has rejects with `Notebook not found`. -- The page's other calls to Deepnote reach a local stand-in that does not support them yet: `appData()` and `run()` reject with a message saying so, and VS Code shows a warning the first time the app calls each of them. +- `run()` runs that notebook, as saved on disk, in a new kernel on the Deepnote server the extension runs for its `.deepnote` file: the project's init notebook first, then the notebook with the page's input values. + - It uses the notebook's Python interpreter. Its SQL blocks use the integrations configured in VS Code, except BigQuery integrations that use Google OAuth. + - Agent blocks run only when the model provider's API key, such as `OPENAI_API_KEY`, is set in VS Code's own environment. The key saved for agent cells is not used. + - 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. - 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 45bd7183b5..f9a3653dc2 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts @@ -1,32 +1,89 @@ +import { getInputBlockValueOverrideValidationError, isInputBlock, type DeepnoteFile } from '@deepnote/blocks'; // 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 { timingSafeEqual } from 'crypto'; -import express, { type NextFunction, type Request, type Response, type Router } from 'express'; +import express, { type NextFunction, type Request, type Response } from 'express'; +import { CancellationTokenSource } from 'vscode'; +import { z } from 'zod'; +import { generateUuid } from '../../../platform/common/uuid'; +import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; import { logger } from '../../../platform/logging'; +import type { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { blocksInNotebookOrder, toNotebookInputs, type WorkspaceNotebook } from './appPreviewWorkspace.node'; +import type { + AppPreviewApi, + AppPreviewInputValue, + AppPreviewRunOutcome, + AppPreviewRunRequest, + IAppPreviewRunner, + PreviewRun, + SnapshotBlock +} from './types'; -export type AppPreviewOperation = 'appData()' | 'run()' | 'dataframe()'; +export type AppPreviewOperation = 'appData()' | 'dataframe()'; export interface AppPreviewApiOptions { token: string; findNotebook(notebookId: string): Promise; onUnsupported(operation: AppPreviewOperation): void; + runFiles: AppPreviewRunFiles; + runner: IAppPreviewRunner; } // 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 RUN_NOT_FOUND_MESSAGE = 'Run not found'; +const PREVIEW_STOPPED_MESSAGE = 'The app preview has stopped'; const INTERNAL_ERROR_MESSAGE = 'Internal server error'; type AppViewerNotebook = operations['getNotebook']['responses'][200]['content']['application/json']['notebook']; +const createRunBodySchema = z.strictObject({ + notebookId: z.string().min(1), + inputs: z.record(z.string().min(1), z.union([z.string(), z.boolean(), z.array(z.string())])).optional(), + detachedRunStorageMode: z.enum(['read_write', 'readonly']).optional() +}); + function notSupportedMessage(operation: AppPreviewOperation): string { return `${operation} is not supported in the local preview yet.`; } +/** The 4xx status of an error body-parser raises for the request itself, such as malformed JSON. */ +function clientErrorStatus(error: unknown): number | undefined { + if (typeof error !== 'object' || error === null || !('status' in error) || !('expose' in error)) { + return undefined; + } + + return typeof error.status === 'number' && error.status < 500 && error.expose === true ? error.status : undefined; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** 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); + for (const [name, value] of Object.entries(inputs)) { + const blocks = inputBlocks.filter((block) => block.metadata.deepnote_variable_name === name); + if (blocks.length === 0) { + return `Input "${name}" is not defined for this notebook`; + } + for (const block of blocks) { + const error = getInputBlockValueOverrideValidationError(block, value); + if (error) { + return `Input "${name}" ${error}`; + } + } + } + + return undefined; +} + function isAuthorized(authorizationHeader: string | undefined, token: string): boolean { if (authorizationHeader === undefined) { return false; @@ -38,6 +95,29 @@ function isAuthorized(authorizationHeader: string | undefined, token: string): b return actual.length === expected.length && timingSafeEqual(actual, expected); } +/** Deepnote's 400 message for a body that fails its schema. */ +function readableErrors(error: z.ZodError): string { + return error.issues + .map((issue) => + issue.path.length === 0 + ? issue.message + : `${issue.path.map(String).join('.')} ${issue.message.toLowerCase()}` + ) + .join('; '); +} + +/** The `snapshotBlocks` of Deepnote's `GET /v2/runs/:runId` answer, from the run's file. */ +function toSnapshotBlocks(file: DeepnoteFile): SnapshotBlock[] { + return file.project.notebooks[0].blocks.map((block) => ({ + id: block.id, + type: block.type, + outputs: ('outputs' in block ? block.outputs : undefined) ?? [], + metadata: block.metadata ?? {}, + outputHead: null, + outputTail: null + })); +} + /** * The `notebook` of Deepnote's `GET /v2/notebooks/:notebookId` answer. Notebooks carry no timestamps in a `.deepnote` * file, so `createdAt` is the file's, and a local notebook has no Deepnote schedule or runs. @@ -60,17 +140,52 @@ 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, 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 handler that fails is logged and gets a JSON 500. + * 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. */ -export function createAppPreviewApi(options: AppPreviewApiOptions): Router { +export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewApi { const router = express.Router(); + const runs = new Map(); + const unfinished = new Set(); + let isDisposed = false; const unsupported = (operation: AppPreviewOperation) => (_req: Request, res: Response) => { options.onUnsupported(operation); res.status(501).json({ message: notSupportedMessage(operation) }); }; + const startRun = (run: PreviewRun, request: AppPreviewRunRequest) => { + const cancellation = new CancellationTokenSource(); + unfinished.add(cancellation); + void options.runner + .run(request, cancellation.token, () => { + run.status = 'running'; + }) + .catch((error): AppPreviewRunOutcome => { + logger.error(`AppPreviewApi: Run ${run.runId} failed`, error); + + return { status: 'internal_error', error: errorMessage(error), file: null }; + }) + .then(async (outcome) => { + const completedAt = new Date().toISOString(); + const snapshotStatus = + 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. + run.status = outcome.status; + run.error = outcome.error; + run.snapshotStatus = snapshotStatus; + run.completedAt = completedAt; + }) + .finally(() => { + unfinished.delete(cancellation); + cancellation.dispose(); + }); + }; + router.use((req: Request, res: Response, next: NextFunction) => { if (!isAuthorized(req.headers.authorization, options.token)) { res.status(401).json({ message: UNAUTHORIZED_MESSAGE }); @@ -90,8 +205,66 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): Router { res.json({ notebook: toAppViewerNotebook(found) }); }); router.get('/notebooks/:notebookId/app-data', unsupported('appData()')); - router.post('/runs', unsupported('run()')); - router.get('/runs/:runId', unsupported('run()')); + 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`. + error: (issue) => (issue.code === 'invalid_type' && issue.input === undefined ? 'is required' : undefined) + }); + if (!parsed.success) { + res.status(400).json({ message: readableErrors(parsed.error) }); + + return; + } + + const { notebookId, inputs = {} } = parsed.data; + const found = await options.findNotebook(notebookId); + // Closing the server does not stop this handler, and a run started now would have nothing left to cancel it. + if (isDisposed) { + res.status(503).json({ message: PREVIEW_STOPPED_MESSAGE }); + + return; + } + // Unlike its GET routes, Deepnote answers 400 here. + if (!found) { + res.status(400).json({ message: NOTEBOOK_NOT_FOUND_MESSAGE }); + + return; + } + const inputError = inputsError(found.notebook, inputs); + if (inputError) { + res.status(400).json({ message: inputError }); + + return; + } + + const run: PreviewRun = { + runId: generateUuid(), + notebookId, + status: 'pending', + snapshotStatus: 'pending', + error: null, + createdAt: new Date().toISOString(), + completedAt: null + }; + runs.set(run.runId, run); + // Run the revision `inputs` were checked against: runtime-core doesn't reject an input no block declares, it + // sets it as a plain variable. + startRun(run, { createdAt: run.createdAt, file: found.file, fileUri: found.fileUri, notebookId, inputs }); + res.status(202).json({ runId: run.runId, status: run.status, createdAt: run.createdAt }); + }); + router.get('/runs/:runId', async (req: Request<{ runId: string }>, res: Response) => { + const run = runs.get(req.params.runId); + if (!run) { + res.status(404).json({ message: RUN_NOT_FOUND_MESSAGE }); + + return; + } + const snapshotBlocks = + run.snapshotStatus === 'available' ? toSnapshotBlocks(await options.runFiles.read(run.runId)) : null; + res.json({ + run: { ...run, snapshotBlocks, snapshotExpiresAt: null, snapshotContent: null, snapshotDownloadUrl: null } + }); + }); router.get('/projects/:projectId/dataframes/:name', unsupported('dataframe()')); router.use((_req: Request, res: Response) => { @@ -99,9 +272,21 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): Router { }); // Express's own handler would answer an HTML page that holds the stack, and log it outside the extension's logger. router.use((error: unknown, req: Request, res: Response, _next: NextFunction) => { + const status = clientErrorStatus(error); + if (status !== undefined) { + res.status(status).json({ message: errorMessage(error) }); + + return; + } logger.error(`AppPreviewApi: ${req.method} ${req.path} failed`, error); res.status(500).json({ message: INTERNAL_ERROR_MESSAGE }); }); - return router; + return { + router, + dispose: () => { + isDisposed = true; + unfinished.forEach((cancellation) => cancellation.cancel()); + } + }; } diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts index cfb945c37f..25d5efaaa8 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.unit.test.ts @@ -3,8 +3,11 @@ import express from 'express'; import * as http from 'http'; import type { AddressInfo } from 'net'; import * as sinon from 'sinon'; +import { anything, capture, instance, mock, verify, when } from 'ts-mockito'; import { Uri } from 'vscode'; +import { createDeferred, type Deferred } from '../../../platform/common/utils/async'; +import { isUUID } from '../../../platform/common/uuid'; import { logger } from '../../../platform/logging'; import { createDeepnoteBlock, @@ -13,9 +16,13 @@ import { createDeepnoteProject } from '../deepnoteTestHelpers'; import { createAppPreviewApi, type AppPreviewOperation } from './appPreviewApi.node'; +import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import type { WorkspaceNotebook } from './appPreviewWorkspace.node'; +import type { AppPreviewApi, AppPreviewRunOutcome, IAppPreviewRunner, SnapshotBlock } from './types'; const TOKEN = 'preview-token'; +const SALES_FILE_URI = Uri.file('/workspace/sales.deepnote'); +const NOW = '2026-01-02T03:04:05.000Z'; const SALES_FILE = createDeepnoteFile({ metadata: { createdAt: '2025-03-04T05:06:07.000Z' }, @@ -45,6 +52,41 @@ const SALES_FILE = createDeepnoteFile({ } } ] + }), + createDeepnoteNotebook({ + id: 'nb-limits', + name: 'Limits', + blocks: [ + { + id: 'limit', + type: 'input-text', + blockGroup: 'g', + sortingKey: 'a0', + metadata: { deepnote_variable_name: 'limit', deepnote_variable_value: '5' } + } + ] + }) + ] + }) +}); + +const CHART_SNAPSHOT: SnapshotBlock[] = [ + { + id: 'chart', + type: 'code', + outputs: [{ output_type: 'display_data', data: { 'application/json': { total: 3 } }, metadata: {} }], + metadata: {}, + outputHead: null, + outputTail: null + } +]; + +const RUN_FILE = createDeepnoteFile({ + project: createDeepnoteProject({ + notebooks: [ + createDeepnoteNotebook({ + id: 'nb-1', + blocks: [createDeepnoteBlock({ id: 'chart', sortingKey: 'a1', outputs: CHART_SNAPSHOT[0].outputs })] }) ] }) @@ -53,22 +95,37 @@ const SALES_FILE = createDeepnoteFile({ suite('createAppPreviewApi', () => { let server: http.Server; let baseUrl: string; + let api: AppPreviewApi; + let runner: IAppPreviewRunner; + let runFiles: AppPreviewRunFiles; let findNotebook: sinon.SinonStub<[string], Promise>; let onUnsupported: sinon.SinonStub<[AppPreviewOperation], void>; setup(async () => { + runner = mock(); + when(runner.run(anything(), anything(), anything())).thenReturn(createDeferred().promise); const notebooks = new Map( SALES_FILE.project.notebooks.map((notebook) => [ notebook.id, - { file: SALES_FILE, fileUri: Uri.file('/workspace/sales.deepnote'), notebook } + { file: SALES_FILE, fileUri: SALES_FILE_URI, notebook } ]) ); findNotebook = sinon .stub<[string], Promise>() .callsFake(async (notebookId) => notebooks.get(notebookId)); onUnsupported = sinon.stub<[AppPreviewOperation], void>(); + runFiles = mock(AppPreviewRunFiles); + when(runFiles.write(anything(), anything())).thenResolve(true); + when(runFiles.read(anything())).thenResolve(RUN_FILE); + api = createAppPreviewApi({ + token: TOKEN, + findNotebook, + onUnsupported, + runFiles: instance(runFiles), + runner: instance(runner) + }); const app = express(); - app.use('/v2', createAppPreviewApi({ token: TOKEN, findNotebook, onUnsupported })); + app.use('/v2', api.router); server = http.createServer(app); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v2`; @@ -76,6 +133,7 @@ suite('createAppPreviewApi', () => { teardown(() => { sinon.restore(); + api.dispose(); server.closeAllConnections(); server.close(); }); @@ -84,6 +142,51 @@ suite('createAppPreviewApi', () => { return fetch(`${baseUrl}${path}`, { method, headers: authorization == null ? {} : { authorization } }); } + function createRun(body: unknown): Promise { + return fetch(`${baseUrl}/runs`, { + method: 'POST', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify(body) + }); + } + + async function getRun(runId: string): Promise> { + const response = await call('GET', `/runs/${runId}`); + assert.strictEqual(response.status, 200); + + return (await response.json()).run; + } + + async function waitForStatus(runId: string, status: string): Promise> { + const deadline = Date.now() + 2_000; + for (;;) { + const run = await getRun(runId); + if (run.status === status || Date.now() > deadline) { + assert.strictEqual(run.status, status); + + return run; + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } + } + + async function startRun(): Promise<{ runId: string; outcome: Deferred }> { + const outcome = createDeferred(); + when(runner.run(anything(), anything(), anything())).thenReturn(outcome.promise); + const response = await createRun({ notebookId: 'nb-1' }); + assert.strictEqual(response.status, 202); + + return { runId: (await response.json()).runId, outcome }; + } + + async function finishRun(status: 'success' | 'error'): Promise { + const { runId, outcome } = await startRun(); + outcome.resolve({ status, error: null, file: RUN_FILE }); + await waitForStatus(runId, status); + + return runId; + } + async function assertJson(response: Response, status: number, body: unknown): Promise { assert.strictEqual(response.status, status); assert.isNull(response.headers.get('access-control-allow-origin')); @@ -144,10 +247,271 @@ suite('createAppPreviewApi', () => { ); }); + test('POST /runs starts a run of the notebook with the inputs, and answers 202 with it pending', async () => { + sinon.useFakeTimers({ now: Date.parse(NOW), toFake: ['Date'] }); + + const response = await createRun({ + notebookId: 'nb-1', + inputs: { region: 'Asia' }, + detachedRunStorageMode: 'readonly' + }); + + assert.strictEqual(response.status, 202); + const body = await response.json(); + assert.isTrue(isUUID(body.runId), `${body.runId} is not a UUID`); + assert.deepStrictEqual(body, { runId: body.runId, status: 'pending', createdAt: NOW }); + verify(runner.run(anything(), anything(), anything())).once(); + assert.deepStrictEqual(capture(runner.run).last()[0], { + createdAt: NOW, + file: SALES_FILE, + fileUri: SALES_FILE_URI, + notebookId: 'nb-1', + inputs: { region: 'Asia' } + }); + sinon.assert.notCalled(onUnsupported); + }); + + test('POST /runs runs the notebook without inputs when the body has none', async () => { + sinon.useFakeTimers({ now: Date.parse(NOW), toFake: ['Date'] }); + + assert.strictEqual((await createRun({ notebookId: 'nb-init' })).status, 202); + + verify(runner.run(anything(), anything(), anything())).once(); + assert.deepStrictEqual(capture(runner.run).last()[0], { + createdAt: NOW, + file: SALES_FILE, + fileUri: SALES_FILE_URI, + notebookId: 'nb-init', + inputs: {} + }); + }); + + test("GET /runs/:runId reports the run as pending, running, and then finished, in Deepnote's shape", async () => { + const clock = sinon.useFakeTimers({ now: Date.parse(NOW), toFake: ['Date'] }); + const { runId, outcome } = await startRun(); + when(runFiles.read(anything())).thenReject(new Error('Not the file of this run')); + when(runFiles.read(runId)).thenResolve(RUN_FILE); + const pending = { + runId, + notebookId: 'nb-1', + status: 'pending', + snapshotStatus: 'pending', + snapshotExpiresAt: null, + snapshotContent: null, + snapshotDownloadUrl: null, + snapshotBlocks: null, + error: null, + createdAt: NOW, + completedAt: null + }; + assert.deepStrictEqual(await getRun(runId), pending); + + const [, , onRunning] = capture(runner.run).last(); + onRunning(); + assert.deepStrictEqual(await getRun(runId), { ...pending, status: 'running' }); + + clock.tick(65_000); + outcome.resolve({ status: 'success', error: null, file: RUN_FILE }); + assert.deepStrictEqual(await waitForStatus(runId, 'success'), { + ...pending, + status: 'success', + snapshotStatus: 'available', + snapshotBlocks: CHART_SNAPSHOT, + completedAt: '2026-01-02T03:05:10.000Z' + }); + verify(runFiles.write(runId, RUN_FILE)).once(); + sinon.assert.notCalled(onUnsupported); + }); + + const outcomes: [AppPreviewRunOutcome, string, SnapshotBlock[] | null, number][] = [ + [{ status: 'error', error: 'ValueError: no data', file: RUN_FILE }, 'available', CHART_SNAPSHOT, 1], + [{ status: 'internal_error', error: 'The kernel died', file: null }, 'unavailable', null, 0], + [{ status: 'stopped', error: null, file: null }, 'unavailable', null, 0] + ]; + for (const [outcome, snapshotStatus, snapshotBlocks, writes] of outcomes) { + test(`GET /runs/:runId reports a run that ended as ${outcome.status} with its snapshot ${snapshotStatus}`, async () => { + const run = await startRun(); + + run.outcome.resolve(outcome); + + const finished = await waitForStatus(run.runId, outcome.status); + assert.deepInclude(finished, { + status: outcome.status, + error: outcome.error, + snapshotStatus, + snapshotBlocks + }); + assert.isString(finished.completedAt); + verify(runFiles.write(anything(), anything())).times(writes); + }); + } + + test('GET /runs/:runId reports a run as running until its file is written', async () => { + const writeStarted = createDeferred(); + const written = createDeferred(); + when(runFiles.write(anything(), anything())).thenCall(() => { + writeStarted.resolve(); + + return written.promise; + }); + const { runId, outcome } = await startRun(); + const [, , onRunning] = capture(runner.run).last(); + onRunning(); + + outcome.resolve({ status: 'success', error: null, file: RUN_FILE }); + await writeStarted.promise; + + assert.deepInclude(await getRun(runId), { + status: 'running', + snapshotStatus: 'pending', + snapshotBlocks: null, + completedAt: null + }); + written.resolve(true); + assert.deepInclude(await waitForStatus(runId, 'success'), { + snapshotStatus: 'available', + snapshotBlocks: CHART_SNAPSHOT + }); + }); + + 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); + + const runId = await finishRun('success'); + + assert.deepInclude(await getRun(runId), { + status: 'success', + error: null, + snapshotStatus: 'unavailable', + snapshotBlocks: null + }); + }); + + test('GET /runs/:runId answers a JSON 500, and logs the error, when the run file cannot be read', async () => { + const logError = sinon.stub(logger, 'error'); + const runId = await finishRun('success'); + 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' }); + assert.deepStrictEqual( + logError.getCalls().map((logged) => logged.args[1]), + [readFailure] + ); + }); + + test('GET /runs/:runId reports a runner that rejects as an internal error, and logs it', async () => { + const logError = sinon.stub(logger, 'error'); + const { runId, outcome } = await startRun(); + const failure = new Error('runner bug'); + + outcome.reject(failure); + + assert.deepInclude(await waitForStatus(runId, 'internal_error'), { + error: 'runner bug', + snapshotStatus: 'unavailable', + snapshotBlocks: null + }); + assert.deepStrictEqual( + logError.getCalls().map((logged) => logged.args[1]), + [failure] + ); + }); + + 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' }); + }); + + test('dispose() cancels the unfinished runs, and records how the runner ended them', async () => { + const stopped = await startRun(); + const finished = await startRun(); + finished.outcome.resolve({ status: 'success', error: null, file: RUN_FILE }); + await waitForStatus(finished.runId, 'success'); + + api.dispose(); + + const [, stoppedToken] = capture(runner.run).first(); + const [, finishedToken] = capture(runner.run).second(); + assert.isTrue(stoppedToken.isCancellationRequested); + assert.isNotTrue(finishedToken.isCancellationRequested); + stopped.outcome.resolve({ status: 'stopped', error: null, file: null }); + assert.deepInclude(await waitForStatus(stopped.runId, 'stopped'), { snapshotStatus: 'unavailable' }); + }); + + test('dispose() keeps a request that is still looking up its notebook from starting a run', async () => { + const lookupStarted = createDeferred(); + const lookup = createDeferred(); + findNotebook.callsFake(() => { + lookupStarted.resolve(); + + return lookup.promise; + }); + const response = createRun({ notebookId: 'nb-1' }); + await lookupStarted.promise; + + 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' }); + verify(runner.run(anything(), anything(), anything())).never(); + }); + + const invalidBodies: [string, unknown, string][] = [ + ['without notebookId', { inputs: {} }, 'notebookId is required'], + [ + 'with an empty notebookId', + { notebookId: '' }, + 'notebookId too small: expected string to have >=1 characters' + ], + ['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'], + [ + 'with an input only another notebook of the file defines', + { notebookId: 'nb-1', inputs: { limit: '5' } }, + 'Input "limit" is not defined for this notebook' + ], + [ + 'with a value the input block cannot hold', + { notebookId: 'nb-1', inputs: { region: true } }, + 'Input "region" must be a string for input-text' + ] + ]; + for (const [condition, body, message] of invalidBodies) { + test(`POST /runs answers 400 to a body ${condition}, without starting a run`, async () => { + await assertJson(await createRun(body), 400, { message }); + verify(runner.run(anything(), anything(), anything())).never(); + }); + } + + const unreadableBodies: [string, string, number, string][] = [ + ['that is not JSON', '{"notebookId":', 400, 'Unexpected end of JSON input'], + [ + 'over the JSON size limit', + JSON.stringify({ notebookId: 'nb-1', inputs: { region: 'x'.repeat(200_000) } }), + 413, + 'request entity too large' + ] + ]; + for (const [condition, body, status, message] of unreadableBodies) { + test(`POST /runs answers ${status} to a body ${condition}, without starting a run or logging an error`, async () => { + const logError = sinon.stub(logger, 'error'); + + const response = await fetch(`${baseUrl}/runs`, { + method: 'POST', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + body + }); + + await assertJson(response, status, { message }); + verify(runner.run(anything(), anything(), anything())).never(); + sinon.assert.notCalled(logError); + }); + } + const stubs: [string, string, AppPreviewOperation][] = [ ['GET', '/notebooks/nb-1/app-data', 'appData()'], - ['POST', '/runs', 'run()'], - ['GET', '/runs/run-1', 'run()'], ['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 17d657ffa3..754c9fad87 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.ts @@ -8,8 +8,10 @@ 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 { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession } from './appPreviewSession.node'; import { resolvePreviewProject } from './appPreviewWorkspace.node'; +import { IAppPreviewRunner } from './types'; const INTEGRATED_BROWSER_OPEN_COMMAND = 'workbench.action.browser.open'; const SIMPLE_BROWSER_OPEN_COMMAND = 'simpleBrowser.api.open'; @@ -20,11 +22,13 @@ function errorMessage(error: unknown): string { @injectable() export class AppPreviewCommandHandler implements IExtensionSyncActivationService { + private runFiles: AppPreviewRunFiles | undefined; private readonly sessions = new Map>(); constructor( @inject(IExtensionContext) private readonly extensionContext: IExtensionContext, - @inject(IDisposableRegistry) private readonly disposables: IDisposableRegistry + @inject(IDisposableRegistry) private readonly disposables: IDisposableRegistry, + @inject(IAppPreviewRunner) private readonly runner: IAppPreviewRunner ) {} public activate(): void { @@ -133,9 +137,14 @@ export class AppPreviewCommandHandler implements IExtensionSyncActivationService private async startSession(folder: Uri): Promise { const warned = new Set(); + this.runFiles ??= new AppPreviewRunFiles( + this.extensionContext.storageUri ?? this.extensionContext.globalStorageUri + ); const session = new AppPreviewSession({ folder, project: await resolvePreviewProject(folder), + runFiles: this.runFiles, + runner: this.runner, // A copy of https://deepnote.com/static/app-client/v1.js, so that previews work offline. scripts: { appClient: Uri.joinPath(this.extensionContext.extensionUri, 'resources', 'appPreview', 'v1.js') diff --git a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts index d7142bafc9..829b702bfe 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewCommandHandler.node.unit.test.ts @@ -3,10 +3,11 @@ import * as fs from 'fs'; import * as os from 'os'; import * as sinon from 'sinon'; import { anything, capture, deepEqual, instance, mock, verify, when } from 'ts-mockito'; -import { Uri, ViewColumn, type WorkspaceConfiguration, type WorkspaceFolder } from 'vscode'; +import { Uri, ViewColumn, workspace, type WorkspaceConfiguration, type WorkspaceFolder } from 'vscode'; 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 * as path from '../../../platform/vscode-path/path'; import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; @@ -14,6 +15,7 @@ import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-m import { serializeProjectFile } from '../deepnoteTestHelpers'; import { AppPreviewCommandHandler } from './appPreviewCommandHandler.node'; import { AppPreviewSession } from './appPreviewSession.node'; +import type { IAppPreviewRunner } from './types'; const HOSTED = 'https://deepnote.com/static/app-client/v1.js'; const SIMPLE_BROWSER_OPEN = 'simpleBrowser.api.open'; @@ -24,6 +26,7 @@ suite('AppPreviewCommandHandler', () => { let tmp: string; let appFolder: string; let disposables: IDisposable[]; + let mockFs: typeof workspace.fs; let previewApp: (arg?: unknown) => Promise; let simpleBrowserConfig: WorkspaceConfiguration; @@ -56,6 +59,13 @@ suite('AppPreviewCommandHandler', () => { setup(async () => { resetVSCodeMocks(); stubWorkspaceFsOnDisk(); + // The on-disk stub keeps its mock to itself, so `delete` is stubbed on one that forwards the reads to it. + const onDisk = workspace.fs; + mockFs = mock(); + when(mockFs.readDirectory(anything())).thenCall((uri: Uri) => onDisk.readDirectory(uri)); + when(mockFs.readFile(anything())).thenCall((uri: Uri) => onDisk.readFile(uri)); + when(mockFs.delete(anything(), anything())).thenResolve(); + when(mockedVSCodeNamespaces.workspace.fs).thenReturn(instance(mockFs)); tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'deepnote-app-preview-handler-')); appFolder = path.join(tmp, 'project', 'app'); await fs.promises.mkdir(appFolder, { recursive: true }); @@ -92,7 +102,8 @@ suite('AppPreviewCommandHandler', () => { const context = mock(); when(context.subscriptions).thenReturn([]); when(context.extensionUri).thenReturn(Uri.file(path.join(tmp, 'extension'))); - new AppPreviewCommandHandler(instance(context), disposables).activate(); + when(context.storageUri).thenReturn(Uri.file('/storage')); + new AppPreviewCommandHandler(instance(context), disposables, instance(mock())).activate(); const [command, handler] = capture(commands().registerCommand).last(); assert.strictEqual(command, Commands.PreviewApp); previewApp = handler; @@ -276,24 +287,45 @@ suite('AppPreviewCommandHandler', () => { assert.include(await page(), '

app

'); }); + test('deletes the runs of earlier windows once, for previews of two folders', async () => { + const otherFolder = path.join(tmp, 'project', 'other-app'); + await fs.promises.mkdir(otherFolder); + + await previewApp(Uri.file(appFolder)); + await previewApp(Uri.file(otherFolder)); + + const forwarded = capture(env().asExternalUri); + assert.notStrictEqual(forwarded.second()[0].toString(true), forwarded.first()[0].toString(true)); + verify(mockFs.delete(anything(), anything())).once(); + assert.strictEqual(capture(mockFs.delete).last()[0].fsPath, '/storage/appPreview/runs'); + }); + + test('starts the preview without waiting for the runs of earlier windows to be deleted', async () => { + when(mockFs.delete(anything(), anything())).thenReturn(createDeferred().promise); + + await previewApp(Uri.file(appFolder)); + + verify(commands().executeCommand(SIMPLE_BROWSER_OPEN, anything(), anything())).once(); + assert.include(await page(), '

app

'); + }); + test('warns once per unsupported operation, naming the operation and the folder', async () => { await previewApp(Uri.file(appFolder)); const { token } = await requestToken(); - const api = (urlPath: string, method = 'GET') => - fetch(`${serverUrl()}v2${urlPath}`, { - method, - headers: { authorization: `Bearer ${token}` } - }); + const api = (urlPath: string) => + 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 api('/runs', 'POST')).status, 501); - assert.strictEqual((await api('/runs/run-1')).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 run(), which the local preview does not support yet.') + win().showWarningMessage('The app in app called dataframe(), which the local preview does not support yet.') ).once(); }); }); diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts new file mode 100644 index 0000000000..2f996ed050 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.ts @@ -0,0 +1,62 @@ +import type { DeepnoteFile } from '@deepnote/blocks'; +import { Uri, workspace } from 'vscode'; + +import { isFileNotFoundError } from '../../../platform/common/platform/errors'; +import { readDeepnoteProjectFile } from '../../../platform/deepnote/deepnoteProjectFileReader'; +import { logger } from '../../../platform/logging'; +import { encodeSnapshotFile, ensureSnapshotsDirectory, SNAPSHOT_FILE_SUFFIX } from '../snapshots/snapshotFiles'; + +const APP_PREVIEW_FOLDER = 'appPreview'; +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. + */ +export class AppPreviewRunFiles { + private readonly clearing: Promise; + private readonly runsDir: Uri; + + constructor(storageUri: Uri) { + this.runsDir = Uri.joinPath(storageUri, APP_PREVIEW_FOLDER, RUNS_FOLDER); + this.clearing = this.clear(); + } + + /** Reads the file of `runId`; rejects when it is missing or does not parse. */ + public read(runId: string): Promise { + return readDeepnoteProjectFile(this.fileOf(runId)); + } + + /** 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; + + if (!(await ensureSnapshotsDirectory(this.runsDir))) { + return false; + } + + try { + await workspace.fs.writeFile(this.fileOf(runId), encodeSnapshotFile(file)); + + return true; + } catch (error) { + logger.error(`AppPreviewRunFiles: Could not save the results of run ${runId}`, error); + + return false; + } + } + + private async clear(): Promise { + try { + await workspace.fs.delete(this.runsDir, { recursive: true, useTrash: false }); + } catch (error) { + if (!(error instanceof Error && isFileNotFoundError(error))) { + logger.warn('AppPreviewRunFiles: Could not clear the runs of earlier windows', error); + } + } + } + + private fileOf(runId: string): Uri { + return Uri.joinPath(this.runsDir, `${runId}${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 new file mode 100644 index 0000000000..6f15166bc8 --- /dev/null +++ b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts @@ -0,0 +1,158 @@ +import { assert, use } from 'chai'; +import chaiAsPromised from 'chai-as-promised'; +import * as sinon from 'sinon'; +import { anything, capture, instance, mock, verify, when } from 'ts-mockito'; +import { FileSystemError, Uri } from 'vscode'; + +import { createDeferred } from '../../../platform/common/utils/async'; +import { logger } from '../../../platform/logging'; +import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; +import { + createDeepnoteBlock, + createDeepnoteFile, + createDeepnoteNotebook, + createDeepnoteProject +} from '../deepnoteTestHelpers'; +import { AppPreviewRunFiles } from './appPreviewRunFiles.node'; + +use(chaiAsPromised); + +const STORAGE = Uri.file('/storage'); +const RUN_FILE_PATH = '/storage/appPreview/runs/run-1.snapshot.deepnote'; + +const RUN_FILE = createDeepnoteFile({ + execution: { startedAt: '2026-01-02T03:04:05.000Z', finishedAt: '2026-01-02T03:04:09.000Z' }, + project: createDeepnoteProject({ + notebooks: [ + createDeepnoteNotebook({ + id: 'nb-1', + blocks: [ + createDeepnoteBlock({ + id: 'total', + sortingKey: 'a0', + outputs: [{ output_type: 'stream', name: 'stdout', text: '3\n' }] + }), + createDeepnoteBlock({ id: 'never-ran', sortingKey: 'a1', outputs: [] }) + ] + }) + ] + }) +}); + +suite('AppPreviewRunFiles', () => { + let mockFs: typeof import('vscode').workspace.fs; + let files: Map; + + setup(() => { + resetVSCodeMocks(); + files = new Map(); + mockFs = mock(); + when(mockFs.delete(anything(), anything())).thenResolve(); + when(mockFs.stat(anything())).thenReject(FileSystemError.FileNotFound()); + when(mockFs.createDirectory(anything())).thenResolve(); + when(mockFs.writeFile(anything(), anything())).thenCall(async (uri: Uri, content: Uint8Array) => { + files.set(uri.fsPath, content); + }); + when(mockFs.readFile(anything())).thenCall(async (uri: Uri) => { + const content = files.get(uri.fsPath); + if (!content) { + throw FileSystemError.FileNotFound(uri); + } + + return content; + }); + when(mockedVSCodeNamespaces.workspace.fs).thenReturn(instance(mockFs)); + }); + + teardown(() => { + sinon.restore(); + }); + + test('starts deleting the runs folder when constructed', () => { + new AppPreviewRunFiles(STORAGE); + + verify(mockFs.delete(anything(), anything())).once(); + const [folder, options] = capture(mockFs.delete).last(); + assert.strictEqual(folder.fsPath, '/storage/appPreview/runs'); + assert.deepStrictEqual(options, { recursive: true, useTrash: false }); + }); + + test('writes the file of a run only after the delete settles', async () => { + const deleted = createDeferred(); + when(mockFs.delete(anything(), anything())).thenReturn(deleted.promise); + const runFiles = new AppPreviewRunFiles(STORAGE); + + const written = runFiles.write('run-1', RUN_FILE); + // A write that skipped the delete would reach writeFile before setImmediate fires, as every other fs mock + // settles at once. + await new Promise((resolve) => setImmediate(resolve)); + verify(mockFs.writeFile(anything(), anything())).never(); + + deleted.resolve(); + + assert.isTrue(await written); + assert.deepStrictEqual([...files.keys()], [RUN_FILE_PATH]); + }); + + test('logs no warning when there is no runs folder to delete', async () => { + const warn = sinon.stub(logger, 'warn'); + when(mockFs.delete(anything(), anything())).thenReject(FileSystemError.FileNotFound()); + + assert.isTrue(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE)); + sinon.assert.notCalled(warn); + }); + + test('logs a warning when the delete fails, and still writes', async () => { + const warn = sinon.stub(logger, 'warn'); + const deleteFailure = new Error('Permission denied'); + when(mockFs.delete(anything(), anything())).thenReject(deleteFailure); + + assert.isTrue(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE)); + sinon.assert.calledOnceWithExactly(warn, sinon.match.string, deleteFailure); + assert.deepStrictEqual([...files.keys()], [RUN_FILE_PATH]); + }); + + test('resolves false and logs an error naming the run when the file cannot be written', async () => { + const logError = sinon.stub(logger, 'error'); + const writeFailure = new Error('Disk full'); + when(mockFs.writeFile(anything(), anything())).thenReject(writeFailure); + + assert.isFalse(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE)); + sinon.assert.calledOnce(logError); + assert.include(logError.firstCall.args[0], 'run-1'); + assert.strictEqual(logError.firstCall.args[1], writeFailure); + }); + + test('resolves false, and writes nothing, when the runs folder cannot be created', async () => { + when(mockFs.createDirectory(anything())).thenReject(new Error('Permission denied')); + + assert.isFalse(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE)); + assert.deepStrictEqual([...files.keys()], []); + }); + + test('reads back the outputs and execution of a written run', async () => { + const runFiles = new AppPreviewRunFiles(STORAGE); + await runFiles.write('run-1', RUN_FILE); + + const file = await runFiles.read('run-1'); + + assert.deepStrictEqual( + file.project.notebooks[0].blocks.map((block) => ({ + id: block.id, + outputs: 'outputs' in block ? block.outputs : undefined + })), + [ + { id: 'total', outputs: [{ output_type: 'stream', name: 'stdout', text: '3\n' }] }, + { id: 'never-ran', outputs: [] } + ] + ); + assert.deepStrictEqual(file.execution, { + startedAt: '2026-01-02T03:04:05.000Z', + finishedAt: '2026-01-02T03:04:09.000Z' + }); + }); + + test('rejects reading a run that has no file', async () => { + await assert.isRejected(new AppPreviewRunFiles(STORAGE).read('run-unknown')); + }); +}); diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts new file mode 100644 index 0000000000..b0c27b6b8f --- /dev/null +++ b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.ts @@ -0,0 +1,249 @@ +import { generateSortingKey, type DeepnoteFile } from '@deepnote/blocks'; +import { mergeOutputsIntoFile } from '@deepnote/convert'; +import { ExecutionEngine, type BlockExecutionResult, type IError, type IOutput } from '@deepnote/runtime-core'; +import { inject, injectable } from 'inversify'; +import { workspace, type CancellationToken, type Disposable, type Uri } from 'vscode'; + +import { + DeepnoteToolkitDependencyResponse, + IDeepnoteServerStarter, + IDeepnoteToolkitDependencyService +} from '../../../kernels/deepnote/types'; +import { Cancellation } from '../../../platform/common/cancellation'; +import { getDisplayPath, getFilePath } from '../../../platform/common/platform/fs-paths.node'; +import { DeepnoteAppPreview } from '../../../platform/common/utils/localize'; +import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; +import { logger } from '../../../platform/logging'; +import * as path from '../../../platform/vscode-path/path'; +import { adaptInitBlockContent, findSiblingInitNotebook } from '../deepnoteInitNotebookRunner.node'; +import { IDeepnoteNotebookInterpreters } from '../deepnoteNotebookInterpreters'; +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: '; + +const STOPPED: AppPreviewRunOutcome = { status: 'stopped', error: null, file: null }; + +interface NotebookRun { + failure: BlockExecutionResult | undefined; + outputs: Map; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** runtime-core sets `error` only when running the block threw; a Python exception arrives as an `error` output. */ +function failureMessage(result: BlockExecutionResult): string { + if (result.error?.message) { + return result.error.message; + } + + const output = result.outputs.find((candidate): candidate is IError => candidate.output_type === 'error'); + const detail = output ? [output.ename, output.evalue].filter(Boolean).join(': ') : ''; + + return detail || DeepnoteAppPreview.blockFailed(result.blockId); +} + +async function findInitNotebook( + file: DeepnoteFile, + fileUri: Uri, + notebookId: string +): Promise { + const { id: projectId, initNotebookId, notebooks } = file.project; + if (!initNotebookId || initNotebookId === notebookId) { + return undefined; + } + + const init = + notebooks.find((notebook) => notebook.id === initNotebookId) ?? + (await findSiblingInitNotebook(fileUri, projectId, initNotebookId)); + if (!init) { + logger.warn(`AppPreviewRunner: No init notebook ${initNotebookId} found for ${getDisplayPath(fileUri)}`); + } + + return init; +} + +function internalError(message: string): AppPreviewRunOutcome { + return { status: 'internal_error', error: message, file: null }; +} + +/** + * A copy of `file` holding only `notebook`, its blocks re-keyed in Deepnote's order: runtime-core sorts blocks with + * `localeCompare`, which would run Deepnote's key `a0` before `Z0j`. + */ +function runCopy(file: DeepnoteFile, notebook: DeepnoteNotebook): DeepnoteFile { + const copy = structuredClone({ ...file, project: { ...file.project, notebooks: [notebook] } }); + const [copied] = copy.project.notebooks; + copied.blocks = blocksInNotebookOrder(copied); + copied.blocks.forEach((block, index) => { + block.sortingKey = generateSortingKey(index); + }); + + return copy; +} + +async function runNotebook( + engine: ExecutionEngine, + file: DeepnoteFile, + signal: AbortSignal, + inputs?: Record +): Promise { + const outputs = new Map(); + let failure: BlockExecutionResult | undefined; + const summary = await engine.runProject(file, { + ...(inputs ? { inputs } : {}), + integrations: file.project.integrations ?? [], + onBlockDone: (result) => { + outputs.set(result.blockId, result.outputs); + if (!result.success) { + failure = result; + } + }, + signal + }); + + // runtime-core reports a failed block an agent added without stopping the run or counting it in failedBlocks. + // A counted failure stops the run, so the last failure reported is the one that stopped it. + return { failure: summary.failedBlocks > 0 ? failure : undefined, outputs }; +} + +/** After a run, `file`'s input blocks hold the run's input values: runtime-core writes them in place. */ +function withOutputs(file: DeepnoteFile, outputs: Map, startedAt: string): DeepnoteFile { + const blockOutputs = file.project.notebooks[0].blocks.map((block) => ({ + id: block.id, + outputs: outputs.get(block.id) ?? [] + })); + + return mergeOutputsIntoFile(file, blockOutputs, { startedAt, finishedAt: new Date().toISOString() }); +} + +@injectable() +export class AppPreviewRunner implements IAppPreviewRunner { + constructor( + @inject(IDeepnoteNotebookInterpreters) private readonly interpreters: IDeepnoteNotebookInterpreters, + @inject(IDeepnoteServerStarter) private readonly serverStarter: IDeepnoteServerStarter, + @inject(IDeepnoteToolkitDependencyService) private readonly toolkit: IDeepnoteToolkitDependencyService + ) {} + + public async run( + request: AppPreviewRunRequest, + token: CancellationToken, + onRunning: () => void + ): Promise { + try { + return await this.execute(request, token, onRunning); + } catch (error) { + if (token.isCancellationRequested) { + return STOPPED; + } + logger.error( + `AppPreviewRunner: Could not run the notebook ${request.notebookId} of ${getDisplayPath( + request.fileUri + )}`, + error + ); + + return internalError(errorMessage(error)); + } + } + + private async execute( + { createdAt, file, fileUri, inputs, notebookId }: AppPreviewRunRequest, + token: CancellationToken, + onRunning: () => void + ): Promise { + const target = file.project.notebooks.find((notebook) => notebook.id === notebookId); + if (!target) { + throw new Error(DeepnoteAppPreview.notebookNotInFile(notebookId)); + } + const init = await findInitNotebook(file, fileUri, notebookId); + const targetCopy = runCopy(file, target); + const initCopy = init ? runCopy(file, init) : undefined; + for (const block of initCopy?.project.notebooks[0].blocks ?? []) { + if (block.type === 'code') { + block.content = adaptInitBlockContent(block.content ?? ''); + } + } + + // The integration endpoint gives a kernel its SQL credentials only for notebooks open in VS Code. + await workspace.openNotebookDocument(fileUri); + Cancellation.throwIfCanceled(token); + + const interpreter = await this.interpreters.resolve(fileUri); + Cancellation.throwIfCanceled(token); + if (!interpreter) { + return internalError(DeepnoteAppPreview.noInterpreter); + } + + const dependency = await this.toolkit.ensureToolkitInstalled(interpreter, fileUri, token); + Cancellation.throwIfCanceled(token); + // No picker from a run the page started: switching pins the notebook's interpreter and rebuilds its kernel. + if (dependency === DeepnoteToolkitDependencyResponse.selectDifferentInterpreter) { + return internalError(DeepnoteAppPreview.selectDifferentInterpreter); + } + if (dependency !== DeepnoteToolkitDependencyResponse.ok) { + return internalError(DeepnoteAppPreview.toolkitNotInstalled); + } + + const server = await this.serverStarter.startServer(interpreter, fileUri, token); + Cancellation.throwIfCanceled(token); + + logger.info(`AppPreviewRunner: Running the notebook ${notebookId} of ${getDisplayPath(fileUri)}`); + const engine = new ExecutionEngine( + { pythonEnv: getFilePath(interpreter.uri), workingDirectory: path.dirname(fileUri.fsPath) }, + { server } + ); + let stopping: Promise | undefined; + // Overlapping stop() calls make runtime-core throw. + const stop = () => { + stopping ??= engine + .stop() + .catch((error) => logger.warn('AppPreviewRunner: Could not stop the kernel', error)); + }; + const abortController = new AbortController(); + let onCancel: Disposable | undefined; + try { + await engine.start(); + Cancellation.throwIfCanceled(token); + // stop() fails an executing code block and shuts the kernel down, but an agent block keeps waiting on its + // model until the signal aborts. Either way runProject then resolves. + onCancel = token.onCancellationRequested(() => { + abortController.abort(); + stop(); + }); + onRunning(); + + if (initCopy) { + const { failure } = await runNotebook(engine, initCopy, abortController.signal); + if (token.isCancellationRequested) { + return STOPPED; + } + if (failure) { + return { + status: 'error', + error: `${INIT_NOTEBOOK_FAILED_PREFIX}${failureMessage(failure)}`, + file: withOutputs(targetCopy, new Map(), createdAt) + }; + } + } + + const { failure, outputs } = await runNotebook(engine, targetCopy, abortController.signal, inputs); + if (token.isCancellationRequested) { + return STOPPED; + } + + return { + status: failure ? 'error' : 'success', + error: failure ? failureMessage(failure) : null, + file: withOutputs(targetCopy, outputs, createdAt) + }; + } finally { + onCancel?.dispose(); + // Not awaited, so the outcome isn't held back while the kernel shuts down. + stop(); + } + } +} diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts new file mode 100644 index 0000000000..0c0d77b98c --- /dev/null +++ b/src/notebooks/deepnote/appPreview/appPreviewRunner.node.unit.test.ts @@ -0,0 +1,836 @@ +import { + deserializeDeepnoteFile, + isExecutableBlock, + isInputBlock, + type DeepnoteBlock, + type DeepnoteFile +} from '@deepnote/blocks'; +import type { + BlockExecutionResult, + ExecutionEngine, + ExecutionEngineOptions, + ExecutionOptions, + ExecutionSummary, + RuntimeConfig +} from '@deepnote/runtime-core'; +import { assert } from 'chai'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as sinon from 'sinon'; +import { anything, capture, instance, mock, verify, when } from 'ts-mockito'; +import { CancellationError, CancellationTokenSource, Uri } from 'vscode'; + +import { + DeepnoteToolkitDependencyResponse, + type DeepnoteServerInfo, + type IDeepnoteServerStarter, + type IDeepnoteToolkitDependencyService +} from '../../../kernels/deepnote/types'; +import { createDeferred, type Deferred } from '../../../platform/common/utils/async'; +import type { DeepnoteNotebook } from '../../../platform/deepnote/deepnoteTypes'; +import { logger } from '../../../platform/logging'; +import type { PythonEnvironment } from '../../../platform/pythonEnvironments/info'; +import * as path from '../../../platform/vscode-path/path'; +import { __resetRuntimeCoreMock, __useExecutionEngine } from '../../../test/mocks/deepnoteRuntimeCore'; +import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs'; +import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock'; +import type { IDeepnoteNotebookInterpreters } from '../deepnoteNotebookInterpreters'; +import { + createDeepnoteBlock, + createDeepnoteFile, + createDeepnoteNotebook, + createDeepnoteProject, + DEEPNOTE_CLOUD_INIT_BLOCK, + WINDOWS_INIT_BLOCK +} from '../deepnoteTestHelpers'; +import { AppPreviewRunner } from './appPreviewRunner.node'; +import type { AppPreviewRunOutcome, AppPreviewRunRequest } from './types'; + +const CREATED_AT = '2026-11-22T10:00:00.000Z'; +const FINISHED_AT = '2026-11-22T10:00:05.000Z'; +const INTERPRETER: PythonEnvironment = { id: 'venv', uri: Uri.file('/venv/bin/python') }; +const SERVER = { url: 'http://127.0.0.1:8888', jupyterPort: 8888, lspPort: 8889 } as DeepnoteServerInfo; + +type BlockResult = Partial>; + +type Step = 'open' | 'resolve' | 'ensureToolkit' | 'startServer' | 'start' | 'running'; + +function textInput(id: string, name: string, value: string, sortingKey = 'a0'): DeepnoteBlock { + return { + id, + type: 'input-text', + blockGroup: 'g', + sortingKey, + metadata: { deepnote_variable_name: name, deepnote_variable_value: value } + }; +} + +function notebookOf(id: string, blocks: DeepnoteBlock[]): DeepnoteNotebook { + return createDeepnoteNotebook({ id, name: id, blocks }); +} + +function projectFile(notebooks: DeepnoteNotebook[], initNotebookId?: string): DeepnoteFile { + return createDeepnoteFile({ + project: createDeepnoteProject({ id: 'project-1', notebooks, ...(initNotebookId ? { initNotebookId } : {}) }) + }); +} + +/** The fields of the run file's blocks that `GET /v2/runs/:runId` answers. */ +function runFileBlocks(outcome: AppPreviewRunOutcome) { + return outcome.file?.project.notebooks[0].blocks.map((block) => ({ + id: block.id, + type: block.type, + outputs: 'outputs' in block ? block.outputs : undefined, + metadata: block.metadata + })); +} + +/** The order runtime-core 0.8.0 runs a file's blocks in. */ +function executionOrder(file: DeepnoteFile): DeepnoteBlock[] { + return file.project.notebooks.flatMap((notebook) => + [...notebook.blocks] + .sort((a, b) => a.sortingKey.localeCompare(b.sortingKey)) + .filter((block) => isExecutableBlock(block)) + ); +} + +/** + * A `runProject` that behaves like runtime-core 0.8.0's: it writes the inputs into the file's input blocks in place + * and stops at the first failure. + */ +function runtimeCoreLike(results: Record = {}) { + return async (file: DeepnoteFile, options: ExecutionOptions): Promise => { + for (const block of file.project.notebooks.flatMap((notebook) => notebook.blocks)) { + const name = isInputBlock(block) ? block.metadata.deepnote_variable_name : undefined; + if (isInputBlock(block) && name !== undefined && options.inputs && name in options.inputs) { + block.metadata.deepnote_variable_value = options.inputs[name] as string; + } + } + + const blocks = executionOrder(file); + let executedBlocks = 0; + for (const block of blocks) { + const result: BlockExecutionResult = { + blockId: block.id, + blockType: block.type, + success: true, + outputs: [], + executionCount: null, + durationMs: 1, + ...results[block.id] + }; + await options.onBlockDone?.(result); + executedBlocks++; + if (!result.success) { + return { totalBlocks: blocks.length, executedBlocks, failedBlocks: 1, totalDurationMs: 1 }; + } + } + + return { totalBlocks: blocks.length, executedBlocks, failedBlocks: 0, totalDurationMs: 1 }; + }; +} + +/** A run whose block executes until the engine is stopped, then fails as runtime-core reports it. */ +function failWhenStopped(blockId: string, stopped: Promise, running: Deferred) { + return async (_file: DeepnoteFile, options: ExecutionOptions): Promise => { + running.resolve(); + await stopped; + await options.onBlockDone?.({ + blockId, + blockType: 'code', + success: false, + outputs: [], + executionCount: null, + durationMs: 1, + error: new Error('Kernel client disconnected while an execution was in flight.') + }); + + return { totalBlocks: 1, executedBlocks: 1, failedBlocks: 1, totalDurationMs: 1 }; + }; +} + +/** A run whose agent block waits on its model until the run's signal aborts, which stopping the kernel doesn't do. */ +function agentUntilAborted(blockId: string, running: Deferred) { + return async (_file: DeepnoteFile, options: ExecutionOptions): Promise => { + running.resolve(); + await new Promise((resolve) => options.signal?.addEventListener('abort', resolve)); + await options.onBlockDone?.({ + blockId, + blockType: 'agent', + success: false, + outputs: [], + executionCount: null, + durationMs: 1, + error: new Error('This operation was aborted') + }); + + return { totalBlocks: 1, executedBlocks: 1, failedBlocks: 1, totalDurationMs: 1 }; + }; +} + +suite('AppPreviewRunner', () => { + let tmp: string; + let steps: Step[]; + let interpreters: IDeepnoteNotebookInterpreters; + let toolkit: IDeepnoteToolkitDependencyService; + let serverStarter: IDeepnoteServerStarter; + let engine: ExecutionEngine; + let createEngine: sinon.SinonStub<[RuntimeConfig, ExecutionEngineOptions?], ExecutionEngine>; + let stopped: Deferred; + let cancellation: CancellationTokenSource; + let runner: AppPreviewRunner; + + function write(name: string, file: DeepnoteFile): Uri { + const fileUri = Uri.file(path.join(tmp, name)); + // JSON is YAML, and keeps the sorting keys, which the `.deepnote` serializer would rewrite. + fs.writeFileSync(fileUri.fsPath, JSON.stringify(file)); + + return fileUri; + } + + function run(fileUri: Uri, notebookId: string, inputs: AppPreviewRunRequest['inputs'] = {}) { + const file = deserializeDeepnoteFile(fs.readFileSync(fileUri.fsPath, 'utf8')); + + return runner.run({ createdAt: CREATED_AT, file, fileUri, notebookId, inputs }, cancellation.token, () => + steps.push('running') + ); + } + + function runProjectCalls(count: number) { + verify(engine.runProject(anything(), anything())).times(count); + const runProject = capture(engine.runProject); + + return Array.from({ length: count }, (_, index) => runProject.byCallIndex(index)); + } + + function notebookIdsPerCall(count: number): string[][] { + return runProjectCalls(count).map(([file]) => file.project.notebooks.map((notebook) => notebook.id)); + } + + setup(() => { + resetVSCodeMocks(); + __resetRuntimeCoreMock(); + stubWorkspaceFsOnDisk(); + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-runner-')); + steps = []; + cancellation = new CancellationTokenSource(); + + when(mockedVSCodeNamespaces.workspace.openNotebookDocument(anything())).thenCall(async () => { + steps.push('open'); + }); + interpreters = mock(); + when(interpreters.resolve(anything())).thenCall(async () => { + steps.push('resolve'); + + return INTERPRETER; + }); + toolkit = mock(); + when(toolkit.ensureToolkitInstalled(anything(), anything(), anything())).thenCall(async () => { + steps.push('ensureToolkit'); + + return DeepnoteToolkitDependencyResponse.ok; + }); + serverStarter = mock(); + when(serverStarter.startServer(anything(), anything(), anything())).thenCall(async () => { + steps.push('startServer'); + + return SERVER; + }); + engine = mock(); + stopped = createDeferred(); + when(engine.start()).thenCall(async () => { + steps.push('start'); + }); + when(engine.runProject(anything(), anything())).thenCall(runtimeCoreLike()); + when(engine.stop()).thenCall(async () => stopped.resolve()); + createEngine = sinon + .stub<[RuntimeConfig, ExecutionEngineOptions?], ExecutionEngine>() + .returns(instance(engine)); + __useExecutionEngine(createEngine); + + runner = new AppPreviewRunner(instance(interpreters), instance(serverStarter), instance(toolkit)); + }); + + teardown(() => { + sinon.restore(); + cancellation.dispose(); + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + suite('what it runs', () => { + test("opens the file's notebook, then starts a kernel on the file's toolkit server, then runs", async () => { + const fileUri = write('main.deepnote', projectFile([notebookOf('nb-1', [createDeepnoteBlock()])])); + + await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(steps, ['open', 'resolve', 'ensureToolkit', 'startServer', 'start', 'running']); + verify(mockedVSCodeNamespaces.workspace.openNotebookDocument(fileUri)).once(); + sinon.assert.calledOnceWithExactly( + createEngine, + { pythonEnv: '/venv/bin/python', workingDirectory: tmp }, + { server: SERVER } + ); + }); + + test('runs the init notebook of the same file first, then the notebook, as separate runs on one kernel', async () => { + const fileUri = write( + 'main.deepnote', + projectFile( + [ + notebookOf('nb-other', [createDeepnoteBlock({ id: 'other' })]), + notebookOf('nb-1', [createDeepnoteBlock({ id: 'main' })]), + notebookOf('nb-init', [createDeepnoteBlock({ id: 'setup' })]) + ], + 'nb-init' + ) + ); + + await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(notebookIdsPerCall(2), [['nb-init'], ['nb-1']]); + sinon.assert.calledOnce(createEngine); + }); + + test("gives the project's integrations to the init notebook's run and the notebook's run", async () => { + const integrations = [{ id: 'pg', name: 'Postgres', type: 'pgsql' }]; + const file = projectFile( + [notebookOf('nb-1', [createDeepnoteBlock()]), notebookOf('nb-init', [createDeepnoteBlock()])], + 'nb-init' + ); + const fileUri = write('main.deepnote', { ...file, project: { ...file.project, integrations } }); + + await run(fileUri, 'nb-1'); + + assert.deepStrictEqual( + runProjectCalls(2).map(([, options]) => options?.integrations), + [integrations, integrations] + ); + }); + + test("runs the init notebook from a sibling file of the same project when the file doesn't have it", async () => { + const fileUri = write( + 'main.deepnote', + projectFile([notebookOf('nb-1', [createDeepnoteBlock()])], 'nb-init') + ); + write( + 'init.deepnote', + projectFile([notebookOf('nb-init', [createDeepnoteBlock({ id: 'setup', content: 'import os' })])]) + ); + + await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(notebookIdsPerCall(2), [['nb-init'], ['nb-1']]); + assert.deepInclude(capture(engine.runProject).first()[0].project.notebooks[0].blocks[0], { + id: 'setup', + content: 'import os' + }); + }); + + const withoutInit: [string, string][] = [ + ['the notebook is the init notebook', 'nb-1'], + ['no file has the init notebook', 'nb-init'] + ]; + for (const [condition, initNotebookId] of withoutInit) { + test(`runs only the notebook when ${condition}`, async () => { + const fileUri = write( + 'main.deepnote', + projectFile([notebookOf('nb-1', [createDeepnoteBlock()])], initNotebookId) + ); + + const outcome = await run(fileUri, 'nb-1'); + + assert.strictEqual(outcome.status, 'success'); + assert.deepStrictEqual(notebookIdsPerCall(1), [['nb-1']]); + }); + } + + test("passes the inputs to the notebook's run only, so the init notebook keeps its saved values", async () => { + const file = projectFile( + [ + notebookOf('nb-init', [ + { + id: 'init-x', + type: 'input-checkbox', + blockGroup: 'g', + sortingKey: 'a0', + metadata: { deepnote_variable_name: 'x', deepnote_variable_value: false } + } + ]), + notebookOf('nb-1', [textInput('x', 'x', 'saved')]) + ], + 'nb-init' + ); + const fileUri = write('main.deepnote', file); + const onDisk = fs.readFileSync(fileUri.fsPath, 'utf8'); + + await run(fileUri, 'nb-1', { x: 'hello' }); + + const [[initFile, initOptions], [, notebookOptions]] = runProjectCalls(2); + assert.isUndefined(initOptions?.inputs); + assert.deepInclude(initFile.project.notebooks[0].blocks[0].metadata, { + deepnote_variable_value: false + }); + assert.deepStrictEqual(notebookOptions?.inputs, { x: 'hello' }); + assert.strictEqual(fs.readFileSync(fileUri.fsPath, 'utf8'), onDisk); + }); + + test('runs the file in the request, not one saved since without its input', async () => { + const checked = projectFile([notebookOf('nb-1', [textInput('region', 'region', 'Europe')])]); + const fileUri = write( + 'main.deepnote', + projectFile([notebookOf('nb-1', [createDeepnoteBlock({ id: 'chart' })])]) + ); + + await runner.run( + { createdAt: CREATED_AT, file: checked, fileUri, notebookId: 'nb-1', inputs: { region: 'Asia' } }, + cancellation.token, + () => undefined + ); + + const [[file]] = runProjectCalls(1); + assert.deepStrictEqual( + file.project.notebooks[0].blocks.map((block) => block.id), + ['region'] + ); + }); + + test("runs the blocks in Deepnote's sorting key order, which runtime-core's localeCompare would not", async () => { + const fileUri = write( + 'main.deepnote', + projectFile([ + notebookOf('nb-1', [ + createDeepnoteBlock({ id: 'lower', sortingKey: 'a0' }), + createDeepnoteBlock({ id: 'upper', sortingKey: 'Z0j' }), + createDeepnoteBlock({ id: 'first', sortingKey: 'V' }) + ]) + ]) + ); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual( + executionOrder(capture(engine.runProject).first()[0]).map((block) => block.id), + ['first', 'upper', 'lower'] + ); + assert.deepStrictEqual( + outcome.file?.project.notebooks[0].blocks.map((block) => block.id), + ['first', 'upper', 'lower'] + ); + }); + + test("runs Windows' replacement for Deepnote Cloud's init block on Windows, and leaves the file alone", async () => { + sinon.stub(process, 'platform').value('win32'); + const fileUri = write( + 'main.deepnote', + projectFile( + [ + notebookOf('nb-init', [ + createDeepnoteBlock({ id: 'setup', content: DEEPNOTE_CLOUD_INIT_BLOCK }) + ]), + notebookOf('nb-1', [createDeepnoteBlock({ id: 'main', content: DEEPNOTE_CLOUD_INIT_BLOCK })]) + ], + 'nb-init' + ) + ); + const onDisk = fs.readFileSync(fileUri.fsPath, 'utf8'); + + await run(fileUri, 'nb-1'); + + const contents = runProjectCalls(2).map(([file]) => + file.project.notebooks[0].blocks.map((block) => (block.type === 'code' ? block.content : '')) + ); + assert.deepStrictEqual(contents, [[WINDOWS_INIT_BLOCK], [DEEPNOTE_CLOUD_INIT_BLOCK]]); + assert.strictEqual(fs.readFileSync(fileUri.fsPath, 'utf8'), onDisk); + }); + }); + + suite('outcomes', () => { + let fileUri: Uri; + + setup(() => { + fileUri = write( + 'main.deepnote', + projectFile([ + notebookOf('nb-1', [ + textInput('region', 'region', 'Europe', 'a0'), + createDeepnoteBlock({ id: 'chart', sortingKey: 'a1' }), + createDeepnoteBlock({ id: 'table', sortingKey: 'a2' }), + { id: 'notes', type: 'markdown', blockGroup: 'g', sortingKey: 'a3', content: '', metadata: {} } + ]) + ]) + ); + }); + + const chartOutput = { output_type: 'display_data', data: { 'application/json': { total: 3 } }, metadata: {} }; + const errorOutput = { output_type: 'error', ename: 'ValueError', evalue: 'no data', traceback: [] }; + + test('succeeds with every block of the notebook and its outputs, and stops the kernel', async () => { + when(engine.runProject(anything(), anything())).thenCall( + runtimeCoreLike({ chart: { outputs: [chartOutput] } }) + ); + sinon.useFakeTimers({ now: Date.parse(FINISHED_AT), toFake: ['Date'] }); + + const outcome = await run(fileUri, 'nb-1', { region: 'Asia' }); + + assert.strictEqual(outcome.status, 'success'); + assert.isNull(outcome.error); + assert.deepStrictEqual(outcome.file?.execution, { startedAt: CREATED_AT, finishedAt: FINISHED_AT }); + assert.deepStrictEqual(runFileBlocks(outcome), [ + { + id: 'region', + type: 'input-text', + outputs: [], + metadata: { deepnote_variable_name: 'region', deepnote_variable_value: 'Asia' } + }, + { id: 'chart', type: 'code', outputs: [chartOutput], metadata: {} }, + { id: 'table', type: 'code', outputs: [], metadata: {} }, + { id: 'notes', type: 'markdown', outputs: [], metadata: {} } + ]); + verify(engine.stop()).once(); + }); + + test('succeeds before the kernel has shut down', async () => { + when(engine.stop()).thenReturn(createDeferred().promise); + + const outcome = await run(fileUri, 'nb-1'); + + assert.strictEqual(outcome.status, 'success'); + verify(engine.stop()).once(); + }); + + test('succeeds when the kernel fails to shut down, and logs the failure', async () => { + const warn = sinon.stub(logger, 'warn'); + const failure = new Error('The kernel did not shut down'); + when(engine.stop()).thenReject(failure); + + const outcome = await run(fileUri, 'nb-1'); + + assert.strictEqual(outcome.status, 'success'); + await waitFor(() => warn.called); + sinon.assert.calledWithMatch(warn, sinon.match.string, failure); + }); + + const failures: [string, BlockResult, string][] = [ + ['a Python exception', { success: false, outputs: [errorOutput] }, 'ValueError: no data'], + [ + 'an error running the block', + { success: false, outputs: [errorOutput], error: new Error('The kernel died') }, + 'The kernel died' + ], + ['no error', { success: false, outputs: [] }, 'Block table failed.'] + ]; + for (const [condition, tableResult, message] of failures) { + test(`fails with the block's message for ${condition}, keeping the outputs so far`, async () => { + when(engine.runProject(anything(), anything())).thenCall( + runtimeCoreLike({ chart: { outputs: [chartOutput] }, table: tableResult }) + ); + + const outcome = await run(fileUri, 'nb-1'); + + assert.strictEqual(outcome.status, 'error'); + assert.strictEqual(outcome.error, message); + assert.deepStrictEqual( + runFileBlocks(outcome)?.map((block) => [block.id, block.outputs]), + [ + ['region', []], + ['chart', [chartOutput]], + ['table', tableResult.outputs], + ['notes', []] + ] + ); + verify(engine.stop()).once(); + }); + } + + test('succeeds when only a block an agent added failed, as runtime-core carries on then', async () => { + when(engine.runProject(anything(), anything())).thenCall( + async (_file: DeepnoteFile, options: ExecutionOptions): Promise => { + await options.onBlockDone?.({ + blockId: 'agent-added', + blockType: 'code', + success: false, + outputs: [errorOutput], + executionCount: null, + durationMs: 0 + }); + + return { totalBlocks: 1, executedBlocks: 1, failedBlocks: 0, totalDurationMs: 1 }; + } + ); + + const outcome = await run(fileUri, 'nb-1'); + + assert.strictEqual(outcome.status, 'success'); + assert.isNull(outcome.error); + }); + + test('fails with the init block\'s message after "Init notebook failed: ", without running the notebook', async () => { + const withInit = write( + 'with-init.deepnote', + projectFile( + [ + notebookOf('nb-init', [createDeepnoteBlock({ id: 'setup' })]), + notebookOf('nb-1', [createDeepnoteBlock({ id: 'chart' })]) + ], + 'nb-init' + ) + ); + when(engine.runProject(anything(), anything())).thenCall( + runtimeCoreLike({ setup: { success: false, outputs: [errorOutput] } }) + ); + sinon.useFakeTimers({ now: Date.parse(FINISHED_AT), toFake: ['Date'] }); + + const outcome = await run(withInit, 'nb-1'); + + assert.strictEqual(outcome.status, 'error'); + assert.strictEqual(outcome.error, 'Init notebook failed: 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']]); + verify(engine.stop()).once(); + }); + + test('is an internal error, without a kernel, when the notebook has no interpreter', async () => { + when(interpreters.resolve(anything())).thenResolve(undefined); + + const outcome = await run(fileUri, 'nb-1'); + + 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.', + 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.selectDifferentInterpreter, + 'Open the notebook in VS Code and run Deepnote: Select Interpreter for Notebook, then run the app again.' + ], + [DeepnoteToolkitDependencyResponse.failed, toolkitNotInstalled] + ]; + for (const [response, message] of declined) { + test(`is an internal error, without a server, when the toolkit install answers ${DeepnoteToolkitDependencyResponse[response]}`, async () => { + when(toolkit.ensureToolkitInstalled(anything(), anything(), anything())).thenResolve(response); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(outcome, { status: 'internal_error', error: message, file: null }); + assert.notInclude(steps, 'startServer'); + }); + } + + test('is an internal error with the message when the server fails to start', async () => { + when(serverStarter.startServer(anything(), anything(), anything())).thenReject( + new Error('The server exited') + ); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(outcome, { + status: 'internal_error', + error: 'The server exited', + file: null + }); + sinon.assert.notCalled(createEngine); + }); + + const engineFailures: [string, () => void][] = [ + ['the kernel fails to start', () => when(engine.start()).thenReject(new Error('The kernel died'))], + [ + 'running the notebook throws', + () => when(engine.runProject(anything(), anything())).thenReject(new Error('The kernel died')) + ] + ]; + for (const [condition, arrange] of engineFailures) { + test(`is an internal error with the message, and stops the kernel, when ${condition}`, async () => { + arrange(); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(outcome, { + status: 'internal_error', + error: 'The kernel died', + file: null + }); + verify(engine.stop()).once(); + }); + } + }); + + suite('cancellation', () => { + let fileUri: Uri; + + setup(() => { + fileUri = write('main.deepnote', projectFile([notebookOf('nb-1', [createDeepnoteBlock()])])); + }); + + const stoppedSteps: [string, () => void, Step[]][] = [ + [ + 'the notebook opens', + () => + when(mockedVSCodeNamespaces.workspace.openNotebookDocument(anything())).thenCall(async () => { + steps.push('open'); + cancellation.cancel(); + }), + ['open'] + ], + [ + 'the interpreter resolves', + () => + when(interpreters.resolve(anything())).thenCall(async () => { + steps.push('resolve'); + cancellation.cancel(); + + return INTERPRETER; + }), + ['open', 'resolve'] + ], + [ + 'the toolkit install is checked', + () => + when(toolkit.ensureToolkitInstalled(anything(), anything(), anything())).thenCall(async () => { + steps.push('ensureToolkit'); + cancellation.cancel(); + + return DeepnoteToolkitDependencyResponse.cancel; + }), + ['open', 'resolve', 'ensureToolkit'] + ], + [ + 'the server starts', + () => + when(serverStarter.startServer(anything(), anything(), anything())).thenCall(async () => { + steps.push('startServer'); + cancellation.cancel(); + + return SERVER; + }), + ['open', 'resolve', 'ensureToolkit', 'startServer'] + ], + [ + 'the server starts, which then throws', + () => + when(serverStarter.startServer(anything(), anything(), anything())).thenCall(async () => { + steps.push('startServer'); + cancellation.cancel(); + throw new CancellationError(); + }), + ['open', 'resolve', 'ensureToolkit', 'startServer'] + ] + ]; + for (const [step, arrange, expectedSteps] of stoppedSteps) { + test(`stops before the next step when cancelled while ${step}`, async () => { + arrange(); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(outcome, { status: 'stopped', error: null, file: null }); + assert.deepStrictEqual(steps, expectedSteps); + sinon.assert.notCalled(createEngine); + }); + } + + test('stops without running, and stops the kernel, when cancelled while the kernel starts', async () => { + const kernelStarting = createDeferred(); + const kernelStarted = createDeferred(); + when(engine.start()).thenCall(() => { + kernelStarting.resolve(); + + return kernelStarted.promise; + }); + + const outcome = run(fileUri, 'nb-1'); + await kernelStarting.promise; + cancellation.cancel(); + kernelStarted.resolve(); + + assert.deepStrictEqual(await outcome, { status: 'stopped', error: null, file: null }); + verify(engine.runProject(anything(), anything())).never(); + verify(engine.stop()).once(); + assert.notInclude(steps, 'running'); + }); + + const cancelCounts: [string, number][] = [ + ['once', 1], + ['twice', 2] + ]; + for (const [times, count] of cancelCounts) { + test(`stops the kernel once, and ends stopped, when cancelled ${times} while a block runs`, async () => { + const blockRunning = createDeferred(); + when(engine.runProject(anything(), anything())).thenCall( + failWhenStopped('block-1', stopped.promise, blockRunning) + ); + + const outcome = run(fileUri, 'nb-1'); + await blockRunning.promise; + for (let cancelled = 0; cancelled < count; cancelled++) { + cancellation.cancel(); + } + await stopped.promise; + + assert.deepStrictEqual(await outcome, { status: 'stopped', error: null, file: null }); + verify(engine.stop()).once(); + }); + } + + test('ends stopped, without running the notebook, when cancelled while the init notebook runs', async () => { + const withInit = write( + 'with-init.deepnote', + projectFile( + [notebookOf('nb-init', [createDeepnoteBlock({ id: 'setup' })]), notebookOf('nb-1', [])], + 'nb-init' + ) + ); + const blockRunning = createDeferred(); + when(engine.runProject(anything(), anything())).thenCall( + failWhenStopped('setup', stopped.promise, blockRunning) + ); + + const outcome = run(withInit, 'nb-1'); + await blockRunning.promise; + cancellation.cancel(); + await stopped.promise; + + assert.deepStrictEqual(await outcome, { status: 'stopped', error: null, file: null }); + assert.deepStrictEqual(notebookIdsPerCall(1), [['nb-init']]); + }); + + test("aborts the agent's model request, and ends stopped, when cancelled while an agent block runs", async () => { + const agentRunning = createDeferred(); + when(engine.runProject(anything(), anything())).thenCall(agentUntilAborted('agent', agentRunning)); + + const outcome = run(fileUri, 'nb-1'); + await agentRunning.promise; + cancellation.cancel(); + + assert.isTrue(capture(engine.runProject).last()[1]?.signal?.aborted); + assert.deepStrictEqual(await outcome, { status: 'stopped', error: null, file: null }); + }); + + test('ends stopped when running throws after a cancel', async () => { + when(engine.runProject(anything(), anything())).thenCall(async () => { + cancellation.cancel(); + throw new Error('Kernel client disconnected while an execution was in flight.'); + }); + + const outcome = await run(fileUri, 'nb-1'); + + assert.deepStrictEqual(outcome, { status: 'stopped', error: null, file: null }); + }); + }); +}); + +async function waitFor(condition: () => boolean): Promise { + const deadline = Date.now() + 2_000; + while (!condition()) { + if (Date.now() > deadline) { + throw new Error('waitFor timed out'); + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts index 0670300015..b45c347fe4 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.ts @@ -8,7 +8,9 @@ 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 type { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { findNotebookById } from './appPreviewWorkspace.node'; +import type { AppPreviewApi, IAppPreviewRunner } from './types'; export interface AppPreviewProject { id: string; @@ -18,6 +20,8 @@ export interface AppPreviewProject { export interface AppPreviewSessionOptions { folder: Uri; project: AppPreviewProject | undefined; + runFiles: AppPreviewRunFiles; + runner: IAppPreviewRunner; scripts: { appClient: Uri }; onUnsupported(operation: AppPreviewOperation): void; } @@ -121,6 +125,7 @@ function swapClientScriptTags(page: string): string { * Deepnote's client in place of the hosted one, the token endpoint the client asks first, and a local API at `/v2`. */ export class AppPreviewSession implements IDisposable { + private api: AppPreviewApi | undefined; private project: AppPreviewProject | undefined; private server: http.Server | undefined; private serverUri: Uri | undefined; @@ -156,6 +161,7 @@ export class AppPreviewSession implements IDisposable { } public dispose(): void { + this.api?.dispose(); const server = this.server; this.server = undefined; if (!server) { @@ -242,14 +248,14 @@ export class AppPreviewSession implements IDisposable { }); app.post('/__deepnote/api-token', (req, res) => this.sendToken(req, res)); app.use('/__deepnote', (_req, res) => notFound(res)); - app.use( - '/v2', - createAppPreviewApi({ - token: this.token, - findNotebook: (notebookId) => findNotebookById(notebookId, this.project?.folder), - onUnsupported: (operation) => this.options.onUnsupported(operation) - }) - ); + this.api = createAppPreviewApi({ + token: this.token, + findNotebook: (notebookId) => findNotebookById(notebookId, this.project?.folder), + onUnsupported: (operation) => this.options.onUnsupported(operation), + runFiles: this.options.runFiles, + runner: this.options.runner + }); + app.use('/v2', this.api.router); app.use((req, res) => this.serveFolder(req, res)); return app; diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts index 7c3d449649..19f6a4a071 100644 --- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts +++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts @@ -3,15 +3,17 @@ import { assert } from 'chai'; import * as fs from 'fs'; import * as http from 'http'; import * as os from 'os'; -import { anything, when } from 'ts-mockito'; -import { Uri } from 'vscode'; +import { anything, instance, mock, when } from 'ts-mockito'; +import { Uri, type CancellationToken } from 'vscode'; 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 { AppPreviewRunFiles } from './appPreviewRunFiles.node'; import { AppPreviewSession, type AppPreviewProject } from './appPreviewSession.node'; +import type { AppPreviewRunOutcome, IAppPreviewRunner } from './types'; const CSP = "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:"; const CLIENT_SCRIPT = '/* the bundled client */\n'; @@ -35,7 +37,7 @@ interface RawResponse { function request( session: AppPreviewSession, urlPath: string, - options: { method?: string; host?: string; headers?: http.OutgoingHttpHeaders } = {} + options: { method?: string; host?: string; headers?: http.OutgoingHttpHeaders; body?: string } = {} ): Promise { const port = Number(new URL(session.serverUrl.toString(true)).port); @@ -60,7 +62,7 @@ function request( } ); req.on('error', reject); - req.end(); + req.end(options.body); }); } @@ -91,6 +93,15 @@ suite('AppPreviewSession', () => { let clientScript: string; let sessions: AppPreviewSession[]; let unsupported: AppPreviewOperation[]; + let runTokens: CancellationToken[]; + + const runner: IAppPreviewRunner = { + run: (_request, token) => + new Promise((resolve) => { + runTokens.push(token); + token.onCancellationRequested(() => resolve({ status: 'stopped', error: null, file: null })); + }) + }; async function startSession( options: { folder?: string; project?: AppPreviewProject | null } = {} @@ -99,6 +110,8 @@ suite('AppPreviewSession', () => { const session = new AppPreviewSession({ folder: Uri.file(options.folder ?? appFolder), project: project ?? undefined, + runFiles: instance(mock(AppPreviewRunFiles)), + runner, scripts: { appClient: Uri.file(clientScript) }, onUnsupported: (operation) => unsupported.push(operation) }); @@ -117,6 +130,7 @@ suite('AppPreviewSession', () => { setup(() => { resetVSCodeMocks(); unsupported = []; + runTokens = []; sessions = []; tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-')); appFolder = path.join(tmp, 'app'); @@ -399,6 +413,36 @@ suite('AppPreviewSession', () => { assert.strictEqual(await notebookName(), 'Copy a'); }); + + test('cancels its unfinished runs when it is disposed', async () => { + const notebook = createDeepnoteNotebook({ id: 'nb-1' }); + const file = createDeepnoteFile({ project: createDeepnoteProject({ notebooks: [notebook] }) }); + write('main.deepnote', serializeDeepnoteFile(file), tmp); + stubWorkspaceFsOnDisk(); + when(mockedVSCodeNamespaces.workspace.findFiles('**/*.deepnote')).thenCall(async () => [ + Uri.file(path.join(tmp, 'main.deepnote')) + ]); + const session = await startSession(); + const { token } = await requestToken(session); + + const created = await request(session, '/v2/runs', { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ notebookId: 'nb-1' }) + }); + assert.strictEqual(created.status, 202); + assert.deepStrictEqual( + runTokens.map((runToken) => runToken.isCancellationRequested === true), + [false] + ); + + session.dispose(); + + assert.deepStrictEqual( + runTokens.map((runToken) => runToken.isCancellationRequested === true), + [true] + ); + }); }); suite('client script swap', () => { diff --git a/src/notebooks/deepnote/appPreview/types.ts b/src/notebooks/deepnote/appPreview/types.ts new file mode 100644 index 0000000000..bff8835c0a --- /dev/null +++ b/src/notebooks/deepnote/appPreview/types.ts @@ -0,0 +1,68 @@ +import type { DeepnoteFile } from '@deepnote/blocks'; +import type { IOutput } from '@deepnote/runtime-core'; +import type { Router } from 'express'; +import type { CancellationToken, Uri } from 'vscode'; + +/** An input value a page can pass to `run()`, as Deepnote's `POST /v2/runs` accepts it. */ +export type AppPreviewInputValue = string | boolean | string[]; + +/** A block of a run's snapshot, as Deepnote's `GET /v2/runs/:runId` lists it in `snapshotBlocks`. */ +export interface SnapshotBlock { + id: string; + metadata: Record; + outputHead: null; + outputs: IOutput[]; + outputTail: null; + type: string; +} + +export interface AppPreviewRunRequest { + createdAt: string; + file: DeepnoteFile; + fileUri: Uri; + inputs: Record; + notebookId: string; +} + +export interface AppPreviewRunOutcome { + error: string | null; + file: DeepnoteFile | null; + status: 'success' | 'error' | 'internal_error' | 'stopped'; +} + +/** + * A run as Deepnote's `GET /v2/runs/:runId` answers it, without `snapshotBlocks`, which are read from the run's file, + * and the snapshot fields a local run never has. + */ +export interface PreviewRun { + completedAt: string | null; + createdAt: string; + error: string | null; + notebookId: string; + runId: string; + snapshotStatus: 'pending' | 'available' | 'unavailable'; + status: 'pending' | 'running' | AppPreviewRunOutcome['status']; +} + +export interface AppPreviewApi { + router: Router; + /** + * Cancels every unfinished run, which stops its kernel once it has one. `POST /runs` starts no run from then on and + * answers 503 instead, also to a request that was still looking up its notebook. + */ + dispose(): void; +} + +export const IAppPreviewRunner = Symbol('IAppPreviewRunner'); +export interface IAppPreviewRunner { + /** + * Runs the notebook `notebookId` of `file`, the `.deepnote` file the caller read from `fileUri`, in a new kernel on + * the toolkit server the extension runs for that file: the project's init notebook first, with its saved inputs, + * then the notebook with `inputs` applied. `onRunning` is called once the kernel is up, before the first block. + * Cancelling `token` ends the run as `stopped`, and once the kernel is up also stops the block that is executing + * and shuts the kernel down. Never rejects: failures are reported in the outcome. For `success` and `error`, the + * outcome's `file` is the run's copy of the notebook, with its outputs and an `execution` from `createdAt` to the + * run's end; otherwise it is `null`. + */ + run(request: AppPreviewRunRequest, token: CancellationToken, onRunning: () => void): Promise; +} diff --git a/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.ts b/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.ts index f624f20397..8545cd3c0d 100644 --- a/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.ts +++ b/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.ts @@ -51,6 +51,57 @@ if os.path.exists("requirements.txt"): else: print("There's no requirements.txt, so nothing to install.")`.trim(); +/** + * The content to run for an init block. On Windows, Deepnote Cloud's default `%%bash` block becomes a Python block + * that installs `requirements.txt` into the kernel's interpreter; any other content is returned unchanged. + */ +export function adaptInitBlockContent(content: string): string { + return process.platform === 'win32' && content.trim() === DEEPNOTE_CLOUD_INIT_NOTEBOOK_BLOCK_CONTENT + ? VSCODE_INIT_NOTEBOOK_BLOCK_CONTENT + : content; +} + +/** + * Scans the `.deepnote` files next to `deepnoteFileUri` (skipping snapshots) and returns the single notebook of the + * first valid init source (same `project.id`, one notebook matching `initNotebookId`), or undefined if none. + */ +export async function findSiblingInitNotebook( + deepnoteFileUri: Uri, + projectId: string, + initNotebookId: string +): Promise { + const dirUri = Uri.joinPath(deepnoteFileUri, '..'); + + let entries: [string, number][]; + try { + entries = await workspace.fs.readDirectory(dirUri); + } catch (error) { + logger.warn(`Failed to read directory ${getDisplayPath(dirUri)} while looking for init notebook:`, error); + return undefined; + } + + for (const [name] of entries) { + if (!name.endsWith(DEEPNOTE_FILE_EXTENSION) || name.endsWith(SNAPSHOT_FILE_SUFFIX)) { + continue; + } + + const candidateUri = Uri.joinPath(dirUri, name); + try { + const candidate: DeepnoteFile = await readDeepnoteProjectFile(candidateUri); + const validation = isValidSiblingInitCandidate(candidate, projectId, initNotebookId); + + if (validation.valid) { + return candidate.project.notebooks[0]; + } + } catch (error) { + // One unreadable/invalid file must not stop the scan of the rest. + logger.warn(`Failed to read candidate init file ${getDisplayPath(candidateUri)}:`, error); + } + } + + return undefined; +} + /** * Runs a project's init notebook (from its sibling `.deepnote` file, referenced by * `project.initNotebookId`) in the kernel on start, and again on restart. Tracked per kernel — not @@ -141,7 +192,7 @@ export class DeepnoteInitNotebookRunner implements IDeepnoteInitNotebookRunner, return; } - const initNotebook = await this.findSiblingInitNotebook(notebook, projectId, initNotebookId); + const initNotebook = await findSiblingInitNotebook(notebook.uri, projectId, initNotebookId); if (!initNotebook) { logger.warn( `No valid sibling init file found for project ${projectId} (initNotebookId ${initNotebookId}), skipping init` @@ -187,48 +238,6 @@ export class DeepnoteInitNotebookRunner implements IDeepnoteInitNotebookRunner, } } - /** - * Scans sibling `.deepnote` files (skipping snapshots) and returns the single notebook of the - * first valid init source (same `project.id`, one notebook matching `initNotebookId`), or - * undefined if none. - */ - private async findSiblingInitNotebook( - notebook: NotebookDocument, - projectId: string, - initNotebookId: string - ): Promise { - const dirUri = Uri.joinPath(notebook.uri, '..'); - - let entries: [string, number][]; - try { - entries = await workspace.fs.readDirectory(dirUri); - } catch (error) { - logger.warn(`Failed to read directory ${getDisplayPath(dirUri)} while looking for init notebook:`, error); - return undefined; - } - - for (const [name] of entries) { - if (!name.endsWith(DEEPNOTE_FILE_EXTENSION) || name.endsWith(SNAPSHOT_FILE_SUFFIX)) { - continue; - } - - const candidateUri = Uri.joinPath(dirUri, name); - try { - const candidate: DeepnoteFile = await readDeepnoteProjectFile(candidateUri); - const validation = isValidSiblingInitCandidate(candidate, projectId, initNotebookId); - - if (validation.valid) { - return candidate.project.notebooks[0]; - } - } catch (error) { - // One unreadable/invalid file must not stop the scan of the rest. - logger.warn(`Failed to read candidate init file ${getDisplayPath(candidateUri)}:`, error); - } - } - - return undefined; - } - /** * Executes the init notebook's code blocks in the kernel. * @param notebook The notebook document (for kernel context) @@ -371,11 +380,8 @@ export class DeepnoteInitNotebookRunner implements IDeepnoteInitNotebookRunner, logger.info(`Executing init notebook block ${i + 1}/${codeBlocks.length}`); try { - // Make sure the init notebook execution works cross-platform - let blockContent = block.content ?? ''; - const isWindows = process.platform === 'win32'; - if (isWindows && blockContent.trim() === DEEPNOTE_CLOUD_INIT_NOTEBOOK_BLOCK_CONTENT) { - blockContent = VSCODE_INIT_NOTEBOOK_BLOCK_CONTENT; + const blockContent = adaptInitBlockContent(block.content ?? ''); + if (blockContent !== (block.content ?? '')) { logger.info( `Replacing Deepnote Cloud init notebook block ${ i + 1 diff --git a/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.unit.test.ts b/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.unit.test.ts index f32c6b8b8e..e307e3cf43 100644 --- a/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.unit.test.ts +++ b/src/notebooks/deepnote/deepnoteInitNotebookRunner.node.unit.test.ts @@ -8,12 +8,14 @@ import { IKernel, IKernelProvider, INotebookKernelExecution } from '../../kernel import { IDisposableRegistry } from '../../platform/common/types'; import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../test/vscode-mock'; import { IDeepnoteNotebookManager } from '../types'; -import { DeepnoteInitNotebookRunner } from './deepnoteInitNotebookRunner.node'; +import { adaptInitBlockContent, DeepnoteInitNotebookRunner } from './deepnoteInitNotebookRunner.node'; import { createDeepnoteBlock, createDeepnoteFile, createDeepnoteNotebook, - createDeepnoteProject + createDeepnoteProject, + DEEPNOTE_CLOUD_INIT_BLOCK, + WINDOWS_INIT_BLOCK } from './deepnoteTestHelpers'; const PROJECT_ID = '11111111-1111-1111-1111-111111111111'; @@ -426,3 +428,30 @@ suite('DeepnoteInitNotebookRunner', () => { assert.isTrue(resolved); }); }); + +suite('adaptInitBlockContent', () => { + teardown(() => { + sinon.restore(); + }); + + test("replaces Deepnote Cloud's init block with the Python block on Windows, whatever whitespace surrounds it", () => { + sinon.stub(process, 'platform').value('win32'); + + assert.strictEqual(adaptInitBlockContent(DEEPNOTE_CLOUD_INIT_BLOCK), WINDOWS_INIT_BLOCK); + assert.strictEqual(adaptInitBlockContent(`\n ${DEEPNOTE_CLOUD_INIT_BLOCK}\n\n`), WINDOWS_INIT_BLOCK); + }); + + test("keeps Deepnote Cloud's init block on Linux", () => { + sinon.stub(process, 'platform').value('linux'); + + assert.strictEqual(adaptInitBlockContent(DEEPNOTE_CLOUD_INIT_BLOCK), DEEPNOTE_CLOUD_INIT_BLOCK); + }); + + test('keeps any other block on Windows', () => { + sinon.stub(process, 'platform').value('win32'); + const edited = DEEPNOTE_CLOUD_INIT_BLOCK.replace('./requirements.txt', './requirements-dev.txt'); + + assert.strictEqual(adaptInitBlockContent(edited), edited); + assert.strictEqual(adaptInitBlockContent('%%bash\necho hi'), '%%bash\necho hi'); + }); +}); diff --git a/src/notebooks/deepnote/deepnoteTestHelpers.ts b/src/notebooks/deepnote/deepnoteTestHelpers.ts index 443627457f..28b17ba835 100644 --- a/src/notebooks/deepnote/deepnoteTestHelpers.ts +++ b/src/notebooks/deepnote/deepnoteTestHelpers.ts @@ -227,3 +227,21 @@ export function createWorkspaceFolder(uri: Uri, index = 0): WorkspaceFolder { export function serializeProjectFile(projectId: string): string { return serializeDeepnoteFile(createDeepnoteFile({ project: createDeepnoteProject({ id: projectId }) })); } + +/** The code block of Deepnote Cloud's default init notebook. */ +export const DEEPNOTE_CLOUD_INIT_BLOCK = `%%bash +# If your project has a 'requirements.txt' file, we'll install it here. +if test -f requirements.txt + then + pip install -r ./requirements.txt + else echo "There's no requirements.txt, so nothing to install." +fi`; + +/** The block that runs in place of {@link DEEPNOTE_CLOUD_INIT_BLOCK} on Windows. */ +export const WINDOWS_INIT_BLOCK = `import os, sys, subprocess + +if os.path.exists("requirements.txt"): + print("Installing requirements.txt") + subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=False) +else: + print("There's no requirements.txt, so nothing to install.")`; diff --git a/src/notebooks/serviceRegistry.node.ts b/src/notebooks/serviceRegistry.node.ts index 0b2b8cb6b3..e9a05b21d4 100644 --- a/src/notebooks/serviceRegistry.node.ts +++ b/src/notebooks/serviceRegistry.node.ts @@ -103,6 +103,8 @@ import { DeepnoteApiTokenService } from './deepnote/cloud/deepnoteApiTokenServic import { DeepnoteCloudOperationLock } from './deepnote/cloud/deepnoteCloudOperationLock'; import { PublishAppCommandHandler } from './deepnote/cloud/publishAppCommandHandler.node'; import { AppPreviewCommandHandler } from './deepnote/appPreview/appPreviewCommandHandler.node'; +import { AppPreviewRunner } from './deepnote/appPreview/appPreviewRunner.node'; +import { IAppPreviewRunner } from './deepnote/appPreview/types'; import { SyncWithDeepnoteCloudCommandHandler } from './deepnote/cloud/syncWithDeepnoteCloudCommandHandler.node'; import { IDeepnoteApiTokenService, IDeepnoteCloudOperationLock } from './deepnote/cloud/types'; import { OpenInDeepnoteHandler } from './deepnote/openInDeepnoteHandler.node'; @@ -251,6 +253,7 @@ export function registerTypes(serviceManager: IServiceManager, isDevMode: boolea IExtensionSyncActivationService, AppPreviewCommandHandler ); + serviceManager.addSingleton(IAppPreviewRunner, AppPreviewRunner); serviceManager.addSingleton( IExtensionSyncActivationService, IntegrationEnvRefreshHandler diff --git a/src/platform/common/utils/localize.ts b/src/platform/common/utils/localize.ts index c163f9f8dc..5307216a68 100644 --- a/src/platform/common/utils/localize.ts +++ b/src/platform/common/utils/localize.ts @@ -1419,6 +1419,18 @@ export namespace DeepnoteAppPreview { export const startFailed = (message: string) => l10n.t('Could not start the app preview: {0}', message); export const operationNotSupported = (operation: string, folderName: string) => l10n.t('The app in {1} called {0}, which the local preview does not support yet.', operation, folderName); + export const noInterpreter = l10n.t( + 'No Python interpreter is selected for the notebook. Select one in VS Code, then run the app again.' + ); + export const toolkitNotInstalled = l10n.t( + "deepnote-toolkit is not installed in the notebook's Python interpreter. Install it from VS Code, then run the app again." + ); + export const selectDifferentInterpreter = l10n.t( + 'Open the notebook in VS Code and run Deepnote: Select Interpreter for Notebook, then run the app again.' + ); + export const blockFailed = (blockId: string) => l10n.t('Block {0} failed.', blockId); + export const notebookNotInFile = (notebookId: string) => + l10n.t('The notebook {0} is no longer in its .deepnote file.', notebookId); } export namespace SelectInputSettings { diff --git a/src/test/mocks/deepnoteRuntimeCore.ts b/src/test/mocks/deepnoteRuntimeCore.ts index 1ed0920579..e530880c94 100644 --- a/src/test/mocks/deepnoteRuntimeCore.ts +++ b/src/test/mocks/deepnoteRuntimeCore.ts @@ -1,5 +1,15 @@ -import type { AgentBlock } from '@deepnote/blocks'; -import type { AgentBlockContext, ServerExit, ServerInfo, ServerOptions } from '@deepnote/runtime-core'; +import type { AgentBlock, DeepnoteFile } from '@deepnote/blocks'; +import type { + AgentBlockContext, + ExecutionEngine as RealExecutionEngine, + ExecutionEngineOptions, + ExecutionOptions, + ExecutionSummary, + RuntimeConfig, + ServerExit, + ServerInfo, + ServerOptions +} from '@deepnote/runtime-core'; import type { ChildProcess } from 'child_process'; /** @@ -8,6 +18,8 @@ import type { ChildProcess } from 'child_process'; */ type RuntimeCore = typeof import('@deepnote/runtime-core'); +type ExecutionEngineMethods = Pick; +type ExecutionEngineFactory = (config: RuntimeConfig, options?: ExecutionEngineOptions) => ExecutionEngineMethods; const executeAgentBlockCalls: { block: AgentBlock; context: AgentBlockContext }[] = []; const serializeNotebookContextFromBlocksCalls: { blockCount: number; notebookName: string }[] = []; @@ -16,6 +28,7 @@ const stopServerCalls: ServerInfo[] = []; let nextServerId = 0; let startServerImpl: RuntimeCore['startServer'] | null = null; let stopServerImpl: RuntimeCore['stopServer'] | null = null; +let createExecutionEngine: ExecutionEngineFactory | null = null; function makeFakeProcess(id: number): ChildProcess { // Partial stand-in: only the members DeepnoteServerStarter touches. @@ -27,6 +40,31 @@ function makeFakeProcess(id: number): ChildProcess { } as unknown as ChildProcess; } +export class ExecutionEngine implements ExecutionEngineMethods { + private readonly engine: ExecutionEngineMethods; + + constructor(config: RuntimeConfig, options?: ExecutionEngineOptions) { + if (!createExecutionEngine) { + throw new Error( + 'No ExecutionEngine factory: call __useExecutionEngine before creating an ExecutionEngine.' + ); + } + this.engine = createExecutionEngine(config, options); + } + + public runProject(file: DeepnoteFile, options?: ExecutionOptions): Promise { + return this.engine.runProject(file, options); + } + + public start(): Promise { + return this.engine.start(); + } + + public stop(): Promise { + return this.engine.stop(); + } +} + export const executeAgentBlock: RuntimeCore['executeAgentBlock'] = async (block, context) => { executeAgentBlockCalls.push({ block, context }); @@ -77,6 +115,10 @@ export const stopServer: RuntimeCore['stopServer'] = async (info) => { }; // Test-only helpers (prefixed with __ to signal they are not part of the real API). +export function __useExecutionEngine(factory: ExecutionEngineFactory): void { + createExecutionEngine = factory; +} + export function __getExecuteAgentBlockCalls(): { block: AgentBlock; context: AgentBlockContext }[] { return executeAgentBlockCalls; } @@ -109,4 +151,5 @@ export function __resetRuntimeCoreMock(): void { nextServerId = 0; startServerImpl = null; stopServerImpl = null; + createExecutionEngine = null; } diff --git a/test/e2e/fixtures/app-preview-runs-init.deepnote b/test/e2e/fixtures/app-preview-runs-init.deepnote new file mode 100644 index 0000000000..024fd05fb5 --- /dev/null +++ b/test/e2e/fixtures/app-preview-runs-init.deepnote @@ -0,0 +1,28 @@ +version: '1.0.0' +metadata: + createdAt: '2025-01-01T00:00:00.000Z' +project: + id: e2e-app-preview-runs-project + name: E2E App Preview Runs + initNotebookId: e2e-runs-init + notebooks: + # Its input shares the run notebook's input name, with another type, and keeps its saved value in a run. + - id: e2e-runs-init + name: Init + blocks: + - id: e2e-runs-init-region + blockGroup: e2e-runs-init-region + type: input-checkbox + sortingKey: a0 + metadata: + deepnote_variable_name: region + deepnote_variable_value: false + - id: e2e-runs-init-code + blockGroup: e2e-runs-init-code + type: code + content: init_region = region + sortingKey: a1 + metadata: {} + executionMode: block + isModule: false + settings: {} diff --git a/test/e2e/fixtures/app-preview-runs.deepnote b/test/e2e/fixtures/app-preview-runs.deepnote new file mode 100644 index 0000000000..70708ff14c --- /dev/null +++ b/test/e2e/fixtures/app-preview-runs.deepnote @@ -0,0 +1,40 @@ +version: '1.0.0' +metadata: + createdAt: '2025-01-01T00:00:00.000Z' +project: + id: e2e-app-preview-runs-project + name: E2E App Preview Runs + initNotebookId: e2e-runs-init + notebooks: + # Sorting keys as Deepnote writes them: Deepnote runs V, Z0j, a0 in that order, while localeCompare would put a0 + # first. + - id: e2e-runs-notebook + name: Sales run + blocks: + - id: e2e-runs-check + blockGroup: e2e-runs-check + type: code + content: |- + if not region: + raise ValueError('Choose a region first') + sortingKey: a0 + metadata: {} + - id: e2e-runs-region + blockGroup: e2e-runs-region + type: input-text + sortingKey: V + metadata: + deepnote_variable_name: region + deepnote_variable_value: Europe + deepnote_input_label: Region + - id: e2e-runs-summary + blockGroup: e2e-runs-summary + type: code + content: |- + from IPython.display import display + display({'application/json': {'region': region, 'init_region': init_region}}, raw=True) + sortingKey: Z0j + metadata: {} + executionMode: block + isModule: false + settings: {} diff --git a/test/e2e/fixtures/app-preview-runs/app.js b/test/e2e/fixtures/app-preview-runs/app.js new file mode 100644 index 0000000000..0b6e78b493 --- /dev/null +++ b/test/e2e/fixtures/app-preview-runs/app.js @@ -0,0 +1,15 @@ +const notebook = window.Deepnote.connect().notebook('e2e-runs-notebook'); +const status = document.getElementById('status'); +const result = document.getElementById('result'); + +document.getElementById('run').addEventListener('click', async () => { + status.textContent = 'running'; + result.textContent = ''; + try { + const { run, result: runResult } = await notebook.run({ region: document.getElementById('region').value }); + status.textContent = `${run.status}${run.error ? `, ${run.error}` : ''}`; + result.textContent = JSON.stringify(runResult()); + } catch (error) { + status.textContent = `rejected: ${error.message}`; + } +}); diff --git a/test/e2e/fixtures/app-preview-runs/index.html b/test/e2e/fixtures/app-preview-runs/index.html new file mode 100644 index 0000000000..a5fd2b5e94 --- /dev/null +++ b/test/e2e/fixtures/app-preview-runs/index.html @@ -0,0 +1,21 @@ + + + + + Runs fixture + + + +

Sales runs

+ + + +

idle

+

+        
+    
+
diff --git a/test/e2e/suite/appPreview/previewApp.e2e.test.ts b/test/e2e/suite/appPreview/previewApp.e2e.test.ts
index 23f6a88ea3..88c2eb1ab9 100644
--- a/test/e2e/suite/appPreview/previewApp.e2e.test.ts
+++ b/test/e2e/suite/appPreview/previewApp.e2e.test.ts
@@ -10,6 +10,7 @@ import * as fs from 'fs';
 import * as os from 'os';
 import * as path from 'path';
 import {
+    By,
     EditorView,
     InputBox,
     NotificationType,
@@ -20,6 +21,7 @@ import {
 } from 'vscode-extension-tester';
 
 import {
+    KERNEL_CONNECT_TIMEOUT,
     QUICK_PICK_TIMEOUT,
     SUITE_TIMEOUT,
     WORKBENCH_TIMEOUT,
@@ -32,12 +34,15 @@ import {
 } from '../../helpers';
 
 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 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');
 const SYNCED_TITLE = 'Synced fixture';
 const RELOAD_TITLE = 'Reload fixture';
 const REUSE_TITLE = 'Reuse fixture';
 const INPUTS_TITLE = 'Inputs fixture';
+const RUNS_TITLE = 'Runs 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: ';
@@ -143,6 +148,28 @@ async function onIntegratedBrowserPage(title: string, read: () => Promise)
     }
 }
 
+async function runWithRegion(
+    region: string,
+    timeout = WORKBENCH_TIMEOUT
+): Promise<{ status: string; result: unknown }> {
+    const driver = VSBrowser.instance.driver;
+    await driver.findElement(By.css(`#region option[value="${region}"]`)).click();
+    await driver.findElement(By.id('run')).click();
+    let status = '';
+    await driver.wait(
+        async () => {
+            status = await driver.findElement(By.id('status')).getText();
+
+            return status !== 'running';
+        },
+        timeout,
+        `the run with region "${region}" did not finish`
+    );
+    const result = await driver.findElement(By.id('result')).getText();
+
+    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();
@@ -282,6 +309,7 @@ describe('Deepnote: Preview App — serve a data app folder in the built-in brow
         // Kept out of every app folder and the folders above them, so no app resolves to this project.
         fs.mkdirSync(path.join(workspaceDir, 'notebooks'));
         inputsNotebookFile = copyFixtureIntoDir(path.join(workspaceDir, 'notebooks'), INPUTS_NOTEBOOK_FIXTURE);
+        RUNS_NOTEBOOK_FIXTURES.forEach((fixture) => copyFixtureIntoDir(path.join(workspaceDir, 'notebooks'), fixture));
 
         await VSBrowser.instance.waitForWorkbench(WORKBENCH_TIMEOUT);
         await openFolderViaDialog(workspaceDir);
@@ -384,6 +412,39 @@ 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 });
+
+        await selectDeepnoteContextMenu(await findRootExplorerItem(path.basename(appDir)), 'Preview App');
+
+        // The first run starts the notebook file's toolkit server and a kernel.
+        const runs = await onIntegratedBrowserPage(RUNS_TITLE, async () => {
+            const asia = await runWithRegion('Asia', KERNEL_CONNECT_TIMEOUT);
+            const americas = await runWithRegion('Americas');
+            const noRegion = await runWithRegion('');
+            await screenshot('run-results');
+
+            return [asia, americas, noRegion];
+        });
+        expect(runs).to.deep.equal([
+            { status: 'success', result: { region: 'Asia', init_region: false } },
+            { status: 'success', result: { region: 'Americas', init_region: false } },
+            // 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('switches to the open tab and reloads it when the same folder is previewed again', async function () {
         const screenshot = createScreenshotter(this);
         const driver = VSBrowser.instance.driver;

From e8c601cc6275bd28665a3750f6b2be33f5315e19 Mon Sep 17 00:00:00 2001
From: tomas 
Date: Mon, 23 Nov 2026 12:35:41 +0000
Subject: [PATCH 3/4] test(app-preview): check runs, unsupported operations and
 run file writes with mocks

The session tests stub the runner with ts-mockito and read the run's
cancellation token with capture(), instead of a hand-written runner that
recorded its tokens, and check onUnsupported with a sinon stub instead
of a recorded list. The run files tests verify and capture the
workspace.fs mock's writeFile and readFile instead of keeping the
written files in a Map.
---
 .../appPreviewRunFiles.node.unit.test.ts      | 29 ++++++-------
 .../appPreviewSession.node.unit.test.ts       | 43 ++++++++-----------
 2 files changed, 31 insertions(+), 41 deletions(-)

diff --git a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts
index 6f15166bc8..47317de17d 100644
--- a/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts
+++ b/src/notebooks/deepnote/appPreview/appPreviewRunFiles.node.unit.test.ts
@@ -41,26 +41,20 @@ const RUN_FILE = createDeepnoteFile({
 
 suite('AppPreviewRunFiles', () => {
     let mockFs: typeof import('vscode').workspace.fs;
-    let files: Map;
+
+    function assertWroteRunFile(): void {
+        verify(mockFs.writeFile(anything(), anything())).once();
+        assert.strictEqual(capture(mockFs.writeFile).last()[0].fsPath, RUN_FILE_PATH);
+    }
 
     setup(() => {
         resetVSCodeMocks();
-        files = new Map();
         mockFs = mock();
         when(mockFs.delete(anything(), anything())).thenResolve();
         when(mockFs.stat(anything())).thenReject(FileSystemError.FileNotFound());
         when(mockFs.createDirectory(anything())).thenResolve();
-        when(mockFs.writeFile(anything(), anything())).thenCall(async (uri: Uri, content: Uint8Array) => {
-            files.set(uri.fsPath, content);
-        });
-        when(mockFs.readFile(anything())).thenCall(async (uri: Uri) => {
-            const content = files.get(uri.fsPath);
-            if (!content) {
-                throw FileSystemError.FileNotFound(uri);
-            }
-
-            return content;
-        });
+        when(mockFs.writeFile(anything(), anything())).thenResolve();
+        when(mockFs.readFile(anything())).thenReject(FileSystemError.FileNotFound());
         when(mockedVSCodeNamespaces.workspace.fs).thenReturn(instance(mockFs));
     });
 
@@ -91,7 +85,7 @@ suite('AppPreviewRunFiles', () => {
         deleted.resolve();
 
         assert.isTrue(await written);
-        assert.deepStrictEqual([...files.keys()], [RUN_FILE_PATH]);
+        assertWroteRunFile();
     });
 
     test('logs no warning when there is no runs folder to delete', async () => {
@@ -109,7 +103,7 @@ suite('AppPreviewRunFiles', () => {
 
         assert.isTrue(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE));
         sinon.assert.calledOnceWithExactly(warn, sinon.match.string, deleteFailure);
-        assert.deepStrictEqual([...files.keys()], [RUN_FILE_PATH]);
+        assertWroteRunFile();
     });
 
     test('resolves false and logs an error naming the run when the file cannot be written', async () => {
@@ -127,15 +121,18 @@ suite('AppPreviewRunFiles', () => {
         when(mockFs.createDirectory(anything())).thenReject(new Error('Permission denied'));
 
         assert.isFalse(await new AppPreviewRunFiles(STORAGE).write('run-1', RUN_FILE));
-        assert.deepStrictEqual([...files.keys()], []);
+        verify(mockFs.writeFile(anything(), anything())).never();
     });
 
     test('reads back the outputs and execution of a written run', async () => {
         const runFiles = new AppPreviewRunFiles(STORAGE);
         await runFiles.write('run-1', RUN_FILE);
+        const [, written] = capture(mockFs.writeFile).last();
+        when(mockFs.readFile(anything())).thenReturn(Promise.resolve(written));
 
         const file = await runFiles.read('run-1');
 
+        assert.strictEqual(capture(mockFs.readFile).last()[0].fsPath, RUN_FILE_PATH);
         assert.deepStrictEqual(
             file.project.notebooks[0].blocks.map((block) => ({
                 id: block.id,
diff --git a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts
index 19f6a4a071..21c0ed22ea 100644
--- a/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts
+++ b/src/notebooks/deepnote/appPreview/appPreviewSession.node.unit.test.ts
@@ -3,9 +3,11 @@ import { assert } from 'chai';
 import * as fs from 'fs';
 import * as http from 'http';
 import * as os from 'os';
-import { anything, instance, mock, when } from 'ts-mockito';
-import { Uri, type CancellationToken } from 'vscode';
+import * as sinon from 'sinon';
+import { anything, capture, instance, mock, verify, when } from 'ts-mockito';
+import { Uri } from 'vscode';
 
+import { createDeferred } from '../../../platform/common/utils/async';
 import * as path from '../../../platform/vscode-path/path';
 import { stubWorkspaceFsOnDisk } from '../../../test/mocks/vscodeFs';
 import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock';
@@ -92,16 +94,8 @@ suite('AppPreviewSession', () => {
     let appFolder: string;
     let clientScript: string;
     let sessions: AppPreviewSession[];
-    let unsupported: AppPreviewOperation[];
-    let runTokens: CancellationToken[];
-
-    const runner: IAppPreviewRunner = {
-        run: (_request, token) =>
-            new Promise((resolve) => {
-                runTokens.push(token);
-                token.onCancellationRequested(() => resolve({ status: 'stopped', error: null, file: null }));
-            })
-    };
+    let onUnsupported: sinon.SinonStub<[AppPreviewOperation], void>;
+    let runner: IAppPreviewRunner;
 
     async function startSession(
         options: { folder?: string; project?: AppPreviewProject | null } = {}
@@ -111,9 +105,9 @@ suite('AppPreviewSession', () => {
             folder: Uri.file(options.folder ?? appFolder),
             project: project ?? undefined,
             runFiles: instance(mock(AppPreviewRunFiles)),
-            runner,
+            runner: instance(runner),
             scripts: { appClient: Uri.file(clientScript) },
-            onUnsupported: (operation) => unsupported.push(operation)
+            onUnsupported
         });
         sessions.push(session);
         await session.start();
@@ -129,8 +123,8 @@ suite('AppPreviewSession', () => {
 
     setup(() => {
         resetVSCodeMocks();
-        unsupported = [];
-        runTokens = [];
+        onUnsupported = sinon.stub<[AppPreviewOperation], void>();
+        runner = mock();
         sessions = [];
         tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'deepnote-app-preview-'));
         appFolder = path.join(tmp, 'app');
@@ -381,7 +375,7 @@ suite('AppPreviewSession', () => {
             assert.deepStrictEqual(JSON.parse(stub.body.toString()), {
                 message: 'appData() is not supported in the local preview yet.'
             });
-            assert.deepStrictEqual(unsupported, ['appData()']);
+            sinon.assert.calledOnceWithExactly(onUnsupported, 'appData()');
 
             assert.strictEqual((await request(session, '/v2/notebooks/nb-1/app-data')).status, 401);
         });
@@ -422,6 +416,9 @@ suite('AppPreviewSession', () => {
             when(mockedVSCodeNamespaces.workspace.findFiles('**/*.deepnote')).thenCall(async () => [
                 Uri.file(path.join(tmp, 'main.deepnote'))
             ]);
+            when(runner.run(anything(), anything(), anything())).thenReturn(
+                createDeferred().promise
+            );
             const session = await startSession();
             const { token } = await requestToken(session);
 
@@ -431,17 +428,13 @@ suite('AppPreviewSession', () => {
                 body: JSON.stringify({ notebookId: 'nb-1' })
             });
             assert.strictEqual(created.status, 202);
-            assert.deepStrictEqual(
-                runTokens.map((runToken) => runToken.isCancellationRequested === true),
-                [false]
-            );
+            verify(runner.run(anything(), anything(), anything())).once();
+            const [, runToken] = capture(runner.run).last();
+            assert.isNotTrue(runToken.isCancellationRequested);
 
             session.dispose();
 
-            assert.deepStrictEqual(
-                runTokens.map((runToken) => runToken.isCancellationRequested === true),
-                [true]
-            );
+            assert.isTrue(runToken.isCancellationRequested);
         });
     });
 

From 068330513ef6ed5ffee098b05a0618e100cfeb37 Mon Sep 17 00:00:00 2001
From: tomas 
Date: Mon, 23 Nov 2026 12:52:06 +0000
Subject: [PATCH 4/4] fix(app-preview): log a run that fails to finalize
 instead of leaving the rejection unhandled

---
 src/notebooks/deepnote/appPreview/appPreviewApi.node.ts | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts
index f9a3653dc2..5cd2432d96 100644
--- a/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts
+++ b/src/notebooks/deepnote/appPreview/appPreviewApi.node.ts
@@ -159,7 +159,7 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp
     const startRun = (run: PreviewRun, request: AppPreviewRunRequest) => {
         const cancellation = new CancellationTokenSource();
         unfinished.add(cancellation);
-        void options.runner
+        options.runner
             .run(request, cancellation.token, () => {
                 run.status = 'running';
             })
@@ -180,6 +180,9 @@ export function createAppPreviewApi(options: AppPreviewApiOptions): AppPreviewAp
                 run.snapshotStatus = snapshotStatus;
                 run.completedAt = completedAt;
             })
+            .catch((error) => {
+                logger.error(`AppPreviewApi: Run ${run.runId} failed to finalize`, error);
+            })
             .finally(() => {
                 unfinished.delete(cancellation);
                 cancellation.dispose();