Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(canvas): run node — VS Code's launch.json "Run Without Debugging" on the canvas
Uri Blochb2ba9d93de3b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6a65b1300..242ae5515 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1866,6 +1866,38 @@ session.one file. Guard on both dialects, construct in one.- **Mobile**: N/A — *nodeterm mobile* attaches to tmux sessions over the transport protocol andhas no canvas or file-browsing concept; adding one means extending that protocol.+- **Run node** (a `terminal` node carrying `data.runConfig`, NOT a new NodeKind;+ `@shared/run-config`, `core/run-service.ts`, `nodes/RunBar.tsx`) — VS Code's "Run Without+ Debugging" for any `.vscode/launch.json` configuration. The toolbar picks a folder (defaults to+ the project's; sibling and `*.worktrees/*` folders with a launch.json or a Flutter pubspec are+ offered), a configuration or compound (stored by NAME, re-read at every run) and, for Flutter, a+ device. **launch.json runs nothing by itself** — each `type` belongs to an extension — so+ `planLaunch` is the table of what each extension would run: dart (flutter run / flutter test /+ dart run / dart test), node/pwa-node/node-terminal, python/debugpy, go, php, coreclr,+ lldb/cppdbg, and chrome/msedge (a browser node). Everything else is REFUSED with a sentence,+ never guessed: debugging itself, `"request": "attach"`, unknown types, PHP "listen for Xdebug",+ and variables that need an editor or extension (`${file}`, `${input:}`, `${command:}` except the+ Python interpreter one, `${config:}`). `preLaunchTask` (+ `dependsOn`, `${defaultBuildTask}`)+ runs shell/process/npm/dart/flutter/typescript/cargo tasks first; a background (watch) task is+ refused. Compounds run their first member in the node and open the rest beside it, started.+ Rules a refactor must keep: (1) **nothing from a repo is ever typed into a shell** — the host+ writes a POSIX launcher (`buildLauncher`, every token single-quoted, owner-only via+ `writeFileAtomic`) and only `sh '<launcher>'` is typed; env and `envFile` values live in that+ file, never in shell history; tested against injection and run for real under `/bin/sh`;+ (2) the launcher records its pid and exit status, and traps INT/TERM with a HANDLER (`trap ':'`,+ never `''`, which children would inherit as "ignore"); **Stop is SIGINT to the launcher's process+ group** (Ctrl+C), SIGTERM if it will not go, and only the launcher + its children when it is not+ a group leader — never a group that could hold the user's shell; (3) a pid is signalled only+ while `ps` says it is still ours (the launcher's path, or flutter for hot reload/restart, which+ are SIGUSR1/SIGUSR2 to `flutter run --pid-file`); (4) Flutter reload on save is a core+ `fs.watch` of `<dir>/lib` that deliberately OUTLIVES the node's view; (5) the terminal is hidden+ by default (`runConfig.showTerminal`, toggled by ⋯ with the extra-args field): collapse's+ `display: none` path via `.term-node:has(.run-bar--compact)` and a node height fitted to the+ rows; a run that ends without our Stop says where to look. No "bring simulator forward":+ Simulator.app can only be activated as a whole (same-named simulators are told apart by id in+ the dropdown). Add menus: **New view ▸ New run configuration**. Local projects only (disabled+ with `RUN_SSH_HINT` in SSH projects; relay stub answers "managed on the host"); POSIX only+ (refused on Windows). Server Edition: real. Kanban card modal: not yet. Mobile: N/A.- **dino** (`DinoNode.tsx`) — a small self-contained T-Rex-style runner on a canvas (no PTY);high score persists via `data.highScore`.- **trigger** (`TriggerNode.tsx`) — a canvas-owned schedule (cron / interval / once) thatdiff --git a/src/core/run-service.test.ts b/src/core/run-service.test.tsnew file mode 100644index 000000000..4102fb60d--- /dev/null+++ b/src/core/run-service.test.ts@@ -0,0 +1,239 @@+import { spawn, type ChildProcess } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { fakePlatform } from './platform-fake'+import { initPlatform, resetPlatformForTests } from './platform'+import {+ discoverProjects,+ flutterPidFile,+ launcherPath,+ listEntries,+ runStatus,+ setWatch,+ signalRun,+ startRun,+ stopAllRunWatches,+ stopRun+} from './run-service'++const PUBSPEC = 'name: app\ndependencies:\n flutter:\n sdk: flutter\n'+const NODE = process.execPath+const posix = process.platform !== 'win32'++let root: string+let children: ChildProcess[] = []++function write(rel: string, text: string): string {+ const p = path.join(root, rel)+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, text)+ return p+}++async function until(fn: () => boolean | Promise<boolean>, ms = 6000): Promise<void> {+ const end = Date.now() + ms+ while (!(await fn())) {+ if (Date.now() > end) throw new Error('timed out')+ await new Promise((r) => setTimeout(r, 40))+ }+}++/** Run the launcher the way the node's shell would: its own job (process group), like `sh x` typed+ * at an interactive prompt. */+function runLauncher(nodeId: string): ChildProcess {+ const child = spawn('/bin/sh', [launcherPath(nodeId)], { detached: true, stdio: 'ignore' })+ children.push(child)+ return child+}++describe('run-service', () => {+ beforeEach(() => {+ initPlatform(fakePlatform())+ root = mkdtempSync(path.join(os.tmpdir(), 'nt-run-'))+ })+ afterEach(() => {+ stopAllRunWatches()+ for (const c of children) {+ try {+ process.kill(-(c.pid as number), 'SIGKILL')+ } catch {+ /* gone */+ }+ }+ children = []+ rmSync(root, { recursive: true, force: true })+ resetPlatformForTests()+ })++ it('lists described entries, and offers plain flutter run to a Flutter checkout with no launch.json', async () => {+ const api = path.join(root, 'api')+ write('api/.vscode/launch.json', `{ "configurations": [+ { "name": "API", "type": "node", "request": "launch", "program": "a.js" },+ { "name": "Attach", "type": "node", "request": "attach" },+ ], "compounds": [ { "name": "All", "configurations": ["API"] } ] }`)+ const r = await listEntries(api)+ expect(r.found).toBe(true)+ expect(r.entries.map((e) => [e.name, e.kind, e.supported])).toEqual([+ ['API', 'config', true],+ ['Attach', 'config', false],+ ['All', 'compound', true]+ ])++ write('app/pubspec.yaml', PUBSPEC)+ const flutter = await listEntries(path.join(root, 'app'))+ expect(flutter).toMatchObject({ found: false, isFlutterProject: true })+ expect(flutter.entries.map((e) => e.typeLabel)).toEqual(['Flutter'])++ write('broken/.vscode/launch.json', '{ nope')+ expect((await listEntries(path.join(root, 'broken'))).error).toMatch(/Could not parse/)+ })++ it('finds runnable folders beside the project, worktrees included', async () => {+ write('api/.vscode/launch.json', '{}')+ write('doc-flutter/pubspec.yaml', PUBSPEC)+ write('doc-flutter.worktrees/feature/pubspec.yaml', PUBSPEC)+ write('notes/readme.md', 'x')+ const found = await discoverProjects(path.join(root, 'notes'))+ expect(found.map((d) => path.relative(root, d))).toEqual([+ 'api',+ 'doc-flutter',+ path.join('doc-flutter.worktrees', 'feature')+ ])+ })++ it('refuses with a sentence: no folder, no config, unsupported config; answers compounds and urls', async () => {+ write('w/.vscode/launch.json', `{ "configurations": [+ { "name": "Attach", "type": "node", "request": "attach" },+ { "name": "Web", "type": "chrome", "request": "launch", "url": "http://localhost:3000" },+ ], "compounds": [ { "name": "Both", "configurations": ["Web", "Attach"] } ] }`)+ const w = path.join(root, 'w')+ expect(await startRun('n1', { projectDir: path.join(root, 'gone'), reloadOnSave: true })).toMatchObject({ ok: false })+ expect(await startRun('n1', { projectDir: w, launchConfig: 'Nope', reloadOnSave: true })).toEqual({+ ok: false,+ error: '“Nope” is not in .vscode/launch.json.'+ })+ expect(await startRun('n1', { projectDir: w, launchConfig: 'Attach', reloadOnSave: true })).toMatchObject({+ ok: false,+ error: expect.stringMatching(/attaches/)+ })+ expect(await startRun('n1', { projectDir: w, launchConfig: 'Web', reloadOnSave: true })).toEqual({+ ok: true,+ kind: 'browser',+ url: 'http://localhost:3000'+ })+ expect(await startRun('n1', { projectDir: w, launchConfig: 'Both', reloadOnSave: true })).toEqual({+ ok: true,+ kind: 'compound',+ members: ['Web', 'Attach']+ })+ expect(await startRun('../x', { projectDir: w, reloadOnSave: true })).toMatchObject({ ok: false })+ })++ it.skipIf(!posix)('runs the preLaunchTask, then the program with env + envFile, and records the exit code', async () => {+ const w = path.join(root, 'w')+ const out = path.join(root, 'out.txt')+ write('w/app.js', `require('fs').writeFileSync(${JSON.stringify(out)}, [process.env.FROM_CFG, process.env.FROM_FILE, process.env.SHARED, process.cwd(), process.argv.slice(2).join(',')].join('|')); process.exit(3)`)+ write('w/.env', 'FROM_FILE=file-value\nSHARED=from-file\n')+ write('w/.vscode/tasks.json', `{ "tasks": [ { "label": "prep", "type": "shell", "command": "echo prepped > prep.txt" } ] }`)+ write('w/.vscode/launch.json', `{ "configurations": [ {+ "name": "API", "type": "node", "request": "launch",+ "runtimeExecutable": ${JSON.stringify(NODE)},+ "program": "\${workspaceFolder}/app.js", "args": ["a", "b c"],+ "env": { "FROM_CFG": "cfg-value", "SHARED": "from-config" },+ "envFile": "\${workspaceFolder}/.env",+ "preLaunchTask": "prep"+ } ] }`)+ const r = await startRun('n2', { projectDir: w, launchConfig: 'API', reloadOnSave: true, extraArgs: '--extra' })+ expect(r).toMatchObject({ ok: true, kind: 'process', hotReload: false })+ if (!r.ok || r.kind !== 'process') return+ expect(r.command).toBe(`sh '${launcherPath('n2')}'`)+ // Owner-only: the launcher can carry an envFile's secrets.+ expect(statSync(launcherPath('n2')).mode & 0o077).toBe(0)++ runLauncher('n2')+ await until(async () => (await runStatus('n2')).exitCode !== null)+ expect(await runStatus('n2')).toEqual({ running: false, exitCode: 3 })+ expect(readFileSync(path.join(w, 'prep.txt'), 'utf8').trim()).toBe('prepped')+ expect(readFileSync(out, 'utf8')).toBe(`cfg-value|file-value|from-config|${w}|a,b c,--extra`)+ })++ it.skipIf(!posix)('a failing preLaunchTask stops the run with its status', async () => {+ const w = path.join(root, 'w')+ write('w/.vscode/tasks.json', `{ "tasks": [ { "label": "fail", "type": "shell", "command": "exit 7" } ] }`)+ write('w/.vscode/launch.json', `{ "configurations": [ { "name": "X", "type": "node", "request": "launch",+ "runtimeExecutable": ${JSON.stringify(NODE)}, "program": "nope.js", "preLaunchTask": "fail" } ] }`)+ expect((await startRun('n3', { projectDir: w, launchConfig: 'X', reloadOnSave: true })).ok).toBe(true)+ runLauncher('n3')+ await until(async () => (await runStatus('n3')).exitCode !== null)+ expect(await runStatus('n3')).toEqual({ running: false, exitCode: 7 })+ })++ it.skipIf(!posix)('reports a live run, and Stop interrupts it like Ctrl+C', async () => {+ const w = path.join(root, 'w')+ const marker = path.join(root, 'got-int')+ const ready = path.join(root, 'ready')+ write('w/serve.js', `const fs = require('fs'); process.on('SIGINT', () => { fs.writeFileSync(${JSON.stringify(marker)}, 'x'); process.exit(130) }); fs.writeFileSync(${JSON.stringify(ready)}, 'x'); setInterval(() => {}, 1000)`)+ write('w/.vscode/launch.json', `{ "configurations": [ { "name": "S", "type": "node", "request": "launch",+ "runtimeExecutable": ${JSON.stringify(NODE)}, "program": "serve.js" } ] }`)+ await startRun('n4', { projectDir: w, launchConfig: 'S', reloadOnSave: true })+ runLauncher('n4')+ await until(async () => (await runStatus('n4')).running)+ // The launcher is live before the program has installed its handler; wait for the program.+ await until(() => existsSync(ready))+ expect(await stopRun('n4')).toBe(true)+ await until(async () => !(await runStatus('n4')).running)+ expect(existsSync(marker)).toBe(true)+ expect((await runStatus('n4')).exitCode).toBe(130)+ expect(await stopRun('n4')).toBe(false)+ })++ it.skipIf(!posix)('hot reload / restart signal only a live flutter process', async () => {+ let out = ''+ const fake = spawn(+ NODE,+ ['-e', "process.on('SIGUSR1',()=>console.log('RELOAD'));process.on('SIGUSR2',()=>console.log('RESTART'));console.log('UP');setInterval(()=>{},1000)", 'flutter_tools.snapshot'],+ { stdio: ['ignore', 'pipe', 'ignore'], detached: true }+ )+ children.push(fake)+ fake.stdout!.on('data', (d) => (out += String(d)))+ await until(() => out.includes('UP'))+ mkdirSync(path.dirname(flutterPidFile('n5')), { recursive: true })+ writeFileSync(flutterPidFile('n5'), String(fake.pid))+ expect(await signalRun('n5', 'reload')).toBe(true)+ await until(() => out.includes('RELOAD'))+ expect(await signalRun('n5', 'restart')).toBe(true)+ await until(() => out.includes('RESTART'))++ // A pid file naming a process that is not flutter (this test runner) is never signalled.+ writeFileSync(flutterPidFile('n6'), String(process.pid))+ expect(await signalRun('n6', 'reload')).toBe(false)+ })++ it.skipIf(!posix)('reload on save: one hot reload per burst of .dart changes under lib/', async () => {+ write('app/lib/main.dart', 'void main() {}')+ let out = ''+ const fake = spawn(NODE, ['-e', "process.on('SIGUSR1',()=>console.log('RELOAD'));console.log('UP');setInterval(()=>{},1000)", 'flutter_tools.snapshot'], {+ stdio: ['ignore', 'pipe', 'ignore'],+ detached: true+ })+ children.push(fake)+ fake.stdout!.on('data', (d) => (out += String(d)))+ await until(() => out.includes('UP'))+ mkdirSync(path.dirname(flutterPidFile('n7')), { recursive: true })+ writeFileSync(flutterPidFile('n7'), String(fake.pid))+ setWatch('n7', path.join(root, 'app'))+ await new Promise((r) => setTimeout(r, 150))+ write('app/lib/notes.txt', 'ignored')+ write('app/lib/a.dart', 'void a() {}')+ write('app/lib/b.dart', 'void b() {}')+ await until(() => out.includes('RELOAD'))+ await new Promise((r) => setTimeout(r, 600))+ expect(out.match(/RELOAD/g)).toHaveLength(1)+ setWatch('n7', null)+ write('app/lib/c.dart', 'void c() {}')+ await new Promise((r) => setTimeout(r, 700))+ expect(out.match(/RELOAD/g)).toHaveLength(1)+ })+})diff --git a/src/core/run-service.ts b/src/core/run-service.tsnew file mode 100644index 000000000..391962308--- /dev/null+++ b/src/core/run-service.ts@@ -0,0 +1,536 @@+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import { mkdir, readFile, readdir, stat, unlink } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { IPC } from '../shared/ipc'+import {+ DEFAULT_FLUTTER_ENTRY,+ RUN_NODE_ID,+ SIMULATOR_UDID,+ buildLauncher,+ defaultFlutterConfig,+ describeLaunchFile,+ isSafeRunDir,+ normalizeRunConfig,+ osKeyFor,+ parseEnvFile,+ parseLaunchFile,+ parseTasksFile,+ planLaunch,+ resolveEntry,+ type LaunchConfig,+ type LaunchEntry,+ type LaunchFile,+ type RunDevice,+ type RunDevicesResult,+ type RunEntriesResult,+ type RunStartResult,+ type RunStatus,+ type TaskDef+} from '../shared/run-config'+import { shellSingleQuote } from '../shared/shell-quote'+import { findInLoginPath, resolveShellEnvVar, resolveShellPath } from './exec-path'+import { writeFileAtomic } from './fs-atomic'+import { platform } from './platform'++/**+ * Host side of the run node (see `@shared/run-config`). Core, so the Server Edition serves it+ * too: there `xcrun` is absent and the simulator list is simply empty; everything else is the same.+ *+ * Nothing here starts a process in the node's terminal. It reads the workspace's launch.json and+ * tasks.json, writes a launcher script, and returns the one line the renderer types+ * (`sh '<launcher>'`); afterwards it reads the run's status from the launcher's pid/exit files and+ * signals it for Stop and (Flutter) hot reload / restart.+ */++const run = promisify(execFile)++function runDir(): string {+ return path.join(platform().userDataDir, 'run-configs')+}+export function launcherPath(nodeId: string): string {+ return path.join(runDir(), `${nodeId}.sh`)+}+export function runPidFile(nodeId: string): string {+ return path.join(runDir(), `${nodeId}.pid`)+}+export function runExitFile(nodeId: string): string {+ return path.join(runDir(), `${nodeId}.exit`)+}+export function flutterPidFile(nodeId: string): string {+ return path.join(runDir(), `${nodeId}.flutter.pid`)+}++const validNode = (id: unknown): id is string => typeof id === 'string' && RUN_NODE_ID.test(id)++// ─── Workspace files ─────────────────────────────────────────────────────────────────────────++async function isFlutterProject(dir: string): Promise<boolean> {+ try {+ const text = await readFile(path.join(dir, 'pubspec.yaml'), 'utf8')+ return /^\s*flutter\s*:/m.test(text) || /sdk:\s*flutter/.test(text)+ } catch {+ return false+ }+}++type ReadLaunch = { found: false } | { found: true; file: LaunchFile } | { found: true; error: string }++async function readLaunch(dir: string): Promise<ReadLaunch> {+ let text: string+ try {+ text = await readFile(path.join(dir, '.vscode', 'launch.json'), 'utf8')+ } catch {+ return { found: false }+ }+ try {+ return { found: true, file: parseLaunchFile(text, osKeyFor(process.platform)) }+ } catch (e) {+ return { found: true, error: `Could not parse .vscode/launch.json: ${(e as Error).message}` }+ }+}++async function readTasks(dir: string): Promise<TaskDef[]> {+ try {+ return parseTasksFile(await readFile(path.join(dir, '.vscode', 'tasks.json'), 'utf8'), osKeyFor(process.platform))+ } catch {+ return [] // a missing or broken tasks.json surfaces as "task not found" if a config needs one+ }+}++export async function listEntries(dir: unknown): Promise<RunEntriesResult> {+ if (!isSafeRunDir(dir)) return { found: false, entries: [], isFlutterProject: false }+ const [launch, flutter] = await Promise.all([readLaunch(dir), isFlutterProject(dir)])+ if (!launch.found) {+ // A Flutter checkout with no launch.json still runs: `flutter run`, as VS Code's F5 would.+ const entries = flutter ? describeLaunchFile({ configs: [defaultFlutterConfig()], compounds: [] }, true) : []+ return { found: false, entries, isFlutterProject: flutter }+ }+ if ('error' in launch) return { found: true, entries: [], error: launch.error, isFlutterProject: flutter }+ return { found: true, entries: describeLaunchFile(launch.file, flutter), isFlutterProject: flutter }+}++// ─── Devices (Flutter) ───────────────────────────────────────────────────────────────────────++async function shellEnv(): Promise<NodeJS.ProcessEnv> {+ const p = (await resolveShellPath()) ?? process.env.PATH+ return p ? { ...process.env, PATH: p } : process.env+}++async function listSimulators(): Promise<RunDevice[]> {+ if (process.platform !== 'darwin') return []+ try {+ const { stdout } = await run('/usr/bin/xcrun', ['simctl', 'list', 'devices', 'available', '-j'], {+ timeout: 15_000,+ maxBuffer: 8 * 1024 * 1024+ })+ const doc = JSON.parse(stdout) as { devices?: Record<string, Array<Record<string, unknown>>> }+ const out: RunDevice[] = []+ for (const [runtime, list] of Object.entries(doc.devices ?? {})) {+ const m = /SimRuntime\.iOS-(\d+)-(\d+)/.exec(runtime)+ if (!m || !Array.isArray(list)) continue+ for (const d of list) {+ if (typeof d.udid !== 'string' || !SIMULATOR_UDID.test(d.udid) || typeof d.name !== 'string') continue+ out.push({+ id: d.udid,+ name: d.name,+ kind: 'simulator',+ platform: `iOS ${m[1]}.${m[2]}`,+ state: d.state === 'Booted' ? 'booted' : 'shutdown'+ })+ }+ }+ return out.sort((a, b) =>+ a.state === b.state ? a.name.localeCompare(b.name) : a.state === 'booted' ? -1 : 1+ )+ } catch {+ return []+ }+}++async function listFlutterDevices(): Promise<{ devices: RunDevice[]; error?: string }> {+ const bin = await findInLoginPath('flutter')+ if (!bin) return { devices: [], error: 'flutter was not found on your login shell PATH' }+ try {+ const { stdout } = await run(bin, ['devices', '--machine'], {+ timeout: 45_000,+ maxBuffer: 8 * 1024 * 1024,+ env: await shellEnv()+ })+ const start = stdout.indexOf('[')+ const list = JSON.parse(start >= 0 ? stdout.slice(start) : stdout) as Array<Record<string, unknown>>+ const out: RunDevice[] = []+ for (const d of list) {+ if (typeof d.id !== 'string' || typeof d.name !== 'string' || d.isSupported === false) continue+ const target = typeof d.targetPlatform === 'string' ? d.targetPlatform : ''+ const kind: RunDevice['kind'] = target.startsWith('web')+ ? 'web'+ : /^(darwin|linux|windows)/.test(target)+ ? 'desktop'+ : d.emulator === true+ ? target.startsWith('ios')+ ? 'simulator'+ : 'emulator'+ : 'device'+ out.push({ id: d.id, name: d.name, kind, platform: target || undefined })+ }+ return { devices: out }+ } catch (e) {+ return { devices: [], error: `flutter devices failed: ${(e as Error).message.split('\n')[0]}` }+ }+}++const DEVICES_TTL_MS = 15_000+let devicesCache: { at: number; value: RunDevicesResult } | null = null+let devicesInFlight: Promise<RunDevicesResult> | null = null++export async function listDevices(refresh = false): Promise<RunDevicesResult> {+ if (!refresh && devicesCache && Date.now() - devicesCache.at < DEVICES_TTL_MS) return devicesCache.value+ if (devicesInFlight) return devicesInFlight+ devicesInFlight = (async () => {+ const [sims, flutter] = await Promise.all([listSimulators(), listFlutterDevices()])+ const seen = new Set(sims.map((d) => d.id))+ const value: RunDevicesResult = {+ devices: [...sims, ...flutter.devices.filter((d) => !seen.has(d.id))],+ ...(flutter.error ? { error: flutter.error } : {})+ }+ devicesCache = { at: Date.now(), value }+ return value+ })().finally(() => {+ devicesInFlight = null+ })+ return devicesInFlight+}++export async function bootSimulator(udid: unknown): Promise<boolean> {+ if (process.platform !== 'darwin' || typeof udid !== 'string' || !SIMULATOR_UDID.test(udid)) return false+ try {+ await run('/usr/bin/xcrun', ['simctl', 'boot', udid], { timeout: 60_000 })+ } catch (e) {+ if (!/current state: Booted/i.test(String((e as { stderr?: string }).stderr ?? (e as Error).message))) return false+ }+ devicesCache = null+ try {+ await run('/usr/bin/open', ['-a', 'Simulator'], { timeout: 15_000 })+ } catch {+ /* booted either way; the window is a convenience */+ }+ return true+}++// ─── Project discovery ───────────────────────────────────────────────────────────────────────++async function subdirs(dir: string): Promise<string[]> {+ try {+ const entries = await readdir(dir, { withFileTypes: true })+ return entries+ .filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')+ .map((e) => path.join(dir, e.name))+ } catch {+ return []+ }+}++async function hasLaunchJson(dir: string): Promise<boolean> {+ try {+ return (await stat(path.join(dir, '.vscode', 'launch.json'))).isFile()+ } catch {+ return false+ }+}++/**+ * Runnable folders near `dir`: `dir`, its siblings and the children of any `*.worktrees` sibling+ * (the worktree layout this app creates) that have a launch.json or are Flutter checkouts. One+ * level each — a bounded scan of directories the user keeps side by side, never a crawl.+ */+export async function discoverProjects(dir: unknown): Promise<string[]> {+ if (!isSafeRunDir(dir)) return []+ const candidates = new Set<string>([dir])+ for (const sib of (await subdirs(path.dirname(dir))).slice(0, 400)) {+ candidates.add(sib)+ if (sib.endsWith('.worktrees')) for (const wt of (await subdirs(sib)).slice(0, 100)) candidates.add(wt)+ }+ const hits: string[] = []+ await Promise.all(+ [...candidates].map(async (c) => {+ if ((await hasLaunchJson(c)) || (await isFlutterProject(c))) hits.push(c)+ })+ )+ return hits.sort((a, b) => a.localeCompare(b))+}++// ─── Start ───────────────────────────────────────────────────────────────────────────────────++/** The interpreter the Python extension would most likely pick: a workspace venv, else python3. */+async function workspacePython(dir: string): Promise<string> {+ for (const rel of ['.venv/bin/python', 'venv/bin/python', 'env/bin/python']) {+ try {+ await stat(path.join(dir, rel))+ return path.join(dir, rel)+ } catch {+ /* next */+ }+ }+ return 'python3'+}++/** `${env:NAME}` values from the user's login environment (a GUI app's own env is thinner). */+async function envFor(names: Iterable<string>): Promise<Record<string, string>> {+ const out: Record<string, string> = {}+ await Promise.all(+ [...new Set(names)].map(async (n) => {+ const v = (await resolveShellEnvVar(n)) ?? process.env[n]+ if (v !== undefined && v !== null) out[n] = v+ })+ )+ return out+}++function referencedEnv(...values: unknown[]): string[] {+ const names: string[] = []+ const re = /\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g+ for (const v of values) {+ const text = JSON.stringify(v) ?? ''+ for (let m = re.exec(text); m; m = re.exec(text)) names.push(m[1])+ }+ return names+}++export async function startRun(nodeId: unknown, rawConfig: unknown): Promise<RunStartResult> {+ if (!validNode(nodeId)) return { ok: false, error: 'Invalid node.' }+ if (process.platform === 'win32') {+ return { ok: false, error: 'Run configurations need a POSIX shell — not supported on Windows yet.' }+ }+ const config = normalizeRunConfig(rawConfig)+ if (!config) return { ok: false, error: 'Choose a folder first.' }+ try {+ if (!(await stat(config.projectDir)).isDirectory()) return { ok: false, error: `${config.projectDir} is not a folder.` }+ } catch {+ return { ok: false, error: `${config.projectDir} does not exist.` }+ }+ const dir = config.projectDir+ const [launch, flutter] = await Promise.all([readLaunch(dir), isFlutterProject(dir)])+ if (launch.found && 'error' in launch) return { ok: false, error: launch.error }+ const file: LaunchFile = launch.found+ ? launch.file+ : flutter+ ? { configs: [defaultFlutterConfig()], compounds: [] }+ : { configs: [], compounds: [] }+ const entries: LaunchEntry[] = describeLaunchFile(file, flutter)+ if (entries.length === 0) return { ok: false, error: 'This folder has no .vscode/launch.json.' }+ const entry = resolveEntry(entries, config.launchConfig)+ if (!entry || (config.launchConfig && entry.name !== config.launchConfig && config.launchConfig !== DEFAULT_FLUTTER_ENTRY)) {+ return { ok: false, error: `“${config.launchConfig}” is not in .vscode/launch.json.` }+ }+ if (!entry.supported) return { ok: false, error: entry.reason ?? 'This configuration cannot run here.' }+ if (entry.kind === 'compound') return { ok: true, kind: 'compound', members: entry.members ?? [] }++ const cfg = file.configs.find((c) => c.name === entry.name) as LaunchConfig+ const tasks = await readTasks(dir)+ const [env, pythonPath] = await Promise.all([+ envFor(referencedEnv(cfg.raw, tasks.map((t) => t.raw))),+ workspacePython(dir)+ ])+ const planned = planLaunch(cfg, {+ workspace: dir,+ home: os.homedir(),+ env,+ isFlutterProject: flutter,+ pythonPath,+ deviceId: config.deviceId,+ extraArgs: config.extraArgs,+ flutterPidFile: flutterPidFile(nodeId),+ tasks+ })+ if (!planned.ok) return planned+ const plan = planned.plan+ if (plan.kind === 'browser') return { ok: true, kind: 'browser', url: plan.url }++ let envFileVars: Record<string, string> = {}+ if (plan.envFile) {+ try {+ envFileVars = parseEnvFile(await readFile(plan.envFile, 'utf8'))+ } catch {+ return { ok: false, error: `envFile ${plan.envFile} could not be read.` }+ }+ }+ await mkdir(runDir(), { recursive: true, mode: 0o700 })+ // Stale state from the previous run must not make this one look alive (or finished) early.+ await Promise.all([runPidFile(nodeId), runExitFile(nodeId), flutterPidFile(nodeId)].map((f) => unlink(f).catch(() => undefined)))+ const script = buildLauncher(plan, envFileVars, { pidFile: runPidFile(nodeId), exitFile: runExitFile(nodeId) })+ // A launcher may carry an envFile's secrets: owner-only from the first byte (unique temp + rename).+ await writeFileAtomic(launcherPath(nodeId), script, { mode: 0o700 })+ return { ok: true, kind: 'process', command: `sh ${shellSingleQuote(launcherPath(nodeId))}`, hotReload: plan.hotReload }+}++// ─── Status, stop, signals ───────────────────────────────────────────────────────────────────++/** pid → the command it was verified to be, per file. A pid is trusted only while its process is+ * still the one we started — a reused pid must never receive our signals. */+const verified = new Map<string, number>()++async function readPid(file: string): Promise<number | null> {+ try {+ const pid = Number.parseInt((await readFile(file, 'utf8')).trim(), 10)+ return Number.isInteger(pid) && pid > 1 ? pid : null+ } catch {+ return null+ }+}++async function livePid(file: string, mustContain: string | RegExp): Promise<number | null> {+ const pid = await readPid(file)+ if (pid === null) return null+ try {+ process.kill(pid, 0)+ } catch {+ verified.delete(file)+ return null+ }+ if (verified.get(file) === pid) return pid+ try {+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'command='], { timeout: 5_000 })+ const ok = typeof mustContain === 'string' ? stdout.includes(mustContain) : mustContain.test(stdout)+ if (!ok) return null+ verified.set(file, pid)+ return pid+ } catch {+ return null+ }+}++const launcherPid = (nodeId: string) => livePid(runPidFile(nodeId), launcherPath(nodeId))+const flutterPid = (nodeId: string) => livePid(flutterPidFile(nodeId), /flutter/i)++export async function runStatus(nodeId: unknown): Promise<RunStatus> {+ if (!validNode(nodeId) || process.platform === 'win32') return { running: false, exitCode: null }+ if ((await launcherPid(nodeId)) !== null) return { running: true, exitCode: null }+ try {+ const code = Number.parseInt((await readFile(runExitFile(nodeId), 'utf8')).trim(), 10)+ return { running: false, exitCode: Number.isInteger(code) ? code : null }+ } catch {+ return { running: false, exitCode: null }+ }+}++/**+ * Interrupt the run the way Ctrl+C would: SIGINT to the launcher's process GROUP (the shell made+ * it a job, so the group is the launcher and the program under it). `force` sends SIGTERM. When+ * the launcher is not a group leader (a shell without job control), only it and its children are+ * signalled — never a group that could include the user's interactive shell.+ */+export async function stopRun(nodeId: unknown, force = false): Promise<boolean> {+ if (!validNode(nodeId) || process.platform === 'win32') return false+ const pid = await launcherPid(nodeId)+ if (pid === null) return false+ const sig = force ? 'SIGTERM' : 'SIGINT'+ let pgid: number | null = null+ try {+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'pgid='], { timeout: 5_000 })+ pgid = Number.parseInt(stdout.trim(), 10)+ } catch {+ /* fall through */+ }+ try {+ if (pgid === pid) {+ process.kill(-pid, sig)+ } else {+ await run('/usr/bin/pkill', [force ? '-TERM' : '-INT', '-P', String(pid)], { timeout: 5_000 }).catch(() => undefined)+ process.kill(pid, sig)+ }+ return true+ } catch {+ return false+ }+}++export async function signalRun(nodeId: unknown, kind: unknown): Promise<boolean> {+ if (!validNode(nodeId) || process.platform === 'win32') return false+ if (kind !== 'reload' && kind !== 'restart') return false+ const pid = await flutterPid(nodeId)+ if (pid === null) return false+ try {+ process.kill(pid, kind === 'reload' ? 'SIGUSR1' : 'SIGUSR2')+ return true+ } catch {+ return false+ }+}++// ─── Reload on save (Flutter) ────────────────────────────────────────────────────────────────++const SAVE_DEBOUNCE_MS = 300+const MAX_WATCHERS = 32++interface Watch {+ dir: string+ watcher: fs.FSWatcher+ timer: ReturnType<typeof setTimeout> | null+}+const watches = new Map<string, Watch>()++function stopWatch(nodeId: string): void {+ const w = watches.get(nodeId)+ if (!w) return+ if (w.timer) clearTimeout(w.timer)+ w.watcher.close()+ watches.delete(nodeId)+}++/**+ * Watch `<dir>/lib` for `.dart` changes and hot-reload the node's Flutter run. Any writer counts+ * (the editor, a checkout, an agent). A burst is one reload; nothing is sent while not running.+ * Watchers outlive the node's view on purpose: the run keeps going in tmux when the user switches+ * projects. Capped, oldest evicted first.+ */+export function setWatch(nodeId: unknown, dir: unknown): void {+ if (!validNode(nodeId)) return+ if (dir === null || dir === undefined) {+ stopWatch(nodeId)+ return+ }+ if (!isSafeRunDir(dir)) return+ if (watches.get(nodeId)?.dir === dir) return+ stopWatch(nodeId)+ let watcher: fs.FSWatcher+ try {+ watcher = fs.watch(path.join(dir, 'lib'), { recursive: true })+ } catch {+ return+ }+ const entry: Watch = { dir, watcher, timer: null }+ watcher.on('change', (_event, file) => {+ if (typeof file === 'string' && !file.endsWith('.dart')) return+ if (entry.timer) clearTimeout(entry.timer)+ entry.timer = setTimeout(() => {+ entry.timer = null+ void signalRun(nodeId, 'reload')+ }, SAVE_DEBOUNCE_MS)+ })+ watcher.on('error', () => stopWatch(nodeId))+ watches.set(nodeId, entry)+ while (watches.size > MAX_WATCHERS) {+ const oldest = watches.keys().next().value+ if (oldest === undefined) break+ stopWatch(oldest)+ }+}++export function stopAllRunWatches(): void {+ for (const id of [...watches.keys()]) stopWatch(id)+}++export function registerRunConfigIpc(): void {+ platform().handle(IPC.runEntries, (dir: unknown) => listEntries(dir))+ platform().handle(IPC.runDevices, (refresh: unknown) => listDevices(refresh === true))+ platform().handle(IPC.runBootDevice, (udid: unknown) => bootSimulator(udid))+ platform().handle(IPC.runDiscover, (dir: unknown) => discoverProjects(dir))+ platform().handle(IPC.runStart, (nodeId: unknown, config: unknown) => startRun(nodeId, config))+ platform().handle(IPC.runStatus, (nodeId: unknown) => runStatus(nodeId))+ platform().handle(IPC.runStop, (nodeId: unknown, force: unknown) => stopRun(nodeId, force === true))+ platform().handle(IPC.runSignal, (nodeId: unknown, kind: unknown) => signalRun(nodeId, kind))+ platform().handle(IPC.runWatch, (nodeId: unknown, dir: unknown) => setWatch(nodeId, dir))+}diff --git a/src/main/index.ts b/src/main/index.tsindex 89446a8a7..5946e4ecc 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -351,6 +351,7 @@ import { registerGrokCliIpc } from '../core/grok-cli'import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'import { codexCliCaps, registerCodexCliIpc } from '../core/codex-cli'import { registerWallpaperIpc } from '../core/wallpaper'+import { registerRunConfigIpc, stopAllRunWatches } from '../core/run-service'import {bindCodexThreadIdentity,setCodexThreadIdentityAuthSecret,@@ -1491,6 +1492,7 @@ app.whenReady().then(async () => {// so registering it costs nothing until the first Codex launch line asks.registerCodexCliIpc()registerWallpaperIpc(settingsStore)+ registerRunConfigIpc()// Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the// renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agent// node — resolves from cache instead of racing the probe into a conservative "no auto".@@ -3950,6 +3952,8 @@ app.whenReady().then(async () => {// window is going away. LIFECYCLE, so no tombstone (the in-memory ledger is gone on quit anyway).app.on('before-quit', () => {revokeAllBrowser(browserRevocation, { userStopped: false })+ // Reload-on-save watchers die with the app; the runs themselves live on in tmux.+ stopAllRunWatches()})ipcMain.on(IPC.agentControlResult,diff --git a/src/preload/index.ts b/src/preload/index.tsindex 603370946..81b75e87f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -554,6 +554,18 @@ const api: NodeTerminalApi = {load: (w) => ipcRenderer.invoke(IPC.wallpaperLoad, w),importImage: (p) => ipcRenderer.invoke(IPC.wallpaperImport, p)},+ runConfig: {+ entries: (dir) => ipcRenderer.invoke(IPC.runEntries, dir),+ devices: (refresh) => ipcRenderer.invoke(IPC.runDevices, refresh),+ bootDevice: (udid) => ipcRenderer.invoke(IPC.runBootDevice, udid),+ discoverProjects: (dir) => ipcRenderer.invoke(IPC.runDiscover, dir),+ start: (nodeId, config) => ipcRenderer.invoke(IPC.runStart, nodeId, config),+ status: (nodeId) => ipcRenderer.invoke(IPC.runStatus, nodeId),+ stop: (nodeId, force) => ipcRenderer.invoke(IPC.runStop, nodeId, force),+ signal: (nodeId, kind) => ipcRenderer.invoke(IPC.runSignal, nodeId, kind),+ watch: (nodeId, dir) => ipcRenderer.invoke(IPC.runWatch, nodeId, dir)+ },+triggers: {arm: (projectId, nodeId, spec) => ipcRenderer.invoke(IPC.triggersArm, { projectId, nodeId, spec }),disarm: (projectId, nodeId) => ipcRenderer.invoke(IPC.triggersDisarm, { projectId, nodeId }),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex fd0e41a4f..277b64ab8 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -339,6 +339,21 @@ export function buildStubApi(): Omit<load: () => Promise.resolve(null),importImage: U('wallpaper.importImage')},+ runConfig: {+ // Superseded by the real WS-backed namespace in ws-bridge (registerRunConfigIpc runs in the+ // server shell). A RELAY tab keeps this: its terminals run on the PEER, so this machine's+ // folders, devices and processes would describe the wrong computer — the run node is not+ // offered there, and these answer "nothing" rather than guess.+ entries: () => Promise.resolve({ found: false, entries: [], isFlutterProject: false }),+ devices: () => Promise.resolve({ devices: [], error: 'Runs are managed on the host' }),+ bootDevice: () => Promise.resolve(false),+ discoverProjects: () => Promise.resolve([]),+ start: () => Promise.resolve({ ok: false as const, error: 'Runs are managed on the host' }),+ status: () => Promise.resolve({ running: false, exitCode: null }),+ stop: () => Promise.resolve(false),+ signal: () => Promise.resolve(false),+ watch: () => Promise.resolve()+ },triggers: {// Superseded by the real WS-backed namespace in ws-bridge (startTriggerService registers the// handlers in the server shell). On the RELAY tab this stub stays in force and REFUSES: thediff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex db60895e9..22ec5847d 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -4,6 +4,13 @@ import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'import type { DesktopWallpaper, WallpaperStill } from '../../shared/wallpaper'import type { AlertSoundSaveResult } from '../../shared/alert-sound'import type { RecentConversationsRequest, RecentConversationsResult } from '../../shared/recent-conversations'+import type {+ RunConfigApi,+ RunDevicesResult,+ RunEntriesResult,+ RunStartResult,+ RunStatus+} from '../../shared/run-config'// WebSocket bridge that reconstructs `window.nodeTerminal` in the browser (Server Edition).//// Under Electron the preload already defines `window.nodeTerminal`; this module only runs when@@ -1070,6 +1077,24 @@ export function buildWallpaperApi(client: RpcClient): Pick<NodeTerminalApi, 'wal}}+/** The run node's host side. Real on the Server Edition (`registerRunConfigIpc` runs in the+ * server shell): the run happens on the server, so its launch.json, devices and processes are the+ * server's — which is the machine the node's terminal runs on. */+export function buildRunConfigApi(client: RpcClient): Pick<NodeTerminalApi, 'runConfig'> {+ const r: RunConfigApi = {+ entries: (dir) => client.request(IPC.runEntries, dir) as Promise<RunEntriesResult>,+ devices: (refresh) => client.request(IPC.runDevices, refresh) as Promise<RunDevicesResult>,+ bootDevice: (udid) => client.request(IPC.runBootDevice, udid) as Promise<boolean>,+ discoverProjects: (dir) => client.request(IPC.runDiscover, dir) as Promise<string[]>,+ start: (nodeId, config) => client.request(IPC.runStart, nodeId, config) as Promise<RunStartResult>,+ status: (nodeId) => client.request(IPC.runStatus, nodeId) as Promise<RunStatus>,+ stop: (nodeId, force) => client.request(IPC.runStop, nodeId, force) as Promise<boolean>,+ signal: (nodeId, kind) => client.request(IPC.runSignal, nodeId, kind) as Promise<boolean>,+ watch: (nodeId, dir) => client.request(IPC.runWatch, nodeId, dir) as Promise<void>+ }+ return { runConfig: r }+}+/*** Build the `claude` namespace over an RpcClient. `cliCaps` is a REAL handler on the server* (`registerClaudeCliIpc` runs in the server shell too), so the browser resolves the very same@@ -1365,6 +1390,7 @@ export async function installWsBridge(): Promise<boolean> {...buildWatchLinkApi(client),...buildRecentConversationsApi(client),...buildWallpaperApi(client),+ ...buildRunConfigApi(client),...buildTriggersApi(client),...buildGitHubApi(client),...buildClaudeAccountsApi(client),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e6111eed0..4131bbe4d 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -103,6 +103,7 @@ import { DinoNode } from '../nodes/DinoNode'import { TriggerNode } from '../nodes/TriggerNode'import BrowserNode from '../nodes/BrowserNode'import { FilesNode } from '../nodes/FilesNode'+import type { RunNodeConfig } from '@shared/run-config'import { normalizeAddress } from '../nodes/browserUrl'import VideoNode from '../nodes/VideoNode'import WebNode from '../nodes/WebNode'@@ -134,6 +135,7 @@ import {IconMinus,IconNote,IconPhone,+ IconPlay,IconPlus,IconPower,IconProject,@@ -823,6 +825,7 @@ import {createDinoNode,createTriggerNode,createFilesNode,+ createRunNode,createDiffNode,createEditorNode,createGroupNode,@@ -5977,6 +5980,53 @@ export function Canvas() {[setNodes, markDirty, activeProjectId, emptyNodePos, cwdForNewNodeIn, parentInto])+ /**+ * A run node (see @shared/run-config and nodes/RunBar): a `.vscode/launch.json` configuration run+ * in a terminal. Rooted in the frame's worktree or the project folder; the node's own folder+ * picker can point it at any other checkout, so one project (say, the backend) can hold runs of+ * several frontend checkouts. A cwd-less canvas asks for the folder up front. Local projects+ * only — an SSH project's terminals run on the host, while the launcher, processes and+ * simulators are this machine's.+ */+ const addRun = useCallback(+ async (center?: { x: number; y: number }, groupId?: string) => {+ const project = useProjects.getState().getProject(activeProjectId)+ if (project?.ssh) {+ setCopyError('Run configurations run on this machine — not in SSH projects yet.')+ return+ }+ const dir = cwdForNewNodeIn(groupId) ?? project?.cwd ?? (await window.nodeTerminal.dialog.selectFolder())+ if (!dir) return+ setNodes((ns) => {+ const node = createRunNode(ns.length, { projectDir: dir, reloadOnSave: true }, center ?? emptyNodePos())+ return [...ns, groupId ? parentInto(node, groupId) : node]+ })+ markDirty()+ },+ [setNodes, markDirty, activeProjectId, emptyNodePos, cwdForNewNodeIn, parentInto]+ )++ // A compound's other members (RunBar's Run on a compound): one run node each, placed to the+ // right of the node that ran it, in its frame, starting immediately — VS Code starts a compound's+ // configurations together.+ useEffect(() => {+ const onOpenRun = (e: Event): void => {+ const d = (e as CustomEvent<{ sourceNodeId?: string; configs?: RunNodeConfig[] }>).detail+ const src = nodesRef.current.find((n) => n.id === d?.sourceNodeId)+ if (!src || !Array.isArray(d?.configs) || d.configs.length === 0) return+ const w = src.measured?.width ?? (src.width as number) ?? 640+ const added = d.configs.slice(0, 8).map((cfg, i) => {+ const node = createRunNode(nodesRef.current.length + i, cfg, undefined, { autoStart: true })+ node.position = { x: src.position.x + (w + 40) * (i + 1), y: src.position.y }+ return src.parentId ? { ...node, parentId: src.parentId, extent: 'parent' as const } : node+ })+ setNodes((ns) => [...ns, ...added])+ markDirty()+ }+ window.addEventListener('nodeterm:open-run-config', onOpenRun)+ return () => window.removeEventListener('nodeterm:open-run-config', onOpenRun)+ }, [setNodes, markDirty])+const addSticky = useCallback((center?: { x: number; y: number }, groupId?: string) => {setNodes((ns) => {@@ -10943,6 +10993,7 @@ export function Canvas() {web: (at) => void addWebView(at),sticky: (at) => addSticky(at),files: (at) => addFiles(at),+ run: (at) => void addRun(at),dino: (at) => addDino(at),trigger: (at) => addTrigger(at),openFile: (at) => void openFileDialog(at),@@ -10955,6 +11006,7 @@ export function Canvas() {openRemotePicker,addBrowser,addFiles,+ addRun,addWebView,addSticky,addDino,@@ -17934,6 +17986,9 @@ export function Canvas() {}]: []),+ ...(isSshProject+ ? []+ : [{ id: 'new-run', label: 'New run configuration', icon: <IconPlay />, run: () => void addRun() }]),{ id: 'new-dino', label: 'New dino game', icon: <IconDino />, run: () => addDino() },{ id: 'open-file', label: 'Open file…', icon: <IconEditor />, run: () => void openFileDialog() },// "New file…" needs a project folder to create into — hidden when the project has no cwd.@@ -18190,6 +18245,7 @@ export function Canvas() {addTerminal,addAgentNode,addSticky,+ addRun,addDino,addWebView,addBrowser,@@ -19488,6 +19544,7 @@ export function Canvas() {onAddDino={addDino}onAddTrigger={addTrigger}onAddFiles={() => addFiles()}+ onAddRun={() => void addRun()}onAddAgent={(aid, accountId) => addAgentNode(aid, undefined, undefined, accountId)}onOpenFile={() => void openFileDialog()}onAddRemote={() => openRemotePicker({ x: window.innerWidth / 2, y: window.innerHeight / 2 })}diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex f19474b4e..45017b922 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -30,6 +30,8 @@ interface DockProps {onAddDino: () => voidonAddTrigger: () => voidonAddFiles: () => void+ /** A run node (a launch.json configuration) rooted in the project folder. */+ onAddRun: () => voidonAddAgent: (agentId: AgentId, accountId?: string) => voidonOpenFile: () => voidonAddRemote: () => void@@ -80,6 +82,7 @@ export function Dock({onAddDino,onAddTrigger,onAddFiles,+ onAddRun,onAddAgent,onOpenFile,onAddRemote,@@ -193,6 +196,7 @@ export function Dock({dino: onAddDino,trigger: onAddTrigger,files: onAddFiles,+ run: onAddRun,openFile: onOpenFile,newFile: onNewFile,worktree: onAddWorktreediff --git a/src/renderer/lib/addMenuSpec.test.tsx b/src/renderer/lib/addMenuSpec.test.tsxindex 3ef03df7d..5e742fef1 100644--- a/src/renderer/lib/addMenuSpec.test.tsx+++ b/src/renderer/lib/addMenuSpec.test.tsx@@ -9,6 +9,7 @@ import {contentAddItemsToMenuItems,contentAddItemsToDockRows,FILES_NO_CWD_HINT,+ RUN_SSH_HINT,NEW_FILE_NO_CWD_HINT,WORKTREE_NO_CWD_HINT,WORKTREE_SSH_HINT,@@ -28,6 +29,7 @@ const handlers = (overrides: Partial<AddHandlers> = {}): AddHandlers => ({web: noop,sticky: noop,files: noop,+ run: noop,dino: noop,trigger: noop,openFile: noop,@@ -40,6 +42,7 @@ const handlers = (overrides: Partial<AddHandlers> = {}): AddHandlers => ({const allKinds: AddItem['kind'][] = ['terminal','remote',+ 'run','browser','web','sticky',@@ -52,6 +55,21 @@ const allKinds: AddItem['kind'][] = ['worktree']+describe('Run configuration row', () => {+ it('is disabled with its reason in an SSH project, on the menu and the Dock alike', () => {+ const ctx = { hasCwd: true, isSshProject: true }+ const [row] = contentAddItemsToMenuItems([{ kind: 'run' }], handlers(), ctx)+ expect(row).toMatchObject({ label: 'New run configuration', disabled: true, hint: RUN_SSH_HINT })+ const [dock] = contentAddItemsToDockRows([{ kind: 'run' }], handlers(), ctx)+ expect(dock).toMatchObject({ kind: 'run', disabled: true, hint: RUN_SSH_HINT })+ })+ it('is enabled in a local project, even with no folder yet (it asks for one)', () => {+ const [row] = contentAddItemsToMenuItems([{ kind: 'run' }], handlers(), { hasCwd: false, isSshProject: false })+ expect(row).toMatchObject({ label: 'New run configuration' })+ expect((row as { disabled?: boolean }).disabled).toBeFalsy()+ })+})+describe('CONTENT_ADD_ITEMS', () => {it('lists every content kind in the canonical order', () => {expect(CONTENT_ADD_ITEMS.map((i) => i.kind)).toEqual(allKinds)@@ -69,6 +87,7 @@ describe('contentAddItemsToMenuItems', () => {expect(labels).toEqual(['New terminal','New remote…',+ 'New run configuration','New browser','New web view…','New sticky note',@@ -171,6 +190,7 @@ describe('contentAddItemsToDockRows', () => {// NO 'terminal' and NO 'remote': the Dock draws its own Terminal button and its own// "New Remote Connection" flow. Emitting a terminal row here duplicated the Terminal entry.expect(rows.map((r) => r.kind)).toEqual([+ 'run','browser','web','sticky',@@ -298,6 +318,7 @@ describe('buildGroupedAddMenu', () => {: []}expect(children(ADD_GROUP_LABEL.view)).toEqual([+ 'New run configuration','New browser','New web view…','New sticky note',diff --git a/src/renderer/lib/addMenuSpec.tsx b/src/renderer/lib/addMenuSpec.tsxindex da748e387..cf457490c 100644--- a/src/renderer/lib/addMenuSpec.tsx+++ b/src/renderer/lib/addMenuSpec.tsx@@ -39,6 +39,7 @@ import {IconExplorer,IconGroup,IconNote,+ IconPlay,IconRemote,IconTerminal,IconWeb,@@ -56,6 +57,7 @@ export type AddPos = { x: number; y: number } | undefinedexport type AddItem =| { kind: 'terminal' }| { kind: 'remote' }+ | { kind: 'run' } // disabledOnSsh| { kind: 'browser' }| { kind: 'web' }| { kind: 'sticky' }@@ -77,6 +79,7 @@ export type AddItem =export const CONTENT_ADD_ITEMS: readonly AddItem[] = [{ kind: 'terminal' },{ kind: 'remote' },+ { kind: 'run' },{ kind: 'browser' },{ kind: 'web' },{ kind: 'sticky' },@@ -108,6 +111,8 @@ export interface AddCtx {export interface AddHandlers {terminal: (at?: AddPos) => voidremote: (screenPos: { x: number; y: number }) => void+ /** A run node (a `.vscode/launch.json` configuration with Run/Stop/Restart), in the project folder. */+ run: (at?: AddPos) => voidbrowser: (at?: AddPos) => voidweb: (at?: AddPos) => voidsticky: (at?: AddPos) => void@@ -124,6 +129,8 @@ export interface AddHandlers {/** The SSH worktree hint shown on the disabled row — kept here so every surface shows the same one. */export const WORKTREE_SSH_HINT = 'Not supported in SSH projects yet'+/** A run node's launcher, processes and (Flutter) simulators all live on THIS machine. */+export const RUN_SSH_HINT = 'Run configurations run on this machine — not in SSH projects yet'/*** The two rows that need a project FOLDER, shown disabled with their reason rather than hidden.@@ -168,6 +175,15 @@ export function contentAddItemsToMenuItems(case 'remote':out.push({ label: 'New remote…', icon: <IconTerminal />, onClick: () => handlers.remote(remotePos) })break+ case 'run':+ out.push({+ label: 'New run configuration',+ icon: <IconPlay />,+ disabled: ctx.isSshProject,+ hint: ctx.isSshProject ? RUN_SSH_HINT : undefined,+ onClick: () => handlers.run(at)+ })+ breakcase 'browser':out.push({ label: 'New browser', icon: <IconRemote />, onClick: () => handlers.browser(at) })break@@ -269,6 +285,16 @@ export function contentAddItemsToDockRows(// The Dock uses its own "New Remote Connection" affordance, not the remote picker. Skip// here so the Dock's content rows don't duplicate it.break+ case 'run':+ out.push({+ kind: 'run',+ label: 'Run Configuration',+ icon: <IconPlay />,+ disabled: ctx.isSshProject,+ hint: ctx.isSshProject ? RUN_SSH_HINT : undefined,+ onClick: () => handlers.run()+ })+ breakcase 'browser':out.push({ kind: 'browser', label: 'Browser', icon: <IconRemote />, onClick: () => handlers.browser() })break@@ -360,6 +386,7 @@ export type AddGroupId = 'top' | 'view' | 'files' | 'orchestrate'export const ADD_ITEM_GROUP: Record<AddItem['kind'], AddGroupId> = {terminal: 'top',remote: 'top',+ run: 'view',browser: 'view',web: 'view',sticky: 'view',diff --git a/src/renderer/lib/reopenNode.ts b/src/renderer/lib/reopenNode.tsindex 14c50fb47..78cb8b452 100644--- a/src/renderer/lib/reopenNode.ts+++ b/src/renderer/lib/reopenNode.ts@@ -13,8 +13,10 @@ import {createStickyNode,createDinoNode,createFilesNode,+ createRunNode,isAccountLoginNode} from '@renderer/state/workspace'+import { normalizeRunConfig } from '@shared/run-config'import { absolutePosition, type FocusableNode } from './nodeFocus'import { normalizeNodeIcon } from '@shared/node-icon'@@ -164,6 +166,10 @@ function buildBase(snapshot: ReopenNodeSnapshot, ctx: RecreateContext): CanvasNoctx.permissionModeFor(d.agentId))}+ // A run node reopens as a run node (same folder/configuration/device); its run is NOT+ // restarted — the toolbar's Run is the user's call, as on first open.+ const runConfig = normalizeRunConfig(d.runConfig)+ if (runConfig) return createRunNode(0, runConfig)return createTerminalNode(0, d.cwd, undefined, undefined, ctx.project?.ssh)}case 'sticky': {diff --git a/src/renderer/nodes/RunBar.tsx b/src/renderer/nodes/RunBar.tsxnew file mode 100644index 000000000..98cc2b2ab--- /dev/null+++ b/src/renderer/nodes/RunBar.tsx@@ -0,0 +1,664 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'+import { useReactFlow, useStore } from '@xyflow/react'+import {+ deviceClaims,+ resolveEntry,+ runDirLabel,+ runNodeTitle,+ type LaunchEntry,+ type RunDevice,+ type RunEntriesResult,+ type RunNodeConfig,+ type RunStatus+} from '@shared/run-config'+import { isShellCommand } from '@shared/agents/pane'+import { useSession } from '../session/session'+import { useProjects } from '../state/projects'+import { terminalNodeSize, type CanvasNode } from '../state/workspace'+import { IconPlay, IconReload } from '../components/icons'++/**+ * The run node's toolbar: VS Code's "Run Without Debugging" for any `.vscode/launch.json`+ * configuration, over the node's own terminal.+ *+ * [folder ▾] [configuration ▾] [device ▾ — Flutter only] [⟳]+ * ▶ Run / ■ Stop ⚡ Reload ↻ Restart [reload on save] status ⋯+ *+ * The host writes a launcher script for the chosen configuration (see `buildLauncher`) and this bar+ * types the one line that runs it, so the run's output, keys and lifetime are the terminal's.+ * Stop is SIGINT to the run's process group (Ctrl+C), then SIGTERM if it will not go. Flutter's+ * `flutter run` additionally gets hot reload / hot restart by signal and reload on save; every+ * other type's Restart is stop + run.+ *+ * The terminal is hidden by default (⋯ shows it, with the extra-arguments field): hidden, the node+ * is just these rows, fitted to their height.+ */++const STATUS_POLL_MS = 2_000+const STOP_GRACE_MS = 5_000+const NOTE_MS = 6_000++type Busy = 'booting' | 'starting' | 'stopping' | 'reloading' | 'restarting' | null++const CHOOSE_FOLDER = '\u0000choose'+const NO_ENTRY = '\u0000none'++interface Props {+ nodeId: string+ config: RunNodeConfig+ /** A compound's sibling: start the run once on mount. */+ autoStart: boolean+}++/** Node id → title → device, for every run node on the live canvas, as one primitive. */+function liveSig(s: { nodes: unknown[] }): string {+ let out = ''+ for (const n of s.nodes as CanvasNode[]) {+ const r = n.data?.runConfig+ if (r?.deviceId) out += `${n.id}\u0001${n.data.title}\u0001${r.deviceId}\u0002`+ }+ return out+}++function storedSig(s: ReturnType<typeof useProjects.getState>): string {+ let out = ''+ for (const p of s.projects) {+ if (p.closed) continue+ for (const n of p.nodes) {+ if (n.runConfig?.deviceId) out += `${n.id}\u0001${n.title}\u0001${n.runConfig.deviceId}\u0002`+ }+ }+ return out+}++function parseSig(sig: string): Array<{ id: string; title: string; runConfig: { deviceId: string } }> {+ return sig+ .split('\u0002')+ .filter(Boolean)+ .map((row) => {+ const [id, title, deviceId] = row.split('\u0001')+ return { id, title, runConfig: { deviceId } }+ })+}++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))++export function RunBar({ nodeId, config, autoStart }: Props) {+ const { api } = useSession()+ const { updateNodeData, setNodes } = useReactFlow()+ const [listing, setListing] = useState<RunEntriesResult | null>(null)+ const [devices, setDevices] = useState<RunDevice[] | null>(null)+ const [devicesError, setDevicesError] = useState<string | null>(null)+ const [projects, setProjects] = useState<string[]>([])+ const [status, setStatus] = useState<RunStatus | null>(null)+ const [busy, setBusy] = useState<Busy>(null)+ const [note, setNote] = useState<{ kind: 'error' | 'info'; text: string } | null>(null)+ const [needsRerun, setNeedsRerun] = useState(false)+ const [argsDraft, setArgsDraft] = useState(config.extraArgs ?? '')+ const mounted = useRef(true)+ useEffect(() => () => void (mounted.current = false), [])++ const cfgRef = useRef(config)+ cfgRef.current = config+ const running = !!status?.running++ const say = useCallback((kind: 'error' | 'info', text: string) => setNote({ kind, text }), [])+ useEffect(() => {+ if (!note) return+ const t = setTimeout(() => setNote(null), NOTE_MS)+ return () => clearTimeout(t)+ }, [note])++ /** Patch the node's run config; the title follows folder + configuration while it is ours. */+ const patch = useCallback(+ (next: Partial<RunNodeConfig>, opts?: { changesRun?: boolean; entryName?: string }) => {+ updateNodeData(nodeId, (n) => {+ const prev = (n.data.runConfig as RunNodeConfig | undefined) ?? cfgRef.current+ const runConfig: RunNodeConfig = { ...prev, ...next }+ const data: Record<string, unknown> = { runConfig }+ if (next.projectDir && next.projectDir !== prev.projectDir) data.cwd = next.projectDir+ if (n.data.titleAuto !== false && (next.projectDir || next.launchConfig || opts?.entryName)) {+ data.title = runNodeTitle(runConfig.projectDir, opts?.entryName ?? runConfig.launchConfig)+ }+ return data+ })+ if (opts?.changesRun && cfgRef.current && running) setNeedsRerun(true)+ },+ [nodeId, updateNodeData, running]+ )++ // ── Loads ────────────────────────────────────────────────────────────────────────────────++ const loadEntries = useCallback(() => {+ void api.runConfig.entries(cfgRef.current.projectDir).then((r) => {+ if (mounted.current) setListing(r)+ })+ }, [api])++ useEffect(() => {+ let live = true+ setListing(null)+ void api.runConfig.entries(config.projectDir).then((r) => {+ if (live) setListing(r)+ })+ void api.runConfig.discoverProjects(config.projectDir).then((dirs) => {+ if (live) setProjects(dirs)+ })+ return () => {+ live = false+ }+ }, [api, config.projectDir])++ const entries = listing?.entries ?? []+ const entry: LaunchEntry | undefined = useMemo(+ () => resolveEntry(entries, config.launchConfig),+ [entries, config.launchConfig]+ )+ const wantsDevices = entries.some((e) => e.usesDevice)++ const loadDevices = useCallback(+ (refresh: boolean) => {+ void api.runConfig.devices(refresh).then((r) => {+ if (!mounted.current) return+ setDevices(r.devices)+ setDevicesError(r.error ?? null)+ })+ },+ [api]+ )+ useEffect(() => {+ if (wantsDevices && devices === null) loadDevices(false)+ }, [wantsDevices, devices, loadDevices])++ // Set while WE are stopping the run, so its end is not reported as unexpected.+ const stoppingRef = useRef(false)+ const lastRunningRef = useRef<boolean | null>(null)+ const pollStatus = useCallback(async () => {+ const s = await api.runConfig.status(nodeId)+ if (!mounted.current) return s.running+ if (lastRunningRef.current === true && !s.running && !stoppingRef.current && !cfgRef.current.showTerminal) {+ const how = s.exitCode === null || s.exitCode === 0 ? 'The run ended' : `The run exited with code ${s.exitCode}`+ setNote({ kind: s.exitCode ? 'error' : 'info', text: `${how} — open ⋯ to see the terminal output.` })+ }+ lastRunningRef.current = s.running+ setStatus(s)+ return s.running+ }, [api, nodeId])++ useEffect(() => {+ void pollStatus()+ const t = setInterval(() => {+ if (document.visibilityState === 'visible') void pollStatus()+ }, STATUS_POLL_MS)+ return () => clearInterval(t)+ }, [pollStatus])++ // Reload on save lives in core and outlives this view (the run keeps going in tmux).+ const hotReload = !!entry?.hotReload+ useEffect(() => {+ void api.runConfig.watch(nodeId, hotReload && config.reloadOnSave ? config.projectDir : null)+ }, [api, nodeId, hotReload, config.reloadOnSave, config.projectDir])++ // ── Derived ──────────────────────────────────────────────────────────────────────────────++ const showDevice = !!entry?.usesDevice && !entry.pinnedDevice+ const live = useStore(liveSig)+ const stored = useProjects(storedSig)+ const claimsFor = useCallback(+ (deviceId: string | undefined) => {+ const l = parseSig(live)+ const ids = new Set(l.map((n) => n.id))+ return deviceClaims([...l, ...parseSig(stored).filter((n) => !ids.has(n.id))], nodeId, deviceId)+ },+ [live, stored, nodeId]+ )++ // First open: adopt the configuration VS Code would show first, and (Flutter) a running+ // simulator nobody else is using — so a fresh node is usually one click from running.+ useEffect(() => {+ if (listing && !config.launchConfig && entry) patch({ launchConfig: entry.name }, { entryName: entry.name })+ }, [listing, config.launchConfig, entry, patch])+ useEffect(() => {+ if (!devices || config.deviceId || !showDevice) return+ const free = devices.find((d) => d.kind === 'simulator' && d.state === 'booted' && claimsFor(d.id).length === 0)+ if (free) patch({ deviceId: free.id, deviceName: free.name })+ }, [devices, config.deviceId, showDevice, claimsFor, patch])++ const device = devices?.find((d) => d.id === config.deviceId)+ const claims = showDevice ? claimsFor(config.deviceId) : []++ // ── Actions ──────────────────────────────────────────────────────────────────────────────++ const start = useCallback(+ async (override?: Partial<RunNodeConfig>) => {+ const cfg = { ...cfgRef.current, ...override }+ const target = resolveEntry(entries, cfg.launchConfig)+ if (target?.usesDevice && !target.pinnedDevice && !cfg.deviceId) {+ say('error', 'Pick a device first.')+ return+ }+ const pane = await api.pty.paneCommand(nodeId)+ if (pane !== null && !isShellCommand(pane)) {+ say('error', `“${pane}” is running in this terminal — stop it first.`)+ return+ }+ const dev = devices?.find((d) => d.id === cfg.deviceId)+ if (target?.usesDevice && !target.pinnedDevice && dev?.kind === 'simulator' && dev.state !== 'booted') {+ setBusy('booting')+ if (!(await api.runConfig.bootDevice(dev.id))) {+ setBusy(null)+ say('error', `Could not boot ${dev.name}.`)+ return+ }+ loadDevices(true)+ }+ setBusy('starting')+ const r = await api.runConfig.start(nodeId, cfg)+ if (!r.ok) {+ setBusy(null)+ say('error', r.error)+ return+ }+ if (r.kind === 'browser') {+ setBusy(null)+ window.dispatchEvent(new CustomEvent('nodeterm:open-url-node', { detail: { url: r.url, sourceNodeId: nodeId } }))+ if (!/^https?:\/\//i.test(r.url)) say('error', `Only http(s) URLs open in a browser node (${r.url}).`)+ return+ }+ if (r.kind === 'compound') {+ // This node runs the first member; the rest open beside it and start at once.+ const [first, ...rest] = r.members+ setBusy(null)+ if (rest.length) {+ const base = cfgRef.current+ window.dispatchEvent(+ new CustomEvent('nodeterm:open-run-config', {+ detail: {+ sourceNodeId: nodeId,+ configs: rest.map((name) => ({ projectDir: base.projectDir, launchConfig: name, reloadOnSave: base.reloadOnSave }))+ }+ })+ )+ }+ patch({ launchConfig: first }, { entryName: first })+ await start({ launchConfig: first })+ return+ }+ const sent = await api.pty.sendText(nodeId, r.command)+ setNeedsRerun(false)+ if (sent === 'pasted-not-submitted') say('info', 'The command is in the terminal — press Enter to start.')+ else if (sent !== true) say('error', 'Could not type into this terminal.')+ const deadline = Date.now() + 15_000+ while (mounted.current && Date.now() < deadline) {+ if (await pollStatus()) break+ await sleep(400)+ }+ if (mounted.current) setBusy(null)+ },+ [api, nodeId, entries, devices, loadDevices, pollStatus, patch, say]+ )++ const waitStopped = useCallback(+ async (ms: number) => {+ const deadline = Date.now() + ms+ while (mounted.current && Date.now() < deadline) {+ if (!(await pollStatus())) return true+ await sleep(300)+ }+ return false+ },+ [pollStatus]+ )++ const stop = useCallback(async () => {+ setBusy('stopping')+ stoppingRef.current = true+ let stopped = false+ if (await api.runConfig.stop(nodeId)) {+ stopped = await waitStopped(STOP_GRACE_MS)+ // Ctrl+C was not enough (a program that traps it): ask harder, once.+ if (!stopped && (await api.runConfig.stop(nodeId, true))) stopped = await waitStopped(STOP_GRACE_MS)+ } else {+ stopped = !(await pollStatus())+ }+ stoppingRef.current = false+ if (mounted.current) {+ setBusy(null)+ if (!stopped) say('error', 'The run did not stop — open ⋯ to check the terminal.')+ }+ return stopped+ }, [api, nodeId, waitStopped, pollStatus, say])++ const restart = useCallback(async () => {+ if (running && !(await stop())) return+ await start()+ }, [running, stop, start])++ const signal = useCallback(+ async (kind: 'reload' | 'restart') => {+ setBusy(kind === 'reload' ? 'reloading' : 'restarting')+ const ok = await api.runConfig.signal(nodeId, kind)+ if (!mounted.current) return+ setTimeout(() => mounted.current && setBusy(null), 600)+ if (!ok) say('error', 'The app is not running.')+ },+ [api, nodeId, say]+ )++ // A compound's sibling starts by itself, once.+ const autoStarted = useRef(false)+ useEffect(() => {+ if (!autoStart || autoStarted.current || !listing || (wantsDevices && devices === null)) return+ autoStarted.current = true+ updateNodeData(nodeId, { runAutoStart: undefined })+ void start()+ }, [autoStart, listing, wantsDevices, devices, start, nodeId, updateNodeData])++ const onFolder = useCallback(+ async (value: string) => {+ let dir: string | null = value+ if (value === CHOOSE_FOLDER) dir = await api.dialog.selectFolder()+ if (!dir || dir === cfgRef.current.projectDir) return+ patch({ projectDir: dir, launchConfig: undefined }, { changesRun: true })+ },+ [api, patch]+ )++ const onDevice = useCallback(+ (id: string) => {+ const d = devices?.find((x) => x.id === id)+ patch({ deviceId: id, deviceName: d?.name }, { changesRun: true })+ },+ [devices, patch]+ )++ // ── Terminal toggle + compact sizing ─────────────────────────────────────────────────────+ //+ // Hidden (the default), the node is just its control rows: the terminal body is hidden by CSS+ // (`.term-node:has(.run-bar--compact)`, the same `display: none` path collapse uses — xterm and+ // the tmux client stay alive) and the node's height is fitted to what is left. The height the+ // terminal had is remembered on the node (not persisted) and handed back on show.++ const showTerminal = !!config.showTerminal+ const barRef = useRef<HTMLDivElement>(null)++ const fitCompact = useCallback(() => {+ const bar = barRef.current+ const root = bar?.closest('.term-node') as HTMLElement | null+ if (!bar || !root) return+ let h = 0+ for (const child of Array.from(root.children) as HTMLElement[]) {+ if (child.classList.contains('term-node__body')) continue+ const pos = getComputedStyle(child).position+ if (pos === 'absolute' || pos === 'fixed') continue+ h += child.offsetHeight+ }+ const cs = getComputedStyle(root)+ h = Math.ceil(h + (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0))+ if (h <= 0) return+ setNodes((ns) =>+ ns.map((n) => {+ if (n.id !== nodeId || n.data.collapsed || n.height === h) return n+ return { ...n, height: h, style: { ...n.style, height: h } }+ })+ )+ }, [nodeId, setNodes])++ useLayoutEffect(() => {+ if (showTerminal) return+ const bar = barRef.current+ if (!bar) return+ fitCompact()+ const ro = new ResizeObserver(() => fitCompact())+ ro.observe(bar)+ return () => ro.disconnect()+ }, [showTerminal, fitCompact])++ const toggleTerminal = useCallback(() => {+ const next = !showTerminal+ setNodes((ns) =>+ ns.map((n) => {+ if (n.id !== nodeId) return n+ const runConfig = { ...((n.data.runConfig as RunNodeConfig | undefined) ?? cfgRef.current), showTerminal: next }+ const current = (n.measured?.height ?? (n.height as number | undefined)) || 0+ if (next) {+ const remembered = n.data.runTerminalHeight as number | undefined+ const height = Math.max(remembered ?? 0, terminalNodeSize().height)+ return { ...n, height, style: { ...n.style, height }, data: { ...n.data, runConfig } }+ }+ return { ...n, data: { ...n.data, runConfig, runTerminalHeight: current } }+ })+ )+ }, [showTerminal, nodeId, setNodes])++ // ── Render ───────────────────────────────────────────────────────────────────────────────++ const folderOptions = useMemo(() => {+ const set = new Set(projects)+ set.add(config.projectDir)+ return [...set].sort((a, b) => a.localeCompare(b))+ }, [projects, config.projectDir])++ const deviceLabel = (d: RunDevice) => {+ const used = claimsFor(d.id)+ const plat = d.platform ? (d.kind === 'simulator' ? ` · ${d.platform}` : ` (${d.platform})`) : ''+ const twin = devices?.some((o) => o.id !== d.id && o.name === d.name && o.platform === d.platform)+ return `${d.name}${plat}${twin ? ` · ${d.id.slice(0, 4)}` : ''}${used.length ? ` — in use by ${used[0]}` : ''}`+ }+ const booted = devices?.filter((d) => d.kind === 'simulator' && d.state === 'booted') ?? []+ const shutdown = devices?.filter((d) => d.kind === 'simulator' && d.state !== 'booted') ?? []+ const others = devices?.filter((d) => d.kind !== 'simulator') ?? []++ const configs = entries.filter((e) => e.kind === 'config')+ const compounds = entries.filter((e) => e.kind === 'compound')+ const entryOption = (e: LaunchEntry) => (+ <option key={e.name} value={e.name}>+ {e.name}+ {e.kind === 'config' ? ` · ${e.typeLabel}` : ''}+ {e.supported ? '' : ' (can’t run here)'}+ </option>+ )++ const browser = !!entry?.browser+ const canRun = !!entry?.supported && !busy+ const statusText =+ busy === 'booting'+ ? 'Booting simulator…'+ : busy === 'starting'+ ? 'Starting…'+ : busy === 'stopping'+ ? 'Stopping…'+ : busy === 'reloading'+ ? 'Hot reload'+ : busy === 'restarting'+ ? 'Hot restart'+ : running+ ? 'Running'+ : status?.exitCode+ ? `Exited (${status.exitCode})`+ : status+ ? 'Stopped'+ : ''+ const statusKind = busy ? 'busy' : running ? 'running' : status?.exitCode ? 'failed' : 'stopped'++ const blocker =+ listing?.error ??+ (listing && entries.length === 0 ? 'No .vscode/launch.json in this folder — choose another folder.' : null) ??+ (entry && !entry.supported ? entry.reason : null)++ return (+ <div ref={barRef} className={`run-bar nodrag nowheel${showTerminal ? '' : ' run-bar--compact'}`}>+ <div className="run-bar__row">+ <select+ className="run-bar__select run-bar__select--folder"+ value={config.projectDir}+ title={config.projectDir}+ onChange={(e) => void onFolder(e.target.value)}+ >+ {folderOptions.map((d) => (+ <option key={d} value={d}>+ {runDirLabel(d)}+ </option>+ ))}+ <option value={CHOOSE_FOLDER}>Choose folder…</option>+ </select>++ <select+ className="run-bar__select run-bar__select--config"+ value={entry?.name ?? NO_ENTRY}+ disabled={entries.length === 0}+ title={entry ? `${entry.name}${entry.preLaunchTask ? ` — runs “${entry.preLaunchTask}” first` : ''}` : ''}+ onChange={(e) => patch({ launchConfig: e.target.value }, { changesRun: true, entryName: e.target.value })}+ >+ {entries.length === 0 && <option value={NO_ENTRY}>{listing ? 'No configurations' : 'Loading…'}</option>}+ {configs.map(entryOption)}+ {compounds.length > 0 && <optgroup label="Compounds">{compounds.map(entryOption)}</optgroup>}+ </select>++ {entry?.usesDevice && entry.pinnedDevice && (+ <span className="run-bar__pinned" title="This configuration chooses its own device">+ {entry.pinnedDevice}+ </span>+ )}+ {showDevice && (+ <select+ className={`run-bar__select${claims.length ? ' run-bar__select--warn' : ''}`}+ value={config.deviceId ?? ''}+ title={+ claims.length+ ? `Also selected by ${claims.join(', ')} — two runs on one device replace each other`+ : (devicesError ?? device?.name ?? 'Device')+ }+ onChange={(e) => onDevice(e.target.value)}+ >+ {!config.deviceId && <option value="">{devices ? 'Pick a device…' : 'Loading devices…'}</option>}+ {config.deviceId && !device && <option value={config.deviceId}>{config.deviceName ?? config.deviceId}</option>}+ {booted.length > 0 && (+ <optgroup label="Running simulators">+ {booted.map((d) => (+ <option key={d.id} value={d.id}>+ {deviceLabel(d)}+ </option>+ ))}+ </optgroup>+ )}+ {shutdown.length > 0 && (+ <optgroup label="Simulators (boots on run)">+ {shutdown.map((d) => (+ <option key={d.id} value={d.id}>+ {deviceLabel(d)}+ </option>+ ))}+ </optgroup>+ )}+ {others.length > 0 && (+ <optgroup label="Other devices">+ {others.map((d) => (+ <option key={d.id} value={d.id}>+ {deviceLabel(d)}+ </option>+ ))}+ </optgroup>+ )}+ </select>+ )}+ <button+ type="button"+ className="run-bar__icon"+ title={showDevice ? 'Reload launch.json and devices' : 'Reload launch.json'}+ aria-label="Refresh"+ onClick={() => {+ loadEntries()+ if (wantsDevices) loadDevices(true)+ }}+ >+ ⟳+ </button>+ </div>++ <div className="run-bar__row">+ {running ? (+ <button type="button" className="run-bar__btn run-bar__btn--stop" title="Stop (Ctrl+C)" disabled={!!busy} onClick={() => void stop()}>+ <span className="run-bar__stop-glyph" aria-hidden /> Stop+ </button>+ ) : (+ <button+ type="button"+ className="run-bar__btn run-bar__btn--run"+ title={browser ? 'Open in a browser node' : entry?.kind === 'compound' ? 'Run every configuration in this compound' : 'Run'}+ disabled={!canRun}+ onClick={() => void start()}+ >+ <IconPlay /> {browser ? 'Open' : 'Run'}+ </button>+ )}+ {hotReload ? (+ <>+ <button type="button" className="run-bar__btn" title="Hot reload (r)" disabled={!running || !!busy} onClick={() => void signal('reload')}>+ ⚡ Reload+ </button>+ <button type="button" className="run-bar__btn" title="Hot restart (R)" disabled={!running || !!busy} onClick={() => void signal('restart')}>+ <IconReload /> Restart+ </button>+ <label className="run-bar__toggle" title="Hot reload when a .dart file under lib/ changes">+ <input type="checkbox" checked={config.reloadOnSave} onChange={(e) => patch({ reloadOnSave: e.target.checked })} />+ Reload on save+ </label>+ </>+ ) : (+ !browser && (+ <button type="button" className="run-bar__btn" title="Stop and run again" disabled={!running || !!busy} onClick={() => void restart()}>+ <IconReload /> Restart+ </button>+ )+ )}+ {needsRerun && running && (+ <button+ type="button"+ className="run-bar__btn run-bar__btn--accent"+ title="Stop and run again with the new folder, configuration or device"+ disabled={!!busy}+ onClick={() => void restart()}+ >+ Apply & re-run+ </button>+ )}++ <span className="run-bar__spacer" />++ <span className={`run-bar__status run-bar__status--${statusKind}`}>{statusText}</span>+ <button+ type="button"+ className={`run-bar__icon${showTerminal ? ' run-bar__icon--on' : ''}`}+ title={showTerminal ? 'Hide the terminal' : 'Show the terminal and extra arguments'}+ aria-label={showTerminal ? 'Hide the terminal' : 'Show the terminal'}+ aria-pressed={showTerminal}+ onClick={toggleTerminal}+ >+ ⋯+ </button>+ </div>++ {showTerminal && (+ <div className="run-bar__row">+ <input+ className="run-bar__args"+ placeholder="Extra arguments, e.g. --dart-define=API_BASE_URL=http://localhost:8081/api/"+ value={argsDraft}+ spellCheck={false}+ onChange={(e) => setArgsDraft(e.target.value)}+ onBlur={() => patch({ extraArgs: argsDraft.trim() || undefined }, { changesRun: true })}+ onKeyDown={(e) => {+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur()+ e.stopPropagation()+ }}+ />+ </div>+ )}++ {(note || blocker) && (+ <div className={`run-bar__note run-bar__note--${note?.kind ?? 'error'}`}>{note?.text ?? blocker}</div>+ )}+ </div>+ )+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 3777057a8..05d42bd37 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -273,6 +273,7 @@ import { isGlobalKanbanOpen, isKanbanOpen, isOmniKanbanEnabled, openIssueOnBoardimport { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'+import { RunBar } from './RunBar'import { useSession, useActiveSessionPresence } from '../session/session'import { isHostedReadOnly, useHostedReadOnly } from '../state/hostedTeams'import { isBrowserRuntime } from '../bridge/runtime'@@ -6549,6 +6550,13 @@ export function TerminalNode({/>)}+ {/* Run node: launch.json run controls over this terminal (see RunBar). Local+ sessions only — a relay tab's or an SSH node's terminal runs on another machine, whose+ checkouts and devices this one cannot see. */}+ {data.runConfig && session.source === 'local' && !data.ssh && !data.sshRemoteTmux && (+ <RunBar nodeId={id} config={data.runConfig} autoStart={!!data.runAutoStart} />+ )}+{/* Body always mounted (keeps xterm alive); hidden via CSS when collapsed. */}<divclassName={`term-node__body${dropping ? ' dropping' : ''}`}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 8674539c1..99440d0a0 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -37,6 +37,7 @@ import { normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'import { isSafeNodeId } from '@shared/safe-id'import { normalizePendingLaunch } from '@shared/pending-launch-shape'import { normalizeTerminalFontSize } from '../terminal/terminal-font-zoom'+import { normalizeRunConfig, runNodeTitle, type RunNodeConfig } from '@shared/run-config'import { useSettings } from './settings'// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the@@ -197,6 +198,10 @@ export interface NodeData {* the machine-local arm store's question, never this field's. See @shared/trigger.*/trigger?: import('@shared/trigger').TriggerSpec+ /** Run nodes only: which launch.json configuration runs, where. See @shared/run-config. Persisted. */+ runConfig?: import('@shared/run-config').RunNodeConfig+ /** Run nodes only, transient: start the run on mount (a compound's sibling). Never persisted. */+ runAutoStart?: boolean[key: string]: unknown}@@ -340,6 +345,37 @@ export function createTerminalNode(}}+/** The macOS system blue swatch, so the color stays inside the node palette. */+const RUN_NODE_COLOR = '#0a84ff'++/**+ * A run node: a terminal node carrying `data.runConfig` (see @shared/run-config) — VS Code's "Run+ * Without Debugging" for a `.vscode/launch.json` configuration. Nothing runs on open unless+ * `autoStart` (a compound's sibling): the toolbar's Run is the user's call, as F5 is.+ */+export function createRunNode(+ index: number,+ config: RunNodeConfig,+ center?: { x: number; y: number },+ opts: { autoStart?: boolean } = {}+): CanvasNode {+ const size = terminalNodeSize()+ return {+ id: nextId('run'),+ type: 'terminal',+ ...placeNode('terminal', center, index, size.width, size.height),+ data: {+ title: runNodeTitle(config.projectDir, config.launchConfig),+ color: RUN_NODE_COLOR,+ group: null,+ tags: [],+ cwd: config.projectDir,+ runConfig: normalizeRunConfig(config),+ ...(opts.autoStart ? { runAutoStart: true } : {})+ }+ }+}+/*** Creates a terminal node that runs `ssh` to a saved server on the local PTY. The connection* is snapshotted inline (`data.ssh`) so the node survives the server being edited/deleted.@@ -2007,7 +2043,9 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {sshRemoteTmux: n.sshRemoteTmux,sshFs: n.sshFs,worktree: n.worktree,- trigger: n.trigger+ trigger: n.trigger,+ // Hostile-input seam (git-shared file → live data), like `icon` above.+ runConfig: normalizeRunConfig(n.runConfig)}}})@@ -2097,6 +2135,8 @@ export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = trusshFs: n.data.sshFs,worktree: n.data.worktree,trigger: n.data.trigger,+ // Re-validated on the way OUT too — the shared file is only as good as its last writer.+ runConfig: normalizeRunConfig(n.data.runConfig),premaxRect: n.data.premaxRect}})diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 0c0b4d6c0..aec1211f8 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3882,10 +3882,178 @@ body,}.term-node.collapsed .term-node__body,-.term-node.collapsed .node-tags {+.term-node.collapsed .node-tags,+.term-node.collapsed .run-bar {display: none;}+/* ── Run node toolbar (nodes/RunBar.tsx) ─────────────────────────────────────────────+ A flex-none strip between the header and the terminal body; the body (flex: 1) shrinks under+ it and the xterm refits through its ResizeObserver. No fill of its own, so it reads as part of+ the node in every appearance (and paints nothing translucent under Liquid Glass). */+.run-bar {+ flex: none;+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 5px 8px;+ border-bottom: 1px solid var(--border);+ font-size: 11.5px;+ color: var(--text);+}+/* Terminal hidden (the default): the node is just the control rows. Same `display: none` path a+ collapsed node takes, so xterm and the tmux client stay alive underneath. */+.term-node:has(.run-bar--compact) .term-node__body {+ display: none;+}+.run-bar--compact {+ border-bottom: none;+}+.run-bar__row {+ display: flex;+ align-items: center;+ gap: 5px;+ flex-wrap: wrap;+ min-width: 0;+}+.run-bar__select {+ max-width: 190px;+ min-width: 0;+ height: 22px;+ padding: 0 4px;+ font: inherit;+ color: var(--text);+ background: var(--panel-2);+ border: 1px solid var(--border);+ border-radius: 5px;+ text-overflow: ellipsis;+}+.run-bar__select--folder {+ font-weight: 600;+}+.run-bar__select--warn {+ border-color: var(--warn);+}+.run-bar__pinned {+ padding: 0 6px;+ height: 22px;+ line-height: 20px;+ border: 1px dashed var(--border);+ border-radius: 5px;+ color: var(--muted);+}+.run-bar__sep {+ width: 1px;+ height: 16px;+ background: var(--border);+ margin: 0 2px;+}+.run-bar__spacer {+ flex: 1;+}+.run-bar__btn,+.run-bar__icon {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ height: 22px;+ padding: 0 8px;+ font: inherit;+ color: var(--text);+ background: transparent;+ border: 1px solid var(--border);+ border-radius: 5px;+ cursor: pointer;+ white-space: nowrap;+}+.run-bar__icon {+ padding: 0 6px;+}+.run-bar__btn svg {+ width: 12px;+ height: 12px;+}+.run-bar__btn:hover:not(:disabled),+.run-bar__icon:hover {+ background: color-mix(in srgb, var(--text) 10%, transparent);+}+.run-bar__btn:disabled {+ opacity: 0.45;+ cursor: default;+}+.run-bar__btn--run {+ color: #fff;+ background: var(--accent);+ border-color: transparent;+}+.run-bar__btn--run:hover:not(:disabled) {+ background: var(--accent);+ filter: brightness(1.12);+}+.run-bar__btn--stop {+ color: var(--danger);+ border-color: color-mix(in srgb, var(--danger) 50%, transparent);+}+.run-bar__stop-glyph {+ width: 8px;+ height: 8px;+ border-radius: 1px;+ background: currentColor;+}+.run-bar__btn--accent {+ color: var(--accent);+ border-color: color-mix(in srgb, var(--accent) 50%, transparent);+}+.run-bar__icon--on {+ color: var(--accent);+}+.run-bar__toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: var(--muted);+ cursor: pointer;+ white-space: nowrap;+}+.run-bar__status {+ min-width: 52px;+ text-align: right;+ color: var(--muted);+ white-space: nowrap;+}+.run-bar__status--running {+ color: var(--success);+}+.run-bar__status--busy {+ color: var(--accent);+}+.run-bar__status--failed {+ color: var(--danger);+}+.run-bar__select--config {+ max-width: 240px;+}+.run-bar__args {+ flex: 1;+ min-width: 0;+ height: 22px;+ padding: 0 6px;+ font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;+ color: var(--text);+ background: var(--panel-2);+ border: 1px solid var(--border);+ border-radius: 5px;+}+.run-bar__note {+ font-size: 11px;+}+.run-bar__note--error {+ color: var(--danger);+}+.run-bar__note--info {+ color: var(--muted);+}+/* ---- Node tags ---- */diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex d7507a177..60d358154 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -11,6 +11,7 @@ import { registerGrokCliIpc } from '../../core/grok-cli'import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'import { registerCodexCliIpc } from '../../core/codex-cli'import { registerWallpaperIpc } from '../../core/wallpaper'+import { registerRunConfigIpc } from '../../core/run-service'import { startUsageService } from '../../core/usage/usage-service'import { registerClaudeAccountsIpc } from '../../core/claude-accounts-service'import { codexUsageAccounts } from '../../core/codex-accounts-core'@@ -90,6 +91,8 @@ export function registerCoreHandlers(get: deps.getSettings,onChange: (cb) => deps.onSettingsChange?.(cb)})+ // The run node's host side: core, so the browser's run nodes run on this server.+ registerRunConfigIpc()void claudeCliCaps()// The answer is populated after server node identity is armed. Early browser callers wait fordiff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex b98476936..9d165ed1c 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -372,6 +372,16 @@ export const IPC = {wallpaperListStills: 'wallpaper:list-stills',wallpaperLoad: 'wallpaper:load',wallpaperImport: 'wallpaper:import',+ // Run node (core/run-service.ts): launch.json entries, devices, launcher, status, stop, signals.+ runEntries: 'run:entries',+ runDevices: 'run:devices',+ runBootDevice: 'run:boot-device',+ runDiscover: 'run:discover',+ runStart: 'run:start',+ runStatus: 'run:status',+ runStop: 'run:stop',+ runSignal: 'run:signal',+ runWatch: 'run:watch',// Trigger nodes (issue #493): machine-local arm/disarm + the card's status/run-now.triggersArm: 'triggers:arm',triggersDisarm: 'triggers:disarm',diff --git a/src/shared/run-config.test.ts b/src/shared/run-config.test.tsnew file mode 100644index 000000000..b3e816919--- /dev/null+++ b/src/shared/run-config.test.ts@@ -0,0 +1,362 @@+import { describe, expect, it } from 'vitest'+import {+ DEFAULT_FLUTTER_ENTRY,+ buildLauncher,+ defaultFlutterConfig,+ describeConfig,+ describeLaunchFile,+ deviceClaims,+ normalizeRunConfig,+ parseEnvFile,+ parseJsonc,+ parseLaunchFile,+ parseTasksFile,+ planLaunch,+ planTask,+ resolveEntry,+ runDirLabel,+ runNodeTitle,+ type LaunchConfig,+ type PlanContext,+ type ProcessPlan+} from './run-config'++const WS = '/Users/me/dev/app'++const ctx = (over: Partial<PlanContext> = {}): PlanContext => ({+ workspace: WS,+ home: '/Users/me',+ env: { API_URL: 'http://localhost:8081' },+ isFlutterProject: false,+ pythonPath: 'python3',+ flutterPidFile: '/data/run/n.flutter.pid',+ tasks: [],+ ...over+})++const cfg = (raw: Record<string, unknown>): LaunchConfig => ({+ name: String(raw.name ?? 'cfg'),+ type: String(raw.type),+ request: String(raw.request ?? 'launch'),+ raw: { name: 'cfg', request: 'launch', ...raw }+})++function proc(raw: Record<string, unknown>, c: Partial<PlanContext> = {}): ProcessPlan {+ const r = planLaunch(cfg(raw), ctx(c))+ if (!r.ok) throw new Error(r.error)+ if (r.plan.kind !== 'process') throw new Error('not a process plan')+ return r.plan+}++function refusal(raw: Record<string, unknown>, c: Partial<PlanContext> = {}): string {+ const r = planLaunch(cfg(raw), ctx(c))+ if (r.ok) throw new Error('expected a refusal')+ return r.error+}++describe('parsing', () => {+ it('reads JSONC (comments, trailing commas) without touching strings', () => {+ expect(parseJsonc('{"a": "http://x//y", "b": "/* no */", "c": ",]", // c\n}')).toEqual({+ a: 'http://x//y',+ b: '/* no */',+ c: ',]'+ })+ })++ it('reads configurations of every type, compounds, and the OS block', () => {+ const file = parseLaunchFile(+ `{+ "configurations": [+ { "name": "App", "type": "dart", "request": "launch", "program": "lib/main.dart", "args": ["--flavor", "dev",], },+ { "name": "API", "type": "node", "request": "launch", "program": "server.js", "osx": { "args": ["--mac"] } },+ // nameless: dropped+ { "type": "python" },+ ],+ "compounds": [ { "name": "Both", "configurations": ["App", "API"] } ]+ }`,+ 'osx'+ )+ expect(file.configs.map((c) => [c.name, c.type])).toEqual([+ ['App', 'dart'],+ ['API', 'node']+ ])+ expect(file.configs[1].raw.args).toEqual(['--mac'])+ expect(file.compounds).toEqual([{ name: 'Both', configurations: ['App', 'API'] }])+ })++ it('reads tasks by label, deriving npm labels like VS Code', () => {+ const tasks = parseTasksFile(+ '{ "tasks": [ { "label": "build", "type": "shell", "command": "make" }, { "type": "npm", "script": "lint" } ] }'+ )+ expect(tasks.map((t) => t.label)).toEqual(['build', 'npm: lint'])+ })+})++describe('describeConfig', () => {+ it('refuses attach, unknown types and editor-only variables, with the reason', () => {+ expect(describeConfig(cfg({ type: 'node', request: 'attach', port: 9229 }), false)).toMatchObject({+ supported: false,+ reason: expect.stringMatching(/attaches/)+ })+ expect(describeConfig(cfg({ type: 'java', mainClass: 'App' }), false)).toMatchObject({+ supported: false,+ reason: '“java” configurations are not supported yet.'+ })+ expect(describeConfig(cfg({ type: 'python', program: '${file}' }), false)).toMatchObject({+ supported: false,+ reason: '${file} needs VS Code to resolve — it cannot run here.'+ })+ expect(describeConfig(cfg({ type: 'php', port: 9003 }), false)).toMatchObject({+ supported: false,+ reason: expect.stringMatching(/Xdebug/)+ })+ })++ it('lets the Python interpreter command through — we can answer that one', () => {+ expect(describeConfig(cfg({ type: 'python', program: 'a.py', python: '${command:python.interpreterPath}' }), false).supported).toBe(true)+ })++ it('knows a Flutter run (device + hot reload) from a Flutter test', () => {+ expect(describeConfig(cfg({ type: 'dart', program: 'lib/main.dart' }), true)).toMatchObject({+ typeLabel: 'Flutter', usesDevice: true, hotReload: true+ })+ expect(describeConfig(cfg({ type: 'dart', program: 'integration_test/auth_test.dart' }), true)).toMatchObject({+ usesDevice: true, hotReload: false+ })+ expect(describeConfig(cfg({ type: 'dart', program: 'test/widget_test.dart' }), true)).toMatchObject({+ usesDevice: false, hotReload: false+ })+ expect(describeConfig(cfg({ type: 'dart', program: 'lib/main.dart', args: ['-d', 'chrome'] }), true).pinnedDevice).toBe('chrome')+ })++ it('marks a compound that names a missing configuration', () => {+ const entries = describeLaunchFile(+ { configs: [cfg({ name: 'A', type: 'node', program: 'a.js' })], compounds: [{ name: 'AB', configurations: ['A', 'B'] }] },+ false+ )+ expect(entries[1]).toMatchObject({ kind: 'compound', supported: false, reason: expect.stringMatching(/: B\.$/) })+ })+})++describe('resolveEntry', () => {+ const entries = describeLaunchFile(+ {+ configs: [+ cfg({ name: 'Web', type: 'dart', program: 'lib/main.dart', args: ['-d', 'chrome'] }),+ cfg({ name: 'Device', type: 'dart', program: 'lib/main.dart' }),+ cfg({ name: 'Attach', type: 'dart', request: 'attach' })+ ],+ compounds: []+ },+ true+ )+ it('prefers the named entry, else the first that leaves the device to the picker', () => {+ expect(resolveEntry(entries, 'Web')?.name).toBe('Web')+ expect(resolveEntry(entries, undefined)?.name).toBe('Device')+ expect(resolveEntry(entries, 'Gone')?.name).toBe('Device')+ })+})++describe('planLaunch — one row per type', () => {+ it('dart (Flutter): flutter run with target, args, mode, device, pid file and extra args', () => {+ const p = proc(+ { type: 'dart', program: 'lib/main_dev.dart', args: ['--flavor', 'dev'], flutterMode: 'profile' },+ { isFlutterProject: true, deviceId: 'SIM-1', extraArgs: '--dart-define=A=1' }+ )+ expect(p.argv).toEqual([+ 'flutter', 'run', '-t', 'lib/main_dev.dart', '--flavor', 'dev', '--profile', '-d', 'SIM-1',+ '--pid-file', '/data/run/n.flutter.pid', '--dart-define=A=1'+ ])+ expect(p.hotReload).toBe(true)+ })++ it('dart (Flutter): a configuration that pins its device wins over the picker', () => {+ const p = proc({ type: 'dart', program: 'lib/main.dart', args: ['-d', 'chrome'] }, { isFlutterProject: true, deviceId: 'SIM-1' })+ expect(p.argv).not.toContain('SIM-1')+ })++ it('dart (Flutter): integration tests run with flutter test on the device', () => {+ const p = proc({ type: 'dart', program: 'integration_test/auth_test.dart' }, { isFlutterProject: true, deviceId: 'SIM-1' })+ expect(p.argv).toEqual(['flutter', 'test', '-d', 'SIM-1', 'integration_test/auth_test.dart'])+ expect(p.hotReload).toBe(false)+ })++ it('dart (no launch.json): plain flutter run', () => {+ const r = planLaunch(defaultFlutterConfig(), ctx({ isFlutterProject: true, deviceId: 'macos' }))+ expect(r.ok && r.plan.kind === 'process' && r.plan.argv).toEqual(['flutter', 'run', '-d', 'macos', '--pid-file', '/data/run/n.flutter.pid'])+ expect(DEFAULT_FLUTTER_ENTRY).toMatch(/flutter run/)+ })++ it('dart (plain): dart run / dart test', () => {+ expect(proc({ type: 'dart', program: 'bin/cli.dart', args: ['x'] }).argv).toEqual(['dart', 'run', 'bin/cli.dart', 'x'])+ expect(proc({ type: 'dart', program: 'test/a_test.dart' }).argv).toEqual(['dart', 'test', 'test/a_test.dart'])+ })++ it('node: program with runtime args, env and envFile; ${env:} resolved', () => {+ const p = proc({+ type: 'node',+ program: '${workspaceFolder}/server.js',+ runtimeArgs: ['--inspect=0'],+ args: '--port 3000',+ cwd: '${workspaceFolder}/api',+ env: { API: '${env:API_URL}', N: 3 },+ envFile: '${workspaceFolder}/.env'+ })+ expect(p.argv).toEqual(['node', '--inspect=0', `${WS}/server.js`, '--port', '3000'])+ expect(p.cwd).toBe(`${WS}/api`)+ expect(p.env).toEqual({ API: 'http://localhost:8081', N: '3' })+ expect(p.envFile).toBe(`${WS}/.env`)+ })++ it('node: npm-style runtimeExecutable with no program', () => {+ expect(proc({ type: 'pwa-node', runtimeExecutable: 'npm', runtimeArgs: ['run', 'dev'] }).argv).toEqual(['npm', 'run', 'dev'])+ expect(refusal({ type: 'node' })).toMatch(/neither a program nor a runtime/)+ })++ it('node-terminal: its command runs in a shell, like VS Code', () => {+ expect(proc({ type: 'node-terminal', command: 'npm run dev -- --open' }).shell).toBe('npm run dev -- --open')+ })++ it('python / debugpy: program, module, interpreter override and workspace venv', () => {+ expect(proc({ type: 'python', program: 'main.py', args: ['-v'] }, { pythonPath: `${WS}/.venv/bin/python` }).argv).toEqual([+ `${WS}/.venv/bin/python`, 'main.py', '-v'+ ])+ expect(proc({ type: 'debugpy', module: 'flask', args: ['run'], python: '/usr/bin/python3' }).argv).toEqual([+ '/usr/bin/python3', '-m', 'flask', 'run'+ ])+ expect(proc({ type: 'python', program: 'a.py', python: '${command:python.interpreterPath}' }, { pythonPath: '/venv/python' }).argv?.[0]).toBe('/venv/python')+ })++ it('go: run / test / exec', () => {+ expect(proc({ type: 'go', program: '${workspaceFolder}/cmd/api', buildFlags: '-tags dev' }).argv).toEqual([+ 'go', 'run', '-tags', 'dev', `${WS}/cmd/api`+ ])+ expect(proc({ type: 'go', mode: 'test', program: './pkg' }).argv).toEqual(['go', 'test', './pkg'])+ expect(proc({ type: 'go', mode: 'exec', program: './bin/api' }).argv).toEqual(['./bin/api'])+ })++ it('php, coreclr, lldb, cppdbg', () => {+ expect(proc({ type: 'php', program: 'bin/console', args: ['app:sync'] }).argv).toEqual(['php', 'bin/console', 'app:sync'])+ expect(proc({ type: 'coreclr', program: 'bin/Debug/App.dll' }).argv).toEqual(['dotnet', 'bin/Debug/App.dll'])+ expect(proc({ type: 'lldb', program: './build/app', args: ['--x'] }).argv).toEqual(['./build/app', '--x'])+ expect(proc({ type: 'cppdbg', program: './a.out', environment: [{ name: 'K', value: 'v' }] }).env).toEqual({ K: 'v' })+ })++ it('chrome / msedge: open the url in a browser node', () => {+ const r = planLaunch(cfg({ type: 'chrome', url: 'http://localhost:${env:PORT}' }), ctx({ env: { PORT: '5173' } }))+ expect(r).toEqual({ ok: true, plan: { kind: 'browser', name: 'cfg', url: 'http://localhost:5173' } })+ })+})++describe('preLaunchTask', () => {+ const tasks = parseTasksFile(`{+ "tasks": [+ { "label": "codegen", "type": "dart", "command": "dart", "args": ["run", "build_runner", "build"] },+ { "label": "deps", "type": "shell", "command": "npm ci", "options": { "cwd": "\${workspaceFolder}/web", "env": { "CI": "1" } } },+ { "label": "all", "dependsOn": ["deps", "codegen"] },+ { "label": "lint", "type": "npm", "script": "lint" },+ { "label": "watch", "type": "shell", "command": "tsc -w", "isBackground": true },+ { "label": "loop", "type": "shell", "command": "x", "dependsOn": "loop" },+ { "label": "default", "type": "process", "command": "make", "group": { "kind": "build", "isDefault": true } },+ { "label": "gulp", "type": "gulp", "task": "x" }+ ]+ }`)+ const c = ctx({ tasks })++ it('runs Dart-Code tasks as their own command, shell tasks via sh, npm via npm run', () => {+ expect(planTask('codegen', c)).toEqual([{ label: 'codegen', cwd: WS, env: {}, argv: ['dart', 'run', 'build_runner', 'build'] }])+ expect(planTask('deps', c)).toEqual([{ label: 'deps', cwd: `${WS}/web`, env: { CI: '1' }, shell: 'npm ci' }])+ expect(planTask('lint', c)).toEqual([{ label: 'lint', cwd: WS, env: {}, argv: ['npm', 'run', 'lint'] }])+ })++ it('runs dependsOn first, in order', () => {+ expect(planTask('all', c).map((s) => s.label)).toEqual(['deps', 'codegen'])+ })++ it('resolves ${defaultBuildTask}', () => {+ expect(planTask('${defaultBuildTask}', c)[0].argv).toEqual(['make'])+ })++ it('refuses background, unknown, missing and self-dependent tasks with a reason', () => {+ expect(() => planTask('watch', c)).toThrow(/background/)+ expect(() => planTask('gulp', c)).toThrow(/“gulp” task/)+ expect(() => planTask('nope', c)).toThrow(/not in .vscode\/tasks.json/)+ expect(() => planTask('loop', c)).toThrow(/depends on itself/)+ })++ it('a configuration carries its preLaunchTask steps', () => {+ expect(proc({ type: 'node', program: 'a.js', preLaunchTask: 'all' }, { tasks }).preTasks).toHaveLength(2)+ expect(refusal({ type: 'node', program: 'a.js', preLaunchTask: 'watch' }, { tasks })).toMatch(/background/)+ })+})++describe('buildLauncher', () => {+ const paths = { pidFile: '/d/n.pid', exitFile: '/d/n.exit' }++ it('quotes every value, so no field can become a second shell command', () => {+ const p = proc({+ type: 'node',+ program: "x'; rm -rf ~; echo '",+ args: ['$(id)', '`id`', '&&', 'reboot'],+ cwd: '/tmp/$(id)',+ env: { EVIL: "'; touch /tmp/pwn; '" }+ })+ const script = buildLauncher(p, { FROM_FILE: '$HOME' }, paths)+ expect(script).toContain(`'node' 'x'\\''; rm -rf ~; echo '\\''' '$(id)' '\`id\`' '&&' 'reboot'`)+ expect(script).toContain(`cd '/tmp/$(id)' || nt_end 1`)+ expect(script).toContain(`export EVIL=''\\''; touch /tmp/pwn; '\\'''`)+ expect(script).toContain(`export FROM_FILE='$HOME'`)+ })++ it('records pid and exit status, and traps INT with a handler (never ignore)', () => {+ const script = buildLauncher(proc({ type: 'node', program: 'a.js' }), {}, paths)+ expect(script).toContain(`echo $$ > '/d/n.pid'`)+ expect(script).toContain(`trap ':' INT TERM`)+ expect(script).not.toContain(`trap '' INT`)+ expect(script.trimEnd().endsWith('nt_end $?')).toBe(true)+ })++ it('lets the config env win over the envFile', () => {+ const script = buildLauncher(proc({ type: 'node', program: 'a.js', env: { K: 'config' } }), { K: 'file' }, paths)+ expect(script).toContain("export K='config'")+ expect(script).not.toContain("export K='file'")+ })+})++describe('parseEnvFile', () => {+ it('reads dotenv lines', () => {+ expect(parseEnvFile('# c\nA=1\nexport B="two words"\nC=\'x # y\'\nD=raw # comment\nbad line\n')).toEqual({+ A: '1',+ B: 'two words',+ C: 'x # y',+ D: 'raw'+ })+ })+})++describe('normalizeRunConfig', () => {+ it('round-trips a valid config', () => {+ expect(normalizeRunConfig({ projectDir: '/a', launchConfig: 'Dev', deviceId: 'macos', deviceName: 'macOS', showTerminal: true })).toEqual({+ projectDir: '/a', launchConfig: 'Dev', deviceId: 'macos', deviceName: 'macOS', showTerminal: true, reloadOnSave: true+ })+ })+ it('drops hostile fields and non-absolute folders', () => {+ expect(normalizeRunConfig({ projectDir: 'rel' })).toBeUndefined()+ expect(normalizeRunConfig({ projectDir: '/a', deviceId: 'x; rm -rf ~', extraArgs: 'a\nb' })).toEqual({ projectDir: '/a', reloadOnSave: true })+ })+})++describe('presentation', () => {+ it('titles a node by configuration and folder', () => {+ expect(runNodeTitle('/dev/doc-flutter', 'Current device LOCAL DEV')).toBe('Current device LOCAL DEV · doc-flutter')+ expect(runNodeTitle('/dev/x')).toBe('Run · x')+ expect(runDirLabel('/dev/doc-flutter.worktrees/family/')).toBe('doc-flutter · family')+ })+ it('names the other nodes on the same device, never itself', () => {+ const nodes = [+ { id: 'a', title: 'A', runConfig: { deviceId: 'sim1' } },+ { id: 'b', title: 'B', runConfig: { deviceId: 'sim1' } }+ ]+ expect(deviceClaims(nodes, 'a', 'sim1')).toEqual(['B'])+ })+})diff --git a/src/shared/run-config.ts b/src/shared/run-config.tsnew file mode 100644index 000000000..e59b016f9--- /dev/null+++ b/src/shared/run-config.ts@@ -0,0 +1,862 @@+/**+ * The run node: VS Code's "Run Without Debugging" for any `.vscode/launch.json` configuration, as+ * a canvas terminal. A terminal node carrying `data.runConfig` (NOT a new NodeKind): the run lives+ * in the node's tmux session, so it inherits everything a terminal already has.+ *+ * launch.json does not run anything by itself — each `type` belongs to a VS Code extension (a+ * debug adapter) that turns the configuration into a process. This module is the table of what+ * those extensions would run, type by type (`planLaunch`), for the `"request": "launch"` form:+ *+ * dart flutter run / flutter test / dart run / dart test (Flutter: hot reload + devices)+ * node, pwa-node, node-terminal node / runtimeExecutable / command+ * python, debugpy python program | -m module+ * go go run / go test / the built binary+ * php php program+ * coreclr dotnet program.dll | program+ * lldb, cppdbg the program itself+ * chrome, msedge, pwa-chrome, pwa-msedge open `url` in a browser node+ *+ * What it deliberately does NOT do, and says so instead of guessing: debugging (breakpoints are a+ * debug-adapter protocol, not a command line), `"request": "attach"` (there is nothing to start),+ * unknown types, and the variables that need an editor or an extension (`${file}`, `${input:…}`,+ * `${command:…}` beyond the Python interpreter one, `${config:…}`).+ *+ * Every value here comes from files in a repository (launch.json, tasks.json, and the git-shared+ * `.nodeterm/project.json` that stores the node's choice), so none of it is ever pasted into a+ * shell: the host writes a launcher script whose every token is single-quoted (`buildLauncher`),+ * and only `sh '<that script>'` is typed into the node's terminal. Environment values (including an+ * `envFile`'s secrets) therefore never land in the user's shell history or scrollback.+ */+import { shellSingleQuote, shellSplit } from './shell-quote'++// ─── The node's persisted choice ─────────────────────────────────────────────────────────────++/** Persisted on a terminal node as `data.runConfig`. */+export interface RunNodeConfig {+ /** Absolute path of the workspace folder (the one holding `.vscode/`). Defaults to the project's. */+ projectDir: string+ /** Name of a configuration or compound in `<projectDir>/.vscode/launch.json`. Absent = default. */+ launchConfig?: string+ /** Flutter: `-d <id>`. Ignored when the configuration pins its own device. */+ deviceId?: string+ /** The device's display name when picked, so the bar can label it before devices load. */+ deviceName?: string+ /** Extra arguments appended to the program's arguments, shell-split and quoted per token. */+ extraArgs?: string+ /** Flutter: hot reload when a `.dart` file under `lib/` changes. Default on. */+ reloadOnSave: boolean+ /** Whether the node shows its terminal (and the extra-arguments field). Default hidden. */+ showTerminal?: boolean+}++const MAX_PATH = 4096+const MAX_EXTRA_ARGS = 2000+const MAX_NAME = 200+/** Device ids are simulator UDIDs, `macos`, `chrome`, emulator ids, physical UDIDs — never shell. */+const DEVICE_ID = /^[A-Za-z0-9._:-]{1,128}$/+/** Node ids become launcher/pid file names; the charset tmux session names are held to. */+export const RUN_NODE_ID = /^[A-Za-z0-9._-]{1,128}$/+export const SIMULATOR_UDID = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/++// eslint-disable-next-line no-control-regex+const CONTROL = /[\u0000-\u001f\u007f]/++/** An absolute POSIX or Windows path with no control characters. */+export function isSafeRunDir(dir: unknown): dir is string {+ if (typeof dir !== 'string' || dir.length === 0 || dir.length > MAX_PATH) return false+ if (CONTROL.test(dir)) return false+ return dir.startsWith('/') || /^[A-Za-z]:[\\/]/.test(dir)+}++export function isSafeDeviceId(id: unknown): id is string {+ return typeof id === 'string' && DEVICE_ID.test(id)+}++function oneLine(v: unknown, max: number): string | undefined {+ if (typeof v !== 'string') return undefined+ const s = v.trim()+ if (!s || s.length > max || CONTROL.test(s)) return undefined+ return s+}++/**+ * Re-validate a persisted run config (git-shared, hand-editable). `undefined` = not a run node (or+ * too broken to describe one), which degrades the node to a plain terminal rather than failing.+ */+export function normalizeRunConfig(raw: unknown): RunNodeConfig | undefined {+ if (!raw || typeof raw !== 'object') return undefined+ const r = raw as Record<string, unknown>+ if (!isSafeRunDir(r.projectDir)) return undefined+ const out: RunNodeConfig = { projectDir: r.projectDir, reloadOnSave: r.reloadOnSave !== false }+ const launchConfig = oneLine(r.launchConfig, MAX_NAME)+ if (launchConfig) out.launchConfig = launchConfig+ if (isSafeDeviceId(r.deviceId)) {+ out.deviceId = r.deviceId+ const deviceName = oneLine(r.deviceName, MAX_NAME)+ if (deviceName) out.deviceName = deviceName+ }+ const extraArgs = oneLine(r.extraArgs, MAX_EXTRA_ARGS)+ if (extraArgs) out.extraArgs = extraArgs+ if (r.showTerminal === true) out.showTerminal = true+ return out+}++// ─── JSONC + the two files ───────────────────────────────────────────────────────────────────++/**+ * VS Code's launch.json / tasks.json are JSONC: `//` and `/* *\/` comments and trailing commas.+ * Strip them outside strings, then JSON.parse. Throws on anything else.+ */+export function parseJsonc(text: string): unknown {+ let out = ''+ let i = 0+ let inString = false+ while (i < text.length) {+ const c = text[i]+ if (inString) {+ out += c+ if (c === '\\' && i + 1 < text.length) {+ out += text[i + 1]+ i += 2+ continue+ }+ if (c === '"') inString = false+ i+++ continue+ }+ if (c === '"') {+ inString = true+ out += c+ i+++ } else if (c === '/' && text[i + 1] === '/') {+ while (i < text.length && text[i] !== '\n') i+++ } else if (c === '/' && text[i + 1] === '*') {+ const end = text.indexOf('*/', i + 2)+ i = end < 0 ? text.length : end + 2+ } else {+ out += c+ i+++ }+ }+ let cleaned = ''+ inString = false+ for (let j = 0; j < out.length; j++) {+ const c = out[j]+ if (inString) {+ cleaned += c+ if (c === '\\' && j + 1 < out.length) cleaned += out[++j]+ else if (c === '"') inString = false+ continue+ }+ if (c === '"') {+ inString = true+ cleaned += c+ continue+ }+ if (c === ',') {+ let k = j + 1+ while (k < out.length && /\s/.test(out[k])) k+++ if (out[k] === ']' || out[k] === '}') continue+ }+ cleaned += c+ }+ return JSON.parse(cleaned)+}++export type OsKey = 'osx' | 'linux' | 'windows'++export function osKeyFor(platform: string): OsKey {+ return platform === 'darwin' ? 'osx' : platform === 'win32' ? 'windows' : 'linux'+}++/** A configuration as written, with its `osx`/`linux`/`windows` block merged over it. */+export interface LaunchConfig {+ name: string+ type: string+ request: string+ raw: Record<string, unknown>+}++export interface LaunchCompound {+ name: string+ configurations: string[]+}++export interface LaunchFile {+ configs: LaunchConfig[]+ compounds: LaunchCompound[]+}++function isRecord(v: unknown): v is Record<string, unknown> {+ return !!v && typeof v === 'object' && !Array.isArray(v)+}++function withOsOverride(raw: Record<string, unknown>, os: OsKey): Record<string, unknown> {+ const o = raw[os]+ return isRecord(o) ? { ...raw, ...o } : raw+}++/** Configurations and compounds, in file order. Throws on unparseable JSONC. */+export function parseLaunchFile(text: string, os: OsKey = 'osx'): LaunchFile {+ const doc = parseJsonc(text) as { configurations?: unknown; compounds?: unknown }+ const configs: LaunchConfig[] = []+ const seen = new Set<string>()+ for (const item of Array.isArray(doc?.configurations) ? doc.configurations : []) {+ if (!isRecord(item)) continue+ const raw = withOsOverride(item, os)+ const name = oneLine(raw.name, MAX_NAME)+ const type = oneLine(raw.type, MAX_NAME)+ if (!name || !type || seen.has(name)) continue+ seen.add(name)+ configs.push({ name, type, request: typeof raw.request === 'string' ? raw.request : 'launch', raw })+ }+ const compounds: LaunchCompound[] = []+ for (const item of Array.isArray(doc?.compounds) ? doc.compounds : []) {+ if (!isRecord(item)) continue+ const name = oneLine(item.name, MAX_NAME)+ if (!name || seen.has(name)) continue+ seen.add(name)+ const members = (Array.isArray(item.configurations) ? item.configurations : [])+ .map((m) => (typeof m === 'string' ? m : isRecord(m) && typeof m.name === 'string' ? m.name : null))+ .filter((m): m is string => !!m)+ compounds.push({ name, configurations: members })+ }+ return { configs, compounds }+}++/** A task from tasks.json, with its OS block merged over it. */+export interface TaskDef {+ label: string+ raw: Record<string, unknown>+}++/** Tasks in file order, keyed by `label` (or VS Code's derived `npm: <script>`). Throws on bad JSONC. */+export function parseTasksFile(text: string, os: OsKey = 'osx'): TaskDef[] {+ const doc = parseJsonc(text) as { tasks?: unknown }+ const out: TaskDef[] = []+ for (const item of Array.isArray(doc?.tasks) ? doc.tasks : []) {+ if (!isRecord(item)) continue+ const raw = withOsOverride(item, os)+ const label =+ oneLine(raw.label, MAX_NAME) ??+ (raw.type === 'npm' && typeof raw.script === 'string' ? `npm: ${raw.script}` : undefined) ??+ (typeof raw.type === 'string' && typeof raw.command === 'string' ? `${raw.type}: ${raw.command}` : undefined)+ if (label) out.push({ label, raw })+ }+ return out+}++// ─── Describing a configuration (cheap, no environment) ──────────────────────────────────────++/** What the bar needs to know about an entry before anything runs. */+export interface LaunchEntry {+ name: string+ kind: 'config' | 'compound'+ /** The VS Code `type` ('' for compounds). */+ type: string+ /** "Flutter", "Node.js", "Python", … — shown beside the name. */+ typeLabel: string+ /** False when this configuration cannot be run here; `reason` says why. */+ supported: boolean+ reason?: string+ /** Flutter runs: pick a device (unless `pinnedDevice`). */+ usesDevice: boolean+ /** Flutter `flutter run`: hot reload / hot restart / reload on save. */+ hotReload: boolean+ /** The device a Flutter configuration names itself. */+ pinnedDevice?: string+ /** Opens a URL in a browser node instead of running a process. */+ browser: boolean+ /** Compounds: the member configuration names. */+ members?: string[]+ /** The configuration's `preLaunchTask`, if any. */+ preLaunchTask?: string+}++const TYPE_LABEL: Record<string, string> = {+ dart: 'Dart',+ node: 'Node.js',+ 'pwa-node': 'Node.js',+ 'node-terminal': 'Node.js',+ python: 'Python',+ debugpy: 'Python',+ go: 'Go',+ php: 'PHP',+ coreclr: '.NET',+ lldb: 'Native',+ cppdbg: 'Native',+ chrome: 'Browser',+ msedge: 'Browser',+ 'pwa-chrome': 'Browser',+ 'pwa-msedge': 'Browser'+}++export const SUPPORTED_TYPES = Object.keys(TYPE_LABEL)++const BROWSER_TYPES = new Set(['chrome', 'msedge', 'pwa-chrome', 'pwa-msedge'])++export function typeLabel(type: string, isFlutterProject: boolean): string {+ if (type === 'dart') return isFlutterProject ? 'Flutter' : 'Dart'+ return TYPE_LABEL[type] ?? type+}++function strArray(v: unknown): string[] {+ if (typeof v === 'string') return shellSplit(v)+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []+}++function str(v: unknown): string | undefined {+ return typeof v === 'string' && v.trim() ? v : undefined+}++/** The device a Dart configuration pins (`-d x`, `--device-id x`, `-d=x`, or `deviceId`). */+export function pinnedDevice(raw: Record<string, unknown>): string | undefined {+ const a = [...strArray(raw.args), ...strArray(raw.toolArgs)]+ for (let i = 0; i < a.length; i++) {+ const t = a[i]+ if ((t === '-d' || t === '--device-id') && a[i + 1]) return a[i + 1]+ if (t.startsWith('-d=')) return t.slice(3)+ if (t.startsWith('--device-id=')) return t.slice('--device-id='.length)+ }+ return isSafeDeviceId(raw.deviceId) ? raw.deviceId : undefined+}++/** Dart-Code runs a `program` under test/ or integration_test/ (or a *_test.dart) as a TEST. */+export function isDartTestProgram(program: string | undefined): boolean {+ if (!program) return false+ const p = program.replace(/\\/g, '/')+ return /(^|\/)(test|integration_test)\//.test(p) || p.endsWith('_test.dart')+}++const UNSUPPORTED_VAR = /\$\{(file|fileBasename|fileBasenameNoExtension|fileDirname|fileExtname|fileWorkspaceFolder|relativeFile|relativeFileDirname|lineNumber|selectedText|execPath|input:[^}]*|config:[^}]*|command:[^}]*|workspaceFolder:[^}]*)\}/++/** The first variable in `raw` that needs an editor or an extension to resolve, if any. */+export function unsupportedVariable(raw: unknown): string | undefined {+ const text = JSON.stringify(raw)+ const re = new RegExp(UNSUPPORTED_VAR.source, 'g')+ for (let m = re.exec(text); m; m = re.exec(text)) {+ // The Python extension's interpreter is the one `${command:…}` we can answer ourselves.+ if (m[1] === 'command:python.interpreterPath') continue+ return m[0]+ }+ return undefined+}++export function describeConfig(cfg: LaunchConfig, isFlutterProject: boolean): LaunchEntry {+ const base: LaunchEntry = {+ name: cfg.name,+ kind: 'config',+ type: cfg.type,+ typeLabel: typeLabel(cfg.type, isFlutterProject),+ supported: true,+ usesDevice: false,+ hotReload: false,+ browser: BROWSER_TYPES.has(cfg.type),+ ...(str(cfg.raw.preLaunchTask) ? { preLaunchTask: str(cfg.raw.preLaunchTask) } : {})+ }+ const refuse = (reason: string): LaunchEntry => ({ ...base, supported: false, reason })+ if (cfg.request !== 'launch') {+ return refuse(`“${cfg.name}” attaches to a process that is already running — there is nothing to start.`)+ }+ if (!(cfg.type in TYPE_LABEL)) return refuse(`“${cfg.type}” configurations are not supported yet.`)+ const v = unsupportedVariable(cfg.raw)+ if (v) return refuse(`${v} needs VS Code to resolve — it cannot run here.`)+ if (cfg.type === 'dart') {+ const program = str(cfg.raw.program)+ const isTest = isDartTestProgram(program)+ const flutter = isFlutterProject || cfg.raw.flutterMode !== undefined+ if (flutter) {+ const pinned = pinnedDevice(cfg.raw)+ // A widget test runs headless; an integration test runs on a device, like the app.+ const onDevice = !isTest || /(^|\/)integration_test\//.test((program ?? '').replace(/\\/g, '/'))+ return {+ ...base,+ typeLabel: 'Flutter',+ usesDevice: onDevice,+ hotReload: !isTest,+ ...(pinned ? { pinnedDevice: pinned } : {})+ }+ }+ if (!program) return refuse(`“${cfg.name}” has no program to run.`)+ return base+ }+ if (cfg.type === 'php' && !str(cfg.raw.program)) {+ return refuse(`“${cfg.name}” listens for Xdebug — there is nothing to start. Run the app separately.`)+ }+ if (base.browser && !str(cfg.raw.url)) return refuse(`“${cfg.name}” has no url to open.`)+ return base+}++export function describeLaunchFile(file: LaunchFile, isFlutterProject: boolean): LaunchEntry[] {+ const configs = file.configs.map((c) => describeConfig(c, isFlutterProject))+ const names = new Set(file.configs.map((c) => c.name))+ const compounds = file.compounds.map((c): LaunchEntry => {+ const missing = c.configurations.filter((m) => !names.has(m))+ return {+ name: c.name,+ kind: 'compound',+ type: '',+ typeLabel: 'Compound',+ supported: missing.length === 0 && c.configurations.length > 0,+ ...(missing.length+ ? { reason: `“${c.name}” names configurations that are not in launch.json: ${missing.join(', ')}.` }+ : c.configurations.length === 0+ ? { reason: `“${c.name}” lists no configurations.` }+ : {}),+ usesDevice: false,+ hotReload: false,+ browser: false,+ members: c.configurations+ }+ })+ return [...configs, ...compounds]+}++/** The synthetic entry a Flutter checkout with no launch.json gets: plain `flutter run`. */+export const DEFAULT_FLUTTER_ENTRY = 'flutter run (lib/main.dart)'++/** Which entry a node runs: its named one, else the first supported configuration that leaves+ * the device to the picker (VS Code's "Current device" style), else the first supported one. */+export function resolveEntry(entries: readonly LaunchEntry[], name: string | undefined): LaunchEntry | undefined {+ if (name) {+ const hit = entries.find((e) => e.name === name)+ if (hit) return hit+ }+ const runnable = entries.filter((e) => e.supported && e.kind === 'config')+ return runnable.find((e) => e.usesDevice && !e.pinnedDevice) ?? runnable[0] ?? entries[0]+}++// ─── Planning a run ──────────────────────────────────────────────────────────────────────────++export interface PlanContext {+ /** `${workspaceFolder}` — the node's projectDir. */+ workspace: string+ /** `${userHome}`. */+ home: string+ /** `${env:NAME}`, pre-resolved by the host from the user's login environment. */+ env: Readonly<Record<string, string>>+ isFlutterProject: boolean+ /** The interpreter the Python extension would pick: a workspace venv, else `python3`. */+ pythonPath: string+ /** The node's device, for Flutter runs. */+ deviceId?: string+ /** The node's extra arguments, appended to the program's own. */+ extraArgs?: string+ /** Where `flutter run` writes its pid (for hot reload / restart signals). */+ flutterPidFile: string+ tasks: readonly TaskDef[]+}++/** One preLaunchTask step: a process argv, or a shell command line (`sh -c`). */+export interface TaskStep {+ label: string+ cwd: string+ env: Record<string, string>+ argv?: string[]+ shell?: string+}++export interface ProcessPlan {+ kind: 'process'+ name: string+ cwd: string+ env: Record<string, string>+ /** Absolute path of an `envFile` to load before `env` (which wins), when the config names one. */+ envFile?: string+ /** A program argv — or, for `node-terminal`'s free-form `command`, a shell line. */+ argv?: string[]+ shell?: string+ preTasks: TaskStep[]+ /** `flutter run` (hot reload by signal), anything else is plain stop/restart. */+ hotReload: boolean+}++export interface BrowserPlan {+ kind: 'browser'+ name: string+ url: string+}++export type PlanResult = { ok: true; plan: ProcessPlan | BrowserPlan } | { ok: false; error: string }++/** Expand the variables we can answer. Throws `Error(<variable>)` on one we cannot. */+export function expandVars(s: string, ctx: PlanContext): string {+ return s.replace(/\$\{([^}]+)\}/g, (whole, name: string) => {+ if (name === 'workspaceFolder' || name === 'workspaceRoot' || name === 'cwd') return ctx.workspace+ if (name === 'workspaceFolderBasename') return ctx.workspace.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? ''+ if (name === 'userHome') return ctx.home+ if (name === 'pathSeparator' || name === '/') return '/'+ if (name === 'command:python.interpreterPath') return ctx.pythonPath+ if (name.startsWith('env:')) return ctx.env[name.slice(4)] ?? ''+ throw new Error(whole)+ })+}++function joinPath(base: string, rel: string): string {+ if (rel.startsWith('/') || /^[A-Za-z]:[\\/]/.test(rel)) return rel+ return `${base.replace(/\/+$/, '')}/${rel.replace(/^\.\//, '')}`+}++function envRecord(v: unknown, ctx: PlanContext): Record<string, string> {+ const out: Record<string, string> = {}+ if (isRecord(v)) {+ for (const [k, val] of Object.entries(v)) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) continue+ if (typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {+ out[k] = expandVars(String(val), ctx)+ }+ }+ } else if (Array.isArray(v)) {+ // cppdbg: `environment: [{ name, value }]`+ for (const e of v) {+ if (isRecord(e) && typeof e.name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name)) {+ out[e.name] = expandVars(String(e.value ?? ''), ctx)+ }+ }+ }+ return out+}++const MAX_TASK_DEPTH = 8++/** The steps a `preLaunchTask` (and its `dependsOn`) runs, in order. Throws Error(reason). */+export function planTask(label: string, ctx: PlanContext, depth = 0, seen = new Set<string>()): TaskStep[] {+ if (depth > MAX_TASK_DEPTH || seen.has(label)) throw new Error(`Task “${label}” depends on itself.`)+ seen.add(label)+ const task =+ label === '${defaultBuildTask}'+ ? ctx.tasks.find((t) => {+ const g = t.raw.group+ return isRecord(g) && g.kind === 'build' && g.isDefault === true+ })+ : ctx.tasks.find((t) => t.label === label)+ if (!task) throw new Error(`Task “${label}” is not in .vscode/tasks.json.`)+ const t = task.raw+ const steps: TaskStep[] = []+ const deps = typeof t.dependsOn === 'string' ? [t.dependsOn] : strArray(t.dependsOn)+ for (const d of deps) steps.push(...planTask(d, ctx, depth + 1, seen))+ if (t.isBackground === true) {+ throw new Error(`Task “${task.label}” runs in the background (a watcher) — start it separately, then run.`)+ }+ const options = isRecord(t.options) ? t.options : {}+ const cwd = joinPath(ctx.workspace, expandVars(str(options.cwd) ?? ctx.workspace, ctx))+ const env = envRecord(options.env, ctx)+ const type = typeof t.type === 'string' ? t.type : 'process'+ const command = str(t.command) ? expandVars(t.command as string, ctx) : undefined+ const args = strArray(t.args).map((a) => expandVars(a, ctx))+ const step = (s: Omit<TaskStep, 'label' | 'cwd' | 'env'>): TaskStep => ({ label: task.label, cwd, env, ...s })+ // A task that only gathers others (`dependsOn` and nothing to run) contributes just those.+ if (deps.length && !command && type !== 'npm' && type !== 'typescript') return steps+ switch (type) {+ case 'shell':+ if (!command) throw new Error(`Task “${task.label}” has no command.`)+ steps.push(step({ shell: [command, ...args.map(shellSingleQuote)].join(' ') }))+ break+ case 'process':+ case 'dart':+ case 'flutter':+ // Dart-Code's tasks carry the tool as `command` ('dart' / 'flutter'), like a process task.+ steps.push(step({ argv: [command ?? type, ...args] }))+ break+ case 'npm': {+ const script = str(t.script)+ if (!script) throw new Error(`Task “${task.label}” has no npm script.`)+ const at = str(t.path) ? joinPath(ctx.workspace, expandVars(t.path as string, ctx)) : cwd+ steps.push({ label: task.label, cwd: at, env, argv: ['npm', 'run', script, ...args] })+ break+ }+ case 'typescript': {+ if (t.option === 'watch') throw new Error(`Task “${task.label}” is a tsc watch — start it separately, then run.`)+ steps.push(step({ argv: ['npx', 'tsc', '-p', expandVars(str(t.tsconfig) ?? 'tsconfig.json', ctx)] }))+ break+ }+ case 'cargo':+ steps.push(step({ argv: ['cargo', command ?? 'build', ...args] }))+ break+ default:+ throw new Error(`Task “${task.label}” is a “${type}” task, which is not supported yet.`)+ }+ return steps+}++/** Turn one launch configuration into what the host runs. Pure; every refusal is a sentence. */+export function planLaunch(cfg: LaunchConfig, ctx: PlanContext): PlanResult {+ const entry = describeConfig(cfg, ctx.isFlutterProject)+ if (!entry.supported) return { ok: false, error: entry.reason ?? 'Not supported.' }+ try {+ const raw = cfg.raw+ const x = (s: string) => expandVars(s, ctx)+ if (entry.browser) return { ok: true, plan: { kind: 'browser', name: cfg.name, url: x(str(raw.url) as string) } }++ const cwd = joinPath(ctx.workspace, x(str(raw.cwd) ?? ctx.workspace))+ const env = envRecord(raw.env ?? raw.environment, ctx)+ const envFile = str(raw.envFile) ? joinPath(ctx.workspace, x(raw.envFile as string)) : undefined+ const args = strArray(raw.args).map(x)+ const extra = ctx.extraArgs ? shellSplit(ctx.extraArgs) : []+ const preTasks = str(raw.preLaunchTask) ? planTask(x(raw.preLaunchTask as string), ctx) : []+ const proc = (argv: string[], hotReload = false): PlanResult => ({+ ok: true,+ plan: {+ kind: 'process',+ name: cfg.name,+ cwd,+ env,+ ...(envFile ? { envFile } : {}),+ argv,+ preTasks,+ hotReload+ }+ })++ switch (cfg.type) {+ case 'dart': {+ const program = str(raw.program) ? x(raw.program as string) : undefined+ const toolArgs = strArray(raw.toolArgs).map(x)+ const isTest = isDartTestProgram(program)+ if (entry.typeLabel === 'Flutter') {+ // Dart-Code passes a Flutter config's `args` to `flutter run` too (the legacy behavior a+ // config like `"args": ["--flavor", "dev"]` relies on), after `toolArgs`.+ const device = !entry.pinnedDevice && entry.usesDevice && ctx.deviceId ? ['-d', ctx.deviceId] : []+ const mode = raw.flutterMode === 'profile' ? ['--profile'] : raw.flutterMode === 'release' ? ['--release'] : []+ if (isTest) return proc(['flutter', 'test', ...toolArgs, ...args, ...device, ...(program ? [program] : []), ...extra])+ return proc(+ [+ 'flutter', 'run',+ ...(program ? ['-t', program] : []),+ ...toolArgs, ...args, ...mode, ...device,+ '--pid-file', ctx.flutterPidFile,+ ...extra+ ],+ true+ )+ }+ if (isTest) return proc(['dart', 'test', ...toolArgs, program as string, ...args, ...extra])+ return proc(['dart', 'run', ...toolArgs, program as string, ...args, ...extra])+ }+ case 'node':+ case 'pwa-node': {+ const runtime = str(raw.runtimeExecutable) ? x(raw.runtimeExecutable as string) : 'node'+ const runtimeArgs = strArray(raw.runtimeArgs).map(x)+ const program = str(raw.program) ? x(raw.program as string) : undefined+ if (!program && runtime === 'node' && runtimeArgs.length === 0) {+ return { ok: false, error: `“${cfg.name}” has neither a program nor a runtime command.` }+ }+ return proc([runtime, ...runtimeArgs, ...(program ? [program] : []), ...args, ...extra])+ }+ case 'node-terminal': {+ const command = str(raw.command)+ if (!command) return { ok: false, error: `“${cfg.name}” has no command.` }+ // A free-form command line the user wrote for a shell — it runs in one (sh -c), like VS Code.+ const line = [x(command), ...extra.map(shellSingleQuote)].join(' ')+ return { ok: true, plan: { kind: 'process', name: cfg.name, cwd, env, ...(envFile ? { envFile } : {}), shell: line, preTasks, hotReload: false } }+ }+ case 'python':+ case 'debugpy': {+ const python = str(raw.python) ? x(raw.python as string) : str(raw.pythonPath) ? x(raw.pythonPath as string) : ctx.pythonPath+ const pythonArgs = strArray(raw.pythonArgs).map(x)+ if (str(raw.module)) return proc([python, ...pythonArgs, '-m', x(raw.module as string), ...args, ...extra])+ if (str(raw.program)) return proc([python, ...pythonArgs, x(raw.program as string), ...args, ...extra])+ return { ok: false, error: `“${cfg.name}” has neither a program nor a module.` }+ }+ case 'go': {+ const program = str(raw.program) ? x(raw.program as string) : ctx.workspace+ const buildFlags = strArray(raw.buildFlags).map(x)+ if (raw.mode === 'test') return proc(['go', 'test', ...buildFlags, program, ...args, ...extra])+ if (raw.mode === 'exec') return proc([program, ...args, ...extra])+ return proc(['go', 'run', ...buildFlags, program, ...args, ...extra])+ }+ case 'php': {+ const runtime = str(raw.runtimeExecutable) ? x(raw.runtimeExecutable as string) : 'php'+ return proc([runtime, ...strArray(raw.runtimeArgs).map(x), x(raw.program as string), ...args, ...extra])+ }+ case 'coreclr': {+ const program = str(raw.program) ? x(raw.program as string) : undefined+ if (!program) return { ok: false, error: `“${cfg.name}” has no program.` }+ return proc(program.endsWith('.dll') ? ['dotnet', program, ...args, ...extra] : [program, ...args, ...extra])+ }+ case 'lldb':+ case 'cppdbg': {+ const program = str(raw.program) ? x(raw.program as string) : undefined+ if (!program) return { ok: false, error: `“${cfg.name}” has no program.` }+ return proc([program, ...args, ...extra])+ }+ default:+ return { ok: false, error: `“${cfg.type}” configurations are not supported yet.` }+ }+ } catch (e) {+ const msg = (e as Error).message+ return { ok: false, error: msg.startsWith('${') ? `${msg} needs VS Code to resolve — it cannot run here.` : msg }+ }+}++/** The plan for a Flutter checkout with no launch.json: `flutter run` on the chosen device. */+export function defaultFlutterConfig(): LaunchConfig {+ return { name: DEFAULT_FLUTTER_ENTRY, type: 'dart', request: 'launch', raw: { name: DEFAULT_FLUTTER_ENTRY, type: 'dart' } }+}++// ─── The launcher script ─────────────────────────────────────────────────────────────────────++/** Parse a dotenv file: `KEY=value`, `export KEY=value`, quotes, `#` comments. */+export function parseEnvFile(text: string): Record<string, string> {+ const out: Record<string, string> = {}+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)?\s*$/.exec(line)+ if (!m) continue+ let v = (m[2] ?? '').trim()+ if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) || (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {+ const dq = v.startsWith('"')+ v = v.slice(1, -1)+ if (dq) v = v.replace(/\\n/g, '\n').replace(/\\"/g, '"')+ } else {+ v = v.replace(/\s+#.*$/, '')+ }+ out[m[1]] = v+ }+ return out+}++export interface LauncherPaths {+ /** Written with the launcher's own pid while it runs; removed when it ends. */+ pidFile: string+ /** Written with the exit status when the run ends. */+ exitFile: string+}++function exports(env: Record<string, string>): string[] {+ return Object.entries(env).map(([k, v]) => `export ${k}=${shellSingleQuote(v)}`)+}++function cmdLine(argv: string[] | undefined, shell: string | undefined): string {+ return argv ? argv.map(shellSingleQuote).join(' ') : `sh -c ${shellSingleQuote(shell ?? '')}`+}++/** What the launcher prints before it runs, so the terminal says what it is doing. Env values are+ * never printed (an envFile is often where the secrets live). */+export function displayCommand(plan: ProcessPlan): string {+ return plan.argv ? plan.argv.map((a) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : shellSingleQuote(a))).join(' ') : (plan.shell ?? '')+}++/**+ * The POSIX sh launcher the node's terminal runs (`sh '<path>'`). Every value is single-quoted.+ *+ * - It records its own pid (the run's status), and its exit status when the run ends.+ * - It traps INT/TERM with a no-op HANDLER (never `''`, which children would inherit as "ignore"):+ * Ctrl+C / Stop interrupts the program, and the launcher survives to record the status.+ * - preLaunchTask steps run first, each in a subshell with its own cwd/env; a failing task stops+ * the run, like VS Code.+ */+export function buildLauncher(plan: ProcessPlan, envFileVars: Record<string, string>, paths: LauncherPaths): string {+ const q = shellSingleQuote+ const lines: string[] = [+ '#!/bin/sh',+ `# nodeterm run configuration: ${plan.name.replace(/[\r\n]/g, ' ')}`,+ `echo $$ > ${q(paths.pidFile)}`,+ `rm -f ${q(paths.exitFile)}`,+ "trap ':' INT TERM",+ `nt_end() { rm -f ${q(paths.pidFile)}; echo "$1" > ${q(paths.exitFile)}; exit "$1"; }`+ ]+ for (const t of plan.preTasks) {+ lines.push(+ `printf '\\033[2m▶ task: %s\\033[0m\\n' ${q(t.label)}`,+ `( cd ${q(t.cwd)} || exit 1`,+ ...exports(t.env).map((l) => ` ${l}`),+ ` ${cmdLine(t.argv, t.shell)}`,+ ')',+ 'nt_rc=$?',+ `if [ "$nt_rc" -ne 0 ]; then printf '\\033[31mTask %s failed (exit %s).\\033[0m\\n' ${q(t.label)} "$nt_rc"; nt_end "$nt_rc"; fi`+ )+ }+ lines.push(+ `cd ${q(plan.cwd)} || nt_end 1`,+ ...exports({ ...envFileVars, ...plan.env }),+ `printf '\\033[2m▶ %s\\033[0m\\n' ${q(displayCommand(plan))}`,+ cmdLine(plan.argv, plan.shell),+ 'nt_end $?'+ )+ return lines.join('\n') + '\n'+}++// ─── Presentation ────────────────────────────────────────────────────────────────────────────++/** Last path segment, for titles and the folder picker. */+export function runDirLabel(dir: string): string {+ const parts = dir.replace(/[\\/]+$/, '').split(/[\\/]/)+ const last = parts[parts.length - 1] || dir+ const parent = parts[parts.length - 2]+ return parent && parent.endsWith('.worktrees') ? `${parent.replace(/\.worktrees$/, '')} · ${last}` : last+}++/** The node title while it is still ours to set (`titleAuto`). */+export function runNodeTitle(dir: string, configName?: string): string {+ return configName ? `${configName} · ${runDirLabel(dir)}` : `Run · ${runDirLabel(dir)}`+}++/** Which other run nodes already use `deviceId` — for the "already in use" warning. */+export function deviceClaims(+ nodes: ReadonlyArray<{ id: string; title?: string; runConfig?: Pick<RunNodeConfig, 'deviceId'> }>,+ selfId: string,+ deviceId: string | undefined+): string[] {+ if (!deviceId) return []+ return nodes.filter((n) => n.id !== selfId && n.runConfig?.deviceId === deviceId).map((n) => n.title || n.id)+}++// ─── Host API ────────────────────────────────────────────────────────────────────────────────++export type RunDeviceKind = 'simulator' | 'emulator' | 'device' | 'desktop' | 'web'++export interface RunDevice {+ id: string+ name: string+ kind: RunDeviceKind+ /** iOS simulators only. */+ state?: 'booted' | 'shutdown'+ /** "iOS 27.1" for a simulator, the target platform otherwise. */+ platform?: string+}++export interface RunDevicesResult {+ devices: RunDevice[]+ error?: string+}++export interface RunEntriesResult {+ /** Whether the folder has a readable `.vscode/launch.json`. */+ found: boolean+ entries: LaunchEntry[]+ /** Set when launch.json exists but could not be parsed. */+ error?: string+ isFlutterProject: boolean+}++export type RunStartResult =+ | { ok: true; kind: 'process'; command: string; hotReload: boolean }+ | { ok: true; kind: 'browser'; url: string }+ | { ok: true; kind: 'compound'; members: string[] }+ | { ok: false; error: string }++export interface RunStatus {+ running: boolean+ /** The last run's exit status, when it ended (null while running / unknown). */+ exitCode: number | null+}++export interface RunConfigApi {+ /** The configurations (and compounds) in `<dir>/.vscode/launch.json`, described. */+ entries(dir: string): Promise<RunEntriesResult>+ /** iOS simulators plus `flutter devices`. `refresh` bypasses the short cache. */+ devices(refresh?: boolean): Promise<RunDevicesResult>+ /** Boot an iOS simulator (no-op when already booted) and open Simulator.app. */+ bootDevice(udid: string): Promise<boolean>+ /** Folders near `dir` that have a launch.json or are Flutter checkouts. */+ discoverProjects(dir: string): Promise<string[]>+ /** Prepare a run: write the launcher and return the line to type (or a URL / compound members). */+ start(nodeId: string, config: RunNodeConfig): Promise<RunStartResult>+ status(nodeId: string): Promise<RunStatus>+ /** Interrupt the run (SIGINT, or SIGTERM when `force`). False when nothing is running. */+ stop(nodeId: string, force?: boolean): Promise<boolean>+ /** Flutter: hot reload (SIGUSR1) / hot restart (SIGUSR2). */+ signal(nodeId: string, kind: 'reload' | 'restart'): Promise<boolean>+ /** Flutter: start (dir) or stop (null) reload-on-save. */+ watch(nodeId: string, dir: string | null): Promise<void>+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 0f90c2846..17da2cb74 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -559,6 +559,12 @@ export interface CanvasNodeState {sshRemoteTmux?: boolean/** editor-only: when true (SSH-project editors), reads/writes go to the project's remote fs via `sshFs`. */sshFs?: boolean+ /**+ * Run nodes only (a terminal node that runs a `.vscode/launch.json` configuration): folder,+ * configuration, device, reload-on-save. Git-shared and hand-editable — read through+ * `normalizeRunConfig` (@shared/run-config) on every load AND save.+ */+ runConfig?: import('./run-config').RunNodeConfig// sticky-onlytext?: string/**@@ -4216,6 +4222,8 @@ export interface NodeTerminalApi {/** "Open recent" — the newest agent conversations in this machine's CLI histories. */recentConversations: import('./recent-conversations').RecentConversationsApiwallpaper: import('./wallpaper').WallpaperApi+ /** Run node host side (launch.json, devices, launcher, status, stop, signals, reload on save). */+ runConfig: import('./run-config').RunConfigApitriggers: TriggersApicontext: ContextApicanvas: CanvasApi