From 76655c24b36d68a7fc15661b6b16ed3721389ea0 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 21 Oct 2026 16:03:50 +0200 Subject: [PATCH] update vscode extension to support hotreload --- modules/jaspr-code/package.json | 30 ++++++ modules/jaspr-code/src/debug.ts | 35 +++++++ modules/jaspr-code/src/extension.ts | 31 ++++++ modules/jaspr-code/src/jaspr/serve_daemon.ts | 97 +++++++++++++++++++ .../lib/src/commands/daemon_command.dart | 7 +- .../lib/src/commands/dev_command.dart | 56 ++++++----- .../jaspr_cli/lib/src/dev/client_domain.dart | 64 +++++++++++- .../src/commands/daemon_command_test.dart | 14 +++ 8 files changed, 308 insertions(+), 26 deletions(-) diff --git a/modules/jaspr-code/package.json b/modules/jaspr-code/package.json index befc18201..4919e0d3e 100644 --- a/modules/jaspr-code/package.json +++ b/modules/jaspr-code/package.json @@ -60,6 +60,16 @@ "command": "jaspr.doctor", "title": "Doctor", "category": "Jaspr" + }, + { + "command": "jaspr.hotReload", + "title": "Hot Reload", + "category": "Jaspr" + }, + { + "command": "jaspr.hotRestart", + "title": "Hot Restart", + "category": "Jaspr" } ], "menus": { @@ -77,9 +87,29 @@ }, { "command": "jaspr.doctor" + }, + { + "command": "jaspr.hotReload", + "when": "jaspr:isRunning" + }, + { + "command": "jaspr.hotRestart", + "when": "jaspr:isRunning" } ] }, + "keybindings": [ + { + "command": "jaspr.hotReload", + "key": "r", + "when": "inDebugMode && jaspr:isRunning && !editorTextFocus" + }, + { + "command": "jaspr.hotRestart", + "key": "shift+r", + "when": "inDebugMode && jaspr:isRunning && !editorTextFocus" + } + ], "debuggers": [ { "type": "jaspr", diff --git a/modules/jaspr-code/src/debug.ts b/modules/jaspr-code/src/debug.ts index 553f05051..c9a224834 100644 --- a/modules/jaspr-code/src/debug.ts +++ b/modules/jaspr-code/src/debug.ts @@ -110,3 +110,38 @@ export class DynamicDebugConfigProvider return results; } } + +export class JasprDebugAdapterTrackerFactory + implements vscode.DebugAdapterTrackerFactory +{ + createDebugAdapterTracker( + session: vscode.DebugSession + ): vscode.ProviderResult { + const processId = session.configuration._processId; + if (!processId) { + return undefined; + } + const daemon = JasprServeDaemon.getDaemonByProcessId(processId); + if (!daemon) { + return undefined; + } + + return { + onWillReceiveMessage(message: any) { + if (message?.type === "request") { + if (message.command === "hotReload") { + daemon.reload(); + } else if ( + message.command === "restart" || + message.command === "hotRestart" || + ((message.command === "disconnect" || + message.command === "terminate") && + Boolean(message.arguments?.restart)) + ) { + daemon.restart(); + } + } + }, + }; + } +} diff --git a/modules/jaspr-code/src/extension.ts b/modules/jaspr-code/src/extension.ts index e66804bc9..b4562a583 100644 --- a/modules/jaspr-code/src/extension.ts +++ b/modules/jaspr-code/src/extension.ts @@ -2,8 +2,10 @@ import * as vscode from "vscode"; import { DynamicDebugConfigProvider, InitialLaunchJsonDebugConfigProvider, + JasprDebugAdapterTrackerFactory, JasprDebugConfigurationProvider, } from "./debug"; +import { JasprServeDaemon } from "./jaspr/serve_daemon"; import { createJasprProject, handleNewProjects } from "./create"; import { jasprClean, jasprDoctor, jasprServe } from "./commands"; @@ -61,6 +63,35 @@ export async function activate(context: vscode.ExtensionContext) { vscode.commands.registerCommand("jaspr.doctor", jasprDoctor) ); + context.subscriptions.push( + vscode.debug.registerDebugAdapterTrackerFactory( + "dart", + new JasprDebugAdapterTrackerFactory() + ) + ); + + context.subscriptions.push( + vscode.commands.registerCommand("jaspr.hotReload", async () => { + const daemon = JasprServeDaemon.getActiveDaemon(); + if (daemon) { + daemon.reload(); + } else { + await vscode.commands.executeCommand("dart.hotReload"); + } + }) + ); + + context.subscriptions.push( + vscode.commands.registerCommand("jaspr.hotRestart", async () => { + const daemon = JasprServeDaemon.getActiveDaemon(); + if (daemon) { + daemon.restart(); + } else { + await vscode.commands.executeCommand("workbench.action.debug.restart"); + } + }) + ); + context.subscriptions.push( vscode.commands.registerCommand("jaspr.serve", jasprServe(context)) ); diff --git a/modules/jaspr-code/src/jaspr/serve_daemon.ts b/modules/jaspr-code/src/jaspr/serve_daemon.ts index fc0761183..1427664b5 100644 --- a/modules/jaspr-code/src/jaspr/serve_daemon.ts +++ b/modules/jaspr-code/src/jaspr/serve_daemon.ts @@ -32,6 +32,40 @@ export class JasprServeDaemon implements vscode.Disposable { private randomId: number = 0; private runName: string = ""; + private static _activeDaemons: Map = new Map(); + public static activeDaemon: JasprServeDaemon | undefined; + + public static getDaemonByProcessId( + processId: number + ): JasprServeDaemon | undefined { + return this._activeDaemons.get(processId); + } + + public static getActiveDaemon(): JasprServeDaemon | undefined { + if (this.activeDaemon && this.activeDaemon.status === "running") { + return this.activeDaemon; + } + const activeSession = vscode.debug.activeDebugSession; + if (activeSession?.configuration?._processId) { + const daemon = this.getDaemonByProcessId( + activeSession.configuration._processId + ); + if (daemon && daemon.status === "running") { + return daemon; + } + } + for (const daemon of this._activeDaemons.values()) { + if (daemon.status === "running") { + return daemon; + } + } + return undefined; + } + + private nextRequestId: number = 1; + private lastReloadTime: number = 0; + private lastRestartTime: number = 0; + async start( context: vscode.ExtensionContext, folder?: vscode.WorkspaceFolder, @@ -46,6 +80,10 @@ export class JasprServeDaemon implements vscode.Disposable { this.randomId = Math.floor(Math.random() * 1000000); this.runName = debugConfiguration?.name ?? "Jaspr"; + JasprServeDaemon.activeDaemon = this; + JasprServeDaemon._activeDaemons.set(this.randomId, this); + void vscode.commands.executeCommand("setContext", "jaspr:isRunning", true); + this.statusBarItem = await vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left, 2 @@ -114,6 +152,15 @@ export class JasprServeDaemon implements vscode.Disposable { } }) ); + + this._disposables.push( + vscode.debug.onDidTerminateDebugSession((session) => { + const index = this.sessions.indexOf(session); + if (index !== -1) { + this.sessions.splice(index, 1); + } + }) + ); } async _startTerminal(context: vscode.ExtensionContext) { @@ -137,6 +184,15 @@ export class JasprServeDaemon implements vscode.Disposable { if (data.length === 1 && data.charCodeAt(0) === 3) { // Ctrl+C this.stop(); + return; + } + + if (data === "r") { + this.reload(); + } else if (data === "R") { + this.restart(); + } else if (data === "q") { + this.stop(); } }, open: () => resolve(terminal), @@ -198,7 +254,41 @@ export class JasprServeDaemon implements vscode.Disposable { }); } + public reload(): void { + const now = Date.now(); + if (now - this.lastReloadTime < 250) { + return; + } + this.lastReloadTime = now; + this.sendRequest("client.restart", { fullRestart: false }); + } + + public restart(): void { + const now = Date.now(); + if (now - this.lastRestartTime < 250) { + return; + } + this.lastRestartTime = now; + this.sendRequest("client.restart", { fullRestart: true }); + } + + public sendRequest(method: string, params?: any): void { + if (this.status !== "running" || !this.process) { + return; + } + const id = `${++this.nextRequestId}`; + const request = [{ method, params, id }]; + this.process.stdin.write(JSON.stringify(request) + "\n"); + } + async stop(): Promise { + if (JasprServeDaemon.activeDaemon === this) { + JasprServeDaemon.activeDaemon = undefined; + } + JasprServeDaemon._activeDaemons.delete(this.randomId); + if (JasprServeDaemon._activeDaemons.size === 0) { + void vscode.commands.executeCommand("setContext", "jaspr:isRunning", false); + } this.process?.stdin.write('[{"method":"daemon.shutdown", "id": "0"}]\n'); this.statusBarCloseItem?.hide(); const sess = this.sessions; @@ -210,6 +300,13 @@ export class JasprServeDaemon implements vscode.Disposable { } async dispose() { + if (JasprServeDaemon.activeDaemon === this) { + JasprServeDaemon.activeDaemon = undefined; + } + JasprServeDaemon._activeDaemons.delete(this.randomId); + if (JasprServeDaemon._activeDaemons.size === 0) { + void vscode.commands.executeCommand("setContext", "jaspr:isRunning", false); + } this.stop(); this.statusBarItem?.dispose(); diff --git a/packages/jaspr_cli/lib/src/commands/daemon_command.dart b/packages/jaspr_cli/lib/src/commands/daemon_command.dart index b27de19ac..c9dbe272f 100644 --- a/packages/jaspr_cli/lib/src/commands/daemon_command.dart +++ b/packages/jaspr_cli/lib/src/commands/daemon_command.dart @@ -39,6 +39,11 @@ class DaemonCommand extends DevCommand with DaemonHelper { @override void handleDevWorkflow(DevWorkflow workflow) { - daemon.registerDomain(ClientDomain(daemon, workflow)); + daemon.registerDomain(ClientDomain( + daemon, + workflow, + onReload: triggerReload, + onRestart: triggerRestart, + )); } } diff --git a/packages/jaspr_cli/lib/src/commands/dev_command.dart b/packages/jaspr_cli/lib/src/commands/dev_command.dart index d0e0d6cc6..d1c48fb4d 100644 --- a/packages/jaspr_cli/lib/src/commands/dev_command.dart +++ b/packages/jaspr_cli/lib/src/commands/dev_command.dart @@ -495,32 +495,44 @@ abstract class DevCommand extends BaseCommand with ProxyHelper { } } + Future triggerReload() async { + if (!canHotReload) { + await triggerRestart(); + return; + } + if (workflow.isBuilding) { + if (workflow.queuedAction == QueuedAction.restart) { + logger.write('Build in progress. Restart already queued.', tag: Tag.client); + } else if (workflow.queuedAction == QueuedAction.reload) { + logger.write('Build in progress. Reload already queued.', tag: Tag.client); + } else { + workflow.queueAction(QueuedAction.reload); + logger.write('Build in progress. Queued reload...', tag: Tag.client); + } + } else { + await _performReload(); + } + } + + Future triggerRestart() async { + if (workflow.isBuilding) { + if (workflow.queuedAction == QueuedAction.restart) { + logger.write('Build in progress. Restart already queued.', tag: Tag.client); + } else { + workflow.queueAction(QueuedAction.restart); + logger.write('Build in progress. Queued restart...', tag: Tag.client); + } + } else { + await _performRestart(); + } + } + Future _handleKey(String key) async { switch (key) { case 'r' when canHotReload: - if (workflow.isBuilding) { - if (workflow.queuedAction == QueuedAction.restart) { - logger.write('Build in progress. Restart already queued.', tag: Tag.client); - } else if (workflow.queuedAction == QueuedAction.reload) { - logger.write('Build in progress. Reload already queued.', tag: Tag.client); - } else { - workflow.queueAction(QueuedAction.reload); - logger.write('Build in progress. Queued reload...', tag: Tag.client); - } - } else { - await _performReload(); - } + await triggerReload(); case 'R': - if (workflow.isBuilding) { - if (workflow.queuedAction == QueuedAction.restart) { - logger.write('Build in progress. Restart already queued.', tag: Tag.client); - } else { - workflow.queueAction(QueuedAction.restart); - logger.write('Build in progress. Queued restart...', tag: Tag.client); - } - } else { - await _performRestart(); - } + await triggerRestart(); case 'l': await workflow.chrome.launch(port); case 'd': diff --git a/packages/jaspr_cli/lib/src/dev/client_domain.dart b/packages/jaspr_cli/lib/src/dev/client_domain.dart index 5a8443d27..d1b0b62c7 100644 --- a/packages/jaspr_cli/lib/src/dev/client_domain.dart +++ b/packages/jaspr_cli/lib/src/dev/client_domain.dart @@ -11,7 +11,13 @@ import 'util.dart'; /// A collection of method and events relevant to the running application. class ClientDomain extends Domain { - ClientDomain(Daemon daemon, this.workflow) : super(daemon, 'client') { + ClientDomain( + Daemon daemon, + this.workflow, { + this.onReload, + this.onRestart, + }) : super(daemon, 'client') { + registerHandler('reload', _reload); registerHandler('restart', _restart); registerHandler('callServiceExtension', _callServiceExtension); registerHandler('stop', _stop); @@ -20,6 +26,8 @@ class ClientDomain extends Domain { } final DevWorkflow workflow; + final Future Function()? onReload; + final Future Function()? onRestart; StreamSubscription? _clientEventSubscription; @@ -41,13 +49,63 @@ class ClientDomain extends Domain { return response?.json; } + Future> _reload(Map args) async { + return _restart({...args, 'fullRestart': false}); + } + Future> _restart(Map args) async { - final appId = getStringArg(args, 'appId', required: true); + final fullRestart = getBoolArg(args, 'fullRestart') ?? false; + final appId = getStringArg(args, 'appId', required: false); + + if (onReload != null && onRestart != null) { + final stopwatch = Stopwatch()..start(); + final actionName = fullRestart ? 'hot restart' : 'hot reload'; + final progressId = fullRestart ? 'hot.restart' : 'hot.reload'; + + sendEvent('app.progress', { + 'appId': ?appId, + 'id': '0', + 'message': 'Performing $actionName...', + 'progressId': progressId, + }); + + try { + if (fullRestart) { + await onRestart!(); + } else { + await onReload!(); + } + + sendEvent('app.progress', { + 'appId': ?appId, + 'id': '0', + 'finished': true, + 'progressId': progressId, + }); + sendEvent('app.log', { + 'appId': ?appId, + 'log': '${fullRestart ? 'Restarted' : 'Reloaded'} application in ${stopwatch.elapsedMilliseconds}ms', + }); + return {'code': 0}; + } catch (e) { + sendEvent('app.progress', { + 'appId': ?appId, + 'id': '0', + 'finished': true, + 'progressId': progressId, + }); + return {'code': 1, 'message': e.toString()}; + } + } + + if (appId == null) { + throw ArgumentError.value(null, 'appId', 'Required when workflow callbacks are not provided'); + } final appState = workflow.clients.getConnection(appId); if (appState == null) { throw ArgumentError.value(appId, 'appId', 'Not found'); } - final fullRestart = getBoolArg(args, 'fullRestart') ?? false; + if (!fullRestart) { final stopwatch = Stopwatch()..start(); sendEvent('app.progress', { diff --git a/packages/jaspr_cli/test/src/commands/daemon_command_test.dart b/packages/jaspr_cli/test/src/commands/daemon_command_test.dart index 47da8b565..5055c3999 100644 --- a/packages/jaspr_cli/test/src/commands/daemon_command_test.dart +++ b/packages/jaspr_cli/test/src/commands/daemon_command_test.dart @@ -55,6 +55,20 @@ void main() { ]), ); + io.stdin.addLine('[{"method":"client.restart","params":{"fullRestart":true},"id":1}]'); + + await expectLater( + io.stdout.queue, + emitsThrough('[{"id":1,"result":{"code":0}}]'), + ); + + io.stdin.addLine('[{"method":"client.reload","id":2}]'); + + await expectLater( + io.stdout.queue, + emitsThrough('[{"id":2,"result":{"code":0}}]'), + ); + io.stdin.addLine('[{"method":"daemon.shutdown","id":0}]'); expect(